vat2: add shared memory argument
[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     {
155       fprintf (stderr, "no such message: %s", msgname);
156     }
157   cJSON *(*fp) (void *);
158   fp = (void *) apifuncs[p[0]].tojson;
159   assert (fp);
160   void *scratch = malloc (2048);
161   memset (scratch, 0, 2048);
162   cJSON *t = fp (scratch);
163   free (scratch);
164   char *output = cJSON_Print (t);
165   cJSON_Delete (t);
166   printf ("%s\n", output);
167   free (output);
168 }
169 static void
170 dump_apis (void)
171 {
172   char *name;
173   u32 *i;
174   hash_foreach_mem (name, i, function_by_name, ({ printf ("%s\n", name); }));
175 }
176
177 static void
178 print_help (void)
179 {
180   char *help_string =
181     "Usage: vat2 [OPTION] <message-name> <JSON object>\n"
182     "Send API message to VPP and print reply\n"
183     "\n"
184     "-d, --debug       Print additional information\n"
185     "-p, --prefix      Specify shared memory prefix to connect to a given VPP "
186     "instance\n"
187     "-f, --file        File containing a JSON object with the arguments for "
188     "the message to send\n"
189     "--dump-apis       List all APIs available in VAT2 (might not reflect "
190     "running VPP)\n"
191     "-t, --template    Print a template JSON object for given API message\n"
192     "\n";
193   printf ("%s", help_string);
194 }
195
196 int main (int argc, char **argv)
197 {
198   /* Create a heap of 64MB */
199   clib_mem_init (0, 64 << 20);
200   char *filename = 0, *prefix = 0;
201   int index;
202   int c;
203   opterr = 0;
204   cJSON *o = 0;
205   int option_index = 0;
206   bool dump_api = false;
207   bool template = false;
208   char *msgname = 0;
209   static int debug_flag;
210   static struct option long_options[] = {
211     { "debug", no_argument, &debug_flag, 1 },
212     { "prefix", optional_argument, 0, 'p' },
213     { "file", required_argument, 0, 'f' },
214     { "dump-apis", no_argument, 0, 0 },
215     { "template", no_argument, 0, 't' },
216     { 0, 0, 0, 0 }
217   };
218
219   while ((c = getopt_long (argc, argv, "hdp:f:", long_options,
220                            &option_index)) != -1)
221     {
222       switch (c)
223         {
224         case 0:
225           if (option_index == 3)
226             dump_api = true;
227           break;
228         case 'd':
229           debug = true;
230           break;
231         case 't':
232           template = true;
233           break;
234         case 'p':
235           prefix = optarg;
236           break;
237         case 'f':
238           filename = optarg;
239           break;
240         case '?':
241           print_help ();
242           return 1;
243         default:
244           abort ();
245         }
246     }
247   debug = debug_flag == 1 ? true : false;
248   DBG ("debug = %d, filename = %s shared memory prefix: %s\n", debug, filename,
249        prefix);
250
251   for (index = optind; index < argc; index++)
252     DBG ("Non-option argument %s\n", argv[index]);
253
254   index = optind;
255
256   if (argc > index + 2)
257     {
258       fprintf (stderr, "%s: Too many arguments\n", argv[0]);
259       exit (-1);
260     }
261
262   /* Load plugins */
263   function_by_name = hash_create_string (0, sizeof (uword));
264   int res = register_function();
265   if (res < 0) {
266     fprintf(stderr, "%s: loading plugins failed\n", argv[0]);
267     exit(-1);
268   }
269
270   if (template)
271     {
272       print_template (argv[index]);
273       exit (0);
274     }
275
276   if (dump_api)
277     {
278       dump_apis ();
279       exit (0);
280     }
281
282   /* Read message arguments from command line */
283   if (argc >= (index + 1))
284     {
285       msgname = argv[index];
286     }
287   if (argc == (index + 2)) {
288     o = cJSON_Parse(argv[index+1]);
289     if (!o) {
290       fprintf(stderr, "%s: Failed parsing JSON input: %s\n", argv[0], cJSON_GetErrorPtr());
291       exit(-1);
292     }
293   }
294
295   /* Read message from file */
296   if (filename) {
297       if (argc > index)
298         {
299           fprintf (stderr, "%s: Superfluous arguments when filename given\n",
300                    argv[0]);
301           exit (-1);
302         }
303
304     FILE *f = fopen(filename, "r");
305     size_t chunksize, bufsize;
306     size_t n_read = 0;
307     size_t n;
308
309     if (!f) {
310       fprintf(stderr, "%s: can't open file: %s\n", argv[0], filename);
311       exit(-1);
312     }
313     chunksize = bufsize = 1024;
314     char *buf = malloc(bufsize);
315     while ((n = fread (buf + n_read, 1, chunksize, f)))
316       {
317         n_read += n;
318         if (n == chunksize)
319           {
320             bufsize += chunksize;
321             buf = realloc (buf, bufsize);
322           }
323       }
324     fclose(f);
325     if (n_read) {
326       o = cJSON_Parse(buf);
327       free(buf);
328       if (!o) {
329         fprintf(stderr, "%s: Failed parsing JSON input: %s\n", argv[0], cJSON_GetErrorPtr());
330         exit(-1);
331       }
332     }
333   }
334
335   if (!msgname && !filename)
336     {
337       print_help ();
338       exit (-1);
339     }
340
341   if (vac_connect ("vat2", prefix, 0, 1024))
342     {
343       fprintf (stderr, "Failed connecting to VPP\n");
344       exit (-1);
345     }
346
347   if (msgname)
348     {
349       vat2_exec_command_by_name (msgname, o);
350     }
351   else
352     {
353       if (cJSON_IsArray (o))
354         {
355           size_t size = cJSON_GetArraySize (o);
356           for (int i = 0; i < size; i++)
357             vat2_exec_command (cJSON_GetArrayItem (o, i));
358         }
359     }
360   cJSON_Delete (o);
361   vac_disconnect();
362   exit (0);
363
364 }