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