session: fix session cli maybe parse wrong args if executed in files
[vpp.git] / src / vlib / cli.c
1 /*
2  * Copyright (c) 2015 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  * cli.c: command line interface
17  *
18  * Copyright (c) 2008 Eliot Dresselhaus
19  *
20  * Permission is hereby granted, free of charge, to any person obtaining
21  * a copy of this software and associated documentation files (the
22  * "Software"), to deal in the Software without restriction, including
23  * without limitation the rights to use, copy, modify, merge, publish,
24  * distribute, sublicense, and/or sell copies of the Software, and to
25  * permit persons to whom the Software is furnished to do so, subject to
26  * the following conditions:
27  *
28  * The above copyright notice and this permission notice shall be
29  * included in all copies or substantial portions of the Software.
30  *
31  *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
32  *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
33  *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
34  *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
35  *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
36  *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
37  *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38  */
39
40 #include <vlib/vlib.h>
41 #include <vlib/stats/stats.h>
42 #include <vlib/unix/unix.h>
43 #include <vppinfra/callback.h>
44 #include <vppinfra/cpu.h>
45 #include <vppinfra/elog.h>
46 #include <unistd.h>
47 #include <ctype.h>
48
49 /** \file src/vlib/cli.c Debug CLI Implementation
50  */
51
52 int vl_api_set_elog_trace_api_messages (int enable);
53 int vl_api_get_elog_trace_api_messages (void);
54
55 static void *current_traced_heap;
56
57 /* Root of all show commands. */
58 /* *INDENT-OFF* */
59 VLIB_CLI_COMMAND (vlib_cli_show_command, static) = {
60   .path = "show",
61   .short_help = "Show commands",
62 };
63 /* *INDENT-ON* */
64
65 /* Root of all clear commands. */
66 /* *INDENT-OFF* */
67 VLIB_CLI_COMMAND (vlib_cli_clear_command, static) = {
68   .path = "clear",
69   .short_help = "Clear commands",
70 };
71 /* *INDENT-ON* */
72
73 /* Root of all set commands. */
74 /* *INDENT-OFF* */
75 VLIB_CLI_COMMAND (vlib_cli_set_command, static) = {
76   .path = "set",
77   .short_help = "Set commands",
78 };
79 /* *INDENT-ON* */
80
81 /* Root of all test commands. */
82 /* *INDENT-OFF* */
83 VLIB_CLI_COMMAND (vlib_cli_test_command, static) = {
84   .path = "test",
85   .short_help = "Test commands",
86 };
87 /* *INDENT-ON* */
88
89 /* Returns bitmap of commands which match key. */
90 static uword *
91 vlib_cli_sub_command_match (vlib_cli_command_t * c, unformat_input_t * input)
92 {
93   int i, n;
94   uword *match = 0;
95   vlib_cli_parse_position_t *p;
96
97   unformat_skip_white_space (input);
98
99   for (i = 0;; i++)
100     {
101       uword k;
102
103       k = unformat_get_input (input);
104       switch (k)
105         {
106         case 'a' ... 'z':
107         case 'A' ... 'Z':
108         case '0' ... '9':
109         case '-':
110         case '_':
111           break;
112
113         case ' ':
114         case '\t':
115         case '\r':
116         case '\n':
117         case UNFORMAT_END_OF_INPUT:
118           /* White space or end of input removes any non-white
119              matches that were before possible. */
120           if (i < vec_len (c->sub_command_positions)
121               && clib_bitmap_count_set_bits (match) > 1)
122             {
123               p = vec_elt_at_index (c->sub_command_positions, i);
124               for (n = 0; n < vec_len (p->bitmaps); n++)
125                 match = clib_bitmap_andnot (match, p->bitmaps[n]);
126             }
127           goto done;
128
129         default:
130           unformat_put_input (input);
131           goto done;
132         }
133
134       if (i >= vec_len (c->sub_command_positions))
135         {
136         no_match:
137           clib_bitmap_free (match);
138           return 0;
139         }
140
141       p = vec_elt_at_index (c->sub_command_positions, i);
142       if (vec_len (p->bitmaps) == 0)
143         goto no_match;
144
145       n = k - p->min_char;
146       if (n < 0 || n >= vec_len (p->bitmaps))
147         goto no_match;
148
149       if (i == 0)
150         match = clib_bitmap_dup (p->bitmaps[n]);
151       else
152         match = clib_bitmap_and (match, p->bitmaps[n]);
153
154       if (clib_bitmap_is_zero (match))
155         goto no_match;
156     }
157
158 done:
159   return match;
160 }
161
162 /* Get current command args */
163 uword
164 unformat_vlib_cli_args (unformat_input_t *i, va_list *va)
165 {
166   unformat_input_t *result = va_arg (*va, unformat_input_t *);
167   u8 *line;
168   uword last_c;
169   u32 index = i->index;
170
171   if (unformat_is_eof (i))
172     {
173       unformat_init (result, 0, 0);
174       return 0;
175     }
176
177   /* try to find last non-space character */
178   do
179     {
180       ASSERT (index > 0);
181       last_c = i->buffer[--index];
182     }
183   while (last_c == ' ');
184
185   if (last_c == '\t' || last_c == '\n' || last_c == '\r' || last_c == '\f' ||
186       last_c == '}')
187     {
188       /* current command has no args */
189       unformat_init (result, 0, 0);
190       return 0;
191     }
192
193   if (!unformat_user (i, unformat_line, &line))
194     {
195       unformat_init (result, 0, 0);
196       return 0;
197     }
198   unformat_init_vector (result, line);
199   return 1;
200 }
201
202 /* Looks for string based sub-input formatted { SUB-INPUT }. */
203 uword
204 unformat_vlib_cli_sub_input (unformat_input_t * i, va_list * args)
205 {
206   unformat_input_t *sub_input = va_arg (*args, unformat_input_t *);
207   u8 *s;
208   uword c;
209
210   while (1)
211     {
212       c = unformat_get_input (i);
213       switch (c)
214         {
215         case ' ':
216         case '\t':
217         case '\n':
218         case '\r':
219         case '\f':
220           break;
221
222         case '{':
223         default:
224           /* Put back paren. */
225           if (c != UNFORMAT_END_OF_INPUT)
226             unformat_put_input (i);
227
228           if (c == '{' && unformat (i, "%v", &s))
229             {
230               unformat_init_vector (sub_input, s);
231               return 1;
232             }
233           return 0;
234         }
235     }
236   return 0;
237 }
238
239 static vlib_cli_command_t *
240 get_sub_command (vlib_cli_main_t * cm, vlib_cli_command_t * parent, u32 si)
241 {
242   vlib_cli_sub_command_t *s = vec_elt_at_index (parent->sub_commands, si);
243   return vec_elt_at_index (cm->commands, s->index);
244 }
245
246 static uword
247 unformat_vlib_cli_sub_command (unformat_input_t * i, va_list * args)
248 {
249   vlib_main_t __clib_unused *vm = va_arg (*args, vlib_main_t *);
250   vlib_global_main_t *vgm = vlib_get_global_main ();
251   vlib_cli_command_t *c = va_arg (*args, vlib_cli_command_t *);
252   vlib_cli_command_t **result = va_arg (*args, vlib_cli_command_t **);
253   vlib_cli_main_t *cm = &vgm->cli_main;
254   uword *match_bitmap, is_unique, index;
255
256   match_bitmap = vlib_cli_sub_command_match (c, i);
257   is_unique = clib_bitmap_count_set_bits (match_bitmap) == 1;
258   index = ~0;
259   if (is_unique)
260     {
261       index = clib_bitmap_first_set (match_bitmap);
262       *result = get_sub_command (cm, c, index);
263     }
264   clib_bitmap_free (match_bitmap);
265
266   return is_unique;
267 }
268
269 static int
270 vlib_cli_cmp_strings (void *a1, void *a2)
271 {
272   u8 *c1 = *(u8 **) a1;
273   u8 *c2 = *(u8 **) a2;
274
275   return vec_cmp (c1, c2);
276 }
277
278 u8 **
279 vlib_cli_get_possible_completions (u8 * str)
280 {
281   vlib_cli_command_t *c;
282   vlib_cli_sub_command_t *sc;
283   vlib_global_main_t *vgm = vlib_get_global_main ();
284   vlib_cli_main_t *vcm = &vgm->cli_main;
285   uword *match_bitmap = 0;
286   uword index, is_unique, help_next_level;
287   u8 **result = 0;
288   unformat_input_t input;
289   unformat_init_vector (&input, vec_dup (str));
290   c = vec_elt_at_index (vcm->commands, 0);
291
292   /* remove trailing whitespace, except for one of them */
293   while (vec_len (input.buffer) >= 2 &&
294          isspace (input.buffer[vec_len (input.buffer) - 1]) &&
295          isspace (input.buffer[vec_len (input.buffer) - 2]))
296     {
297       vec_del1 (input.buffer, vec_len (input.buffer) - 1);
298     }
299
300   /* if input is empty, directly return list of root commands */
301   if (vec_len (input.buffer) == 0 ||
302       (vec_len (input.buffer) == 1 && isspace (input.buffer[0])))
303     {
304       vec_foreach (sc, c->sub_commands)
305       {
306         vec_add1 (result, (u8 *) sc->name);
307       }
308       goto done;
309     }
310
311   /* add a trailing '?' so that vlib_cli_sub_command_match can find
312    * all commands starting with the input string */
313   vec_add1 (input.buffer, '?');
314
315   while (1)
316     {
317       match_bitmap = vlib_cli_sub_command_match (c, &input);
318       /* no match: return no result */
319       if (match_bitmap == 0)
320         {
321           goto done;
322         }
323       is_unique = clib_bitmap_count_set_bits (match_bitmap) == 1;
324       /* unique match: try to step one subcommand level further */
325       if (is_unique)
326         {
327           /* stop if no more input */
328           if (input.index >= vec_len (input.buffer) - 1)
329             {
330               break;
331             }
332
333           index = clib_bitmap_first_set (match_bitmap);
334           c = get_sub_command (vcm, c, index);
335           clib_bitmap_free (match_bitmap);
336           continue;
337         }
338       /* multiple matches: stop here, return all matches */
339       break;
340     }
341
342   /* remove trailing '?' */
343   vec_del1 (input.buffer, vec_len (input.buffer) - 1);
344
345   /* if we have a space at the end of input, and a unique match,
346    * autocomplete the next level of subcommands */
347   help_next_level = (vec_len (str) == 0) || isspace (str[vec_len (str) - 1]);
348   /* *INDENT-OFF* */
349   clib_bitmap_foreach (index, match_bitmap) {
350     if (help_next_level && is_unique) {
351         c = get_sub_command (vcm, c, index);
352         vec_foreach (sc, c->sub_commands) {
353           vec_add1 (result, (u8*) sc->name);
354         }
355         goto done; /* break doesn't work in this macro-loop */
356     }
357     sc = &c->sub_commands[index];
358     vec_add1(result, (u8*) sc->name);
359   }
360   /* *INDENT-ON* */
361
362 done:
363   clib_bitmap_free (match_bitmap);
364   unformat_free (&input);
365
366   if (result)
367     vec_sort_with_function (result, vlib_cli_cmp_strings);
368   return result;
369 }
370
371 static u8 *
372 format_vlib_cli_command_help (u8 * s, va_list * args)
373 {
374   vlib_cli_command_t *c = va_arg (*args, vlib_cli_command_t *);
375   int is_long = va_arg (*args, int);
376   if (is_long && c->long_help)
377     s = format (s, "%s", c->long_help);
378   else if (c->short_help)
379     s = format (s, "%s", c->short_help);
380   else
381     s = format (s, "%v commands", c->path);
382   return s;
383 }
384
385 static u8 *
386 format_vlib_cli_path (u8 * s, va_list * args)
387 {
388   u8 *path = va_arg (*args, u8 *);
389
390   s = format (s, "%v", path);
391
392   return s;
393 }
394
395 static vlib_cli_command_t *
396 all_subs (vlib_cli_main_t * cm, vlib_cli_command_t * subs, u32 command_index)
397 {
398   vlib_cli_command_t *c = vec_elt_at_index (cm->commands, command_index);
399   vlib_cli_sub_command_t *sc;
400
401   if (c->function)
402     vec_add1 (subs, c[0]);
403
404   vec_foreach (sc, c->sub_commands) subs = all_subs (cm, subs, sc->index);
405
406   return subs;
407 }
408
409 static int
410 vlib_cli_cmp_rule (void *a1, void *a2)
411 {
412   vlib_cli_sub_rule_t *r1 = a1;
413   vlib_cli_sub_rule_t *r2 = a2;
414
415   return vec_cmp (r1->name, r2->name);
416 }
417
418 static int
419 vlib_cli_cmp_command (void *a1, void *a2)
420 {
421   vlib_cli_command_t *c1 = a1;
422   vlib_cli_command_t *c2 = a2;
423
424   return vec_cmp (c1->path, c2->path);
425 }
426
427 static clib_error_t *
428 vlib_cli_dispatch_sub_commands (vlib_main_t * vm,
429                                 vlib_cli_main_t * cm,
430                                 unformat_input_t * input,
431                                 uword parent_command_index)
432 {
433   vlib_global_main_t *vgm = vlib_get_global_main ();
434   vlib_cli_command_t *parent, *c;
435   clib_error_t *error = 0;
436   unformat_input_t sub_input;
437   u8 *string;
438   uword is_main_dispatch = cm == &vgm->cli_main;
439
440   parent = vec_elt_at_index (cm->commands, parent_command_index);
441   if (is_main_dispatch && unformat (input, "help"))
442     {
443       uword help_at_end_of_line, i;
444
445       help_at_end_of_line =
446         unformat_check_input (input) == UNFORMAT_END_OF_INPUT;
447       while (1)
448         {
449           c = parent;
450           if (unformat_user
451               (input, unformat_vlib_cli_sub_command, vm, c, &parent))
452             ;
453
454           else if (!(unformat_check_input (input) == UNFORMAT_END_OF_INPUT))
455             goto unknown;
456
457           else
458             break;
459         }
460
461       /* help SUB-COMMAND => long format help.
462          "help" at end of line: show all commands. */
463       if (!help_at_end_of_line)
464         vlib_cli_output (vm, "%U", format_vlib_cli_command_help, c,
465                          /* is_long */ 1);
466
467       else if (vec_len (c->sub_commands) == 0)
468         vlib_cli_output (vm, "%v: no sub-commands", c->path);
469
470       else
471         {
472           vlib_cli_sub_rule_t *sr, *subs = 0;
473           vlib_cli_sub_command_t *sc;
474
475           vec_foreach (sc, c->sub_commands)
476           {
477             vec_add2 (subs, sr, 1);
478             sr->name = sc->name;
479             sr->command_index = sc->index;
480             sr->rule_index = ~0;
481           }
482
483           vec_sort_with_function (subs, vlib_cli_cmp_rule);
484
485           for (i = 0; i < vec_len (subs); i++)
486             {
487               vlib_cli_command_t *d;
488
489               d = vec_elt_at_index (cm->commands, subs[i].command_index);
490               vlib_cli_output
491                 (vm, "  %-30v %U", subs[i].name,
492                  format_vlib_cli_command_help, d, /* is_long */ 0);
493             }
494
495           vec_free (subs);
496         }
497     }
498
499   else if (is_main_dispatch
500            && (unformat (input, "choices") || unformat (input, "?")))
501     {
502       vlib_cli_command_t *sub, *subs;
503
504       subs = all_subs (cm, 0, parent_command_index);
505       vec_sort_with_function (subs, vlib_cli_cmp_command);
506       vec_foreach (sub, subs)
507         vlib_cli_output (vm, "  %-40U %U",
508                          format_vlib_cli_path, sub->path,
509                          format_vlib_cli_command_help, sub, /* is_long */ 0);
510       vec_free (subs);
511     }
512
513   else if (unformat (input, "comment %v", &string))
514     {
515       vec_free (string);
516     }
517
518   else if (unformat (input, "vpplog %v", &string))
519     {
520       int i;
521       /*
522        * Delete leading whitespace, so "vpplog { this and that }"
523        * and "vpplog this" line up nicely.
524        */
525       for (i = 0; i < vec_len (string); i++)
526         if (string[i] != ' ')
527           break;
528       if (i > 0)
529         vec_delete (string, i, 0);
530
531       vlib_log_notice (cm->log, "CLI: %v", string);
532       vec_free (string);
533     }
534
535   else if (unformat (input, "uncomment %U",
536                      unformat_vlib_cli_sub_input, &sub_input))
537     {
538       error =
539         vlib_cli_dispatch_sub_commands (vm, cm, &sub_input,
540                                         parent_command_index);
541       unformat_free (&sub_input);
542     }
543   else if (unformat (input, "leak-check %U",
544                      unformat_vlib_cli_sub_input, &sub_input))
545     {
546       u8 *leak_report;
547       if (current_traced_heap)
548         {
549           void *oldheap;
550           oldheap = clib_mem_set_heap (current_traced_heap);
551           clib_mem_trace (0);
552           clib_mem_set_heap (oldheap);
553           current_traced_heap = 0;
554         }
555       clib_mem_trace (1);
556       error =
557         vlib_cli_dispatch_sub_commands (vm, cm, &sub_input,
558                                         parent_command_index);
559       unformat_free (&sub_input);
560
561       /* Otherwise, the clib_error_t shows up as a leak... */
562       if (error)
563         {
564           vlib_cli_output (vm, "%v", error->what);
565           clib_error_free (error);
566           error = 0;
567         }
568
569       (void) clib_mem_trace_enable_disable (0);
570       leak_report = format (0, "%U", format_clib_mem_heap, 0,
571                             1 /* verbose, i.e. print leaks */ );
572       clib_mem_trace (0);
573       vlib_cli_output (vm, "%v", leak_report);
574       vec_free (leak_report);
575     }
576
577   else
578     if (unformat_user (input, unformat_vlib_cli_sub_command, vm, parent, &c))
579     {
580       unformat_input_t *si;
581       uword has_sub_commands =
582         vec_len (c->sub_commands) + vec_len (c->sub_rules) > 0;
583
584       si = input;
585       if (unformat_user (input, unformat_vlib_cli_sub_input, &sub_input))
586         si = &sub_input;
587
588       if (has_sub_commands)
589         error = vlib_cli_dispatch_sub_commands (vm, cm, si, c - cm->commands);
590
591       if (has_sub_commands && !error)
592         /* Found valid sub-command. */ ;
593
594       else if (c->function)
595         {
596           clib_error_t *c_error;
597
598           /* Skip white space for benefit of called function. */
599           unformat_skip_white_space (si);
600
601           if (unformat (si, "?"))
602             {
603               vlib_cli_output (vm, "  %-40U %U", format_vlib_cli_path, c->path, format_vlib_cli_command_help, c,        /* is_long */
604                                0);
605             }
606           else
607             {
608               if (PREDICT_FALSE (vm->elog_trace_cli_commands))
609                 {
610                   /* *INDENT-OFF* */
611                   ELOG_TYPE_DECLARE (e) =
612                     {
613                       .format = "cli-cmd: %s",
614                       .format_args = "T4",
615                     };
616                   /* *INDENT-ON* */
617                   struct
618                   {
619                     u32 c;
620                   } *ed;
621                   ed = ELOG_DATA (vlib_get_elog_main (), e);
622                   ed->c = elog_string (vlib_get_elog_main (), "%v", c->path);
623                 }
624
625               if (!c->is_mp_safe)
626                 vlib_worker_thread_barrier_sync (vm);
627               if (PREDICT_FALSE (vec_len (cm->perf_counter_cbs) != 0))
628                 clib_call_callbacks (cm->perf_counter_cbs, cm,
629                                      c - cm->commands, 0 /* before */ );
630
631               c->hit_counter++;
632               c_error = c->function (vm, si, c);
633
634               if (PREDICT_FALSE (vec_len (cm->perf_counter_cbs) != 0))
635                 clib_call_callbacks (cm->perf_counter_cbs, cm,
636                                      c - cm->commands, 1 /* after */ );
637               if (!c->is_mp_safe)
638                 vlib_worker_thread_barrier_release (vm);
639
640               if (PREDICT_FALSE (vm->elog_trace_cli_commands))
641                 {
642                   /* *INDENT-OFF* */
643                   ELOG_TYPE_DECLARE (e) =
644                     {
645                       .format = "cli-cmd: %s %s",
646                       .format_args = "T4T4",
647                     };
648                   /* *INDENT-ON* */
649                   struct
650                   {
651                     u32 c, err;
652                   } *ed;
653                   ed = ELOG_DATA (vlib_get_elog_main (), e);
654                   ed->c = elog_string (vlib_get_elog_main (), "%v", c->path);
655                   if (c_error)
656                     {
657                       vec_add1 (c_error->what, 0);
658                       ed->err = elog_string (vlib_get_elog_main (),
659                                              (char *) c_error->what);
660                       vec_dec_len (c_error->what, 1);
661                     }
662                   else
663                     ed->err = elog_string (vlib_get_elog_main (), "OK");
664                 }
665
666               if (c_error)
667                 {
668                   error =
669                     clib_error_return (0, "%v: %v", c->path, c_error->what);
670                   clib_error_free (c_error);
671                   /* Free sub input. */
672                   if (si != input)
673                     unformat_free (si);
674
675                   return error;
676                 }
677             }
678
679           /* Free any previous error. */
680           clib_error_free (error);
681         }
682
683       else if (!error)
684         error = clib_error_return (0, "%v: no sub-commands", c->path);
685
686       /* Free sub input. */
687       if (si != input)
688         unformat_free (si);
689     }
690
691   else
692     goto unknown;
693
694   return error;
695
696 unknown:
697   if (parent->path)
698     return clib_error_return (0, "%v: unknown input `%U'", parent->path,
699                               format_unformat_error, input);
700   else
701     return clib_error_return (0, "unknown input `%U'", format_unformat_error,
702                               input);
703 }
704
705
706 void vlib_unix_error_report (vlib_main_t *, clib_error_t *)
707   __attribute__ ((weak));
708
709 void
710 vlib_unix_error_report (vlib_main_t * vm, clib_error_t * error)
711 {
712 }
713
714 /* Process CLI input. */
715 int
716 vlib_cli_input (vlib_main_t * vm,
717                 unformat_input_t * input,
718                 vlib_cli_output_function_t * function, uword function_arg)
719 {
720   vlib_global_main_t *vgm = vlib_get_global_main ();
721   vlib_process_t *cp = vlib_get_current_process (vm);
722   clib_error_t *error;
723   vlib_cli_output_function_t *save_function;
724   uword save_function_arg;
725   int rv = 0;
726
727   save_function = cp->output_function;
728   save_function_arg = cp->output_function_arg;
729
730   cp->output_function = function;
731   cp->output_function_arg = function_arg;
732
733   do
734     {
735       error = vlib_cli_dispatch_sub_commands (vm, &vgm->cli_main, input,
736                                               /* parent */ 0);
737     }
738   while (!error && !unformat (input, "%U", unformat_eof));
739
740   if (error)
741     {
742       vlib_cli_output (vm, "%v", error->what);
743       vlib_unix_error_report (vm, error);
744       /* clib_error_return is unfortunately often called with a '0'
745          return code */
746       rv = error->code != 0 ? error->code : -1;
747       clib_error_free (error);
748     }
749
750   cp->output_function = save_function;
751   cp->output_function_arg = save_function_arg;
752   return rv;
753 }
754
755 /* Output to current CLI connection. */
756 void
757 vlib_cli_output (vlib_main_t * vm, char *fmt, ...)
758 {
759   vlib_process_t *cp = vlib_get_current_process (vm);
760   va_list va;
761   u8 *s;
762
763   va_start (va, fmt);
764   s = va_format (0, fmt, &va);
765   va_end (va);
766
767   /* some format functions might return 0
768    * e.g. show int addr */
769   if (NULL == s)
770     return;
771
772   /* Terminate with \n if not present. */
773   if (vec_len (s) > 0 && s[vec_len (s) - 1] != '\n')
774     vec_add1 (s, '\n');
775
776   if ((!cp) || (!cp->output_function))
777     fformat (stdout, "%v", s);
778   else
779     cp->output_function (cp->output_function_arg, s, vec_len (s));
780
781   vec_free (s);
782 }
783
784 void *vl_msg_push_heap (void) __attribute__ ((weak));
785 void *
786 vl_msg_push_heap (void)
787 {
788   return 0;
789 }
790
791 void vl_msg_pop_heap (void *oldheap) __attribute__ ((weak));
792 void
793 vl_msg_pop_heap (void *oldheap)
794 {
795 }
796
797 static clib_error_t *
798 show_memory_usage (vlib_main_t * vm,
799                    unformat_input_t * input, vlib_cli_command_t * cmd)
800 {
801   clib_mem_main_t *mm = &clib_mem_main;
802   int verbose __attribute__ ((unused)) = 0;
803   int api_segment = 0, stats_segment = 0, main_heap = 0, numa_heaps = 0;
804   int map = 0;
805   clib_error_t *error;
806   u32 index = 0;
807   int i;
808   uword clib_mem_trace_enable_disable (uword enable);
809   uword was_enabled;
810
811
812   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
813     {
814       if (unformat (input, "verbose"))
815         verbose = 1;
816       else if (unformat (input, "api-segment"))
817         api_segment = 1;
818       else if (unformat (input, "stats-segment"))
819         stats_segment = 1;
820       else if (unformat (input, "main-heap"))
821         main_heap = 1;
822       else if (unformat (input, "numa-heaps"))
823         numa_heaps = 1;
824       else if (unformat (input, "map"))
825         map = 1;
826       else
827         {
828           error = clib_error_return (0, "unknown input `%U'",
829                                      format_unformat_error, input);
830           return error;
831         }
832     }
833
834   if ((api_segment + stats_segment + main_heap + numa_heaps + map) == 0)
835     return clib_error_return
836       (0, "Need one of api-segment, stats-segment, main-heap, numa-heaps "
837        "or map");
838
839   if (api_segment)
840     {
841       void *oldheap = vl_msg_push_heap ();
842       was_enabled = clib_mem_trace_enable_disable (0);
843       u8 *s_in_svm = format (0, "%U\n", format_clib_mem_heap, 0, 1);
844       vl_msg_pop_heap (oldheap);
845       u8 *s = vec_dup (s_in_svm);
846
847       oldheap = vl_msg_push_heap ();
848       vec_free (s_in_svm);
849       clib_mem_trace_enable_disable (was_enabled);
850       vl_msg_pop_heap (oldheap);
851       vlib_cli_output (vm, "API segment");
852       vlib_cli_output (vm, "%v", s);
853       vec_free (s);
854     }
855   if (stats_segment)
856     {
857       void *oldheap = vlib_stats_set_heap (0);
858       was_enabled = clib_mem_trace_enable_disable (0);
859       u8 *s_in_svm = format (0, "%U\n", format_clib_mem_heap, 0, 1);
860       if (oldheap)
861         clib_mem_set_heap (oldheap);
862       u8 *s = vec_dup (s_in_svm);
863
864       oldheap = vlib_stats_set_heap (0);
865       vec_free (s_in_svm);
866       if (oldheap)
867         {
868           clib_mem_trace_enable_disable (was_enabled);
869           clib_mem_set_heap (oldheap);
870         }
871       vlib_cli_output (vm, "Stats segment");
872       vlib_cli_output (vm, "%v", s);
873       vec_free (s);
874     }
875
876
877   {
878     if (main_heap)
879       {
880         /*
881          * Note: the foreach_vlib_main causes allocator traffic,
882          * so shut off tracing before we go there...
883          */
884         was_enabled = clib_mem_trace_enable_disable (0);
885
886         foreach_vlib_main ()
887           {
888             vlib_cli_output (vm, "%sThread %d %s\n", index ? "\n" : "", index,
889                              vlib_worker_threads[index].name);
890             vlib_cli_output (vm, "  %U\n", format_clib_mem_heap,
891                              mm->per_cpu_mheaps[index], verbose);
892             index++;
893           }
894
895         /* Restore the trace flag */
896         clib_mem_trace_enable_disable (was_enabled);
897       }
898     if (numa_heaps)
899       {
900         for (i = 0; i < ARRAY_LEN (mm->per_numa_mheaps); i++)
901           {
902             if (mm->per_numa_mheaps[i] == 0)
903               continue;
904             if (mm->per_numa_mheaps[i] == mm->per_cpu_mheaps[i])
905               {
906                 vlib_cli_output (vm, "Numa %d uses the main heap...", i);
907                 continue;
908               }
909             was_enabled = clib_mem_trace_enable_disable (0);
910
911             vlib_cli_output (vm, "Numa %d:", i);
912             vlib_cli_output (vm, "  %U\n", format_clib_mem_heap,
913                              mm->per_numa_mheaps[index], verbose);
914           }
915       }
916     if (map)
917       {
918         clib_mem_page_stats_t stats = { };
919         clib_mem_vm_map_hdr_t *hdr = 0;
920         u8 *s = 0;
921         int numa = -1;
922
923         s = format (s, "\n%-16s%7s%5s%7s%7s",
924                     "StartAddr", "size", "FD", "PageSz", "Pages");
925         while ((numa = vlib_mem_get_next_numa_node (numa)) != -1)
926           s = format (s, " Numa%u", numa);
927         s = format (s, " NotMap");
928         s = format (s, " Name");
929         vlib_cli_output (vm, "%v", s);
930         vec_reset_length (s);
931
932         while ((hdr = clib_mem_vm_get_next_map_hdr (hdr)))
933           {
934             clib_mem_get_page_stats ((void *) hdr->base_addr,
935                                      hdr->log2_page_sz, hdr->num_pages,
936                                      &stats);
937             s = format (s, "%016lx%7U",
938                         hdr->base_addr, format_memory_size,
939                         hdr->num_pages << hdr->log2_page_sz);
940
941             if (hdr->fd != -1)
942               s = format (s, "%5d", hdr->fd);
943             else
944               s = format (s, "%5s", " ");
945
946             s = format (s, "%7U%7lu",
947                         format_log2_page_size, hdr->log2_page_sz,
948                         hdr->num_pages);
949             while ((numa = vlib_mem_get_next_numa_node (numa)) != -1)
950               s = format (s, "%6lu", stats.per_numa[numa]);
951             s = format (s, "%7lu", stats.not_mapped);
952             s = format (s, " %s", hdr->name);
953             vlib_cli_output (vm, "%v", s);
954             vec_reset_length (s);
955           }
956         vec_free (s);
957       }
958   }
959   return 0;
960 }
961
962 /* *INDENT-OFF* */
963 VLIB_CLI_COMMAND (show_memory_usage_command, static) = {
964   .path = "show memory",
965   .short_help = "show memory [api-segment][stats-segment][verbose]\n"
966   "            [numa-heaps][map]",
967   .function = show_memory_usage,
968 };
969 /* *INDENT-ON* */
970
971 static clib_error_t *
972 show_cpu (vlib_main_t * vm, unformat_input_t * input,
973           vlib_cli_command_t * cmd)
974 {
975 #define _(a,b,c) vlib_cli_output (vm, "%-25s " b, a ":", c);
976   _("Model name", "%U", format_cpu_model_name);
977   _("Microarch model (family)", "%U", format_cpu_uarch);
978   _("Flags", "%U", format_cpu_flags);
979   _("Base frequency", "%.2f GHz",
980     ((f64) vm->clib_time.clocks_per_second) * 1e-9);
981 #undef _
982   return 0;
983 }
984
985 /*?
986  * Displays various information about the CPU.
987  *
988  * @cliexpar
989  * @cliexstart{show cpu}
990  * Model name:               Intel(R) Xeon(R) CPU E5-2667 v4 @ 3.20GHz
991  * Microarchitecture:        Broadwell (Broadwell-EP/EX)
992  * Flags:                    sse3 ssse3 sse41 sse42 avx avx2 aes
993  * Base Frequency:           3.20 GHz
994  * @cliexend
995 ?*/
996 /* *INDENT-OFF* */
997 VLIB_CLI_COMMAND (show_cpu_command, static) = {
998   .path = "show cpu",
999   .short_help = "Show cpu information",
1000   .function = show_cpu,
1001 };
1002 /* *INDENT-ON* */
1003
1004 static clib_error_t *
1005 enable_disable_memory_trace (vlib_main_t * vm,
1006                              unformat_input_t * input,
1007                              vlib_cli_command_t * cmd)
1008 {
1009   clib_mem_main_t *mm = &clib_mem_main;
1010   unformat_input_t _line_input, *line_input = &_line_input;
1011   int enable = 1;
1012   int api_segment = 0;
1013   int stats_segment = 0;
1014   int main_heap = 0;
1015   u32 numa_id = ~0;
1016   void *oldheap;
1017
1018   if (!unformat_user (input, unformat_line_input, line_input))
1019     return 0;
1020
1021   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1022     {
1023       if (unformat (line_input, "%U", unformat_vlib_enable_disable, &enable))
1024         ;
1025       else if (unformat (line_input, "api-segment"))
1026         api_segment = 1;
1027       else if (unformat (line_input, "stats-segment"))
1028         stats_segment = 1;
1029       else if (unformat (line_input, "main-heap"))
1030         main_heap = 1;
1031       else if (unformat (line_input, "numa-heap %d", &numa_id))
1032         ;
1033       else
1034         {
1035           unformat_free (line_input);
1036           return clib_error_return (0, "invalid input");
1037         }
1038     }
1039   unformat_free (line_input);
1040
1041   if ((api_segment + stats_segment + main_heap + (enable == 0)
1042        + (numa_id != ~0)) == 0)
1043     {
1044       return clib_error_return
1045         (0, "Need one of main-heap, stats-segment, api-segment,\n"
1046          "numa-heap <nn> or disable");
1047     }
1048
1049   /* Turn off current trace, if any */
1050   if (current_traced_heap)
1051     {
1052       void *oldheap;
1053       oldheap = clib_mem_set_heap (current_traced_heap);
1054       clib_mem_trace (0);
1055       clib_mem_set_heap (oldheap);
1056       current_traced_heap = 0;
1057     }
1058
1059   if (enable == 0)
1060     return 0;
1061
1062   /* API segment */
1063   if (api_segment)
1064     {
1065       oldheap = vl_msg_push_heap ();
1066       current_traced_heap = clib_mem_get_heap ();
1067       clib_mem_trace (1);
1068       vl_msg_pop_heap (oldheap);
1069
1070     }
1071
1072   /* Stats segment */
1073   if (stats_segment)
1074     {
1075       oldheap = vlib_stats_set_heap ();
1076       current_traced_heap = clib_mem_get_heap ();
1077       clib_mem_trace (stats_segment);
1078       /* We don't want to call vlib_stats_pop_heap... */
1079       if (oldheap)
1080         clib_mem_set_heap (oldheap);
1081     }
1082
1083   /* main_heap */
1084   if (main_heap)
1085     {
1086       current_traced_heap = clib_mem_get_heap ();
1087       clib_mem_trace (main_heap);
1088     }
1089
1090   if (numa_id != ~0)
1091     {
1092       if (numa_id >= ARRAY_LEN (mm->per_numa_mheaps))
1093         return clib_error_return (0, "Numa %d out of range", numa_id);
1094       if (mm->per_numa_mheaps[numa_id] == 0)
1095         return clib_error_return (0, "Numa %d heap not active", numa_id);
1096
1097       if (mm->per_numa_mheaps[numa_id] == clib_mem_get_heap ())
1098         return clib_error_return (0, "Numa %d uses the main heap...",
1099                                   numa_id);
1100       current_traced_heap = mm->per_numa_mheaps[numa_id];
1101       oldheap = clib_mem_set_heap (current_traced_heap);
1102       clib_mem_trace (1);
1103       clib_mem_set_heap (oldheap);
1104     }
1105
1106
1107   return 0;
1108 }
1109
1110 /* *INDENT-OFF* */
1111 VLIB_CLI_COMMAND (enable_disable_memory_trace_command, static) = {
1112   .path = "memory-trace",
1113   .short_help = "memory-trace on|off [api-segment][stats-segment][main-heap]\n"
1114   "                   [numa-heap <numa-id>]\n",
1115   .function = enable_disable_memory_trace,
1116 };
1117 /* *INDENT-ON* */
1118
1119 static clib_error_t *
1120 restart_cmd_fn (vlib_main_t * vm, unformat_input_t * input,
1121                 vlib_cli_command_t * cmd)
1122 {
1123   vlib_global_main_t *vgm = vlib_get_global_main ();
1124   clib_file_main_t *fm = &file_main;
1125   clib_file_t *f;
1126
1127   /* environ(7) does not indicate a header for this */
1128   extern char **environ;
1129
1130   /* Close all known open files */
1131   /* *INDENT-OFF* */
1132   pool_foreach (f, fm->file_pool)
1133      {
1134       if (f->file_descriptor > 2)
1135         close(f->file_descriptor);
1136     }
1137   /* *INDENT-ON* */
1138
1139   /* Exec ourself */
1140   execve (vgm->name, (char **) vgm->argv, environ);
1141
1142   return 0;
1143 }
1144
1145 /* *INDENT-OFF* */
1146 VLIB_CLI_COMMAND (restart_cmd,static) = {
1147     .path = "restart",
1148     .short_help = "restart process",
1149     .function = restart_cmd_fn,
1150 };
1151 /* *INDENT-ON* */
1152
1153 #ifdef TEST_CODE
1154 /*
1155  * A trivial test harness to verify the per-process output_function
1156  * is working correcty.
1157  */
1158
1159 static clib_error_t *
1160 sleep_ten_seconds (vlib_main_t * vm,
1161                    unformat_input_t * input, vlib_cli_command_t * cmd)
1162 {
1163   u16 i;
1164   u16 my_id = rand ();
1165
1166   vlib_cli_output (vm, "Starting 10 seconds sleep with id %u\n", my_id);
1167
1168   for (i = 0; i < 10; i++)
1169     {
1170       vlib_process_wait_for_event_or_clock (vm, 1.0);
1171       vlib_cli_output (vm, "Iteration number %u, my id: %u\n", i, my_id);
1172     }
1173   vlib_cli_output (vm, "Done with sleep with id %u\n", my_id);
1174   return 0;
1175 }
1176
1177 /* *INDENT-OFF* */
1178 VLIB_CLI_COMMAND (ping_command, static) = {
1179   .path = "test sleep",
1180   .function = sleep_ten_seconds,
1181   .short_help = "Sleep for 10 seconds",
1182 };
1183 /* *INDENT-ON* */
1184 #endif /* ifdef TEST_CODE */
1185
1186 static uword
1187 vlib_cli_normalize_path (char *input, char **result)
1188 {
1189   char *i = input;
1190   char *s = 0;
1191   uword l = 0;
1192   uword index_of_last_space = ~0;
1193
1194   while (*i != 0)
1195     {
1196       u8 c = *i++;
1197       /* Multiple white space -> single space. */
1198       switch (c)
1199         {
1200         case ' ':
1201         case '\t':
1202         case '\n':
1203         case '\r':
1204           if (l > 0 && s[l - 1] != ' ')
1205             {
1206               vec_add1 (s, ' ');
1207               l++;
1208             }
1209           break;
1210
1211         default:
1212           if (l > 0 && s[l - 1] == ' ')
1213             index_of_last_space = vec_len (s);
1214           vec_add1 (s, c);
1215           l++;
1216           break;
1217         }
1218     }
1219
1220   /* Remove any extra space at end. */
1221   if (l > 0 && s[l - 1] == ' ')
1222     vec_dec_len (s, 1);
1223
1224   *result = s;
1225   return index_of_last_space;
1226 }
1227
1228 always_inline uword
1229 parent_path_len (char *path)
1230 {
1231   word i;
1232   for (i = vec_len (path) - 1; i >= 0; i--)
1233     {
1234       if (path[i] == ' ')
1235         return i;
1236     }
1237   return ~0;
1238 }
1239
1240 static void
1241 add_sub_command (vlib_cli_main_t * cm, uword parent_index, uword child_index)
1242 {
1243   vlib_cli_command_t *p, *c;
1244   vlib_cli_sub_command_t *sub_c;
1245   u8 *sub_name;
1246   word i, l;
1247
1248   p = vec_elt_at_index (cm->commands, parent_index);
1249   c = vec_elt_at_index (cm->commands, child_index);
1250
1251   l = parent_path_len (c->path);
1252   if (l == ~0)
1253     sub_name = vec_dup ((u8 *) c->path);
1254   else
1255     {
1256       ASSERT (l + 1 < vec_len (c->path));
1257       sub_name = 0;
1258       vec_add (sub_name, c->path + l + 1, vec_len (c->path) - (l + 1));
1259     }
1260
1261   /* "Can't happen," check mainly to shut up coverity */
1262   ALWAYS_ASSERT (sub_name != 0);
1263
1264   if (sub_name[0] == '%')
1265     {
1266       uword *q;
1267       vlib_cli_sub_rule_t *sr;
1268
1269       /* Remove %. */
1270       vec_delete (sub_name, 1, 0);
1271
1272       if (!p->sub_rule_index_by_name)
1273         p->sub_rule_index_by_name = hash_create_vec ( /* initial length */ 32,
1274                                                      sizeof (sub_name[0]),
1275                                                      sizeof (uword));
1276       q = hash_get_mem (p->sub_rule_index_by_name, sub_name);
1277       if (q)
1278         {
1279           sr = vec_elt_at_index (p->sub_rules, q[0]);
1280           ASSERT (sr->command_index == child_index);
1281           return;
1282         }
1283
1284       hash_set_mem (p->sub_rule_index_by_name, sub_name,
1285                     vec_len (p->sub_rules));
1286       vec_add2 (p->sub_rules, sr, 1);
1287       sr->name = sub_name;
1288       sr->rule_index = sr - p->sub_rules;
1289       sr->command_index = child_index;
1290       return;
1291     }
1292
1293   if (!p->sub_command_index_by_name)
1294     p->sub_command_index_by_name = hash_create_vec ( /* initial length */ 32,
1295                                                     sizeof (c->path[0]),
1296                                                     sizeof (uword));
1297
1298   /* Check if sub-command has already been created. */
1299   if (hash_get_mem (p->sub_command_index_by_name, sub_name))
1300     {
1301       vec_free (sub_name);
1302       return;
1303     }
1304
1305   vec_add2 (p->sub_commands, sub_c, 1);
1306   sub_c->index = child_index;
1307   sub_c->name = sub_name;
1308   hash_set_mem (p->sub_command_index_by_name, sub_c->name,
1309                 sub_c - p->sub_commands);
1310
1311   vec_validate (p->sub_command_positions, vec_len (sub_c->name) - 1);
1312   for (i = 0; i < vec_len (sub_c->name); i++)
1313     {
1314       int n;
1315       vlib_cli_parse_position_t *pos;
1316
1317       pos = vec_elt_at_index (p->sub_command_positions, i);
1318
1319       if (!pos->bitmaps)
1320         pos->min_char = sub_c->name[i];
1321
1322       n = sub_c->name[i] - pos->min_char;
1323       if (n < 0)
1324         {
1325           pos->min_char = sub_c->name[i];
1326           vec_insert (pos->bitmaps, -n, 0);
1327           n = 0;
1328         }
1329
1330       vec_validate (pos->bitmaps, n);
1331       pos->bitmaps[n] =
1332         clib_bitmap_ori (pos->bitmaps[n], sub_c - p->sub_commands);
1333     }
1334 }
1335
1336 static void
1337 vlib_cli_make_parent (vlib_cli_main_t * cm, uword ci)
1338 {
1339   uword p_len, pi, *p;
1340   char *p_path;
1341   vlib_cli_command_t *c, *parent;
1342
1343   /* Root command (index 0) should have already been added. */
1344   ASSERT (vec_len (cm->commands) > 0);
1345
1346   c = vec_elt_at_index (cm->commands, ci);
1347   p_len = parent_path_len (c->path);
1348
1349   /* No space?  Parent is root command. */
1350   if (p_len == ~0)
1351     {
1352       add_sub_command (cm, 0, ci);
1353       return;
1354     }
1355
1356   p_path = 0;
1357   vec_add (p_path, c->path, p_len);
1358
1359   p = hash_get_mem (cm->command_index_by_path, p_path);
1360
1361   /* Parent exists? */
1362   if (!p)
1363     {
1364       /* Parent does not exist; create it. */
1365       vec_add2 (cm->commands, parent, 1);
1366       parent->path = p_path;
1367       hash_set_mem (cm->command_index_by_path, parent->path,
1368                     parent - cm->commands);
1369       pi = parent - cm->commands;
1370     }
1371   else
1372     {
1373       pi = p[0];
1374       vec_free (p_path);
1375     }
1376
1377   add_sub_command (cm, pi, ci);
1378
1379   /* Create parent's parent. */
1380   if (!p)
1381     vlib_cli_make_parent (cm, pi);
1382 }
1383
1384 always_inline uword
1385 vlib_cli_command_is_empty (vlib_cli_command_t * c)
1386 {
1387   return (c->long_help == 0 && c->short_help == 0 && c->function == 0);
1388 }
1389
1390 clib_error_t *
1391 vlib_cli_register (vlib_main_t * vm, vlib_cli_command_t * c)
1392 {
1393   vlib_global_main_t *vgm = vlib_get_global_main ();
1394   vlib_cli_main_t *cm = &vgm->cli_main;
1395   clib_error_t *error = 0;
1396   uword ci, *p;
1397   char *normalized_path;
1398
1399   if ((error = vlib_call_init_function (vm, vlib_cli_init)))
1400     return error;
1401
1402   (void) vlib_cli_normalize_path (c->path, &normalized_path);
1403
1404   if (!cm->command_index_by_path)
1405     cm->command_index_by_path = hash_create_vec ( /* initial length */ 32,
1406                                                  sizeof (c->path[0]),
1407                                                  sizeof (uword));
1408
1409   /* See if command already exists with given path. */
1410   p = hash_get_mem (cm->command_index_by_path, normalized_path);
1411   if (p)
1412     {
1413       vlib_cli_command_t *d;
1414
1415       ci = p[0];
1416       d = vec_elt_at_index (cm->commands, ci);
1417
1418       /* If existing command was created via vlib_cli_make_parent
1419          replaced it with callers data. */
1420       if (vlib_cli_command_is_empty (d))
1421         {
1422           vlib_cli_command_t save = d[0];
1423
1424           ASSERT (!vlib_cli_command_is_empty (c));
1425
1426           /* Copy callers fields. */
1427           d[0] = c[0];
1428
1429           /* Save internal fields. */
1430           d->path = save.path;
1431           d->sub_commands = save.sub_commands;
1432           d->sub_command_index_by_name = save.sub_command_index_by_name;
1433           d->sub_command_positions = save.sub_command_positions;
1434           d->sub_rules = save.sub_rules;
1435         }
1436       else
1437         error =
1438           clib_error_return (0, "duplicate command name with path %v",
1439                              normalized_path);
1440
1441       vec_free (normalized_path);
1442       if (error)
1443         return error;
1444     }
1445   else
1446     {
1447       /* Command does not exist: create it. */
1448
1449       /* Add root command (index 0). */
1450       if (vec_len (cm->commands) == 0)
1451         {
1452           /* Create command with index 0; path is empty string. */
1453           vec_resize (cm->commands, 1);
1454         }
1455
1456       ci = vec_len (cm->commands);
1457       hash_set_mem (cm->command_index_by_path, normalized_path, ci);
1458       vec_add1 (cm->commands, c[0]);
1459
1460       c = vec_elt_at_index (cm->commands, ci);
1461       c->path = normalized_path;
1462
1463       /* Don't inherit from registration. */
1464       c->sub_commands = 0;
1465       c->sub_command_index_by_name = 0;
1466       c->sub_command_positions = 0;
1467     }
1468
1469   vlib_cli_make_parent (cm, ci);
1470   return 0;
1471 }
1472
1473 #if 0
1474 /* $$$ turn back on again someday, maybe */
1475 clib_error_t *
1476 vlib_cli_register_parse_rule (vlib_main_t * vm, vlib_cli_parse_rule_t * r_reg)
1477 {
1478   vlib_cli_main_t *cm = &vm->cli_main;
1479   vlib_cli_parse_rule_t *r;
1480   clib_error_t *error = 0;
1481   u8 *r_name;
1482   uword *p;
1483
1484   if (!cm->parse_rule_index_by_name)
1485     cm->parse_rule_index_by_name = hash_create_vec ( /* initial length */ 32,
1486                                                     sizeof (r->name[0]),
1487                                                     sizeof (uword));
1488
1489   /* Make vector copy of name. */
1490   r_name = format (0, "%s", r_reg->name);
1491
1492   if ((p = hash_get_mem (cm->parse_rule_index_by_name, r_name)))
1493     {
1494       vec_free (r_name);
1495       return clib_error_return (0, "duplicate parse rule name `%s'",
1496                                 r_reg->name);
1497     }
1498
1499   vec_add2 (cm->parse_rules, r, 1);
1500   r[0] = r_reg[0];
1501   r->name = (char *) r_name;
1502   hash_set_mem (cm->parse_rule_index_by_name, r->name, r - cm->parse_rules);
1503
1504   return error;
1505 }
1506
1507 static clib_error_t *vlib_cli_register_parse_rules (vlib_main_t * vm,
1508                                                     vlib_cli_parse_rule_t *
1509                                                     lo,
1510                                                     vlib_cli_parse_rule_t *
1511                                                     hi)
1512   __attribute__ ((unused))
1513 {
1514   clib_error_t *error = 0;
1515   vlib_cli_parse_rule_t *r;
1516
1517   for (r = lo; r < hi; r = clib_elf_section_data_next (r, 0))
1518     {
1519       if (!r->name || strlen (r->name) == 0)
1520         {
1521           error = clib_error_return (0, "parse rule with no name");
1522           goto done;
1523         }
1524
1525       error = vlib_cli_register_parse_rule (vm, r);
1526       if (error)
1527         goto done;
1528     }
1529
1530 done:
1531   return error;
1532 }
1533 #endif
1534
1535 static clib_error_t *
1536 event_logger_trace_command_fn (vlib_main_t * vm,
1537                                unformat_input_t * input,
1538                                vlib_cli_command_t * cmd)
1539 {
1540   unformat_input_t _line_input, *line_input = &_line_input;
1541   int enable = 1;
1542   int api = 0, cli = 0, barrier = 0, dispatch = 0, circuit = 0;
1543   u32 circuit_node_index;
1544
1545   if (!unformat_user (input, unformat_line_input, line_input))
1546     goto print_status;
1547
1548   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1549     {
1550       if (unformat (line_input, "api"))
1551         api = 1;
1552       else if (unformat (line_input, "dispatch"))
1553         dispatch = 1;
1554       else if (unformat (line_input, "circuit-node %U",
1555                          unformat_vlib_node, vm, &circuit_node_index))
1556         circuit = 1;
1557       else if (unformat (line_input, "cli"))
1558         cli = 1;
1559       else if (unformat (line_input, "barrier"))
1560         barrier = 1;
1561       else if (unformat (line_input, "disable"))
1562         enable = 0;
1563       else if (unformat (line_input, "enable"))
1564         enable = 1;
1565       else
1566         break;
1567     }
1568   unformat_free (line_input);
1569
1570   vl_api_set_elog_trace_api_messages
1571     (api ? enable : vl_api_get_elog_trace_api_messages ());
1572   vm->elog_trace_cli_commands = cli ? enable : vm->elog_trace_cli_commands;
1573   vm->elog_trace_graph_dispatch = dispatch ?
1574     enable : vm->elog_trace_graph_dispatch;
1575   vm->elog_trace_graph_circuit = circuit ?
1576     enable : vm->elog_trace_graph_circuit;
1577   vlib_worker_threads->barrier_elog_enabled =
1578     barrier ? enable : vlib_worker_threads->barrier_elog_enabled;
1579   vm->elog_trace_graph_circuit_node_index = circuit_node_index;
1580
1581   /*
1582    * Set up start-of-buffer logic-analyzer trigger
1583    * for main loop event logs, which are fairly heavyweight.
1584    * See src/vlib/main/vlib_elog_main_loop_event(...), which
1585    * will fully disable the scheme when the elog buffer fills.
1586    */
1587   if (dispatch || circuit)
1588     {
1589       elog_main_t *em = &vlib_global_main.elog_main;
1590
1591       em->n_total_events_disable_limit =
1592         em->n_total_events + vec_len (em->event_ring);
1593     }
1594
1595
1596 print_status:
1597   vlib_cli_output (vm, "Current status:");
1598
1599   vlib_cli_output
1600     (vm, "    Event log API message trace: %s\n    CLI command trace: %s",
1601      vl_api_get_elog_trace_api_messages ()? "on" : "off",
1602      vm->elog_trace_cli_commands ? "on" : "off");
1603   vlib_cli_output
1604     (vm, "    Barrier sync trace: %s",
1605      vlib_worker_threads->barrier_elog_enabled ? "on" : "off");
1606   vlib_cli_output
1607     (vm, "    Graph Dispatch: %s",
1608      vm->elog_trace_graph_dispatch ? "on" : "off");
1609   vlib_cli_output
1610     (vm, "    Graph Circuit: %s",
1611      vm->elog_trace_graph_circuit ? "on" : "off");
1612   if (vm->elog_trace_graph_circuit)
1613     vlib_cli_output
1614       (vm, "                   node %U",
1615        format_vlib_node_name, vm, vm->elog_trace_graph_circuit_node_index);
1616
1617   return 0;
1618 }
1619
1620 /*?
1621  * Control event logging of api, cli, and thread barrier events
1622  * With no arguments, displays the current trace status.
1623  * Name the event groups you wish to trace or stop tracing.
1624  *
1625  * @cliexpar
1626  * @clistart
1627  * event-logger trace api cli barrier
1628  * event-logger trace api cli barrier disable
1629  * event-logger trace dispatch
1630  * event-logger trace circuit-node ethernet-input
1631  * @cliend
1632  * @cliexcmd{event-logger trace [api][cli][barrier][disable]}
1633 ?*/
1634 /* *INDENT-OFF* */
1635 VLIB_CLI_COMMAND (event_logger_trace_command, static) =
1636 {
1637   .path = "event-logger trace",
1638   .short_help = "event-logger trace [api][cli][barrier][dispatch]\n"
1639   "[circuit-node <name> e.g. ethernet-input][disable]",
1640   .function = event_logger_trace_command_fn,
1641 };
1642 /* *INDENT-ON* */
1643
1644 static clib_error_t *
1645 suspend_command_fn (vlib_main_t * vm,
1646                     unformat_input_t * input, vlib_cli_command_t * cmd)
1647 {
1648   vlib_process_suspend (vm, 30e-3);
1649   return 0;
1650 }
1651
1652 /* *INDENT-OFF* */
1653 VLIB_CLI_COMMAND (suspend_command, static) =
1654 {
1655   .path = "suspend",
1656   .short_help = "suspend debug CLI for 30ms",
1657   .function = suspend_command_fn,
1658   .is_mp_safe = 1,
1659 };
1660 /* *INDENT-ON* */
1661
1662
1663 static int
1664 sort_cmds_by_path (void *a1, void *a2)
1665 {
1666   u32 *index1 = a1;
1667   u32 *index2 = a2;
1668   vlib_global_main_t *vgm = vlib_get_global_main ();
1669   vlib_cli_main_t *cm = &vgm->cli_main;
1670   vlib_cli_command_t *c1, *c2;
1671   int i, lmin;
1672
1673   c1 = vec_elt_at_index (cm->commands, *index1);
1674   c2 = vec_elt_at_index (cm->commands, *index2);
1675
1676   lmin = vec_len (c1->path);
1677   lmin = (vec_len (c2->path) >= lmin) ? lmin : vec_len (c2->path);
1678
1679   for (i = 0; i < lmin; i++)
1680     {
1681       if (c1->path[i] < c2->path[i])
1682         return -1;
1683       else if (c1->path[i] > c2->path[i])
1684         return 1;
1685     }
1686
1687   return 0;
1688 }
1689
1690 typedef struct
1691 {
1692   vlib_cli_main_t *cm;
1693   u32 parent_command_index;
1694   int show_mp_safe;
1695   int show_not_mp_safe;
1696   int show_hit;
1697   int clear_hit;
1698 } vlib_cli_walk_args_t;
1699
1700 static void
1701 cli_recursive_walk (vlib_cli_walk_args_t * aa)
1702 {
1703   vlib_cli_command_t *parent;
1704   vlib_cli_sub_command_t *sub;
1705   vlib_cli_walk_args_t _a, *a = &_a;
1706   vlib_cli_main_t *cm;
1707   int i;
1708
1709   /* Copy args into this stack frame */
1710   *a = *aa;
1711   cm = a->cm;
1712
1713   parent = vec_elt_at_index (cm->commands, a->parent_command_index);
1714
1715   if (parent->function)
1716     {
1717       if (((a->show_mp_safe && parent->is_mp_safe)
1718            || (a->show_not_mp_safe && !parent->is_mp_safe))
1719           && (a->show_hit == 0 || parent->hit_counter))
1720         {
1721           vec_add1 (cm->sort_vector, a->parent_command_index);
1722         }
1723
1724       if (a->clear_hit)
1725         parent->hit_counter = 0;
1726     }
1727
1728   for (i = 0; i < vec_len (parent->sub_commands); i++)
1729     {
1730       sub = vec_elt_at_index (parent->sub_commands, i);
1731       a->parent_command_index = sub->index;
1732       cli_recursive_walk (a);
1733     }
1734 }
1735
1736 static u8 *
1737 format_mp_safe (u8 * s, va_list * args)
1738 {
1739   vlib_cli_main_t *cm = va_arg (*args, vlib_cli_main_t *);
1740   int show_mp_safe = va_arg (*args, int);
1741   int show_not_mp_safe = va_arg (*args, int);
1742   int show_hit = va_arg (*args, int);
1743   int clear_hit = va_arg (*args, int);
1744   vlib_cli_command_t *c;
1745   vlib_cli_walk_args_t _a, *a = &_a;
1746   int i;
1747   char *format_string = "\n%v";
1748
1749   if (show_hit)
1750     format_string = "\n%v: %u";
1751
1752   vec_reset_length (cm->sort_vector);
1753
1754   a->cm = cm;
1755   a->parent_command_index = 0;
1756   a->show_mp_safe = show_mp_safe;
1757   a->show_not_mp_safe = show_not_mp_safe;
1758   a->show_hit = show_hit;
1759   a->clear_hit = clear_hit;
1760
1761   cli_recursive_walk (a);
1762
1763   vec_sort_with_function (cm->sort_vector, sort_cmds_by_path);
1764
1765   for (i = 0; i < vec_len (cm->sort_vector); i++)
1766     {
1767       c = vec_elt_at_index (cm->commands, cm->sort_vector[i]);
1768       s = format (s, format_string, c->path, c->hit_counter);
1769     }
1770
1771   return s;
1772 }
1773
1774
1775 static clib_error_t *
1776 show_cli_command_fn (vlib_main_t * vm,
1777                      unformat_input_t * input, vlib_cli_command_t * cmd)
1778 {
1779   vlib_global_main_t *vgm = vlib_get_global_main ();
1780   int show_mp_safe = 0;
1781   int show_not_mp_safe = 0;
1782   int show_hit = 0;
1783   int clear_hit = 0;
1784
1785   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1786     {
1787       if (unformat (input, "mp-safe"))
1788         show_mp_safe = 1;
1789       if (unformat (input, "not-mp-safe"))
1790         show_not_mp_safe = 1;
1791       else if (unformat (input, "hit"))
1792         show_hit = 1;
1793       else if (unformat (input, "clear-hit"))
1794         clear_hit = 1;
1795       else
1796         break;
1797     }
1798
1799   /* default set: all cli commands */
1800   if (clear_hit == 0 && (show_mp_safe + show_not_mp_safe) == 0)
1801     show_mp_safe = show_not_mp_safe = 1;
1802
1803   vlib_cli_output (vm, "%U", format_mp_safe, &vgm->cli_main, show_mp_safe,
1804                    show_not_mp_safe, show_hit, clear_hit);
1805   if (clear_hit)
1806     vlib_cli_output (vm, "hit counters cleared...");
1807
1808   return 0;
1809 }
1810
1811 /*?
1812  * Displays debug cli command information
1813  *
1814  * @cliexpar
1815  * @cliexstart{show cli [mp-safe][not-mp-safe][hit][clear-hit]}
1816  *
1817  * "show cli" displays the entire debug cli:
1818  *
1819  * abf attach
1820  * abf policy
1821  * adjacency counters
1822  * api trace
1823  * app ns
1824  * bfd key del
1825  * ... and so on ...
1826  *
1827  * "show cli mp-safe" displays mp-safe debug CLI commands:
1828  *
1829  * abf policy
1830  * binary-api
1831  * create vhost-user
1832  * exec
1833  * ip container
1834  * ip mroute
1835  * ip probe-neighbor
1836  * ip route
1837  * ip scan-neighbor
1838  * ip table
1839  * ip6 table
1840  *
1841  * "show cli not-mp-safe" displays debug CLI commands
1842  * which cause worker thread barrier synchronization
1843  *
1844  * "show cli hit" displays commands which have been executed. Qualify
1845  * as desired with "mp-safe" or "not-mp-safe".
1846  *
1847  * "show cli clear-hit" clears the per-command hit counters.
1848  * @cliexend
1849 ?*/
1850
1851 /* *INDENT-OFF* */
1852 VLIB_CLI_COMMAND (show_cli_command, static) =
1853 {
1854   .path = "show cli",
1855   .short_help = "show cli [mp-safe][not-mp-safe][hit][clear-hit]",
1856   .function = show_cli_command_fn,
1857   .is_mp_safe = 1,
1858 };
1859 /* *INDENT-ON* */
1860
1861 static clib_error_t *
1862 vlib_cli_init (vlib_main_t * vm)
1863 {
1864   vlib_global_main_t *vgm = vlib_get_global_main ();
1865   vlib_cli_main_t *cm = &vgm->cli_main;
1866   clib_error_t *error = 0;
1867   vlib_cli_command_t *cmd;
1868
1869   cmd = cm->cli_command_registrations;
1870
1871   while (cmd)
1872     {
1873       error = vlib_cli_register (vm, cmd);
1874       if (error)
1875         return error;
1876       cmd = cmd->next_cli_command;
1877     }
1878
1879   cm->log = vlib_log_register_class_rate_limit (
1880     "cli", "log", 0x7FFFFFFF /* aka no rate limit */);
1881   return error;
1882 }
1883
1884 VLIB_INIT_FUNCTION (vlib_cli_init);
1885
1886 /*
1887  * fd.io coding-style-patch-verification: ON
1888  *
1889  * Local Variables:
1890  * eval: (c-set-style "gnu")
1891  * End:
1892  */