208e0c5d2c20e189fad69fb8a7e067a790896b42
[vpp.git] / src / vat2 / main.c
1 /*
2  * Copyright (c) 2020 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <stdbool.h>
19 #include <ctype.h>
20 #include <getopt.h>
21 #include <assert.h>
22 #include <vlib/vlib.h>
23 #include <vlibapi/api_types.h>
24 #include <vppinfra/hash.h>
25 #include <vppinfra/cJSON.h>
26
27 /* VPP API client includes */
28 #include <vpp-api/client/vppapiclient.h>
29
30 #include <limits.h>
31 #include "vat2.h"
32
33 uword *function_by_name;
34 bool debug = false;
35
36 char *vat2_plugin_path;
37 static void
38 vat2_find_plugin_path ()
39 {
40   char *p, path[PATH_MAX];
41   int rv;
42   u8 *s;
43
44   /* find executable path */
45   if ((rv = readlink ("/proc/self/exe", path, PATH_MAX - 1)) == -1)
46     return;
47
48   /* readlink doesn't provide null termination */
49   path[rv] = 0;
50
51   /* strip filename */
52   if ((p = strrchr (path, '/')) == 0)
53     return;
54   *p = 0;
55
56   /* strip bin/ */
57   if ((p = strrchr (path, '/')) == 0)
58     return;
59   *p = 0;
60
61   s = format (0, "%s/lib/" CLIB_TARGET_TRIPLET "/vat2_plugins:"
62               "%s/lib/vat2_plugins", path, path);
63   vec_add1 (s, 0);
64   vat2_plugin_path = (char *) s;
65 }
66
67 void
68 vac_callback (unsigned char *data, int len)
69 {
70   u16 result_msg_id = ntohs(*((u16 *)data));
71   DBG("Received something async: %d\n", result_msg_id);
72 }
73
74 int vat2_load_plugins (char *path, char *filter, int *loaded);
75
76 static int
77 register_function (void)
78 {
79   int loaded;
80
81   vat2_find_plugin_path();
82   DBG("Plugin Path %s\n", vat2_plugin_path);
83   int rv = vat2_load_plugins(vat2_plugin_path, 0, &loaded);
84   DBG("Loaded %u plugins\n", loaded);
85   return rv;
86 }
87
88 struct apifuncs_s
89 {
90   cJSON (*f) (cJSON *);
91   cJSON (*tojson) (void *);
92 };
93
94 struct apifuncs_s *apifuncs = 0;
95
96 void
97 vat2_register_function (char *name, cJSON (*f) (cJSON *),
98                         cJSON (*tojson) (void *))
99 {
100   struct apifuncs_s funcs = { .f = f, .tojson = tojson };
101   vec_add1 (apifuncs, funcs);
102   hash_set_mem (function_by_name, name, vec_len (apifuncs) - 1);
103 }
104
105 static int
106 vat2_exec_command_by_name (char *msgname, cJSON *o)
107 {
108   uword *p = hash_get_mem (function_by_name, msgname);
109   if (!p)
110     {
111       fprintf (stderr, "No such command %s", msgname);
112       return -1;
113     }
114
115   cJSON *(*fp) (cJSON *);
116   fp = (void *) apifuncs[p[0]].f;
117   cJSON *r = (*fp) (o);
118
119   if (r)
120     {
121       char *output = cJSON_Print (r);
122       cJSON_Delete (r);
123       printf ("%s\n", output);
124       free (output);
125     }
126   else
127     {
128       fprintf (stderr, "Call failed: %s\n", msgname);
129       return -1;
130     }
131   return 0;
132 }
133
134 static int
135 vat2_exec_command (cJSON *o)
136 {
137
138   cJSON *msg_id_obj = cJSON_GetObjectItem (o, "_msgname");
139   if (!msg_id_obj)
140     {
141       fprintf (stderr, "Missing '_msgname' element!\n");
142       return -1;
143     }
144
145   char *name = cJSON_GetStringValue (msg_id_obj);
146   assert (name);
147   return vat2_exec_command_by_name (name, o);
148 }
149 static void
150 print_template (char *msgname)
151 {
152   uword *p = hash_get_mem (function_by_name, msgname);
153   if (!p)
154     goto error;
155
156   cJSON *(*fp) (void *);
157   fp = (void *) apifuncs[p[0]].tojson;
158   if (!fp)
159     goto error;
160
161   void *scratch = malloc (2048);
162   if (!scratch)
163     goto error;
164
165   memset (scratch, 0, 2048);
166   cJSON *t = fp (scratch);
167   if (!t)
168     goto error;
169   free (scratch);
170   char *output = cJSON_Print (t);
171   if (!output)
172     goto error;
173
174   cJSON_Delete (t);
175   printf ("%s\n", output);
176   free (output);
177
178   return;
179
180 error:
181   fprintf (stderr, "error printing template for: %s\n", msgname);
182 }
183
184 static void
185 dump_apis (void)
186 {
187   char *name;
188   u32 *i;
189   hash_foreach_mem (name, i, function_by_name, ({ printf ("%s\n", name); }));
190 }
191
192 static void
193 print_help (void)
194 {
195   char *help_string =
196     "Usage: vat2 [OPTION] <message-name> <JSON object>\n"
197     "Send API message to VPP and print reply\n"
198     "\n"
199     "-d, --debug       Print additional information\n"
200     "-p, --prefix      Specify shared memory prefix to connect to a given VPP "
201     "instance\n"
202     "-f, --file        File containing a JSON object with the arguments for "
203     "the message to send\n"
204     "--dump-apis       List all APIs available in VAT2 (might not reflect "
205     "running VPP)\n"
206     "-t, --template    Print a template JSON object for given API message\n"
207     "\n";
208   printf ("%s", help_string);
209 }
210
211 int main (int argc, char **argv)
212 {
213   /* Create a heap of 64MB */
214   clib_mem_init (0, 64 << 20);
215   char *filename = 0, *prefix = 0;
216   int index;
217   int c;
218   opterr = 0;
219   cJSON *o = 0;
220   int option_index = 0;
221   bool dump_api = false;
222   bool template = false;
223   char *msgname = 0;
224   static int debug_flag;
225   static struct option long_options[] = {
226     { "debug", no_argument, &debug_flag, 1 },
227     { "prefix", optional_argument, 0, 'p' },
228     { "file", required_argument, 0, 'f' },
229     { "dump-apis", no_argument, 0, 0 },
230     { "template", no_argument, 0, 't' },
231     { 0, 0, 0, 0 }
232   };
233
234   while ((c = getopt_long (argc, argv, "hdp:f:", long_options,
235                            &option_index)) != -1)
236     {
237       switch (c)
238         {
239         case 0:
240           if (option_index == 3)
241             dump_api = true;
242           break;
243         case 'd':
244           debug = true;
245           break;
246         case 't':
247           template = true;
248           break;
249         case 'p':
250           prefix = optarg;
251           break;
252         case 'f':
253           filename = optarg;
254           break;
255         case '?':
256           print_help ();
257           return 1;
258         default:
259           abort ();
260         }
261     }
262   debug = debug_flag == 1 ? true : false;
263   DBG ("debug = %d, filename = %s shared memory prefix: %s\n", debug, filename,
264        prefix);
265
266   for (index = optind; index < argc; index++)
267     DBG ("Non-option argument %s\n", argv[index]);
268
269   index = optind;
270
271   if (argc > index + 2)
272     {
273       fprintf (stderr, "%s: Too many arguments\n", argv[0]);
274       exit (-1);
275     }
276
277   /* Load plugins */
278   function_by_name = hash_create_string (0, sizeof (uword));
279   int res = register_function();
280   if (res < 0) {
281     fprintf(stderr, "%s: loading plugins failed\n", argv[0]);
282     exit(-1);
283   }
284
285   if (template)
286     {
287       print_template (argv[index]);
288       exit (0);
289     }
290
291   if (dump_api)
292     {
293       dump_apis ();
294       exit (0);
295     }
296
297   /* Read message arguments from command line */
298   if (argc >= (index + 1))
299     {
300       msgname = argv[index];
301     }
302   if (argc == (index + 2)) {
303     o = cJSON_Parse(argv[index+1]);
304     if (!o) {
305       fprintf(stderr, "%s: Failed parsing JSON input: %s\n", argv[0], cJSON_GetErrorPtr());
306       exit(-1);
307     }
308   }
309
310   /* Read message from file */
311   if (filename) {
312       if (argc > index)
313         {
314           fprintf (stderr, "%s: Superfluous arguments when filename given\n",
315                    argv[0]);
316           exit (-1);
317         }
318
319     FILE *f = fopen(filename, "r");
320     size_t chunksize, bufsize;
321     size_t n_read = 0;
322     size_t n;
323
324     if (!f) {
325       fprintf(stderr, "%s: can't open file: %s\n", argv[0], filename);
326       exit(-1);
327     }
328     chunksize = bufsize = 1024;
329     char *buf = malloc(bufsize);
330     while ((n = fread (buf + n_read, 1, chunksize, f)))
331       {
332         n_read += n;
333         if (n == chunksize)
334           {
335             bufsize += chunksize;
336             buf = realloc (buf, bufsize);
337           }
338       }
339     fclose(f);
340     if (n_read) {
341       o = cJSON_Parse(buf);
342       free(buf);
343       if (!o) {
344         fprintf(stderr, "%s: Failed parsing JSON input: %s\n", argv[0], cJSON_GetErrorPtr());
345         exit(-1);
346       }
347     }
348   }
349
350   if (!msgname && !filename)
351     {
352       print_help ();
353       exit (-1);
354     }
355
356   if (vac_connect ("vat2", prefix, 0, 1024))
357     {
358       fprintf (stderr, "Failed connecting to VPP\n");
359       exit (-1);
360     }
361
362   if (msgname)
363     {
364       vat2_exec_command_by_name (msgname, o);
365     }
366   else
367     {
368       if (cJSON_IsArray (o))
369         {
370           size_t size = cJSON_GetArraySize (o);
371           for (int i = 0; i < size; i++)
372             vat2_exec_command (cJSON_GetArrayItem (o, i));
373         }
374     }
375   cJSON_Delete (o);
376   vac_disconnect();
377   exit (0);
378
379 }