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