xref: /dpdk/doc/guides/prog_guide/cmdline.rst (revision 43f062ac3a926e53993b52a3d4333f2de2c6a706)
1..  SPDX-License-Identifier: BSD-3-Clause
2    Copyright(c) 2023 Intel Corporation.
3
4Command-line Library
5====================
6
7Since its earliest versions, DPDK has included a command-line library -
8primarily for internal use by, for example, ``dpdk-testpmd`` and the ``dpdk-test`` binaries,
9but the library is also exported on install and can be used by any end application.
10This chapter covers the basics of the command-line library and how to use it in an application.
11
12Library Features
13----------------
14
15The DPDK command-line library supports the following features:
16
17* Tab-completion available for interactive terminal sessions
18
19* Ability to read and process commands taken from an input file, e.g. startup script
20
21* Parameterized commands able to take multiple parameters with different datatypes:
22
23   * Strings
24   * Signed/unsigned 16/32/64-bit integers
25   * IP Addresses
26   * Ethernet Addresses
27
28* Ability to multiplex multiple commands to a single callback function
29
30Adding Command-line to an Application
31-------------------------------------
32
33Adding a command-line instance to an application involves a number of coding steps.
34
35#. Define the result structure for the command, specifying the command parameters
36
37#. Provide an initializer for each field in the result
38
39#. Define the callback function for the command
40
41#. Provide a parse result structure instance for the command, linking the callback to the command
42
43#. Add the parse result structure to a command-line context
44
45#. Within your main application code, create a new command-line instance passing in the context.
46
47Many of these steps can be automated using the script ``dpdk-cmdline-gen.py`` installed by DPDK,
48and found in the ``buildtools`` folder in the source tree.
49This section covers adding a command-line using this script to generate the boiler plate,
50while the following section,
51`Worked Example of Adding Command-line to an Application`_ covers the steps to do so manually.
52
53Creating a Command List File
54~~~~~~~~~~~~~~~~~~~~~~~~~~~~
55
56The ``dpdk-cmdline-gen.py`` script takes as input a list of commands to be used by the application.
57While these can be piped to it via standard input, using a list file is probably best.
58
59The format of the list file must be:
60
61* Comment lines start with '#' as first non-whitespace character
62
63* One command per line
64
65* Variable fields are prefixed by the type-name in angle-brackets, for example:
66
67  * ``<STRING>message``
68
69  * ``<UINT16>port_id``
70
71  * ``<IP>src_ip``
72
73* The help text for a command is given in the form of a comment on the same line as the command
74
75An example list file, with a variety of (unrelated) commands, is shown below::
76
77   # example list file
78   list                     # show all entries
79   add <UINT16>x <UINT16>y  # add x and y
80   echo <STRING>message     # print message to screen
81   add socket <STRING>path  # add unix socket with the given path
82   quit                     # close the application
83
84Running the Generator Script
85~~~~~~~~~~~~~~~~~~~~~~~~~~~~
86
87To generate the necessary definitions for a command-line, run ``dpdk-cmdline-gen.py`` passing the list file as parameter.
88The script will output the generated C code to standard output,
89the contents of which are in the form of a C header file.
90Optionally, an output filename may be specified via the ``-o/--output-file`` argument.
91
92The generated content includes:
93
94* The result structure definitions for each command
95
96* The token initializers for each structure field
97
98* An "extern" function prototype for the callback for each command
99
100* A parse context for each command, including the per-command comments as help string
101
102* A command-line context array definition, suitable for passing to ``cmdline_new``
103
104If so desired, the script can also output function stubs for the callback functions for each command.
105This behaviour is triggered by passing the ``--stubs`` flag to the script.
106In this case, an output file must be provided with a filename ending in ".h",
107and the callback stubs will be written to an equivalent ".c" file.
108
109.. note::
110
111   The stubs are written to a separate file,
112   to allow continuous use of the script to regenerate the command-line header,
113   without overwriting any code the user has added to the callback functions.
114   This makes it easy to incrementally add new commands to an existing application.
115
116Providing the Function Callbacks
117~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
118
119As discussed above, the script output is a header file, containing structure definitions,
120but the callback functions themselves obviously have to be provided by the user.
121These callback functions must be provided as non-static functions in a C file,
122and named ``cmd_<cmdname>_parsed``.
123The function prototypes can be seen in the generated output header.
124
125The "cmdname" part of the function name is built up by combining the non-variable initial tokens in the command.
126So, given the commands in our worked example below: ``quit`` and ``show port stats <n>``,
127the callback functions would be:
128
129.. code:: c
130
131   void
132   cmd_quit_parsed(void *parsed_result, struct cmdline *cl, void *data)
133   {
134        ...
135   }
136
137   void
138   cmd_show_port_stats_parsed(void *parsed_result, struct cmdline *cl, void *data)
139   {
140        ...
141   }
142
143These functions must be provided by the developer, but, as stated above,
144stub functions may be generated by the script automatically using the ``--stubs`` parameter.
145
146The same "cmdname" stem is used in the naming of the generated structures too.
147To get at the results structure for each command above,
148the ``parsed_result`` parameter should be cast to ``struct cmd_quit_result``
149or ``struct cmd_show_port_stats_result`` respectively.
150
151Integrating with the Application
152~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
153
154To integrate the script output with the application,
155we must ``#include`` the generated header into our applications C file,
156and then have the command-line created via either ``cmdline_new`` or ``cmdline_stdin_new``.
157The first parameter to the function call should be the context array in the generated header file,
158``ctx`` by default. (Modifiable via script parameter).
159
160The callback functions may be in this same file, or in a separate one -
161they just need to be available to the linker at build-time.
162
163Limitations of the Script Approach
164~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
165
166The script approach works for most commands that a user may wish to add to an application.
167However, it does not support the full range of functions possible with the DPDK command-line library.
168For example,
169it is not possible using the script to multiplex multiple commands into a single callback function.
170To use this functionality, the user should follow the instructions in the next section
171`Worked Example of Adding Command-line to an Application`_ to manually configure a command-line instance.
172
173Worked Example of Adding Command-line to an Application
174-------------------------------------------------------
175
176The next few subsections will cover each of the steps listed in `Adding Command-line to an Application`_ in more detail,
177working through an example to add two commands to a command-line instance.
178Those two commands will be:
179
180#. ``quit`` - as the name suggests, to close the application
181
182#. ``show port stats <n>`` - to display on-screen the statistics for a given ethernet port
183
184.. note::
185
186   For further examples of use of the command-line, see
187   :doc:`cmdline example application <../sample_app_ug/cmd_line>`
188
189Defining Command Result Structure
190~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
191
192The first structure to be defined is the structure which will be created on successful parse of a command.
193This structure contains one member field for each token, or word, in the command.
194The simplest case is for a one-word command, like ``quit``.
195For this, we only need to define a structure with a single string parameter to contain that word.
196
197.. code-block:: c
198
199   struct cmd_quit_result {
200      cmdline_fixed_string_t quit;
201   };
202
203For readability, the name of the struct member should match that of the token in the command.
204
205For our second command, we need a structure with four member fields in it,
206as there are four words/tokens in our command.
207The first three are strings, and the final one is a 16-bit numeric value.
208The resulting struct looks like:
209
210.. code-block:: c
211
212   struct cmd_show_port_stats_result {
213      cmdline_fixed_string_t show;
214      cmdline_fixed_string_t port;
215      cmdline_fixed_string_t stats;
216      uint16_t n;
217   };
218
219As before, we choose names to match the tokens in the command.
220Since our numeric parameter is a 16-bit value, we use ``uint16_t`` type for it.
221Any of the standard sized integer types can be used as parameters, depending on the desired result.
222
223Beyond the standard integer types,
224the library also allows variable parameters to be of a number of other types,
225as called out in the feature list above.
226
227* For variable string parameters,
228  the type should be ``cmdline_fixed_string_t`` - the same as for fixed tokens,
229  but these will be initialized differently (as described below).
230
231* For ethernet addresses use type ``struct rte_ether_addr``
232
233* For IP addresses use type ``cmdline_ipaddr_t``
234
235Providing Field Initializers
236~~~~~~~~~~~~~~~~~~~~~~~~~~~~
237
238Each field of our result structure needs an initializer.
239For fixed string tokens, like "quit", "show" and "port", the initializer will be the string itself.
240
241.. code-block:: c
242
243   static cmdline_parse_token_string_t cmd_quit_quit_tok =
244      TOKEN_STRING_INITIALIZER(struct cmd_quit_result, quit, "quit");
245
246The convention for naming used here is to include the base name of the overall result structure -
247``cmd_quit`` in this case,
248as well as the name of the field within that structure - ``quit`` in this case, followed by ``_tok``.
249(This is why there is a double ``quit`` in the name above).
250
251This naming convention is seen in our second example,
252which also demonstrates how to define a numeric initializer.
253
254
255.. code-block:: c
256
257   static cmdline_parse_token_string_t cmd_show_port_stats_show_tok =
258      TOKEN_STRING_INITIALIZER(struct cmd_show_port_stats_result, show, "show");
259   static cmdline_parse_token_string_t cmd_show_port_stats_port_tok =
260      TOKEN_STRING_INITIALIZER(struct cmd_show_port_stats_result, port, "port");
261   static cmdline_parse_token_string_t cmd_show_port_stats_stats_tok =
262      TOKEN_STRING_INITIALIZER(struct cmd_show_port_stats_result, stats, "stats");
263   static cmdline_parse_token_num_t cmd_show_port_stats_n_tok =
264      TOKEN_NUM_INITIALIZER(struct cmd_show_port_stats_result, n, RTE_UINT16);
265
266For variable string tokens, the same ``TOKEN_STRING_INITIALIZER`` macro should be used.
267However, the final parameter should be ``NULL`` rather than a hard-coded token string.
268
269For numeric parameters, the final parameter to the ``TOKEN_NUM_INITIALIZER`` macro should be the
270cmdline type matching the variable type defined in the result structure,
271e.g. RTE_UINT8, RTE_UINT32, etc.
272
273For IP addresses, the macro ``TOKEN_IPADDR_INITIALIZER`` should be used.
274
275For ethernet addresses, the macro ``TOKEN_ETHERADDR_INITIALIZER`` should be used.
276
277Defining Callback Function
278~~~~~~~~~~~~~~~~~~~~~~~~~~
279
280For each command, we need to define a function to be called once the command has been recognised.
281The callback function should have type:
282
283.. code:: c
284
285   void (*f)(void *, struct cmdline *, void *)
286
287where the first parameter is a pointer to the result structure defined above,
288the second parameter is the command-line instance,
289and the final parameter is a user-defined pointer provided when we associate the callback with the command.
290Most callback functions only use the first parameter, or none at all,
291but the additional two parameters provide some extra flexibility,
292to allow the callback to work with non-global state in your application.
293
294For our two example commands, the relevant callback functions would look very similar in definition.
295However, within the function body,
296we assume that the user would need to reference the result structure to extract the port number in
297the second case.
298
299.. code:: c
300
301   void
302   cmd_quit_parsed(void *parsed_result, struct cmdline *cl, void *data)
303   {
304      quit = 1;
305   }
306   void
307   cmd_show_port_stats_parsed(void *parsed_result, struct cmdline *cl, void *data)
308   {
309      struct cmd_show_port_stats_result *res = parsed_result;
310      uint16_t port_id = res->n;
311      ...
312   }
313
314
315Associating Callback and Command
316~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
317
318The ``cmdline_parse_inst_t`` type defines a "parse instance",
319i.e. a sequence of tokens to be matched and then an associated function to be called.
320Also included in the instance type are a field for help text for the command,
321and any additional user-defined parameter to be passed to the callback functions referenced above.
322For example, for our simple "quit" command:
323
324.. code-block:: c
325
326   static cmdline_parse_inst_t cmd_quit = {
327       .f = cmd_quit_parsed,
328       .data = NULL,
329       .help_str = "Close the application",
330       .tokens = {
331           (void *)&cmd_quit_quit_tok,
332           NULL
333       }
334   };
335
336In this case, we firstly identify the callback function to be called,
337then set the user-defined parameter to NULL,
338provide a help message to be given, on request, to the user explaining the command,
339before finally listing out the single token to be matched for this command instance.
340
341For our second, port stats, example,
342as well as making things a little more complicated by having multiple tokens to be matched,
343we can also demonstrate passing in a parameter to the function.
344Let us suppose that our application does not always use all the ports available to it,
345but instead only uses a subset of the ports, stored in an array called ``active_ports``.
346Our stats command, therefore, should only display stats for the currently in-use ports,
347so we pass this ``active_ports`` array.
348(For simplicity of illustration, we shall assume that the array uses a terminating marker,
349e.g. -1 for the end of the port list, so we don't need to pass in a length parameter too.)
350
351.. code-block:: c
352
353   extern int16_t active_ports[];
354   ...
355   static cmdline_parse_inst_t cmd_show_port_stats = {
356       .f = cmd_show_port_stats_parsed,
357       .data = active_ports,
358       .help_str = "Show statistics for active network ports",
359       .tokens = {
360           (void *)&cmd_show_port_stats_show_tok,
361           (void *)&cmd_show_port_stats_port_tok,
362           (void *)&cmd_show_port_stats_stats_tok,
363           (void *)&cmd_show_port_stats_n_tok,
364           NULL
365       }
366   };
367
368
369Adding Command to Command-line Context
370~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
371
372Now that we have configured each individual command and callback,
373we need to merge these into a single array of command-line "contexts".
374This context array will be used to create the actual command-line instance in the application.
375Thankfully, each context entry is the same as each parse instance,
376so our array is defined by simply listing out the previously defined command parse instances.
377
378.. code-block:: c
379
380   static cmdline_parse_ctx_t ctx[] = {
381       &cmd_quit,
382       &cmd_show_port_stats,
383       NULL
384   };
385
386The context list must be terminated by a NULL entry.
387
388Creating a Command-line Instance
389~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
390
391Once we have our ``ctx`` variable defined,
392we now just need to call the API to create the new command-line instance in our application.
393The basic API is ``cmdline_new`` which will create an interactive command-line with all commands available.
394However, if additional features for interactive use - such as tab-completion -
395are desired, it is recommended that ``cmdline_new_stdin`` be used instead.
396
397A pattern that can be used in applications is to use ``cmdline_new`` for processing any startup commands,
398either from file or from the environment (as is done in the "dpdk-test" application),
399and then using ``cmdline_stdin_new`` thereafter to handle the interactive part.
400For example, to handle a startup file and then provide an interactive prompt:
401
402.. code-block:: c
403
404   struct cmdline *cl;
405   int fd = open(startup_file, O_RDONLY);
406
407   if (fd >= 0) {
408       cl = cmdline_new(ctx, "", fd, STDOUT_FILENO);
409       if (cl == NULL) {
410           /* error handling */
411       }
412       cmdline_interact(cl);
413       cmdline_quit(cl);
414       close(fd);
415   }
416
417   cl = cmdline_stdin_new(ctx, "Proxy>> ");
418   if (cl == NULL) {
419       /* error handling */
420   }
421   cmdline_interact(cl);
422   cmdline_stdin_exit(cl);
423
424
425Multiplexing Multiple Commands to a Single Function
426~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
427
428To reduce the amount of boiler-plate code needed when creating a command-line for an application,
429it is possible to merge a number of commands together to have them call a separate function.
430This can be done in a number of different ways:
431
432* A callback function can be used as the target for a number of different commands.
433  Which command was used for entry to the function can be determined by examining the first parameter,
434  ``parsed_result`` in our examples above.
435
436* For simple string commands, multiple options can be concatenated using the "#" character.
437  For example: ``exit#quit``, specified as a token initializer,
438  will match either on the string "exit" or the string "quit".
439
440As a concrete example,
441these two techniques are used in the DPDK unit test application ``dpdk-test``,
442where a single command ``cmdline_parse_t`` instance is used for all the "dump_<item>" test cases.
443
444.. literalinclude:: ../../../app/test/commands.c
445    :language: c
446    :start-after: Add the dump_* tests cases 8<
447    :end-before: >8 End of add the dump_* tests cases
448
449
450Examples of Command-line Use in DPDK
451------------------------------------
452
453To help the user follow the steps provided above,
454the following DPDK files can be consulted for examples of command-line use.
455
456.. note::
457
458   This is not an exhaustive list of examples of command-line use in DPDK.
459   It is simply a list of a few files that may be of use to the application developer.
460   Some of these referenced files contain more complex examples of use that others.
461
462* ``commands.c/.h`` in ``examples/cmdline``
463
464* ``mp_commands.c/.h`` in ``examples/multi_process/simple_mp``
465
466* ``commands.c`` in ``app/test``
467