make cmdline library easier to use
cover make cmdline library easier to use
And now for something completely different... :-)
While it's nice that DPDK includes a commandline library for easily adding interactivity to applications, the library itself is a little clunky to use, due to the massive amounts of boilerplate definitions required. Having used it recently on an app I was playing with for testing, I decided the situation can potentially be improved with it by use of a script to produce the boilerplate when given a simple list of commands the user wants to add to the app.
This is the result of that effort. Sending it here as a rough-draft to get feedback on whether this is worth including in DPDK itself. Hopefully others may find it of use.
Bruce Richardson (1):
cmdline/dpdk-cmdline-gen: generate boilerplate for simple cmds
lib/cmdline/dpdk-cmdline-gen.py | 143 ++++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100755 lib/cmdline/dpdk-cmdline-gen.py
--
2.39.2
RFC PATCH 1/1 cmdline/dpdk-cmdline-gen: generate boilerplate for simple cmds
Provide a script for application developers to quickly generate the boilerplate code necessary for using the cmdline library.
This initial version works only with commands using simple strings and numbers, but this is sufficient for many use-cases. Future extensions could, no doubt, expand support to expose more capabilities of the library.
Example of use:
The script takes an input file with a list of commands the user wants in the app, where the parameter variables are tagged with the type. For example:
$ cat commands.list list add <UINT16>x <UINT16>y echo <STRING>message add socket <STRING>path quit
When run through the script as "./dpdk-cmdline-gen.py commands.list", the output will be the contents of a header file with all the boilerplate necessary for a commandline instance with those commands.
If the flag --stubs is passed, an output header filename must also be passed, in which case both a header file with the definitions and a C file with function stubs in it is written to disk. The separation is so that the header file can be rewritten at any future point to add more commands, while the C file can be kept as-is and extended by the user with any additional functions needed.
--- lib/cmdline/dpdk-cmdline-gen.py | 143 ++++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100755 lib/cmdline/dpdk-cmdline-gen.py
lib/cmdline/dpdk-cmdline-gen.py new file +143 -0
@@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# + +import sys +import os +import argparse + +PARSE_FN_PARAMS = "void *parsed_result, struct cmdline *cl, void *data" +PARSE_FN_BODY = """ + /* TODO: command action */ + RTE_SET_USED(parsed_result); + RTE_SET_USED(cl); + RTE_SET_USED(data); +""" + +def process_command(tokens, cfile): + name = [] + + if tokens[0].startswith('<'): + print("Error: each command must start with at least one literal string", + file=sys.stderr) + sys.exit(1) + for t in tokens: + if t.startswith('<'): + break; + name.append(t) + name = "_".join(name) + + result_struct = [] + initializers = [] + token_list = [] + for t in tokens: + if t.startswith('<'): + t_type, t_name = t[1:].split('>') + t_val = "NULL" + else: + t_type = "STRING" + t_name = t + t_val = f'"{t}"' + + if t_type == "STRING": + result_struct.append(f"\tcmdline_fixed_string_t {t_name};") + initializers.append(f"static cmdline_parse_token_string_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_STRING_INITIALIZER(struct cmd_{name}_result, {t_name}, {t_val});") + elif t_type in ['UINT8', 'UINT16', 'UINT32', 'UINT64', + 'INT8', 'INT16', 'INT32', 'INT64']: + result_struct.append(f"\t{t_type.lower()}_t {t_name};") + initializers.append(f"static cmdline_parse_token_num_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_NUM_INITIALIZER(struct cmd_{name}_result, {t_name}, RTE_{t_type});") + else: + print(f"Error: unknown token-type {t}", file=sys.stderr) + sys.exit(1) + token_list.append(f"cmd_{name}_{t_name}_tok") + + print(f"/* Auto-generated handling for command '{' '.join(tokens)}' */") + # output function prototype + func_sig = f"void\ncmd_{name}_parsed({PARSE_FN_PARAMS})" + print(f"extern {func_sig};\n") + # output function template if C file being written + if (cfile): + print(f"{func_sig}\n{{{PARSE_FN_BODY}}}\n", file=cfile) + # output result data structure + print(f"struct cmd_{name}_result {{\n" + + '\n'.join(result_struct) + + "\n};\n") + # output the initializer tokens + print("\n".join(initializers) + '\n') + # output the instance structure + print(f"static cmdline_parse_inst_t cmd_{name} = {{\n" + + f'\t.f = cmd_{name}_parsed,\n' + + f'\t.data = NULL,\n' + + f'\t.help_str = "",\n' + + f'\t.tokens = {{') + for t in token_list: + print(f"\t\t(void *)&{t},") + print("\t\tNULL\n" + + "\t}\n" + + "};\n") + + # return the instance structure name + return f"cmd_{name}" + +def process_commands(infile, hfile, cfile): + instances = [] + + # redirect stdout to output the header, to save passing file= each print + old_sys_stdout = sys.stdout + sys.stdout = hfile + + print(f"/* File autogenerated by {sys.argv[0]} */") + print('#ifndef GENERATED_COMMANDS_H') + print('#define GENERATED_COMMANDS_H') + print("#include <cmdline.h>") + print("#include <cmdline_parse_string.h>") + print("#include <cmdline_parse_num.h>") + print("") + + for line in infile.readlines(): + if line.lstrip().startswith('#'): + continue + instances.append(process_command(line.strip().split(), cfile)) + + print('static cmdline_parse_ctx_t ctx[] = {') + for inst in instances: + print(f'\t&{inst},') + print('\tNULL') + print('};\n') + print('#endif /* GENERATED_COMMANDS_H */') + + sys.stdout = old_sys_stdout + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--stubs", action="store_true", + help="Produce C file with empty function stubs for each command") + ap.add_argument("--output-file", "-o", default="-", + help="Output header filename [default to stdout]") + ap.add_argument("infile", type=argparse.FileType('r'), + help="File with list of commands") + args = ap.parse_args() + + if not args.stubs: + if args.output_file == '-': + process_commands(args.infile, sys.stdout, None) + else: + with open(args.output_file, "w") as hfile: + process_commands(args.infile, hfile, None) + else: + if not args.output_file.endswith('.h'): + print("Error: output filename must end with '.h' extension when creating stubs", + file=sys.stderr) + sys.exit(1) + + cfilename = args.output_file[:-2] + '.c' + with open(args.output_file, "w") as hfile: + with open(cfilename, "w") as cfile: + print(f"#include \"{args.output_file}\"\n", file=cfile) + process_commands(args.infile, hfile, cfile) + +if __name__ == "__main__": + main()
Signature · 1 line
2.39.2
Quoted 14 lines · On Wed, 2 Aug 2023 18:00:51 +0100 Bruce Richardson…
And now for something completely different... :-)
While it's nice that DPDK includes a commandline library for easily adding interactivity to applications, the library itself is a little clunky to use, due to the massive amounts of boilerplate definitions required. Having used it recently on an app I was playing with for testing, I decided the situation can potentially be improved with it by use of a script to produce the boilerplate when given a simple list of commands the user wants to add to the app.
This is the result of that effort. Sending it here as a rough-draft to get feedback on whether this is worth including in DPDK itself. Hopefully others may find it of use.
Quoted 6 lines
Bruce Richardson (1):
cmdline/dpdk-cmdline-gen: generate boilerplate for simple cmdslib/cmdline/dpdk-cmdline-gen.py | 143 ++++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100755 lib/cmdline/dpdk-cmdline-gen.py
Ok, but this surely is a solved problem is some other open source library. Or does every project reinvent this parsing?
Seems to me that something like bison/flex (ie yacc/lex) would be better in terms of expressing the syntax separate from the implementation.
Quoted 24 lines · Stephen Hemminger
Quoted 14 lines · On Wed, 2 Aug 2023 18:00:51 +0100 Bruce Richardson…
And now for something completely different... :-)
While it's nice that DPDK includes a commandline library for easily adding interactivity to applications, the library itself is a little clunky to use, due to the massive amounts of boilerplate definitions required. Having used it recently on an app I was playing with for testing, I decided the situation can potentially be improved with it by use of a script to produce the boilerplate when given a simple list of commands the user wants to add to the app.
This is the result of that effort. Sending it here as a rough-draft to get feedback on whether this is worth including in DPDK itself. Hopefully others may find it of use.
Quoted 6 lines
Bruce Richardson (1):
cmdline/dpdk-cmdline-gen: generate boilerplate for simple cmdslib/cmdline/dpdk-cmdline-gen.py | 143 ++++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100755 lib/cmdline/dpdk-cmdline-gen.py
Quoted 5 lines
Ok, but this surely is a solved problem is some other open source library. Or does every project reinvent this parsing?
Seems to me that something like bison/flex (ie yacc/lex) would be better in terms of expressing the syntax separate from the implementation.
Sure, but it has been many, many years since I last even looked at those tools, so it was faster for me to just use this python script for quick cmdline generation when prototyping things! :-) I wanted something that worked for me, so I'm just sharing it with the community in case others find it useful.
If you have time, please do indeed come up with a lex/yacc generator instead, it would indeed be a better solution. [If not, I suggest we take what we can get if it works! :-)]
/Bruce
v2 cover use script to simplify use of cmdline lib
In reply to Bruce RichardsonThe DPDK commandline library is widely used by apps and examples within DPDK, but requires a lot of boilerplate code definitions in order to used. We can improve this situation by creating a simple python script to automatically generate the boilerplate from a list of commands.
This RFC v2 contains the (slightly enhanced from v1) script, as well as a set of three patches showing its use, by converting three examples to use the script instead of having the hard-coded boilerplate. Once the script is used, adding a new command becomes as simple as adding the desired command to the .list file, and then writing the required function which will be called for that command. No other boilerplate coding is necessary.
Script obviously does not cover the full range of capabilities of the commandline lib, but does cover the most used parts - with one
exception: it does not yet support defining the help text for a command (hence the fact this is another RFC). If there is a general acceptance that this is worthwhile, that gap can be closed, making the shortened boiler-plate-free examples fully equivalent to the original code.
V2-RFC:
* Add support for IP addresses in commands
* Move to buildtools directory and make installable
* Convert 3 examples to use script, and eliminate their boilerplate
Bruce Richardson (5):
buildtools/dpdk-cmdline-gen: generate boilerplate for simple cmds examples/simple_mp: convert to use cmdline script examples/hotplug_mp: auto-generate cmdline boilerplate buildtools/dpdk-cmdline-gen: add IP address support examples/bond: auto-generate cmdline boilerplate
buildtools/dpdk-cmdline-gen.py | 151 ++++++++++++++++ buildtools/meson.build | 7 + examples/bond/Makefile | 10 +- examples/bond/commands.list | 6 + examples/bond/main.c | 161 ++---------------- examples/bond/main.h | 10 -- examples/bond/meson.build | 8 + examples/multi_process/hotplug_mp/Makefile | 10 +- examples/multi_process/hotplug_mp/commands.c | 147 ++-------------- examples/multi_process/hotplug_mp/commands.h | 10 -- .../multi_process/hotplug_mp/commands.list | 5 + examples/multi_process/hotplug_mp/meson.build | 9 + examples/multi_process/simple_mp/Makefile | 10 +- examples/multi_process/simple_mp/meson.build | 9 + .../multi_process/simple_mp/mp_commands.c | 106 ++---------- .../multi_process/simple_mp/mp_commands.h | 14 -- .../multi_process/simple_mp/mp_commands.list | 3 + 17 files changed, 257 insertions(+), 419 deletions(-) create mode 100755 buildtools/dpdk-cmdline-gen.py create mode 100644 examples/bond/commands.list delete mode 100644 examples/bond/main.h delete mode 100644 examples/multi_process/hotplug_mp/commands.h create mode 100644 examples/multi_process/hotplug_mp/commands.list delete mode 100644 examples/multi_process/simple_mp/mp_commands.h create mode 100644 examples/multi_process/simple_mp/mp_commands.list
--
2.39.2
RFC PATCH v2 1/5 buildtools/dpdk-cmdline-gen: generate boilerplate for simple cmds
Provide a script for application developers to quickly generate the boilerplate code necessary for using the cmdline library.
This initial version works only with commands using simple strings and numbers, but this is sufficient for many use-cases. Future extensions could, no doubt, expand support to expose more capabilities of the library.
Example of use:
The script takes an input file with a list of commands the user wants in the app, where the parameter variables are tagged with the type. For example:
$ cat commands.list list add <UINT16>x <UINT16>y echo <STRING>message add socket <STRING>path quit
When run through the script as "./dpdk-cmdline-gen.py commands.list", the output will be the contents of a header file with all the boilerplate necessary for a commandline instance with those commands.
If the flag --stubs is passed, an output header filename must also be passed, in which case both a header file with the definitions and a C file with function stubs in it is written to disk. The separation is so that the header file can be rewritten at any future point to add more commands, while the C file can be kept as-is and extended by the user with any additional functions needed.
--- buildtools/dpdk-cmdline-gen.py | 146 +++++++++++++++++++++++++++++++++ buildtools/meson.build | 7 ++ 2 files changed, 153 insertions(+) create mode 100755 buildtools/dpdk-cmdline-gen.py
buildtools/dpdk-cmdline-gen.py new file +146 -0
@@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# + +import sys +import os +import argparse + +PARSE_FN_PARAMS = "void *parsed_result, struct cmdline *cl, void *data" +PARSE_FN_BODY = """ + /* TODO: command action */ + RTE_SET_USED(parsed_result); + RTE_SET_USED(cl); + RTE_SET_USED(data); +""" + +def process_command(tokens, cfile): + name = [] + + if tokens[0].startswith('<'): + print("Error: each command must start with at least one literal string", + file=sys.stderr) + sys.exit(1) + for t in tokens: + if t.startswith('<'): + break; + name.append(t) + name = "_".join(name) + + result_struct = [] + initializers = [] + token_list = [] + for t in tokens: + if t.startswith('<'): + t_type, t_name = t[1:].split('>') + t_val = "NULL" + else: + t_type = "STRING" + t_name = t + t_val = f'"{t}"' + + if t_type == "STRING": + result_struct.append(f"\tcmdline_fixed_string_t {t_name};") + initializers.append(f"static cmdline_parse_token_string_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_STRING_INITIALIZER(struct cmd_{name}_result, {t_name}, {t_val});") + elif t_type in ['UINT8', 'UINT16', 'UINT32', 'UINT64', + 'INT8', 'INT16', 'INT32', 'INT64']: + result_struct.append(f"\t{t_type.lower()}_t {t_name};") + initializers.append(f"static cmdline_parse_token_num_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_NUM_INITIALIZER(struct cmd_{name}_result, {t_name}, RTE_{t_type});") + else: + print(f"Error: unknown token-type {t}", file=sys.stderr) + sys.exit(1) + token_list.append(f"cmd_{name}_{t_name}_tok") + + print(f"/* Auto-generated handling for command '{' '.join(tokens)}' */") + # output function prototype + func_sig = f"void\ncmd_{name}_parsed({PARSE_FN_PARAMS})" + print(f"extern {func_sig};\n") + # output function template if C file being written + if (cfile): + print(f"{func_sig}\n{{{PARSE_FN_BODY}}}\n", file=cfile) + # output result data structure + print(f"struct cmd_{name}_result {{\n" + + '\n'.join(result_struct) + + "\n};\n") + # output the initializer tokens + print("\n".join(initializers) + '\n') + # output the instance structure + print(f"static cmdline_parse_inst_t cmd_{name} = {{\n" + + f'\t.f = cmd_{name}_parsed,\n' + + f'\t.data = NULL,\n' + + f'\t.help_str = "",\n' + + f'\t.tokens = {{') + for t in token_list: + print(f"\t\t(void *)&{t},") + print("\t\tNULL\n" + + "\t}\n" + + "};\n") + + # return the instance structure name + return f"cmd_{name}" + +def process_commands(infile, hfile, cfile, ctxname): + instances = [] + + # redirect stdout to output the header, to save passing file= each print + old_sys_stdout = sys.stdout + sys.stdout = hfile + + print(f"/* File autogenerated by {sys.argv[0]} */") + print('#ifndef GENERATED_COMMANDS_H') + print('#define GENERATED_COMMANDS_H') + print("#include <rte_common.h>") + print("#include <cmdline.h>") + print("#include <cmdline_parse_string.h>") + print("#include <cmdline_parse_num.h>") + print("") + + for line in infile.readlines(): + if line.lstrip().startswith('#'): + continue + instances.append(process_command(line.strip().split(), cfile)) + + print(f'static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{') + for inst in instances: + print(f'\t&{inst},') + print('\tNULL') + print('};\n') + print('#endif /* GENERATED_COMMANDS_H */') + + sys.stdout = old_sys_stdout + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--stubs", action="store_true", + help="Produce C file with empty function stubs for each command") + ap.add_argument("--output-file", "-o", default="-", + help="Output header filename [default to stdout]") + ap.add_argument("--context-name", default="ctx", + help="Name given to the cmdline context variable in the output header [default=ctx]") + ap.add_argument("infile", type=argparse.FileType('r'), + help="File with list of commands") + args = ap.parse_args() + + if not args.stubs: + if args.output_file == '-': + process_commands(args.infile, sys.stdout, None, args.context_name) + else: + with open(args.output_file, "w") as hfile: + process_commands(args.infile, hfile, None, args.context_name) + else: + if not args.output_file.endswith('.h'): + print("Error: output filename must end with '.h' extension when creating stubs", + file=sys.stderr) + sys.exit(1) + + cfilename = args.output_file[:-2] + '.c' + with open(args.output_file, "w") as hfile: + with open(cfilename, "w") as cfile: + print(f"#include \"{args.output_file}\"\n", file=cfile) + process_commands(args.infile, hfile, cfile, args.context_name) + +if __name__ == "__main__": + main()
buildtools/meson.build +7 -0
@@ -19,6 +19,13 @@ get_cpu_count_cmd = py3 + files('get-cpu-count.py') get_numa_count_cmd = py3 + files('get-numa-count.py') get_test_suites_cmd = py3 + files('get-test-suites.py') has_hugepages_cmd = py3 + files('has-hugepages.py') +cmdline_gen_cmd = py3 + files('dpdk-cmdline-gen.py') + +# install any build tools that end-users might want also +install_data([ + 'dpdk-cmdline-gen.py', + ], + install_dir: 'bin') # select library and object file format pmdinfo = py3 + files('gen-pmdinfo-cfile.py') + [meson.current_build_dir()]
Signature · 1 line
2.39.2
RFC PATCH v2 2/5 examples/simple_mp: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/multi_process/simple_mp/Makefile | 10 +- examples/multi_process/simple_mp/meson.build | 9 ++ .../multi_process/simple_mp/mp_commands.c | 106 ++---------------- .../multi_process/simple_mp/mp_commands.h | 14 --- .../multi_process/simple_mp/mp_commands.list | 3 + 5 files changed, 29 insertions(+), 113 deletions(-) delete mode 100644 examples/multi_process/simple_mp/mp_commands.h create mode 100644 examples/multi_process/simple_mp/mp_commands.list
examples/multi_process/simple_mp/Makefile +7 -3
@@ -6,6 +6,7 @@ APP = simple_mp # all source are stored in SRCS-y SRCS-y := main.c mp_commands.c +SRC-DEPS := build/mp_commands.h PKGCONF ?= pkg-config
@@ -22,10 +23,13 @@ static: build/$(APP)-static ln -sf $(APP)-static build/$(APP) PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/mp_commands.h: mp_commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=simple_mp_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -36,10 +40,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
examples/multi_process/simple_mp/meson.build +9 -0
@@ -7,7 +7,16 @@ # DPDK instance, use 'make' allow_experimental_apis = true + +cmd_h = custom_target('commands_hdr', + output: 'mp_commands.h', + input: files('mp_commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=simple_mp_ctx', '@INPUT@'] +) + sources = files( 'mp_commands.c', 'main.c', ) +sources += cmd_h
examples/multi_process/simple_mp/mp_commands.c +10 -96
133 lines not on this page · raw message
examples/multi_process/simple_mp/mp_commands.h deleted +0 -14
@@ -1,14 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2010-2014 Intel Corporation -*/ - -#ifndef _SIMPLE_MP_COMMANDS_H_ -#define _SIMPLE_MP_COMMANDS_H_ - -extern struct rte_ring *send_ring; -extern struct rte_mempool *message_pool; -extern volatile int quit; - -extern cmdline_parse_ctx_t simple_mp_ctx[]; - -#endif /* _SIMPLE_MP_COMMANDS_H_ */
examples/multi_process/simple_mp/mp_commands.list new file +3 -0
@@ -0,0 +1,3 @@ +send <STRING>message +help +quit
--
2.39.2
RFC PATCH v2 3/5 examples/hotplug_mp: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/multi_process/hotplug_mp/Makefile | 10 +- examples/multi_process/hotplug_mp/commands.c | 147 ++---------------- examples/multi_process/hotplug_mp/commands.h | 10 -- .../multi_process/hotplug_mp/commands.list | 5 + examples/multi_process/hotplug_mp/meson.build | 9 ++ 5 files changed, 34 insertions(+), 147 deletions(-) delete mode 100644 examples/multi_process/hotplug_mp/commands.h create mode 100644 examples/multi_process/hotplug_mp/commands.list
examples/multi_process/hotplug_mp/Makefile +7 -3
@@ -6,6 +6,7 @@ APP = hotplug_mp # all source are stored in SRCS-y SRCS-y := main.c commands.c +SRC-DEPS := build/commands.h PKGCONF ?= pkg-config
@@ -22,10 +23,13 @@ static: build/$(APP)-static ln -sf $(APP)-static build/$(APP) PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -36,10 +40,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
examples/multi_process/hotplug_mp/commands.c +13 -134
189 lines not on this page · raw message
examples/multi_process/hotplug_mp/commands.h deleted +0 -10
@@ -1,10 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2018 Intel Corporation -*/ - -#ifndef _COMMANDS_H_ -#define _COMMANDS_H_ - -extern cmdline_parse_ctx_t main_ctx[]; - -#endif /* _COMMANDS_H_ */
examples/multi_process/hotplug_mp/commands.list new file +5 -0
@@ -0,0 +1,5 @@ +help +quit +list +attach <STRING>devargs +detach <STRING>devargs
examples/multi_process/hotplug_mp/meson.build +9 -0
@@ -7,7 +7,16 @@ # DPDK instance, use 'make' allow_experimental_apis = true + +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) + sources = files( 'commands.c', 'main.c', ) +sources += cmd_h
Signature · 1 line
2.39.2
RFC PATCH v2 4/5 buildtools/dpdk-cmdline-gen: add IP address support
In reply to Bruce RichardsonAdd support for apps to have IP addresses as command parameters
--- buildtools/dpdk-cmdline-gen.py | 5 +++++ 1 file changed, 5 insertions(+)
buildtools/dpdk-cmdline-gen.py +5 -0
@@ -49,6 +49,10 @@ def process_command(tokens, cfile): result_struct.append(f"\t{t_type.lower()}_t {t_name};") initializers.append(f"static cmdline_parse_token_num_t cmd_{name}_{t_name}_tok =\n" + f"\tTOKEN_NUM_INITIALIZER(struct cmd_{name}_result, {t_name}, RTE_{t_type});") + elif t_type in ['IP', 'IP_ADDR', 'IPADDR']: + result_struct.append(f"\tcmdline_ipaddr_t {t_name};") + initializers.append(f"cmdline_parse_token_ipaddr_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_IPV4_INITIALIZER(struct cmd_{name}_result, {t_name});") else: print(f"Error: unknown token-type {t}", file=sys.stderr) sys.exit(1)
@@ -96,6 +100,7 @@ def process_commands(infile, hfile, cfile, ctxname): print("#include <cmdline.h>") print("#include <cmdline_parse_string.h>") print("#include <cmdline_parse_num.h>") + print("#include <cmdline_parse_ipaddr.h>") print("") for line in infile.readlines():
Signature · 1 line
2.39.2
RFC PATCH v2 5/5 examples/bond: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/bond/Makefile | 10 ++- examples/bond/commands.list | 6 ++ examples/bond/main.c | 161 ++++-------------------------------- examples/bond/main.h | 10 --- examples/bond/meson.build | 8 ++ 5 files changed, 36 insertions(+), 159 deletions(-) create mode 100644 examples/bond/commands.list delete mode 100644 examples/bond/main.h
examples/bond/Makefile +7 -3
@@ -6,6 +6,7 @@ APP = bond_app # all source are stored in SRCS-y SRCS-y := main.c +SRC-DEPS := build/commands.h PKGCONF ?= pkg-config
@@ -24,10 +25,13 @@ static: build/$(APP)-static LDFLAGS += -lrte_net_bond PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -38,10 +42,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
examples/bond/commands.list new file +6 -0
@@ -0,0 +1,6 @@ +send <IP>ip +start +stop +show +help +quit
examples/bond/main.c +15 -146
218 lines not on this page · raw message
examples/bond/main.h deleted +0 -10
@@ -1,10 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2010-2015 Intel Corporation -*/ - -#ifndef _MAIN_H_ -#define _MAIN_H_ - -int main (int argc,char *argv[]); - -#endif /* ifndef _MAIN_H_ */
examples/bond/meson.build +8 -0
@@ -11,3 +11,11 @@ allow_experimental_apis = true sources = files( 'main.c', ) + +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) +sources += cmd_h
Signature · 1 line
2.39.2
v3 cover document and simplify use of cmdline
In reply to Bruce RichardsonThe DPDK commandline library is widely used by apps and examples within DPDK, but it is not documented in our programmers guide and it requires a lot of boilerplate code definitions in order to used. We can improve this situation by creating a simple python script to automatically generate the boilerplate from a list of commands.
This patchset contains a new documentation chapter on cmdline library, going through step-by-step how to add commands and create the necessary token lists and parse contexts.
Following that initial doc patch, the set then contains a boilerplate-generating script, as well as a set of three patches showing its use, by converting three examples to use the script instead of having the hard-coded boilerplate. Once the script is used, adding a new command becomes as simple as adding the desired command to the .list file, and then writing the required function which will be called for that command. No other boilerplate coding is necessary.
Script obviously does not cover the full range of capabilities of the commandline lib, but does cover the most used parts. The code-saving to each of the examples by auto-generating the boilerplate is significant, and probably more examples with commandlines can be converted over in future.
The "cmdline" example itself, is not converted over, as it should probably remain as a simple example of direct library use without the script.
V3:
* Added lots of documentation
* Added support for help text for each command
* Cleaned up script a little so it passes pycodestyle and most flake8 checks, when line-length is set to max 100.
* Removed RFC tag, as I consider this patchset stable enough for consideration in a release.
V2-RFC:
* Add support for IP addresses in commands
* Move to buildtools directory and make installable
* Convert 3 examples to use script, and eliminate their boilerplate
Bruce Richardson (5):
doc/prog_guide: new chapter on cmdline library
buildtools: script to generate cmdline boilerplate examples/simple_mp: auto-generate cmdline boilerplate examples/hotplug_mp: auto-generate cmdline boilerplate examples/bond: auto-generate cmdline boilerplate
app/test/commands.c | 2 + buildtools/dpdk-cmdline-gen.py | 167 +++++++ buildtools/meson.build | 7 + doc/guides/prog_guide/cmdline.rst | 466 ++++++++++++++++++ doc/guides/prog_guide/index.rst | 1 + examples/bond/Makefile | 12 +- examples/bond/commands.list | 6 + examples/bond/main.c | 161 +----- examples/bond/main.h | 10 - examples/bond/meson.build | 8 + examples/multi_process/hotplug_mp/Makefile | 12 +- examples/multi_process/hotplug_mp/commands.c | 147 +----- examples/multi_process/hotplug_mp/commands.h | 10 - .../multi_process/hotplug_mp/commands.list | 5 + examples/multi_process/hotplug_mp/meson.build | 9 + examples/multi_process/simple_mp/Makefile | 12 +- examples/multi_process/simple_mp/meson.build | 9 + .../multi_process/simple_mp/mp_commands.c | 106 +--- .../multi_process/simple_mp/mp_commands.h | 14 - .../multi_process/simple_mp/mp_commands.list | 3 + 20 files changed, 745 insertions(+), 422 deletions(-) create mode 100755 buildtools/dpdk-cmdline-gen.py create mode 100644 doc/guides/prog_guide/cmdline.rst create mode 100644 examples/bond/commands.list delete mode 100644 examples/bond/main.h delete mode 100644 examples/multi_process/hotplug_mp/commands.h create mode 100644 examples/multi_process/hotplug_mp/commands.list delete mode 100644 examples/multi_process/simple_mp/mp_commands.h create mode 100644 examples/multi_process/simple_mp/mp_commands.list
--
2.39.2
PATCH v3 1/5 doc/prog_guide: new chapter on cmdline library
The cmdline library was not documented in our programmers guide, so add a new chapter on it. This chapter covers step-by-step how to use the library, rather than focusing on the library internals. This complements the existing cmdline example app document, providing more details on the process of using the library.
--- app/test/commands.c | 2 + doc/guides/prog_guide/cmdline.rst | 337 ++++++++++++++++++++++++++++++ doc/guides/prog_guide/index.rst | 1 + 3 files changed, 340 insertions(+) create mode 100644 doc/guides/prog_guide/cmdline.rst
app/test/commands.c +2 -0
@@ -108,6 +108,7 @@ dump_struct_sizes(void)#undef DUMP_SIZE } +/* Add the dump_* tests cases 8< */ static void cmd_dump_parsed (void *parsed_result, __rte_unused struct cmdline *cl, __rte_unused void *data)
@@ -155,6 +156,7 @@ cmdline_parse_inst_t cmd_dump = { NULL, }, }; +/* >8 End of add the dump_* tests cases */ /****************/
doc/guides/prog_guide/cmdline.rst new file +337 -0
337 lines not on this page · raw message
doc/guides/prog_guide/index.rst +1 -0
@@ -13,6 +13,7 @@ Programmer's Guide source_org env_abstraction_layer log_lib + cmdline service_cores trace_lib rcu_lib
Signature · 1 line
2.39.2
PATCH v3 2/5 buildtools: script to generate cmdline boilerplate
In reply to Bruce RichardsonProvide a "dpdk-cmdline-gen.py" script for application developers to quickly generate the boilerplate code necessary for using the cmdline library.
Example of use:
The script takes an input file with a list of commands the user wants in the app, where the parameter variables are tagged with the type. For example:
$ cat commands.list list add <UINT16>x <UINT16>y echo <STRING>message add socket <STRING>path quit
When run through the script as "./dpdk-cmdline-gen.py commands.list", the output will be the contents of a header file with all the boilerplate necessary for a commandline instance with those commands.
If the flag --stubs is passed, an output header filename must also be passed, in which case both a header file with the definitions and a C file with function stubs in it is written to disk. The separation is so that the header file can be rewritten at any future point to add more commands, while the C file can be kept as-is and extended by the user with any additional functions needed.
--- buildtools/dpdk-cmdline-gen.py | 167 ++++++++++++++++++++++++++++++ buildtools/meson.build | 7 ++ doc/guides/prog_guide/cmdline.rst | 131 ++++++++++++++++++++++- 3 files changed, 304 insertions(+), 1 deletion(-) create mode 100755 buildtools/dpdk-cmdline-gen.py
buildtools/dpdk-cmdline-gen.py new file +167 -0
@@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +"""Script to automatically generate boilerplate for using DPDK cmdline library.""" + +import argparse +import sys + +PARSE_FN_PARAMS = 'void *parsed_result, struct cmdline *cl, void *data' +PARSE_FN_BODY = """ + /* TODO: command action */ + RTE_SET_USED(parsed_result); + RTE_SET_USED(cl); + RTE_SET_USED(data); +""" + + +def process_command(tokens, cfile, comment): + """Generate the structures and definitions for a single command.""" + name = [] + + if tokens[0].startswith('<'): + print('Error: each command must start with at least one literal string', file=sys.stderr) + sys.exit(1) + for t in tokens: + if t.startswith('<'): + break + name.append(t) + name = '_'.join(name) + + result_struct = [] + initializers = [] + token_list = [] + for t in tokens: + if t.startswith('<'): + t_type, t_name = t[1:].split('>') + t_val = 'NULL' + else: + t_type = 'STRING' + t_name = t + t_val = f'"{t}"' + + if t_type == 'STRING': + result_struct.append(f'\tcmdline_fixed_string_t {t_name};') + initializers.append( + f'static cmdline_parse_token_string_t cmd_{name}_{t_name}_tok =\n' + + f'\tTOKEN_STRING_INITIALIZER(struct cmd_{name}_result, {t_name}, {t_val});') + elif t_type in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'INT8', 'INT16', 'INT32', 'INT64']: + result_struct.append(f'\t{t_type.lower()}_t {t_name};') + initializers.append( + f'static cmdline_parse_token_num_t cmd_{name}_{t_name}_tok =\n' + + f'\tTOKEN_NUM_INITIALIZER(struct cmd_{name}_result, {t_name}, RTE_{t_type});') + elif t_type in ['IP', 'IP_ADDR', 'IPADDR']: + result_struct.append(f'\tcmdline_ipaddr_t {t_name};') + initializers.append( + f'cmdline_parse_token_ipaddr_t cmd_{name}_{t_name}_tok =\n' + + f'\tTOKEN_IPV4_INITIALIZER(struct cmd_{name}_result, {t_name});') + else: + print(f'Error: unknown token-type {t}', file=sys.stderr) + sys.exit(1) + token_list.append(f'cmd_{name}_{t_name}_tok') + + print(f'/* Auto-generated handling for command "{" ".join(tokens)}" */') + # output function prototype + func_sig = f'void\ncmd_{name}_parsed({PARSE_FN_PARAMS})' + print(f'extern {func_sig};\n') + # output function template if C file being written + if (cfile): + print(f'{func_sig}\n{{{PARSE_FN_BODY}}}\n', file=cfile) + # output result data structure + print( + f'struct cmd_{name}_result {{\n' + + '\n'.join(result_struct) + + '\n};\n') + # output the initializer tokens + print('\n'.join(initializers) + '\n') + # output the instance structure + print( + f'static cmdline_parse_inst_t cmd_{name} = {{\n' + + f'\t.f = cmd_{name}_parsed,\n' + + '\t.data = NULL,\n' + + f'\t.help_str = "{comment}",\n' + + '\t.tokens = {') + for t in token_list: + print(f'\t\t(void *)&{t},') + print('\t\tNULL\n' + '\t}\n' + '};\n') + + # return the instance structure name + return f'cmd_{name}' + + +def process_commands(infile, hfile, cfile, ctxname): + """Generate boilerplate output for a list of commands from infile.""" + instances = [] + + # redirect stdout to output the header, to save passing file= each print + old_sys_stdout = sys.stdout + sys.stdout = hfile + + print(f'/* File autogenerated by {sys.argv[0]} */') + print('#ifndef GENERATED_COMMANDS_H') + print('#define GENERATED_COMMANDS_H') + print('#include <rte_common.h>') + print('#include <cmdline.h>') + print('#include <cmdline_parse_string.h>') + print('#include <cmdline_parse_num.h>') + print('#include <cmdline_parse_ipaddr.h>') + print('') + + for line in infile.readlines(): + if line.lstrip().startswith('#'): + continue + if '#' not in line: + line = line + '#' # ensure split always works, even if no help text + tokens, comment = line.split('#', 1) + instances.append(process_command(tokens.strip().split(), cfile, comment.strip())) + + print(f'static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{') + for inst in instances: + print(f'\t&{inst},') + print('\tNULL') + print('};\n') + print('#endif /* GENERATED_COMMANDS_H */') + + sys.stdout = old_sys_stdout + + +def main(): + """Application main entry point.""" + ap = argparse.ArgumentParser() + ap.add_argument( + '--stubs', action='store_true', + help='Produce C file with empty function stubs for each command') + ap.add_argument( + '--output-file', '-o', default='-', + help='Output header filename [default to stdout]') + ap.add_argument( + '--context-name', default='ctx', + help='Name given to the cmdline context variable in the output header [default=ctx]') + ap.add_argument( + 'infile', type=argparse.FileType('r'), + help='File with list of commands') + args = ap.parse_args() + + if not args.stubs: + if args.output_file == '-': + process_commands(args.infile, sys.stdout, None, args.context_name) + else: + with open(args.output_file, 'w') as hfile: + process_commands(args.infile, hfile, None, args.context_name) + else: + if not args.output_file.endswith('.h'): + print( + 'Error: output filename must end with ".h" extension when creating stubs', + file=sys.stderr) + sys.exit(1) + + cfilename = args.output_file[:-2] + '.c' + with open(args.output_file, 'w') as hfile: + with open(cfilename, 'w') as cfile: + print(f'#include "{args.output_file}"\n', file=cfile) + process_commands(args.infile, hfile, cfile, args.context_name) + + +if __name__ == '__main__': + main()
buildtools/meson.build +7 -0
@@ -19,6 +19,13 @@ get_cpu_count_cmd = py3 + files('get-cpu-count.py') get_numa_count_cmd = py3 + files('get-numa-count.py') get_test_suites_cmd = py3 + files('get-test-suites.py') has_hugepages_cmd = py3 + files('has-hugepages.py') +cmdline_gen_cmd = py3 + files('dpdk-cmdline-gen.py') + +# install any build tools that end-users might want also +install_data([ + 'dpdk-cmdline-gen.py', + ], + install_dir: 'bin') # select library and object file format pmdinfo = py3 + files('gen-pmdinfo-cfile.py') + [meson.current_build_dir()]
doc/guides/prog_guide/cmdline.rst +130 -1
137 lines not on this page · raw message
Signature · 1 line
2.39.2
Re: [PATCH v3 2/5] buildtools: script to generate cmdline boilerplate
Bruce Richardson, Oct 11, 2023 at 15:33:
Quoted 27 lines
Provide a "
dpdk-cmdline-gen.py" script for application developers to quickly generate the boilerplate code necessary for using the cmdline library.Example of use:
The script takes an input file with a list of commands the user wants in the app, where the parameter variables are tagged with the type. For example:$ cat commands.list list add <UINT16>x <UINT16>y echo <STRING>message add socket <STRING>path quitWhen run through the script as "./dpdk-cmdline-gen.py commands.list", the output will be the contents of a header file with all the boilerplate necessary for a commandline instance with those commands.
If the flag --stubs is passed, an output header filename must also be passed, in which case both a header file with the definitions and a C file with function stubs in it is written to disk. The separation is so that the header file can be rewritten at any future point to add more commands, while the C file can be kept as-is and extended by the user with any additional functions needed.
Quoted 2 lines
Signed-off-by Bruce Richardson <[email protected]>---
Hi Bruce,
this is a nice addition, I have a few python style remarks below.
In general, I would advise formatting your code with black[1] to avoid debates over coding style. It makes all code homogeneous and lets you focus on more important things :)
Quoted 12 lines
buildtools/dpdk-cmdline-gen.py | 167 ++++++++++++++++++++++++++++++ buildtools/meson.build | 7 ++ doc/guides/prog_guide/cmdline.rst | 131 ++++++++++++++++++++++- 3 files changed, 304 insertions(+), 1 deletion(-) create mode 100755 buildtools/dpdk-cmdline-gen.pybuildtools/dpdk-cmdline-gen.py new file +0
-0
buildtools/dpdk-cmdline-gen.py line 5
Quoted 5 lines
buildtools/dpdk-cmdline-gen.py new file +5
-0@@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +"""Script to automatically generate boilerplate for using DPDK cmdline library."""
Multi line (or single line) doc strings are usually formatted as follows:
"""
Script to automatically generate boilerplate for using DPDK cmdline library. """
It makes adding new lines more readable and saves a bit of characters per line.
Quoted 10 lines
buildtools/dpdk-cmdline-gen.py new file +10
-0+ +import argparse +import sys + +PARSE_FN_PARAMS = 'void *parsed_result, struct cmdline *cl, void *data' +PARSE_FN_BODY = """ + /* TODO: command action */ + RTE_SET_USED(parsed_result); + RTE_SET_USED(cl); + RTE_SET_USED(data);
buildtools/dpdk-cmdline-gen.py line 25
Quoted 10 lines
buildtools/dpdk-cmdline-gen.py new file +10
-0+""" + + +def process_command(tokens, cfile, comment): + """Generate the structures and definitions for a single command.""" + name = [] + + if tokens[0].startswith('<'): + print('Error: each command must start with at least one literal string', file=sys.stderr) + sys.exit(1)
It would be better to raise an exception here and handle it in main() for error reporting.
Quoted 64 lines
buildtools/dpdk-cmdline-gen.py new file +64
-0+ for t in tokens: + if t.startswith('<'): + break + name.append(t) + name = '_'.join(name) + + result_struct = [] + initializers = [] + token_list = [] + for t in tokens: + if t.startswith('<'): + t_type, t_name = t[1:].split('>') + t_val = 'NULL' + else: + t_type = 'STRING' + t_name = t + t_val = f'"{t}"' + + if t_type == 'STRING': + result_struct.append(f'\tcmdline_fixed_string_t {t_name};') + initializers.append( + f'static cmdline_parse_token_string_t cmd_{name}_{t_name}_tok =\n' + + f'\tTOKEN_STRING_INITIALIZER(struct cmd_{name}_result, {t_name}, {t_val});') + elif t_type in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'INT8', 'INT16', 'INT32', 'INT64']: + result_struct.append(f'\t{t_type.lower()}_t {t_name};') + initializers.append( + f'static cmdline_parse_token_num_t cmd_{name}_{t_name}_tok =\n' + + f'\tTOKEN_NUM_INITIALIZER(struct cmd_{name}_result, {t_name}, RTE_{t_type});') + elif t_type in ['IP', 'IP_ADDR', 'IPADDR']: + result_struct.append(f'\tcmdline_ipaddr_t {t_name};') + initializers.append( + f'cmdline_parse_token_ipaddr_t cmd_{name}_{t_name}_tok =\n' + + f'\tTOKEN_IPV4_INITIALIZER(struct cmd_{name}_result, {t_name});') + else: + print(f'Error: unknown token-type {t}', file=sys.stderr) + sys.exit(1) + token_list.append(f'cmd_{name}_{t_name}_tok') + + print(f'/* Auto-generated handling for command "{" ".join(tokens)}" */') + # output function prototype + func_sig = f'void\ncmd_{name}_parsed({PARSE_FN_PARAMS})' + print(f'extern {func_sig};\n') + # output function template if C file being written + if (cfile): + print(f'{func_sig}\n{{{PARSE_FN_BODY}}}\n', file=cfile) + # output result data structure + print( + f'struct cmd_{name}_result {{\n' + + '\n'.join(result_struct) + + '\n};\n') + # output the initializer tokens + print('\n'.join(initializers) + '\n') + # output the instance structure + print( + f'static cmdline_parse_inst_t cmd_{name} = {{\n' + + f'\t.f = cmd_{name}_parsed,\n' + + '\t.data = NULL,\n' + + f'\t.help_str = "{comment}",\n' + + '\t.tokens = {') + for t in token_list: + print(f'\t\t(void *)&{t},') + print('\t\tNULL\n' + '\t}\n' + '};\n') + + # return the instance structure name
buildtools/dpdk-cmdline-gen.py line 99
Quoted 10 lines
buildtools/dpdk-cmdline-gen.py new file +10
-0+ return f'cmd_{name}' + + +def process_commands(infile, hfile, cfile, ctxname): + """Generate boilerplate output for a list of commands from infile.""" + instances = [] + + # redirect stdout to output the header, to save passing file= each print + old_sys_stdout = sys.stdout + sys.stdout = hfile
Why not use hfile.write()?
I think the main issue here is to use print() in process_commands(). It would probably be cleaner to have process_command() return a list of lines and print them in this function.
buildtools/dpdk-cmdline-gen.py line 109
Quoted 10 lines
buildtools/dpdk-cmdline-gen.py new file +10
-0+ + print(f'/* File autogenerated by {sys.argv[0]} */') + print('#ifndef GENERATED_COMMANDS_H') + print('#define GENERATED_COMMANDS_H') + print('#include <rte_common.h>') + print('#include <cmdline.h>') + print('#include <cmdline_parse_string.h>') + print('#include <cmdline_parse_num.h>') + print('#include <cmdline_parse_ipaddr.h>') + print('')
You can use a multi-line f-string here with a single print/write.
hfile.write(f"""/* File autogenerated by {sys.argv[0]} */
#ifndef GENERATED_COMMANDS_H
#define GENERATED_COMMANDS_H
#include <rte_common.h>
#include <cmdline.h>
#include <cmdline_parse_string.h>
#include <cmdline_parse_num.h>
#include <cmdline_parse_ipaddr.h>
""")
buildtools/dpdk-cmdline-gen.py line 117
Quoted 8 lines
buildtools/dpdk-cmdline-gen.py new file +8
-0+ + for line in infile.readlines(): + if line.lstrip().startswith('#'): + continue + if '#' not in line: + line = line + '#' # ensure split always works, even if no help text + tokens, comment = line.split('#', 1) + instances.append(process_command(tokens.strip().split(), cfile, comment.strip()))
If process_command returns a name and a list of lines, that could be transformed as:
name, lines = process_command(tokens.strip().split(), cfile, comment.strip()) instances.append(name)
hfile.write("\n".join(lines) + "\n")
buildtools/dpdk-cmdline-gen.py line 124
Quoted 7 lines
buildtools/dpdk-cmdline-gen.py new file +7
-0+ + print(f'static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{') + for inst in instances: + print(f'\t&{inst},') + print('\tNULL') + print('};\n') + print('#endif /* GENERATED_COMMANDS_H */')
also multi line print here:
hfile.write("""\tNULL
};
#endif /* GENERATED_COMMANDS_H */
""")
buildtools/dpdk-cmdline-gen.py line 131
Quoted 7 lines
buildtools/dpdk-cmdline-gen.py new file +7
-0+ + sys.stdout = old_sys_stdout + + +def main(): + """Application main entry point.""" + ap = argparse.ArgumentParser()
Nit to have a nice description of the command with --help:
ap = argparse.ArgumentParser(description=__doc__)
Quoted 16 lines
buildtools/dpdk-cmdline-gen.py new file +16
-0+ ap.add_argument( + '--stubs', action='store_true', + help='Produce C file with empty function stubs for each command') + ap.add_argument( + '--output-file', '-o', default='-', + help='Output header filename [default to stdout]') + ap.add_argument( + '--context-name', default='ctx', + help='Name given to the cmdline context variable in the output header [default=ctx]') + ap.add_argument( + 'infile', type=argparse.FileType('r'), + help='File with list of commands') + args = ap.parse_args() + + if not args.stubs: + if args.output_file == '-':
buildtools/dpdk-cmdline-gen.py line 157
Quoted 10 lines
buildtools/dpdk-cmdline-gen.py new file +10
-0+ process_commands(args.infile, sys.stdout, None, args.context_name) + else: + with open(args.output_file, 'w') as hfile: + process_commands(args.infile, hfile, None, args.context_name) + else: + if not args.output_file.endswith('.h'): + print( + 'Error: output filename must end with ".h" extension when creating stubs', + file=sys.stderr) + sys.exit(1)
You can replace print to stderr + exit with:
ap.error("-o/--output-file: must end with .h extension when creating stubs")
buildtools/dpdk-cmdline-gen.py line 167
Quoted 10 lines
buildtools/dpdk-cmdline-gen.py new file +10
-0+ + cfilename = args.output_file[:-2] + '.c' + with open(args.output_file, 'w') as hfile: + with open(cfilename, 'w') as cfile: + print(f'#include "{args.output_file}"\n', file=cfile) + process_commands(args.infile, hfile, cfile, args.context_name) + + +if __name__ == '__main__': + main()
I'll stop here ;) Thanks!
Re: [PATCH v3 2/5] buildtools: script to generate cmdline boilerplate
Quoted 31 lines · Robin Jarry
Bruce Richardson, Oct 11, 2023 at 15:33:
Quoted 27 lines
Provide a "
dpdk-cmdline-gen.py" script for application developers to quickly generate the boilerplate code necessary for using the cmdline library.Example of use:
The script takes an input file with a list of commands the user wants in the app, where the parameter variables are tagged with the type. For example:$ cat commands.list list add <UINT16>x <UINT16>y echo <STRING>message add socket <STRING>path quitWhen run through the script as "./dpdk-cmdline-gen.py commands.list", the output will be the contents of a header file with all the boilerplate necessary for a commandline instance with those commands.
If the flag --stubs is passed, an output header filename must also be passed, in which case both a header file with the definitions and a C file with function stubs in it is written to disk. The separation is so that the header file can be rewritten at any future point to add more commands, while the C file can be kept as-is and extended by the user with any additional functions needed.
Quoted 2 lines
Signed-off-by Bruce Richardson <[email protected]>---
Quoted 8 lines
Hi Bruce,
this is a nice addition, I have a few python style remarks below.
In general, I would advise formatting your code with black[1] to avoid debates over coding style. It makes all code homogeneous and lets you focus on more important things :)
Thanks for the feedback. I'll look into black.
Quoted 20 lines
Quoted 12 lines
buildtools/dpdk-cmdline-gen.py | 167 ++++++++++++++++++++++++++++++ buildtools/meson.build | 7 ++ doc/guides/prog_guide/cmdline.rst | 131 ++++++++++++++++++++++- 3 files changed, 304 insertions(+), 1 deletion(-) create mode 100755 buildtools/dpdk-cmdline-gen.pybuildtools/dpdk-cmdline-gen.py new file +0
-0buildtools/dpdk-cmdline-gen.py line 5
Quoted 5 lines
buildtools/dpdk-cmdline-gen.py new file +5
-0@@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +"""Script to automatically generate boilerplate for using DPDK cmdline library."""Multi line (or single line) doc strings are usually formatted as follows:
Quoted 7 lines
"""
Script to automatically generate boilerplate for using DPDK cmdline library. """It makes adding new lines more readable and saves a bit of characters per line.
Sure.
Quoted 15 lines
Quoted 15 lines
buildtools/dpdk-cmdline-gen.py new file +15
-0+ +import argparse +import sys + +PARSE_FN_PARAMS = 'void *parsed_result, struct cmdline *cl, void *data' +PARSE_FN_BODY = """ + /* TODO: command action */ + RTE_SET_USED(parsed_result); + RTE_SET_USED(cl); + RTE_SET_USED(data); +""" + + +def process_command(tokens, cfile, comment): + """Generate the structures and definitions for a single command."""
Quoted 9 lines
buildtools/dpdk-cmdline-gen.py line 25
Quoted 5 lines
buildtools/dpdk-cmdline-gen.py new file +5
-0+ name = [] + + if tokens[0].startswith('<'): + print('Error: each command must start with at least one literal string', file=sys.stderr) + sys.exit(1)It would be better to raise an exception here and handle it in
main()for error reporting.
I'll look into that. I probably should include the offending line/token in the error report too.
Quoted 77 lines
Quoted 64 lines
buildtools/dpdk-cmdline-gen.py new file +64
-0+ for t in tokens: + if t.startswith('<'): + break + name.append(t) + name = '_'.join(name) + + result_struct = [] + initializers = [] + token_list = [] + for t in tokens: + if t.startswith('<'): + t_type, t_name = t[1:].split('>') + t_val = 'NULL' + else: + t_type = 'STRING' + t_name = t + t_val = f'"{t}"' + + if t_type == 'STRING': + result_struct.append(f'\tcmdline_fixed_string_t {t_name};') + initializers.append( + f'static cmdline_parse_token_string_t cmd_{name}_{t_name}_tok =\n' + + f'\tTOKEN_STRING_INITIALIZER(struct cmd_{name}_result, {t_name}, {t_val});') + elif t_type in ['UINT8', 'UINT16', 'UINT32', 'UINT64', 'INT8', 'INT16', 'INT32', 'INT64']: + result_struct.append(f'\t{t_type.lower()}_t {t_name};') + initializers.append( + f'static cmdline_parse_token_num_t cmd_{name}_{t_name}_tok =\n' + + f'\tTOKEN_NUM_INITIALIZER(struct cmd_{name}_result, {t_name}, RTE_{t_type});') + elif t_type in ['IP', 'IP_ADDR', 'IPADDR']: + result_struct.append(f'\tcmdline_ipaddr_t {t_name};') + initializers.append( + f'cmdline_parse_token_ipaddr_t cmd_{name}_{t_name}_tok =\n' + + f'\tTOKEN_IPV4_INITIALIZER(struct cmd_{name}_result, {t_name});') + else: + print(f'Error: unknown token-type {t}', file=sys.stderr) + sys.exit(1) + token_list.append(f'cmd_{name}_{t_name}_tok') + + print(f'/* Auto-generated handling for command "{" ".join(tokens)}" */') + # output function prototype + func_sig = f'void\ncmd_{name}_parsed({PARSE_FN_PARAMS})' + print(f'extern {func_sig};\n') + # output function template if C file being written + if (cfile): + print(f'{func_sig}\n{{{PARSE_FN_BODY}}}\n', file=cfile) + # output result data structure + print( + f'struct cmd_{name}_result {{\n' + + '\n'.join(result_struct) + + '\n};\n') + # output the initializer tokens + print('\n'.join(initializers) + '\n') + # output the instance structure + print( + f'static cmdline_parse_inst_t cmd_{name} = {{\n' + + f'\t.f = cmd_{name}_parsed,\n' + + '\t.data = NULL,\n' + + f'\t.help_str = "{comment}",\n' + + '\t.tokens = {') + for t in token_list: + print(f'\t\t(void *)&{t},') + print('\t\tNULL\n' + '\t}\n' + '};\n') + + # return the instance structure namebuildtools/dpdk-cmdline-gen.py line 99
Quoted 10 lines
buildtools/dpdk-cmdline-gen.py new file +10
-0+ return f'cmd_{name}' + + +def process_commands(infile, hfile, cfile, ctxname): + """Generate boilerplate output for a list of commands from infile.""" + instances = [] + + # redirect stdout to output the header, to save passing file= each print + old_sys_stdout = sys.stdout + sys.stdout = hfileWhy not use
hfile.write()?
Quoted 4 lines
I think the main issue here is to use
print()inprocess_commands(). It would probably be cleaner to haveprocess_command()return a list of lines and print them in this function.
Good idea, let me look into that. Just using print was shorter than hfile.write, and I felt it would save me some line-breaking.
Quoted 17 lines
buildtools/dpdk-cmdline-gen.py line 109
Quoted 10 lines
buildtools/dpdk-cmdline-gen.py new file +10
-0+ + print(f'/* File autogenerated by {sys.argv[0]} */') + print('#ifndef GENERATED_COMMANDS_H') + print('#define GENERATED_COMMANDS_H') + print('#include <rte_common.h>') + print('#include <cmdline.h>') + print('#include <cmdline_parse_string.h>') + print('#include <cmdline_parse_num.h>') + print('#include <cmdline_parse_ipaddr.h>') + print('')You can use a multi-line f-string here with a single print/write.
hfile.write(f"""/* File autogenerated by {sys.argv[0]} */#ifndef
GENERATED_COMMANDS_H
#defineGENERATED_COMMANDS_H
Quoted 8 lines
#include <
rte_common.h>
#include <cmdline.h>
#include <cmdline_parse_string.h>
#include <cmdline_parse_num.h>
#include <cmdline_parse_ipaddr.h>""")
Yes, I was aware of that. However, I deliberately didn't use it, because the indentation looks completely wrong with it (at least to my eyes). I really don't like having each line start at column zero in the middle of a block of code.
Quoted 9 lines
buildtools/dpdk-cmdline-gen.py line 117
Quoted 8 lines
buildtools/dpdk-cmdline-gen.py new file +8
-0+ + for line in infile.readlines(): + if line.lstrip().startswith('#'): + continue + if '#' not in line: + line = line + '#' # ensure split always works, even if no help text + tokens, comment = line.split('#', 1) + instances.append(process_command(tokens.strip().split(), cfile, comment.strip()))
Quoted 7 lines
If
process_commandreturns a name and a list of lines, that could be transformed as:name, lines =
process_command(tokens.strip().split(), cfile, comment.strip())instances.append(name)
hfile.write("\n".join(lines) + "\n")
Will investigate
Quoted 8 lines
buildtools/dpdk-cmdline-gen.py line 124
Quoted 7 lines
buildtools/dpdk-cmdline-gen.py new file +7
-0+ + print(f'static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{') + for inst in instances: + print(f'\t&{inst},') + print('\tNULL') + print('};\n') + print('#endif /* GENERATED_COMMANDS_H */')
Quoted 7 lines
also multi line print here:
hfile.write("""\tNULL
};
#endif /*GENERATED_COMMANDS_H*/
""")
As above, I didn't like the non-indented nature of it.
Quoted 39 lines
buildtools/dpdk-cmdline-gen.py line 131
Quoted 7 lines
buildtools/dpdk-cmdline-gen.py new file +7
-0+ + sys.stdout = old_sys_stdout + + +def main(): + """Application main entry point.""" + ap = argparse.ArgumentParser()Nit to have a nice description of the command with --help:
ap =
argparse.ArgumentParser(description=__doc__)Quoted 16 lines
buildtools/dpdk-cmdline-gen.py new file +16
-0+ ap.add_argument( + '--stubs', action='store_true', + help='Produce C file with empty function stubs for each command') + ap.add_argument( + '--output-file', '-o', default='-', + help='Output header filename [default to stdout]') + ap.add_argument( + '--context-name', default='ctx', + help='Name given to the cmdline context variable in the output header [default=ctx]') + ap.add_argument( + 'infile', type=argparse.FileType('r'), + help='File with list of commands') + args = ap.parse_args() + + if not args.stubs: + if args.output_file == '-':buildtools/dpdk-cmdline-gen.py line 157
Quoted 10 lines
buildtools/dpdk-cmdline-gen.py new file +10
-0+ process_commands(args.infile, sys.stdout, None, args.context_name) + else: + with open(args.output_file, 'w') as hfile: + process_commands(args.infile, hfile, None, args.context_name) + else: + if not args.output_file.endswith('.h'): + print( + 'Error: output filename must end with ".h" extension when creating stubs', + file=sys.stderr) + sys.exit(1)
Quoted 4 lines
You can replace print to stderr + exit with:
ap.error("-o/--output-file: must end with .h extension when creating stubs")
Ack.
Quoted 13 lines
buildtools/dpdk-cmdline-gen.py line 167
Quoted 10 lines
buildtools/dpdk-cmdline-gen.py new file +10
-0+ + cfilename = args.output_file[:-2] + '.c' + with open(args.output_file, 'w') as hfile: + with open(cfilename, 'w') as cfile: + print(f'#include "{args.output_file}"\n', file=cfile) + process_commands(args.infile, hfile, cfile, args.context_name) + + +if __name__ == '__main__': + main()I'll stop here ;) Thanks!
PATCH v3 3/5 examples/simple_mp: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/multi_process/simple_mp/Makefile | 12 +- examples/multi_process/simple_mp/meson.build | 9 ++ .../multi_process/simple_mp/mp_commands.c | 106 ++---------------- .../multi_process/simple_mp/mp_commands.h | 14 --- .../multi_process/simple_mp/mp_commands.list | 3 + 5 files changed, 30 insertions(+), 114 deletions(-) delete mode 100644 examples/multi_process/simple_mp/mp_commands.h create mode 100644 examples/multi_process/simple_mp/mp_commands.list
examples/multi_process/simple_mp/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = simple_mp # all source are stored in SRCS-y SRCS-y := main.c mp_commands.c +SRC-DEPS := build/mp_commands.h PKGCONF ?= pkg-config
@@ -22,10 +23,13 @@ static: build/$(APP)-static ln -sf $(APP)-static build/$(APP) PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/mp_commands.h: mp_commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=simple_mp_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -36,10 +40,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -47,5 +51,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/mp_commands.h test -d build && rmdir -p build || true
examples/multi_process/simple_mp/meson.build +9 -0
@@ -7,7 +7,16 @@ # DPDK instance, use 'make' allow_experimental_apis = true + +cmd_h = custom_target('commands_hdr', + output: 'mp_commands.h', + input: files('mp_commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=simple_mp_ctx', '@INPUT@'] +) + sources = files( 'mp_commands.c', 'main.c', ) +sources += cmd_h
examples/multi_process/simple_mp/mp_commands.c +10 -96
133 lines not on this page · raw message
examples/multi_process/simple_mp/mp_commands.h deleted +0 -14
@@ -1,14 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2010-2014 Intel Corporation -*/ - -#ifndef _SIMPLE_MP_COMMANDS_H_ -#define _SIMPLE_MP_COMMANDS_H_ - -extern struct rte_ring *send_ring; -extern struct rte_mempool *message_pool; -extern volatile int quit; - -extern cmdline_parse_ctx_t simple_mp_ctx[]; - -#endif /* _SIMPLE_MP_COMMANDS_H_ */
examples/multi_process/simple_mp/mp_commands.list new file +3 -0
@@ -0,0 +1,3 @@ +send <STRING>message # send a string to another process +help # show help +quit # close the application
Signature · 1 line
2.39.2
PATCH v3 4/5 examples/hotplug_mp: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/multi_process/hotplug_mp/Makefile | 12 +- examples/multi_process/hotplug_mp/commands.c | 147 ++---------------- examples/multi_process/hotplug_mp/commands.h | 10 -- .../multi_process/hotplug_mp/commands.list | 5 + examples/multi_process/hotplug_mp/meson.build | 9 ++ 5 files changed, 35 insertions(+), 148 deletions(-) delete mode 100644 examples/multi_process/hotplug_mp/commands.h create mode 100644 examples/multi_process/hotplug_mp/commands.list
examples/multi_process/hotplug_mp/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = hotplug_mp # all source are stored in SRCS-y SRCS-y := main.c commands.c +SRC-DEPS := build/commands.h PKGCONF ?= pkg-config
@@ -22,10 +23,13 @@ static: build/$(APP)-static ln -sf $(APP)-static build/$(APP) PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -36,10 +40,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -47,5 +51,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/commands.h test -d build && rmdir -p build || true
examples/multi_process/hotplug_mp/commands.c +13 -134
189 lines not on this page · raw message
examples/multi_process/hotplug_mp/commands.h deleted +0 -10
@@ -1,10 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2018 Intel Corporation -*/ - -#ifndef _COMMANDS_H_ -#define _COMMANDS_H_ - -extern cmdline_parse_ctx_t main_ctx[]; - -#endif /* _COMMANDS_H_ */
examples/multi_process/hotplug_mp/commands.list new file +5 -0
@@ -0,0 +1,5 @@ +attach <STRING>devargs # attach a device +detach <STRING>devargs # detach a device +list # list all devices +help # show help +quit # quit
examples/multi_process/hotplug_mp/meson.build +9 -0
@@ -7,7 +7,16 @@ # DPDK instance, use 'make' allow_experimental_apis = true + +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) + sources = files( 'commands.c', 'main.c', ) +sources += cmd_h
Signature · 1 line
2.39.2
PATCH v3 5/5 examples/bond: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
---
Note: the original help text on some of the commands in this example
were not useful "this command do not handle any arguments". Therefore, when converting over to the command script, the per-command help info has been updated with reference to the code rather than a literal transfer of the existing help text, as was done with the previous 2 example apps.
--- examples/bond/Makefile | 12 ++- examples/bond/commands.list | 6 ++ examples/bond/main.c | 161 ++++-------------------------------- examples/bond/main.h | 10 --- examples/bond/meson.build | 8 ++ 5 files changed, 37 insertions(+), 160 deletions(-) create mode 100644 examples/bond/commands.list delete mode 100644 examples/bond/main.h
examples/bond/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = bond_app # all source are stored in SRCS-y SRCS-y := main.c +SRC-DEPS := build/commands.h PKGCONF ?= pkg-config
@@ -24,10 +25,13 @@ static: build/$(APP)-static LDFLAGS += -lrte_net_bond PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -38,10 +42,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -49,5 +53,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/*.h test -d build && rmdir -p build || true
examples/bond/commands.list new file +6 -0
@@ -0,0 +1,6 @@ +send <IP>ip # sends one ARPrequest through bonding for IP +start # starts listening if not started at startup +stop # stops listening +show # shows some bond info, e.g. active members +help # show help +quit # close application
examples/bond/main.c +15 -146
218 lines not on this page · raw message
examples/bond/main.h deleted +0 -10
@@ -1,10 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2010-2015 Intel Corporation -*/ - -#ifndef _MAIN_H_ -#define _MAIN_H_ - -int main (int argc,char *argv[]); - -#endif /* ifndef _MAIN_H_ */
examples/bond/meson.build +8 -0
@@ -11,3 +11,11 @@ allow_experimental_apis = true sources = files( 'main.c', ) + +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) +sources += cmd_h
Signature · 1 line
2.39.2
Re: [PATCH v3 0/5] document and simplify use of cmdline
In reply to Bruce RichardsonQuoted 62 lines · Bruce Richardson
The DPDK commandline library is widely used by apps and examples within DPDK, but it is not documented in our programmers guide and it requires a lot of boilerplate code definitions in order to used. We can improve this situation by creating a simple python script to automatically generate the boilerplate from a list of commands.
This patchset contains a new documentation chapter on cmdline library, going through step-by-step how to add commands and create the necessary token lists and parse contexts.
Following that initial doc patch, the set then contains a boilerplate-generating script, as well as a set of three patches showing its use, by converting three examples to use the script instead of having the hard-coded boilerplate. Once the script is used, adding a new command becomes as simple as adding the desired command to the .list file, and then writing the required function which will be called for that command. No other boilerplate coding is necessary.
Script obviously does not cover the full range of capabilities of the commandline lib, but does cover the most used parts. The code-saving to each of the examples by auto-generating the boilerplate is significant, and probably more examples with commandlines can be converted over in future.
The "cmdline" example itself, is not converted over, as it should probably remain as a simple example of direct library use without the script.
V3:
* Added lots of documentation
* Added support for help text for each command
* Cleaned up script a little so it passes pycodestyle and most flake8 checks, when line-length is set to max 100.
* Removed RFC tag, as I consider this patchset stable enough for consideration in a release.V2-RFC:
* Add support for IP addresses in commands
* Move to buildtools directory and make installable
* Convert 3 examples to use script, and eliminate their boilerplateBruce Richardson (5):
doc/prog_guide: new chapter on cmdline library
buildtools: script to generate cmdline boilerplate examples/simple_mp: auto-generate cmdline boilerplate examples/hotplug_mp: auto-generate cmdline boilerplate examples/bond: auto-generate cmdline boilerplateapp/test/commands.c | 2 + buildtools/dpdk-cmdline-gen.py | 167 +++++++ buildtools/meson.build | 7 + doc/guides/prog_guide/cmdline.rst | 466 ++++++++++++++++++ doc/guides/prog_guide/index.rst | 1 + examples/bond/Makefile | 12 +- examples/bond/commands.list | 6 + examples/bond/main.c | 161 +----- examples/bond/main.h | 10 - examples/bond/meson.build | 8 + examples/multi_process/hotplug_mp/Makefile | 12 +- examples/multi_process/hotplug_mp/commands.c | 147 +----- examples/multi_process/hotplug_mp/commands.h | 10 -
Quoted 8 lines
.../multi_process/hotplug_mp/commands.list | 5 + examples/multi_process/hotplug_mp/meson.build | 9 + examples/multi_process/simple_mp/Makefile | 12 +- examples/multi_process/simple_mp/meson.build | 9 + .../multi_process/simple_mp/mp_commands.c | 106 +--- .../multi_process/simple_mp/mp_commands.h | 14 - .../multi_process/simple_mp/mp_commands.list | 3 + 20 files changed, 745 insertions(+), 422 deletions(-)
Interesting series.
So if we remove the doc addition, this patch is removing loc, so +1 from me :-).
There is a problem though with externally building the examples. Maybe the dpdk-cmdline-gen.py has not been exported in the install process.
Quoted 12 lines
create mode 100755 buildtools/dpdk-cmdline-gen.py create mode 100644 doc/guides/prog_guide/cmdline.rst create mode 100644 examples/bond/commands.list delete mode 100644 examples/bond/main.h delete mode 100644 examples/multi_process/hotplug_mp/commands.h create mode 100644 examples/multi_process/hotplug_mp/commands.list delete mode 100644 examples/multi_process/simple_mp/mp_commands.h create mode 100644 examples/multi_process/simple_mp/mp_commands.list--
2.39.2
Signature · 1 line
David Marchand
Re: [PATCH v3 0/5] document and simplify use of cmdline
Quoted 73 lines · David Marchand
Quoted 62 lines · Bruce Richardson
The DPDK commandline library is widely used by apps and examples within DPDK, but it is not documented in our programmers guide and it requires a lot of boilerplate code definitions in order to used. We can improve this situation by creating a simple python script to automatically generate the boilerplate from a list of commands.
This patchset contains a new documentation chapter on cmdline library, going through step-by-step how to add commands and create the necessary token lists and parse contexts.
Following that initial doc patch, the set then contains a boilerplate-generating script, as well as a set of three patches showing its use, by converting three examples to use the script instead of having the hard-coded boilerplate. Once the script is used, adding a new command becomes as simple as adding the desired command to the .list file, and then writing the required function which will be called for that command. No other boilerplate coding is necessary.
Script obviously does not cover the full range of capabilities of the commandline lib, but does cover the most used parts. The code-saving to each of the examples by auto-generating the boilerplate is significant, and probably more examples with commandlines can be converted over in future.
The "cmdline" example itself, is not converted over, as it should probably remain as a simple example of direct library use without the script.
V3:
* Added lots of documentation
* Added support for help text for each command
* Cleaned up script a little so it passes pycodestyle and most flake8 checks, when line-length is set to max 100.
* Removed RFC tag, as I consider this patchset stable enough for consideration in a release.V2-RFC:
* Add support for IP addresses in commands
* Move to buildtools directory and make installable
* Convert 3 examples to use script, and eliminate their boilerplateBruce Richardson (5):
doc/prog_guide: new chapter on cmdline library
buildtools: script to generate cmdline boilerplate examples/simple_mp: auto-generate cmdline boilerplate examples/hotplug_mp: auto-generate cmdline boilerplate examples/bond: auto-generate cmdline boilerplateapp/test/commands.c | 2 + buildtools/dpdk-cmdline-gen.py | 167 +++++++ buildtools/meson.build | 7 + doc/guides/prog_guide/cmdline.rst | 466 ++++++++++++++++++ doc/guides/prog_guide/index.rst | 1 + examples/bond/Makefile | 12 +- examples/bond/commands.list | 6 + examples/bond/main.c | 161 +----- examples/bond/main.h | 10 - examples/bond/meson.build | 8 + examples/multi_process/hotplug_mp/Makefile | 12 +- examples/multi_process/hotplug_mp/commands.c | 147 +----- examples/multi_process/hotplug_mp/commands.h | 10 -Quoted 8 lines
.../multi_process/hotplug_mp/commands.list | 5 + examples/multi_process/hotplug_mp/meson.build | 9 + examples/multi_process/simple_mp/Makefile | 12 +- examples/multi_process/simple_mp/meson.build | 9 + .../multi_process/simple_mp/mp_commands.c | 106 +--- .../multi_process/simple_mp/mp_commands.h | 14 - .../multi_process/simple_mp/mp_commands.list | 3 + 20 files changed, 745 insertions(+), 422 deletions(-)
Quoted 6 lines
Interesting series.
So if we remove the doc addition, this patch is removing loc, so +1 from me :-).There is a problem though with externally building the examples. Maybe the
dpdk-cmdline-gen.pyhas not been exported in the install process.
It has, but it's not visible to the external builds in github actions. The following one-line fix should correct that, I believe.
I was testing it in my own github yesterday, but never sent a v4 series.
/Bruce
.ci/linux-build.sh +1 -0
@@ -174,6 +174,7 @@ fi if [ "$BUILD_EXAMPLES" = "true" ]; then [ -d install ] || DESTDIR=$(pwd)/install meson install -C build export LD_LIBRARY_PATH=$(dirname $(find $(pwd)/install -name librte_eal.so)):$LD_LIBRARY_PATH + export PATH=$(dirname $(find $(pwd)/install -name dpdk-devbind.py)):$PATH export PKG_CONFIG_PATH=$(dirname $(find $(pwd)/install -name libdpdk.pc)):$PKG_CONFIG_PATH export PKGCONF="pkg-config --define-prefix" find build/examples -maxdepth 1 -type f -name "dpdk-*" |
Re: [PATCH v3 0/5] document and simplify use of cmdline
In reply to David MarchandQuoted 73 lines · David Marchand
Quoted 62 lines · Bruce Richardson
The DPDK commandline library is widely used by apps and examples within DPDK, but it is not documented in our programmers guide and it requires a lot of boilerplate code definitions in order to used. We can improve this situation by creating a simple python script to automatically generate the boilerplate from a list of commands.
This patchset contains a new documentation chapter on cmdline library, going through step-by-step how to add commands and create the necessary token lists and parse contexts.
Following that initial doc patch, the set then contains a boilerplate-generating script, as well as a set of three patches showing its use, by converting three examples to use the script instead of having the hard-coded boilerplate. Once the script is used, adding a new command becomes as simple as adding the desired command to the .list file, and then writing the required function which will be called for that command. No other boilerplate coding is necessary.
Script obviously does not cover the full range of capabilities of the commandline lib, but does cover the most used parts. The code-saving to each of the examples by auto-generating the boilerplate is significant, and probably more examples with commandlines can be converted over in future.
The "cmdline" example itself, is not converted over, as it should probably remain as a simple example of direct library use without the script.
V3:
* Added lots of documentation
* Added support for help text for each command
* Cleaned up script a little so it passes pycodestyle and most flake8 checks, when line-length is set to max 100.
* Removed RFC tag, as I consider this patchset stable enough for consideration in a release.V2-RFC:
* Add support for IP addresses in commands
* Move to buildtools directory and make installable
* Convert 3 examples to use script, and eliminate their boilerplateBruce Richardson (5):
doc/prog_guide: new chapter on cmdline library
buildtools: script to generate cmdline boilerplate examples/simple_mp: auto-generate cmdline boilerplate examples/hotplug_mp: auto-generate cmdline boilerplate examples/bond: auto-generate cmdline boilerplateapp/test/commands.c | 2 + buildtools/dpdk-cmdline-gen.py | 167 +++++++ buildtools/meson.build | 7 + doc/guides/prog_guide/cmdline.rst | 466 ++++++++++++++++++ doc/guides/prog_guide/index.rst | 1 + examples/bond/Makefile | 12 +- examples/bond/commands.list | 6 + examples/bond/main.c | 161 +----- examples/bond/main.h | 10 - examples/bond/meson.build | 8 + examples/multi_process/hotplug_mp/Makefile | 12 +- examples/multi_process/hotplug_mp/commands.c | 147 +----- examples/multi_process/hotplug_mp/commands.h | 10 -Quoted 8 lines
.../multi_process/hotplug_mp/commands.list | 5 + examples/multi_process/hotplug_mp/meson.build | 9 + examples/multi_process/simple_mp/Makefile | 12 +- examples/multi_process/simple_mp/meson.build | 9 + .../multi_process/simple_mp/mp_commands.c | 106 +--- .../multi_process/simple_mp/mp_commands.h | 14 - .../multi_process/simple_mp/mp_commands.list | 3 + 20 files changed, 745 insertions(+), 422 deletions(-)
Quoted 3 lines
Interesting series.
So if we remove the doc addition, this patch is removing loc, so +1 from me :-).
There's probably lots more LOC that can be removed beyond this, if we put in a bit of effort looking. I just took three simple examples, and managed to save ~100LOC each.
However, the big benefit I find is for anyone working on new apps - using a script makes it SOOOO much easier to add a commandline and then subsequently to extend with new commands as you go! Just add the new command to the list file, and write the new callback function and you're done.
Since cmdline library is not going to be going anywhere, anytime soon, since it's so integrated into testpmd and dpdk-test, we might as well make it useful for others.
/Bruce
v4 cover document and simplify use of cmdline
In reply to Bruce RichardsonThe DPDK commandline library is widely used by apps and examples within DPDK, but it is not documented in our programmers guide and it requires a lot of boilerplate code definitions in order to used. We can improve this situation by creating a simple python script to automatically generate the boilerplate from a list of commands.
This patchset contains a new documentation chapter on cmdline library, going through step-by-step how to add commands and create the necessary token lists and parse contexts.
Following that initial doc patch, the set then contains a boilerplate-generating script, as well as a set of four patches showing its use, by converting four examples to use the script instead of having the hard-coded boilerplate. Once the script is used, adding a new command becomes as simple as adding the desired command to the .list file, and then writing the required function which will be called for that command. No other boilerplate coding is necessary.
Script obviously does not cover the full range of capabilities of the commandline lib, but does cover the most used parts. The code-saving to each of the examples by auto-generating the boilerplate is significant, and probably more examples with commandlines can be converted over in future.
The "cmdline" example itself, is not converted over, as it should probably remain as a simple example of direct library use without the script.
V4:
* Reworked script following feedback from Robin J.
- formatted code with black
- used multi-line strings
- replaced sys.exit(1) with proper error handling
- per-command function returns lists rather than printing directly
- other small cleanups
* Added change to CI script so the cmdline script is in PATH
* Converted VDPA example to script, saving another 100 LOC
V3:
* Added lots of documentation
* Added support for help text for each command
* Cleaned up script a little so it passes pycodestyle and most flake8 checks, when line-length is set to max 100.
* Removed RFC tag, as I consider this patchset stable enough for consideration in a release.
V2-RFC:
* Add support for IP addresses in commands
* Move to buildtools directory and make installable
* Convert 3 examples to use script, and eliminate their boilerplate
Bruce Richardson (7):
doc/prog_guide: new chapter on cmdline library
buildtools: script to generate cmdline boilerplate
ci: allow use of DPDK tools when building examples examples/simple_mp: auto-generate cmdline boilerplate examples/hotplug_mp: auto-generate cmdline boilerplate examples/bond: auto-generate cmdline boilerplate examples/vdpa: auto-generate cmdline boilerplate
.ci/linux-build.sh | 1 + app/test/commands.c | 2 + buildtools/dpdk-cmdline-gen.py | 190 +++++++ buildtools/meson.build | 7 + doc/guides/prog_guide/cmdline.rst | 466 ++++++++++++++++++ doc/guides/prog_guide/index.rst | 1 + examples/bond/Makefile | 12 +- examples/bond/commands.list | 6 + examples/bond/main.c | 161 +----- examples/bond/main.h | 10 - examples/bond/meson.build | 8 + examples/multi_process/hotplug_mp/Makefile | 12 +- examples/multi_process/hotplug_mp/commands.c | 147 +----- examples/multi_process/hotplug_mp/commands.h | 10 - .../multi_process/hotplug_mp/commands.list | 5 + examples/multi_process/hotplug_mp/meson.build | 9 + examples/multi_process/simple_mp/Makefile | 12 +- examples/multi_process/simple_mp/meson.build | 9 + .../multi_process/simple_mp/mp_commands.c | 106 +--- .../multi_process/simple_mp/mp_commands.h | 14 - .../multi_process/simple_mp/mp_commands.list | 3 + examples/vdpa/Makefile | 12 +- examples/vdpa/commands.list | 5 + examples/vdpa/main.c | 131 +---- examples/vdpa/meson.build | 7 + 25 files changed, 796 insertions(+), 550 deletions(-) create mode 100755 buildtools/dpdk-cmdline-gen.py create mode 100644 doc/guides/prog_guide/cmdline.rst create mode 100644 examples/bond/commands.list delete mode 100644 examples/bond/main.h delete mode 100644 examples/multi_process/hotplug_mp/commands.h create mode 100644 examples/multi_process/hotplug_mp/commands.list delete mode 100644 examples/multi_process/simple_mp/mp_commands.h create mode 100644 examples/multi_process/simple_mp/mp_commands.list create mode 100644 examples/vdpa/commands.list
--
2.39.2
PATCH v4 1/7 doc/prog_guide: new chapter on cmdline library
The cmdline library was not documented in our programmers guide, so add a new chapter on it. This chapter covers step-by-step how to use the library, rather than focusing on the library internals. This complements the existing cmdline example app document, providing more details on the process of using the library.
--- app/test/commands.c | 2 + doc/guides/prog_guide/cmdline.rst | 337 ++++++++++++++++++++++++++++++ doc/guides/prog_guide/index.rst | 1 + 3 files changed, 340 insertions(+) create mode 100644 doc/guides/prog_guide/cmdline.rst
app/test/commands.c +2 -0
@@ -108,6 +108,7 @@ dump_struct_sizes(void)#undef DUMP_SIZE } +/* Add the dump_* tests cases 8< */ static void cmd_dump_parsed (void *parsed_result, __rte_unused struct cmdline *cl, __rte_unused void *data)
@@ -155,6 +156,7 @@ cmdline_parse_inst_t cmd_dump = { NULL, }, }; +/* >8 End of add the dump_* tests cases */ /****************/
doc/guides/prog_guide/cmdline.rst new file +337 -0
337 lines not on this page · raw message
doc/guides/prog_guide/index.rst +1 -0
@@ -13,6 +13,7 @@ Programmer's Guide source_org env_abstraction_layer log_lib + cmdline service_cores trace_lib rcu_lib
Signature · 1 line
2.39.2
PATCH v4 2/7 buildtools: script to generate cmdline boilerplate
In reply to Bruce RichardsonProvide a "dpdk-cmdline-gen.py" script for application developers to quickly generate the boilerplate code necessary for using the cmdline library.
Example of use:
The script takes an input file with a list of commands the user wants in the app, where the parameter variables are tagged with the type. For example:
$ cat commands.list list add <UINT16>x <UINT16>y echo <STRING>message add socket <STRING>path quit
When run through the script as "./dpdk-cmdline-gen.py commands.list", the output will be the contents of a header file with all the boilerplate necessary for a commandline instance with those commands.
If the flag --stubs is passed, an output header filename must also be passed, in which case both a header file with the definitions and a C file with function stubs in it is written to disk. The separation is so that the header file can be rewritten at any future point to add more commands, while the C file can be kept as-is and extended by the user with any additional functions needed.
--- buildtools/dpdk-cmdline-gen.py | 190 ++++++++++++++++++++++++++++++ buildtools/meson.build | 7 ++ doc/guides/prog_guide/cmdline.rst | 131 +++++++++++++++++++- 3 files changed, 327 insertions(+), 1 deletion(-) create mode 100755 buildtools/dpdk-cmdline-gen.py
buildtools/dpdk-cmdline-gen.py new file +190 -0
@@ -0,0 +1,190 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +""" +Script to automatically generate boilerplate for using DPDK cmdline library. +""" + +import argparse +import sys + +PARSE_FN_PARAMS = "void *parsed_result, struct cmdline *cl, void *data" +PARSE_FN_BODY = """ + /* TODO: command action */ + RTE_SET_USED(parsed_result); + RTE_SET_USED(cl); + RTE_SET_USED(data); +""" +NUMERIC_TYPES = [ + "UINT8", + "UINT16", + "UINT32", + "UINT64", + "INT8", + "INT16", + "INT32", + "INT64", +] + + +def process_command(lineno, tokens, comment): + """Generate the structures and definitions for a single command.""" + out = [] + cfile_out = [] + + if tokens[0].startswith("<"): + raise ValueError(f"Error line {lineno + 1}: command must start with a literal string") + + name_tokens = [] + for t in tokens: + if t.startswith("<"): + break + name_tokens.append(t) + name = "_".join(name_tokens) + + result_struct = [] + initializers = [] + token_list = [] + for t in tokens: + if t.startswith("<"): + t_type, t_name = t[1:].split(">") + t_val = "NULL" + else: + t_type = "STRING" + t_name = t + t_val = f'"{t}"' + + if t_type == "STRING": + result_struct.append(f"\tcmdline_fixed_string_t {t_name};") + initializers.append( + f"static cmdline_parse_token_string_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_STRING_INITIALIZER(struct cmd_{name}_result, {t_name}, {t_val});" + ) + elif t_type in NUMERIC_TYPES: + result_struct.append(f"\t{t_type.lower()}_t {t_name};") + initializers.append( + f"static cmdline_parse_token_num_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_NUM_INITIALIZER(struct cmd_{name}_result, {t_name}, RTE_{t_type});" + ) + elif t_type in ["IP", "IP_ADDR", "IPADDR"]: + result_struct.append(f"\tcmdline_ipaddr_t {t_name};") + initializers.append( + f"cmdline_parse_token_ipaddr_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_IPV4_INITIALIZER(struct cmd_{name}_result, {t_name});" + ) + else: + raise TypeError(f"Error line {lineno + 1}: unknown token type '{t_type}'") + token_list.append(f"cmd_{name}_{t_name}_tok") + + out.append(f'/* Auto-generated handling for command "{" ".join(tokens)}" */') + # output function prototype + func_sig = f"void\ncmd_{name}_parsed({PARSE_FN_PARAMS})" + out.append(f"extern {func_sig};\n") + # output result data structure + out.append(f"struct cmd_{name}_result {{\n" + "\n".join(result_struct) + "\n};\n") + # output the initializer tokens + out.append("\n".join(initializers) + "\n") + # output the instance structure + out.append( + f"static cmdline_parse_inst_t cmd_{name} = {{\n" + + f"\t.f = cmd_{name}_parsed,\n" + + "\t.data = NULL,\n" + + f'\t.help_str = "{comment}",\n' + + "\t.tokens = {" + ) + for t in token_list: + out.append(f"\t\t(void *)&{t},") + out.append("\t\tNULL\n" + "\t}\n" + "};\n") + # output function template if C file being written + cfile_out.append(f"{func_sig}\n{{{PARSE_FN_BODY}}}\n") + + # return the instance structure name + return (f"cmd_{name}", out, cfile_out) + + +def process_commands(infile, hfile, cfile, ctxname): + """Generate boilerplate output for a list of commands from infile.""" + instances = [] + + hfile.write( + f"""/* File autogenerated by {sys.argv[0]} */ +#ifndef GENERATED_COMMANDS_H +#define GENERATED_COMMANDS_H +#include <rte_common.h> +#include <cmdline.h> +#include <cmdline_parse_string.h> +#include <cmdline_parse_num.h> +#include <cmdline_parse_ipaddr.h> + +""" + ) + + for lineno, line in enumerate(infile.readlines()): + if line.lstrip().startswith("#"): + continue + if "#" not in line: + line = line + "#" # ensure split always works, even if no help text + tokens, comment = line.split("#", 1) + cmd_inst, h_out, c_out = process_command(lineno, tokens.strip().split(), comment.strip()) + hfile.write("\n".join(h_out)) + if cfile: + cfile.write("\n".join(c_out)) + instances.append(cmd_inst) + + inst_join_str = ",\n\t&" + hfile.write( + f""" +static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{ +\t&{inst_join_str.join(instances)}, +\tNULL +}}; + +#endif /* GENERATED_COMMANDS_H */ +""" + ) + + +def main(): + """Application main entry point.""" + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument( + "--stubs", + action="store_true", + help="Produce C file with empty function stubs for each command", + ) + ap.add_argument( + "--output-file", + "-o", + default="-", + help="Output header filename [default to stdout]", + ) + ap.add_argument( + "--context-name", + default="ctx", + help="Name given to the cmdline context variable in the output header [default=ctx]", + ) + ap.add_argument("infile", type=argparse.FileType("r"), help="File with list of commands") + args = ap.parse_args() + + if not args.stubs: + if args.output_file == "-": + process_commands(args.infile, sys.stdout, None, args.context_name) + else: + with open(args.output_file, "w") as hfile: + process_commands(args.infile, hfile, None, args.context_name) + else: + if not args.output_file.endswith(".h"): + ap.error( + "-o/--output-file: specify an output filename ending with .h when creating stubs" + ) + + cfilename = args.output_file[:-2] + ".c" + with open(args.output_file, "w") as hfile: + with open(cfilename, "w") as cfile: + cfile.write(f'#include "{args.output_file}"\n\n') + process_commands(args.infile, hfile, cfile, args.context_name) + + +if __name__ == "__main__": + main()
buildtools/meson.build +7 -0
@@ -19,6 +19,13 @@ get_cpu_count_cmd = py3 + files('get-cpu-count.py') get_numa_count_cmd = py3 + files('get-numa-count.py') get_test_suites_cmd = py3 + files('get-test-suites.py') has_hugepages_cmd = py3 + files('has-hugepages.py') +cmdline_gen_cmd = py3 + files('dpdk-cmdline-gen.py') + +# install any build tools that end-users might want also +install_data([ + 'dpdk-cmdline-gen.py', + ], + install_dir: 'bin') # select library and object file format pmdinfo = py3 + files('gen-pmdinfo-cfile.py') + [meson.current_build_dir()]
doc/guides/prog_guide/cmdline.rst +130 -1
137 lines not on this page · raw message
Signature · 1 line
2.39.2
PATCH v4 3/7 ci: allow use of DPDK tools when building examples
In reply to Bruce RichardsonTo allow use of the DPDK python scripts (installed in $(prefix)/bin) from within the makefiles of our examples, we need to export the PATH variable with the location of our installed scripts from within our CI scripts. This matches what is already done for other paths e.g. the PKG_CONFIG_PATH variable.
--- .ci/linux-build.sh | 1 + 1 file changed, 1 insertion(+)
.ci/linux-build.sh +1 -0
@@ -174,6 +174,7 @@ fi if [ "$BUILD_EXAMPLES" = "true" ]; then [ -d install ] || DESTDIR=$(pwd)/install meson install -C build export LD_LIBRARY_PATH=$(dirname $(find $(pwd)/install -name librte_eal.so)):$LD_LIBRARY_PATH + export PATH=$(dirname $(find $(pwd)/install -name dpdk-devbind.py)):$PATH export PKG_CONFIG_PATH=$(dirname $(find $(pwd)/install -name libdpdk.pc)):$PKG_CONFIG_PATH export PKGCONF="pkg-config --define-prefix" find build/examples -maxdepth 1 -type f -name "dpdk-*" |
Signature · 1 line
2.39.2
Re: [PATCH v4 3/7] ci: allow use of DPDK tools when building examples
Quoted 8 lines · Bruce Richardson
To allow use of the DPDK python scripts (installed in $(prefix)/bin) from within the makefiles of our examples, we need to export the PATH variable with the location of our installed scripts from within our CI scripts. This matches what is already done for other paths e.g. the
PKG_CONFIG_PATHvariable.Signed-off-by Bruce Richardson <[email protected]>---
I guess this should work, but it's a bit strange that we need to key off something like dpdk-devbind.py. Not a complaint, just an observation.
Maybe a future change would be to update the meson.build to set the exec_prefix variable - but I guess for now that might be a much bigger change. But it means we could get the path after setting the pkgconfig path and then just run something like:
pkg-config libdpdk --variable=exec_prefix
and wouldn't need to search for the python utility.
As I wrote - it's a more involved change, and I don't think it should hold up this patch. Just something to consider for the future (maybe Michael or I could look at it)
Quoted 15 lines
.ci/linux-build.sh | 1 + 1 file changed, 1 insertion(+).ci/linux-build.sh +1
-0@@ -174,6 +174,7 @@ fi if [ "$BUILD_EXAMPLES" = "true" ]; then [ -d install ] || DESTDIR=$(pwd)/install meson install -C build export LD_LIBRARY_PATH=$(dirname $(find $(pwd)/install -name librte_eal.so)):$LD_LIBRARY_PATH + export PATH=$(dirname $(find $(pwd)/install -name dpdk-devbind.py)):$PATH export PKG_CONFIG_PATH=$(dirname $(find $(pwd)/install -name libdpdk.pc)):$PKG_CONFIG_PATH export PKGCONF="pkg-config --define-prefix" find build/examples -maxdepth 1 -type f -name "dpdk-*" |
Re: [PATCH v4 3/7] ci: allow use of DPDK tools when building examples
Quoted 8 lines · Aaron Conole
Quoted 6 lines · Bruce Richardson
To allow use of the DPDK python scripts (installed in $(prefix)/bin) from within the makefiles of our examples, we need to export the PATH variable with the location of our installed scripts from within our CI scripts. This matches what is already done for other paths e.g. the
PKG_CONFIG_PATHvariable.
Quoted 6 lines
Quoted 2 lines
Signed-off-by Bruce Richardson <[email protected]>---
I guess this should work, but it's a bit strange that we need to key off something like
dpdk-devbind.py. Not a complaint, just an observation.
Yes, I also find it a bit strange, but I decided to just copy the style used for the other paths which also key off a "known-good" file. As you say, it also works though, which is nice :-)
Quoted 5 lines
Maybe a future change would be to update the meson.build to set the
exec_prefixvariable - but I guess for now that might be a much bigger change. But it means we could get the path after setting the pkgconfig path and then just run something like:
Quoted 7 lines
pkg-config libdpdk --variable=exec_prefixand wouldn't need to search for the python utility.
As I wrote - it's a more involved change, and I don't think it should hold up this patch. Just something to consider for the future (maybe Michael or I could look at it)
Thanks for the input.
/Bruce
PATCH v4 4/7 examples/simple_mp: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/multi_process/simple_mp/Makefile | 12 +- examples/multi_process/simple_mp/meson.build | 9 ++ .../multi_process/simple_mp/mp_commands.c | 106 ++---------------- .../multi_process/simple_mp/mp_commands.h | 14 --- .../multi_process/simple_mp/mp_commands.list | 3 + 5 files changed, 30 insertions(+), 114 deletions(-) delete mode 100644 examples/multi_process/simple_mp/mp_commands.h create mode 100644 examples/multi_process/simple_mp/mp_commands.list
examples/multi_process/simple_mp/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = simple_mp # all source are stored in SRCS-y SRCS-y := main.c mp_commands.c +SRC-DEPS := build/mp_commands.h PKGCONF ?= pkg-config
@@ -22,10 +23,13 @@ static: build/$(APP)-static ln -sf $(APP)-static build/$(APP) PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/mp_commands.h: mp_commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=simple_mp_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -36,10 +40,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -47,5 +51,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/mp_commands.h test -d build && rmdir -p build || true
examples/multi_process/simple_mp/meson.build +9 -0
@@ -7,7 +7,16 @@ # DPDK instance, use 'make' allow_experimental_apis = true + +cmd_h = custom_target('commands_hdr', + output: 'mp_commands.h', + input: files('mp_commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=simple_mp_ctx', '@INPUT@'] +) + sources = files( 'mp_commands.c', 'main.c', ) +sources += cmd_h
examples/multi_process/simple_mp/mp_commands.c +10 -96
133 lines not on this page · raw message
examples/multi_process/simple_mp/mp_commands.h deleted +0 -14
@@ -1,14 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2010-2014 Intel Corporation -*/ - -#ifndef _SIMPLE_MP_COMMANDS_H_ -#define _SIMPLE_MP_COMMANDS_H_ - -extern struct rte_ring *send_ring; -extern struct rte_mempool *message_pool; -extern volatile int quit; - -extern cmdline_parse_ctx_t simple_mp_ctx[]; - -#endif /* _SIMPLE_MP_COMMANDS_H_ */
examples/multi_process/simple_mp/mp_commands.list new file +3 -0
@@ -0,0 +1,3 @@ +send <STRING>message # send a string to another process +help # show help +quit # close the application
Signature · 1 line
2.39.2
PATCH v4 5/7 examples/hotplug_mp: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/multi_process/hotplug_mp/Makefile | 12 +- examples/multi_process/hotplug_mp/commands.c | 147 ++---------------- examples/multi_process/hotplug_mp/commands.h | 10 -- .../multi_process/hotplug_mp/commands.list | 5 + examples/multi_process/hotplug_mp/meson.build | 9 ++ 5 files changed, 35 insertions(+), 148 deletions(-) delete mode 100644 examples/multi_process/hotplug_mp/commands.h create mode 100644 examples/multi_process/hotplug_mp/commands.list
examples/multi_process/hotplug_mp/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = hotplug_mp # all source are stored in SRCS-y SRCS-y := main.c commands.c +SRC-DEPS := build/commands.h PKGCONF ?= pkg-config
@@ -22,10 +23,13 @@ static: build/$(APP)-static ln -sf $(APP)-static build/$(APP) PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -36,10 +40,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -47,5 +51,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/commands.h test -d build && rmdir -p build || true
examples/multi_process/hotplug_mp/commands.c +13 -134
189 lines not on this page · raw message
examples/multi_process/hotplug_mp/commands.h deleted +0 -10
@@ -1,10 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2018 Intel Corporation -*/ - -#ifndef _COMMANDS_H_ -#define _COMMANDS_H_ - -extern cmdline_parse_ctx_t main_ctx[]; - -#endif /* _COMMANDS_H_ */
examples/multi_process/hotplug_mp/commands.list new file +5 -0
@@ -0,0 +1,5 @@ +attach <STRING>devargs # attach a device +detach <STRING>devargs # detach a device +list # list all devices +help # show help +quit # quit
examples/multi_process/hotplug_mp/meson.build +9 -0
@@ -7,7 +7,16 @@ # DPDK instance, use 'make' allow_experimental_apis = true + +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) + sources = files( 'commands.c', 'main.c', ) +sources += cmd_h
Signature · 1 line
2.39.2
PATCH v4 6/7 examples/bond: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
---
Note: the original help text on some of the commands in this example
were not useful "this command do not handle any arguments". Therefore, when converting over to the command script, the per-command help info has been updated with reference to the code rather than a literal transfer of the existing help text, as was done with the previous 2 example apps.
--- examples/bond/Makefile | 12 ++- examples/bond/commands.list | 6 ++ examples/bond/main.c | 161 ++++-------------------------------- examples/bond/main.h | 10 --- examples/bond/meson.build | 8 ++ 5 files changed, 37 insertions(+), 160 deletions(-) create mode 100644 examples/bond/commands.list delete mode 100644 examples/bond/main.h
examples/bond/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = bond_app # all source are stored in SRCS-y SRCS-y := main.c +SRC-DEPS := build/commands.h PKGCONF ?= pkg-config
@@ -24,10 +25,13 @@ static: build/$(APP)-static LDFLAGS += -lrte_net_bond PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -38,10 +42,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -49,5 +53,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/*.h test -d build && rmdir -p build || true
examples/bond/commands.list new file +6 -0
@@ -0,0 +1,6 @@ +send <IP>ip # sends one ARPrequest through bonding for IP +start # starts listening if not started at startup +stop # stops listening +show # shows some bond info, e.g. active members +help # show help +quit # close application
examples/bond/main.c +15 -146
218 lines not on this page · raw message
examples/bond/main.h deleted +0 -10
@@ -1,10 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2010-2015 Intel Corporation -*/ - -#ifndef _MAIN_H_ -#define _MAIN_H_ - -int main (int argc,char *argv[]); - -#endif /* ifndef _MAIN_H_ */
examples/bond/meson.build +8 -0
@@ -11,3 +11,11 @@ allow_experimental_apis = true sources = files( 'main.c', ) + +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) +sources += cmd_h
Signature · 1 line
2.39.2
PATCH v4 7/7 examples/vdpa: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/vdpa/Makefile | 12 ++-- examples/vdpa/commands.list | 5 ++ examples/vdpa/main.c | 131 ++---------------------------------- examples/vdpa/meson.build | 7 ++ 4 files changed, 27 insertions(+), 128 deletions(-) create mode 100644 examples/vdpa/commands.list
examples/vdpa/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = vdpa # all source are stored in SRCS-y SRCS-y := main.c +SRC-DEPS := build/commands.h CFLAGS += -DALLOW_EXPERIMENTAL_API PKGCONF ?= pkg-config
@@ -23,10 +24,13 @@ static: build/$(APP)-static ln -sf $(APP)-static build/$(APP) PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -35,10 +39,10 @@ $(error "Cannot generate statically-linked binaries with this version of pkg-con endif endif -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -46,5 +50,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/*.h test -d build && rmdir -p build || true
examples/vdpa/commands.list new file +5 -0
@@ -0,0 +1,5 @@ +help # show help +list # list all available vdpa devices +create <STRING>socket_path <STRING>bdf # create a new vdpa port +stats <STRING>bdf <UINT32>qid # show device statistics +quit # exit application
examples/vdpa/main.c +7 -124
175 lines not on this page · raw message
examples/vdpa/meson.build +7 -0
@@ -16,3 +16,10 @@ allow_experimental_apis = true sources = files( 'main.c', ) +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) +sources += cmd_h
Signature · 1 line
2.39.2
Re: [PATCH v4 0/7] document and simplify use of cmdline
In reply to Bruce RichardsonHi Bruce,
Quoted 19 lines · Bruce Richardson
The DPDK commandline library is widely used by apps and examples within DPDK, but it is not documented in our programmers guide and it requires a lot of boilerplate code definitions in order to used. We can improve this situation by creating a simple python script to automatically generate the boilerplate from a list of commands.
This patchset contains a new documentation chapter on cmdline library, going through step-by-step how to add commands and create the necessary token lists and parse contexts.
Following that initial doc patch, the set then contains a boilerplate-generating script, as well as a set of four patches showing its use, by converting four examples to use the script instead of having the hard-coded boilerplate. Once the script is used, adding a new command becomes as simple as adding the desired command to the .list file, and then writing the required function which will be called for that command. No other boilerplate coding is necessary.
Quoted 5 lines
Script obviously does not cover the full range of capabilities of the commandline lib, but does cover the most used parts. The code-saving to each of the examples by auto-generating the boilerplate is significant, and probably more examples with commandlines can be converted over in future.
This is not something blocking for the series, but I had a quick try with testpmd to see where this series stands.
I hit, right off the bat, some of those limitations, but I think there are not that difficult to deal with.
- testpmd accepts both "help" and "help <section>" commands. But the cmdline library does not provide a way (afair) for specifiying this "optional" aspect.
And it can't be expressed with this series current syntax since generated symbols would conflict if we ask for two "help" commands.
My quick hack was to introduce a way to select the prefix of the generated symbols.
There may be a better way, like finding a better discriminant for naming symbols...
But, on the other hand, the symbols prefix might be something a developer wants to control (instead of currently hardcoded cmd_ prefix).
@@ -20,6 +20,12 @@ def process_command(tokens, cfile, comment):
"""Generate the structures and definitions for a single command.""" name = []
+ prefix, sep, cmd_name = tokens[0].partition(':')
+ if cmd_name:
+ tokens[0] = cmd_name
+ else:
+ prefix = 'cmd'
+
if tokens[0].startswith('<'):
print('Error: each command must start with at least one
literal string', file=sys.stderr)
sys.exit(1)
(etc... I am not copying the rest of the diff)
I then used as:
cmd_brief:help # help: Show help
help <STRING>section # help: Show help
- Multi choice fixed strings is something that is often used in testpmd, like here, in the help <section> command. Here is my quick hack:
buildtools/dpdk-cmdline-gen.py +5 -1
@@ -35,7 +35,11 @@ def process_command(tokens, cfile, comment): for t in tokens: if t.startswith('<'): t_type, t_name = t[1:].split('>') - t_val = 'NULL' + if len(t_type.split('(')) == 2: + t_type, t_val = t_type.split('(') + t_val = '"' + t_val.split(')')[0] + '"' + else: + t_val = 'NULL' else: t_type = 'STRING' t_name = t
@@ -113,7 +117,7 @@ def process_commands(infile, hfile, cfile, ctxname): continue if '#' not in line: line = line + '#' # ensure split always works, even if
no help text
- tokens, comment = line.split('#', 1)
+ tokens, comment = line.rsplit('#', 1)
instances.append(process_command(tokens.strip().split(),
cfile, comment.strip()))
print(f'static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{')Which translates as:
cmd_brief:help # help: Show help
help <STRING(all#control#display#config#ports)>section # help: Show help
Quoted 4 lines
The "cmdline" example itself, is not converted over, as it should probably remain as a simple example of direct library use without the script.
+1
Signature · 1 line
David Marchand
Re: [PATCH v4 0/7] document and simplify use of cmdline
Quoted 29 lines · David Marchand
Hi Bruce,
Quoted 19 lines · Bruce Richardson
The DPDK commandline library is widely used by apps and examples within DPDK, but it is not documented in our programmers guide and it requires a lot of boilerplate code definitions in order to used. We can improve this situation by creating a simple python script to automatically generate the boilerplate from a list of commands.
This patchset contains a new documentation chapter on cmdline library, going through step-by-step how to add commands and create the necessary token lists and parse contexts.
Following that initial doc patch, the set then contains a boilerplate-generating script, as well as a set of four patches showing its use, by converting four examples to use the script instead of having the hard-coded boilerplate. Once the script is used, adding a new command becomes as simple as adding the desired command to the .list file, and then writing the required function which will be called for that command. No other boilerplate coding is necessary.
Quoted 5 lines
Script obviously does not cover the full range of capabilities of the commandline lib, but does cover the most used parts. The code-saving to each of the examples by auto-generating the boilerplate is significant, and probably more examples with commandlines can be converted over in future.
Quoted 5 lines
This is not something blocking for the series, but I had a quick try with testpmd to see where this series stands.
I hit, right off the bat, some of those limitations, but I think there are not that difficult to deal with.
Thanks for investigating. Item #2 below is something I'd already been thinking of, but had not yet implemented. The hope was to get the basics in first and iterate thereafter, rather than trying to get it all in in one go. However, if I have the chance, and depending on how long before this set gets merged, I might have a try at a respin with an additional feature.
Quoted 31 lines
- testpmd accepts both "help" and "help <section>" commands. But the cmdline library does not provide a way (afair) for specifiying this "optional" aspect.
And it can't be expressed with this series current syntax since generated symbols would conflict if we ask for two "help" commands.
My quick hack was to introduce a way to select the prefix of the generated symbols.
There may be a better way, like finding a better discriminant for naming symbols...
But, on the other hand, the symbols prefix might be something a developer wants to control (instead of currently hardcodedcmd_prefix).(quoted diff) +6
-0@@ -20,6 +20,12 @@ def process_command(tokens, cfile, comment): """Generate the structures and definitions for a single command.""" name = [] + prefix, sep, cmd_name = tokens[0].partition(':') + if cmd_name: + tokens[0] = cmd_name + else: + prefix = 'cmd' + if tokens[0].startswith('<'): print('Error: each command must start with at least one literal string', file=sys.stderr)sys.exit(1)
Quoted 7 lines
(etc... I am not copying the rest of the diff)
I then used as:
cmd_brief:help # help: Show help
help <STRING>section # help: Show help
Interesting. I actually had no plans to even consider moving something like testpmd over. However, this is an interesting one, though I'm not really sure I like it that much as a feature :-) I rather like having unique prefixes for each command. I wasn't actually aware of the testpmd "help <section>" command at all. I will have to look into it.
Quoted 32 lines
- Multi choice fixed strings is something that is often used in testpmd, like here, in the help <section> command. Here is my quick hack:
buildtools/dpdk-cmdline-gen.py +5
-1@@ -35,7 +35,11 @@ def process_command(tokens, cfile, comment): for t in tokens: if t.startswith('<'): t_type, t_name = t[1:].split('>') - t_val = 'NULL' + if len(t_type.split('(')) == 2: + t_type, t_val = t_type.split('(') + t_val = '"' + t_val.split(')')[0] + '"' + else: + t_val = 'NULL' else: t_type = 'STRING' t_name = t@@ -113,7 +117,7 @@ def process_commands(infile, hfile, cfile, ctxname): continue if '#' not in line: line = line + '#' # ensure split always works, even ifno help text
buildtools/dpdk-cmdline-gen.py +1
-1- tokens, comment = line.split('#', 1) + tokens, comment = line.rsplit('#', 1) instances.append(process_command(tokens.strip().split(),cfile,
comment.strip()))
Quoted 7 lines
print(f'static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{')Which translates as:
cmd_brief:help # help: Show help
help <STRING(all#control#display#config#ports)>section # help: Show help
+1
I was actualy thinking that adding support for multi-choice fixed strings is something we should add. One thought that I had was that "#" is not a particularly good choice of separator here. While, as you show, it can be made to work; I think - since we are defining our own syntax here - that it would be both simpler for the script, and simpler for the user, to have "|" as the option separator. It should be familiar for everyone as an option separator from regexes, unlike "#" which is more familar for comments.
So what about:
help <|all|control|display|config|ports|>section
By starting with the separator, we should avoid having to provide the STRING type at all.
To my previous point on not liking to have a prefix-specifier, the alternative to making testpmd work with the script is to tweak very slightly the "help <section>".
help # show general help
help on <|all|control|display|config|ports|>section
By making the command "help on ports" rather than "help ports" we would avoid the need for the prefix syntax.
WDYT?
/Bruce
Re: [PATCH v4 0/7] document and simplify use of cmdline
Quoted 1 line · Bruce Richardson
On Tue, Oct 17, 2023 at 09:10:51AM +0200, David Marchand wrote:
<snip>
Quoted 38 lines
Quoted 22 lines
- Multi choice fixed strings is something that is often used in testpmd, like here, in the help <section> command. Here is my quick hack:
(quoted diff) +0
-0
b/buildtools/dpdk-cmdline-gen.pyindex3b41fb0493..e8c9e079de100755 ---a/buildtools/dpdk-cmdline-gen.py+++b/buildtools/dpdk-cmdline-gen.py@@ -35,7 +35,11 @@ defprocess_command(tokens, cfile, comment): for t in tokens: ift.startswith('<'):t_type,t_name= t[1:].split('>') -t_val
= 'NULL' + if len(t_type.split('(')) == 2: +t_type,t_val= t_type.split('(') +t_val= '"' +
t_val.split(')')[0] + '"' + else: +t_val=
'NULL' else:t_type= 'STRING't_name= t @@ -113,7 +117,7 @@ defprocess_commands(infile, hfile, cfile, ctxname): continue if '#' not in
line: line = line + '#' # ensure split always works, even if no help
text - tokens, comment =line.split('#', 1)+ tokens,
comment =line.rsplit('#', 1)instances.append(process_command(tokens.strip().split(), cfile, comment.strip()))Quoted 6 lines
print(f'static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{')Which translates as: cmd_brief:help # help: Show help help <STRING(all#control#display#config#ports)>section # help: Show help
+1 I was actualy thinking that adding support for multi-choice fixed strings is something we should add. One thought that I had was that "#" is not a particularly good choice of separator here. While, as you show, it can be made to work; I think - since we are defining our own syntax here - that it would be both simpler for the script, and simpler for the user, to have "|" as the option separator. It should be familiar for everyone as an option separator from regexes, unlike "#" which is more familar for comments.
Quoted 5 lines
So what about: help <|all|control|display|config|ports|>section
By starting with the separator, we should avoid having to provide the STRING type at all.
This (my suggestion) is now prototyped in V5. I've kept it as a separate patch so it's easily to review and discuss without affecting the rest of the set. To test it out, I've converted over the ntb example app which uses option lists.
/Bruce
Re: [PATCH v4 0/7] document and simplify use of cmdline
In reply to Bruce RichardsonQuoted 33 lines · Bruce Richardson
Quoted 33 lines
- testpmd accepts both "help" and "help <section>" commands. But the cmdline library does not provide a way (afair) for specifiying this "optional" aspect.
And it can't be expressed with this series current syntax since generated symbols would conflict if we ask for two "help" commands.
My quick hack was to introduce a way to select the prefix of the generated symbols.
There may be a better way, like finding a better discriminant for naming symbols...
But, on the other hand, the symbols prefix might be something a developer wants to control (instead of currently hardcodedcmd_prefix).(quoted diff) +6
-0@@ -20,6 +20,12 @@ def process_command(tokens, cfile, comment): """Generate the structures and definitions for a single command.""" name = [] + prefix, sep, cmd_name = tokens[0].partition(':') + if cmd_name: + tokens[0] = cmd_name + else: + prefix = 'cmd' + if tokens[0].startswith('<'): print('Error: each command must start with at least one literal string', file=sys.stderr)sys.exit(1)(etc... I am not copying the rest of the diff)
Quoted 8 lines
Quoted 5 lines
I then used as:
cmd_brief:help # help: Show help
help <STRING>section # help: Show helpInteresting. I actually had no plans to even consider moving something like testpmd over. However, this is an interesting one, though I'm not really
Given the extensive use of the cmdline library in testpmd, it is a good way to identify the limits of this series :-).
Quoted 3 lines
sure I like it that much as a feature :-) I rather like having unique prefixes for each command. I wasn't actually aware of the testpmd "help <section>" command at all. I will have to look into it.
Let me propose an alternative hack.
I mentionned previously that we could have a better namespace / discriminant for those symbols, and it seems easier than I thought:
@@ -25,8 +25,10 @@ def process_command(tokens, cfile, comment):
sys.exit(1)
for t in tokens:
if t.startswith('<'):- break
- name.append(t)
+ t_type, t_name = t[1:].split('>')
+ name.append(t_name)
+ else:
+ name.append(t)
name = '_'.join(name)
result_struct = []With this, any command implementation symbol has the full chain of token names as a prefix which will ensure there is no conflict. WDYT?
help # help: Show help
help <STRING>section # help: Show help
Results in:
cmd_help_parsed(void *parsed_result, struct cmdline *cl, void *data); struct cmd_help_result {
static cmdline_parse_token_string_t cmd_help_help_tok =
TOKEN_STRING_INITIALIZER(struct cmd_help_result, help, "help");
static cmdline_parse_inst_t cmd_help = {
.f = cmd_help_parsed,
(void *)&cmd_help_help_tok,
And:
cmd_help_section_parsed(void *parsed_result, struct cmdline *cl, void *data); struct cmd_help_section_result {
static cmdline_parse_token_string_t cmd_help_section_help_tok =
TOKEN_STRING_INITIALIZER(struct cmd_help_section_result, help, "help");
static cmdline_parse_token_string_t cmd_help_section_section_tok =
TOKEN_STRING_INITIALIZER(struct cmd_help_section_result, section, NULL);static cmdline_parse_inst_t cmd_help_section = {
.f = cmd_help_section_parsed,
(void *)&cmd_help_section_help_tok,
(void *)&cmd_help_section_section_tok,
Quoted 50 lines
Quoted 33 lines
- Multi choice fixed strings is something that is often used in testpmd, like here, in the help <section> command. Here is my quick hack:
buildtools/dpdk-cmdline-gen.py +5
-1@@ -35,7 +35,11 @@ def process_command(tokens, cfile, comment): for t in tokens: if t.startswith('<'): t_type, t_name = t[1:].split('>') - t_val = 'NULL' + if len(t_type.split('(')) == 2: + t_type, t_val = t_type.split('(') + t_val = '"' + t_val.split(')')[0] + '"' + else: + t_val = 'NULL' else: t_type = 'STRING' t_name = t@@ -113,7 +117,7 @@ def process_commands(infile, hfile, cfile, ctxname): continue if '#' not in line: line = line + '#' # ensure split always works, even ifno help text
buildtools/dpdk-cmdline-gen.py +1
-1- tokens, comment = line.split('#', 1) + tokens, comment = line.rsplit('#', 1) instances.append(process_command(tokens.strip().split(),cfile,
comment.strip()))Quoted 7 lines
print(f'static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{')Which translates as:
cmd_brief:help # help: Show help
help <STRING(all#control#display#config#ports)>section # help: Show help+1
I was actualy thinking that adding support for multi-choice fixed strings is something we should add. One thought that I had was that "#" is not a particularly good choice of separator here. While, as you show, it can be made to work; I think - since we are defining our own syntax here - that it would be both simpler for the script, and simpler for the user, to have "|" as the option separator. It should be familiar for everyone as an option separator from regexes, unlike "#" which is more familar for comments.
Quoted 2 lines
So what about:
help <|all|control|display|config|ports|>section
I don't like using | as it gives the false impression regexp are supported...
Quoted 3 lines
By starting with the separator, we should avoid having to provide the STRING type at all.
... and as a consequence, I find <|all confusing, it is like an empty value would be acceptable.
About skipping the token type for such lists, I had considered it, but I thought other types took an optional list of allowed values... Now looking at the cmdline types, it is not the case.
Maybe I mixed with some other cli framework I played with in the past...
All of this to say, ok for me to omit the type.
Quoted 10 lines
To my previous point on not liking to have a prefix-specifier, the alternative to making testpmd work with the script is to tweak very slightly the "help <section>".
help # show general help
help on <|all|control|display|config|ports|>sectionBy making the command "help on ports" rather than "help ports" we would avoid the need for the prefix syntax.
There are other cases where a "chain of command" returns the value of a parameter.
And the same parameter may be set via "chain of command <UINT>value".
Signature · 1 line
David Marchand
Re: [PATCH v4 0/7] document and simplify use of cmdline
Quoted 44 lines · David Marchand
Quoted 33 lines · Bruce Richardson
Quoted 33 lines
- testpmd accepts both "help" and "help <section>" commands. But the cmdline library does not provide a way (afair) for specifiying this "optional" aspect.
And it can't be expressed with this series current syntax since generated symbols would conflict if we ask for two "help" commands.
My quick hack was to introduce a way to select the prefix of the generated symbols.
There may be a better way, like finding a better discriminant for naming symbols...
But, on the other hand, the symbols prefix might be something a developer wants to control (instead of currently hardcodedcmd_prefix).(quoted diff) +6
-0@@ -20,6 +20,12 @@ def process_command(tokens, cfile, comment): """Generate the structures and definitions for a single command.""" name = [] + prefix, sep, cmd_name = tokens[0].partition(':') + if cmd_name: + tokens[0] = cmd_name + else: + prefix = 'cmd' + if tokens[0].startswith('<'): print('Error: each command must start with at least one literal string', file=sys.stderr)sys.exit(1)(etc... I am not copying the rest of the diff)
Quoted 8 lines
Quoted 5 lines
I then used as:
cmd_brief:help # help: Show help
help <STRING>section # help: Show helpInteresting. I actually had no plans to even consider moving something like testpmd over. However, this is an interesting one, though I'm not really
Quoted 3 lines
Given the extensive use of the cmdline library in testpmd, it is a good way to identify the limits of this series :-).
It is indeed. That was never meant to be the target of this series, rather it was to make writing new apps simpler. However, if we have a path to getting there, then I suppose we might as well continue.
Quoted 23 lines
Quoted 4 lines
sure I like it that much as a feature :-) I rather like having unique prefixes for each command. I wasn't actually aware of the testpmd "help <section>" command at all. I will have to look into it.
Let me propose an alternative hack.
I mentionned previously that we could have a better namespace / discriminant for those symbols, and it seems easier than I thought:(quoted diff) +4
-2@@ -25,8 +25,10 @@ def process_command(tokens, cfile, comment): sys.exit(1) for t in tokens: if t.startswith('<'): - break - name.append(t) + t_type, t_name = t[1:].split('>') + name.append(t_name) + else: + name.append(t) name = '_'.join(name) result_struct = []
Quoted 4 lines
With this, any command implementation symbol has the full chain of token names as a prefix which will ensure there is no conflict. WDYT?
I actually think I like this less than the previous proposal. :-(
The main reason for that is that we would need to decide immediately whether to go with this or not, as it would break compatibility with what is already proposed - because the function and struct names would get longer. The other scheme you proposed had the advantage that it could at least be adopted later. It also had the advantage that it was largely invisble except for the non-trivial cases that needed it.
Quoted 77 lines
help # help: Show help
help <STRING>section # help: Show helpResults in:
cmd_help_parsed(void *parsed_result, struct cmdline *cl, void *data); structcmd_help_result{
staticcmdline_parse_token_string_tcmd_help_help_tok=TOKEN_STRING_INITIALIZER(struct cmd_help_result, help, "help");static
cmdline_parse_inst_tcmd_help= {
.f =cmd_help_parsed,
(void *)&cmd_help_help_tok,And:
cmd_help_section_parsed(void *parsed_result, struct cmdline *cl, void *data); structcmd_help_section_result{
staticcmdline_parse_token_string_tcmd_help_section_help_tok=TOKEN_STRING_INITIALIZER(struct cmd_help_section_result, help, "help"); static cmdline_parse_token_string_t cmd_help_section_section_tok = TOKEN_STRING_INITIALIZER(struct cmd_help_section_result, section, NULL);static
cmdline_parse_inst_tcmd_help_section= {
.f =cmd_help_section_parsed,
(void *)&cmd_help_section_help_tok,
(void *)&cmd_help_section_section_tok,Quoted 50 lines
Quoted 33 lines
- Multi choice fixed strings is something that is often used in testpmd, like here, in the help <section> command. Here is my quick hack:
buildtools/dpdk-cmdline-gen.py +5
-1@@ -35,7 +35,11 @@ def process_command(tokens, cfile, comment): for t in tokens: if t.startswith('<'): t_type, t_name = t[1:].split('>') - t_val = 'NULL' + if len(t_type.split('(')) == 2: + t_type, t_val = t_type.split('(') + t_val = '"' + t_val.split(')')[0] + '"' + else: + t_val = 'NULL' else: t_type = 'STRING' t_name = t@@ -113,7 +117,7 @@ def process_commands(infile, hfile, cfile, ctxname): continue if '#' not in line: line = line + '#' # ensure split always works, even ifno help text
buildtools/dpdk-cmdline-gen.py +1
-1- tokens, comment = line.split('#', 1) + tokens, comment = line.rsplit('#', 1) instances.append(process_command(tokens.strip().split(),cfile,
comment.strip()))Quoted 7 lines
print(f'static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{')Which translates as:
cmd_brief:help # help: Show help
help <STRING(all#control#display#config#ports)>section # help: Show help+1
I was actualy thinking that adding support for multi-choice fixed strings is something we should add. One thought that I had was that "#" is not a particularly good choice of separator here. While, as you show, it can be made to work; I think - since we are defining our own syntax here - that it would be both simpler for the script, and simpler for the user, to have "|" as the option separator. It should be familiar for everyone as an option separator from regexes, unlike "#" which is more familar for comments.
Quoted 5 lines
Quoted 2 lines
So what about:
help <|all|control|display|config|ports|>sectionI don't like using | as it gives the false impression regexp are supported...
I'm not sure it does particularly. The bit that struck me was that if you look at the help texts for the commands that take multiple options, they all give the options separated with "|". Therefore, it seems logical to also use that in command specifiers too.
Quoted 8 lines
Quoted 4 lines
By starting with the separator, we should avoid having to provide the STRING type at all.
... and as a consequence, I find <|all confusing, it is like an empty value would be acceptable.
I'm ok to drop the initial and terminating |, if that is what the issue is
- or else I'm misunderstanding things. For example:
help <all|control|display|config|ports>section
Quoted 8 lines
About skipping the token type for such lists, I had considered it, but I thought other types took an optional list of allowed values... Now looking at the cmdline types, it is not the case.
Maybe I mixed with some other cli framework I played with in the past...All of this to say, ok for me to omit the type.
Good. However, it only works if we come up with a suitable separator character to detect to split on. I don't like "#" as separator as it is used so many places as a comment character. What about bracketed, comma-separated lists?
help <(all,control,display,config,ports)>section
Quoted 9 lines
Quoted 9 lines
To my previous point on not liking to have a prefix-specifier, the alternative to making testpmd work with the script is to tweak very slightly the "help <section>".
help # show general help
help on <|all|control|display|config|ports|>section
Quoted 7 lines
Quoted 2 lines
By making the command "help on ports" rather than "help ports" we would avoid the need for the prefix syntax.
There are other cases where a "chain of command" returns the value of a parameter.
And the same parameter may be set via "chain of command <UINT>value".
Ok, let me think on it a bit....
/Bruce
Re: [PATCH v4 0/7] document and simplify use of cmdline
In reply to David MarchandQuoted 70 lines · David Marchand
Quoted 33 lines · Bruce Richardson
Quoted 33 lines
- testpmd accepts both "help" and "help <section>" commands. But the cmdline library does not provide a way (afair) for specifiying this "optional" aspect.
And it can't be expressed with this series current syntax since generated symbols would conflict if we ask for two "help" commands.
My quick hack was to introduce a way to select the prefix of the generated symbols.
There may be a better way, like finding a better discriminant for naming symbols...
But, on the other hand, the symbols prefix might be something a developer wants to control (instead of currently hardcodedcmd_prefix).(quoted diff) +6
-0@@ -20,6 +20,12 @@ def process_command(tokens, cfile, comment): """Generate the structures and definitions for a single command.""" name = [] + prefix, sep, cmd_name = tokens[0].partition(':') + if cmd_name: + tokens[0] = cmd_name + else: + prefix = 'cmd' + if tokens[0].startswith('<'): print('Error: each command must start with at least one literal string', file=sys.stderr)sys.exit(1)(etc... I am not copying the rest of the diff)
Quoted 8 lines
Quoted 5 lines
I then used as:
cmd_brief:help # help: Show help
help <STRING>section # help: Show helpInteresting. I actually had no plans to even consider moving something like testpmd over. However, this is an interesting one, though I'm not really
Given the extensive use of the cmdline library in testpmd, it is a good way to identify the limits of this series :-).
Quoted 3 lines
sure I like it that much as a feature :-) I rather like having unique prefixes for each command. I wasn't actually aware of the testpmd "help <section>" command at all. I will have to look into it.
Let me propose an alternative hack.
I mentionned previously that we could have a better namespace / discriminant for those symbols, and it seems easier than I thought:(quoted diff) +4
-2@@ -25,8 +25,10 @@ def process_command(tokens, cfile, comment): sys.exit(1) for t in tokens: if t.startswith('<'): - break - name.append(t) + t_type, t_name = t[1:].split('>') + name.append(t_name) + else: + name.append(t) name = '_'.join(name) result_struct = []
Quoted 4 lines
With this, any command implementation symbol has the full chain of token names as a prefix which will ensure there is no conflict. WDYT?
Having thought a little more about it, I still don't like having the full command in all cases, but I can see it being useful for cases of overlapping prefixes.
How about making it optional - setting a flag in the typename, or in the parameter name to indicate that it should be included in the overall command name. For example, if we prefix the variable name with "_" or "__", it could indicate that we can choose to include this.
show port <UINT16>n --> void cmd_show_port_parsed(...) show port <UINT16>_n --> void cmd_show_port_n_parsed(...)
Prefixes on strings beyond initial tokens could just be silently stripped. [Obviously open to other ideas on what form tagging could take]
/Bruce
Re: [PATCH v4 0/7] document and simplify use of cmdline
Hello Bruce,
Quoted 30 lines · Bruce Richardson
Quoted 22 lines
Quoted 3 lines
sure I like it that much as a feature :-) I rather like having unique prefixes for each command. I wasn't actually aware of the testpmd "help <section>" command at all. I will have to look into it.
Let me propose an alternative hack.
I mentionned previously that we could have a better namespace / discriminant for those symbols, and it seems easier than I thought:(quoted diff) +4
-2@@ -25,8 +25,10 @@ def process_command(tokens, cfile, comment): sys.exit(1) for t in tokens: if t.startswith('<'): - break - name.append(t) + t_type, t_name = t[1:].split('>') + name.append(t_name) + else: + name.append(t) name = '_'.join(name) result_struct = []Quoted 4 lines
With this, any command implementation symbol has the full chain of token names as a prefix which will ensure there is no conflict. WDYT?
Having thought a little more about it, I still don't like having the full command in all cases, but I can see it being useful for cases of overlapping prefixes.
Quoted 8 lines
How about making it optional - setting a flag in the typename, or in the parameter name to indicate that it should be included in the overall command name. For example, if we prefix the variable name with "_" or "__", it could indicate that we can choose to include this.
show port <UINT16>n --> void
cmd_show_port_parsed(...)show port <UINT16>_n --> voidcmd_show_port_n_parsed(...)
I think I get what you mean, and it seems acceptable.
Quoted 1 line
Prefixes on strings beyond initial tokens could just be silently stripped.
By initial tokens, do you mean fixed strings token before a <> typed token ?
Signature · 1 line
David Marchand
Re: [PATCH v4 0/7] document and simplify use of cmdline
Quoted 40 lines · David Marchand
Hello Bruce,
Quoted 35 lines · Bruce Richardson
Quoted 22 lines
Quoted 3 lines
sure I like it that much as a feature :-) I rather like having unique prefixes for each command. I wasn't actually aware of the testpmd "help <section>" command at all. I will have to look into it.
Let me propose an alternative hack.
I mentionned previously that we could have a better namespace / discriminant for those symbols, and it seems easier than I thought:(quoted diff) +4
-2@@ -25,8 +25,10 @@ def process_command(tokens, cfile, comment): sys.exit(1) for t in tokens: if t.startswith('<'): - break - name.append(t) + t_type, t_name = t[1:].split('>') + name.append(t_name) + else: + name.append(t) name = '_'.join(name) result_struct = []Quoted 4 lines
With this, any command implementation symbol has the full chain of token names as a prefix which will ensure there is no conflict. WDYT?
Having thought a little more about it, I still don't like having the full command in all cases, but I can see it being useful for cases of overlapping prefixes.
How about making it optional - setting a flag in the typename, or in the parameter name to indicate that it should be included in the overall command name. For example, if we prefix the variable name with "_" or "__", it could indicate that we can choose to include this.
Quoted 6 lines
Quoted 3 lines
show port <UINT16>n --> void
cmd_show_port_parsed(...)show port <UINT16>_n --> voidcmd_show_port_n_parsed(...)I think I get what you mean, and it seems acceptable.
Cool. Any suggestions for a preferred prefix to indicate inclusion in the cmd name? "_", "__" or something else? I'm trending towards single "_" as above.
Quoted 5 lines
Quoted 2 lines
Prefixes on strings beyond initial tokens could just be silently stripped.
By initial tokens, do you mean fixed strings token before a <> typed token ?
Yes.
So:
add <UINT16>x --> cmd_add_parsed
add <UINT16>_x --> cmd_add_x_parsed
add <UINT16>_x <UINT16>_y --> cmd_add_x_y_parsed
add <UINT16>x <UINT16>_y --> cmd_add_parsed, strip "_" off y silently
/Bruce
v5 cover document and simplify use of cmdline
In reply to Bruce RichardsonThe DPDK commandline library is widely used by apps and examples within DPDK, but it is not documented in our programmers guide and it requires a lot of boilerplate code definitions in order to used. We can improve this situation by creating a simple python script to automatically generate the boilerplate from a list of commands.
This patchset contains a new documentation chapter on cmdline library, going through step-by-step how to add commands and create the necessary token lists and parse contexts.
Following that initial doc patch, the set then contains a boilerplate-generating script, as well as a set of four patches showing its use, by converting four examples to use the script instead of having the hard-coded boilerplate. Once the script is used, adding a new command becomes as simple as adding the desired command to the .list file, and then writing the required function which will be called for that command. No other boilerplate coding is necessary.
Final two patches, new in V5, add support for option-lists in values, and then use that support to convert over a fifth sample app - ntb.
Cmdline script obviously does not cover the full range of capabilities of the commandline lib, but does cover the most used parts. The code-saving to each of the examples by auto-generating the boilerplate is significant, and probably more examples with commandlines can be converted over in future.
The "cmdline" example itself, is not converted over, as it should probably remain as a simple example of direct library use without the script.
V5:
* Added copyright headers to command list files
* Add support for option lists
* Convert examples/ntb to use script
V4:
* Reworked script following feedback from Robin J.
- formatted code with black
- used multi-line strings
- replaced sys.exit(1) with proper error handling
- per-command function returns lists rather than printing directly
- other small cleanups
* Added change to CI script so the cmdline script is in PATH
* Converted VDPA example to script, saving another 100 LOC
V3:
* Added lots of documentation
* Added support for help text for each command
* Cleaned up script a little so it passes pycodestyle and most flake8 checks, when line-length is set to max 100.
* Removed RFC tag, as I consider this patchset stable enough for consideration in a release.
V2-RFC:
* Add support for IP addresses in commands
* Move to buildtools directory and make installable
* Convert 3 examples to use script, and eliminate their boilerplate
Bruce Richardson (9):
doc/prog_guide: new chapter on cmdline library
buildtools: script to generate cmdline boilerplate
ci: allow use of DPDK tools when building examples examples/simple_mp: auto-generate cmdline boilerplate examples/hotplug_mp: auto-generate cmdline boilerplate examples/bond: auto-generate cmdline boilerplate examples/vdpa: auto-generate cmdline boilerplate buildtools/dpdk-cmdline-gen: support option strings examples/ntb: auto-generate cmdline boilerplate
.ci/linux-build.sh | 1 + app/test/commands.c | 2 + buildtools/dpdk-cmdline-gen.py | 197 ++++++++ buildtools/meson.build | 7 + doc/guides/prog_guide/cmdline.rst | 470 ++++++++++++++++++ doc/guides/prog_guide/index.rst | 1 + examples/bond/Makefile | 12 +- examples/bond/commands.list | 6 + examples/bond/main.c | 161 +----- examples/bond/main.h | 10 - examples/bond/meson.build | 8 + examples/multi_process/hotplug_mp/Makefile | 12 +- examples/multi_process/hotplug_mp/commands.c | 147 +----- examples/multi_process/hotplug_mp/commands.h | 10 - .../multi_process/hotplug_mp/commands.list | 8 + examples/multi_process/hotplug_mp/meson.build | 9 + examples/multi_process/simple_mp/Makefile | 12 +- examples/multi_process/simple_mp/meson.build | 9 + .../multi_process/simple_mp/mp_commands.c | 106 +--- .../multi_process/simple_mp/mp_commands.h | 14 - .../multi_process/simple_mp/mp_commands.list | 6 + examples/ntb/Makefile | 12 +- examples/ntb/commands.list | 11 + examples/ntb/meson.build | 7 + examples/ntb/ntb_fwd.c | 200 +------- examples/vdpa/Makefile | 12 +- examples/vdpa/commands.list | 8 + examples/vdpa/main.c | 131 +---- examples/vdpa/meson.build | 7 + 29 files changed, 863 insertions(+), 733 deletions(-) create mode 100755 buildtools/dpdk-cmdline-gen.py create mode 100644 doc/guides/prog_guide/cmdline.rst create mode 100644 examples/bond/commands.list delete mode 100644 examples/bond/main.h delete mode 100644 examples/multi_process/hotplug_mp/commands.h create mode 100644 examples/multi_process/hotplug_mp/commands.list delete mode 100644 examples/multi_process/simple_mp/mp_commands.h create mode 100644 examples/multi_process/simple_mp/mp_commands.list create mode 100644 examples/ntb/commands.list create mode 100644 examples/vdpa/commands.list
--
2.39.2
PATCH v5 1/9 doc/prog_guide: new chapter on cmdline library
The cmdline library was not documented in our programmers guide, so add a new chapter on it. This chapter covers step-by-step how to use the library, rather than focusing on the library internals. This complements the existing cmdline example app document, providing more details on the process of using the library.
--- app/test/commands.c | 2 + doc/guides/prog_guide/cmdline.rst | 337 ++++++++++++++++++++++++++++++ doc/guides/prog_guide/index.rst | 1 + 3 files changed, 340 insertions(+) create mode 100644 doc/guides/prog_guide/cmdline.rst
app/test/commands.c +2 -0
@@ -108,6 +108,7 @@ dump_struct_sizes(void)#undef DUMP_SIZE } +/* Add the dump_* tests cases 8< */ static void cmd_dump_parsed (void *parsed_result, __rte_unused struct cmdline *cl, __rte_unused void *data)
@@ -155,6 +156,7 @@ cmdline_parse_inst_t cmd_dump = { NULL, }, }; +/* >8 End of add the dump_* tests cases */ /****************/
doc/guides/prog_guide/cmdline.rst new file +337 -0
337 lines not on this page · raw message
doc/guides/prog_guide/index.rst +1 -0
@@ -13,6 +13,7 @@ Programmer's Guide source_org env_abstraction_layer log_lib + cmdline service_cores trace_lib rcu_lib
Signature · 1 line
2.39.2
PATCH v5 2/9 buildtools: script to generate cmdline boilerplate
In reply to Bruce RichardsonProvide a "dpdk-cmdline-gen.py" script for application developers to quickly generate the boilerplate code necessary for using the cmdline library.
Example of use:
The script takes an input file with a list of commands the user wants in the app, where the parameter variables are tagged with the type. For example:
$ cat commands.list list add <UINT16>x <UINT16>y echo <STRING>message add socket <STRING>path quit
When run through the script as "./dpdk-cmdline-gen.py commands.list", the output will be the contents of a header file with all the boilerplate necessary for a commandline instance with those commands.
If the flag --stubs is passed, an output header filename must also be passed, in which case both a header file with the definitions and a C file with function stubs in it is written to disk. The separation is so that the header file can be rewritten at any future point to add more commands, while the C file can be kept as-is and extended by the user with any additional functions needed.
--- buildtools/dpdk-cmdline-gen.py | 190 ++++++++++++++++++++++++++++++ buildtools/meson.build | 7 ++ doc/guides/prog_guide/cmdline.rst | 131 +++++++++++++++++++- 3 files changed, 327 insertions(+), 1 deletion(-) create mode 100755 buildtools/dpdk-cmdline-gen.py
buildtools/dpdk-cmdline-gen.py new file +190 -0
@@ -0,0 +1,190 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +""" +Script to automatically generate boilerplate for using DPDK cmdline library. +""" + +import argparse +import sys + +PARSE_FN_PARAMS = "void *parsed_result, struct cmdline *cl, void *data" +PARSE_FN_BODY = """ + /* TODO: command action */ + RTE_SET_USED(parsed_result); + RTE_SET_USED(cl); + RTE_SET_USED(data); +""" +NUMERIC_TYPES = [ + "UINT8", + "UINT16", + "UINT32", + "UINT64", + "INT8", + "INT16", + "INT32", + "INT64", +] + + +def process_command(lineno, tokens, comment): + """Generate the structures and definitions for a single command.""" + out = [] + cfile_out = [] + + if tokens[0].startswith("<"): + raise ValueError(f"Error line {lineno + 1}: command must start with a literal string") + + name_tokens = [] + for t in tokens: + if t.startswith("<"): + break + name_tokens.append(t) + name = "_".join(name_tokens) + + result_struct = [] + initializers = [] + token_list = [] + for t in tokens: + if t.startswith("<"): + t_type, t_name = t[1:].split(">") + t_val = "NULL" + else: + t_type = "STRING" + t_name = t + t_val = f'"{t}"' + + if t_type == "STRING": + result_struct.append(f"\tcmdline_fixed_string_t {t_name};") + initializers.append( + f"static cmdline_parse_token_string_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_STRING_INITIALIZER(struct cmd_{name}_result, {t_name}, {t_val});" + ) + elif t_type in NUMERIC_TYPES: + result_struct.append(f"\t{t_type.lower()}_t {t_name};") + initializers.append( + f"static cmdline_parse_token_num_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_NUM_INITIALIZER(struct cmd_{name}_result, {t_name}, RTE_{t_type});" + ) + elif t_type in ["IP", "IP_ADDR", "IPADDR"]: + result_struct.append(f"\tcmdline_ipaddr_t {t_name};") + initializers.append( + f"cmdline_parse_token_ipaddr_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_IPV4_INITIALIZER(struct cmd_{name}_result, {t_name});" + ) + else: + raise TypeError(f"Error line {lineno + 1}: unknown token type '{t_type}'") + token_list.append(f"cmd_{name}_{t_name}_tok") + + out.append(f'/* Auto-generated handling for command "{" ".join(tokens)}" */') + # output function prototype + func_sig = f"void\ncmd_{name}_parsed({PARSE_FN_PARAMS})" + out.append(f"extern {func_sig};\n") + # output result data structure + out.append(f"struct cmd_{name}_result {{\n" + "\n".join(result_struct) + "\n};\n") + # output the initializer tokens + out.append("\n".join(initializers) + "\n") + # output the instance structure + out.append( + f"static cmdline_parse_inst_t cmd_{name} = {{\n" + + f"\t.f = cmd_{name}_parsed,\n" + + "\t.data = NULL,\n" + + f'\t.help_str = "{comment}",\n' + + "\t.tokens = {" + ) + for t in token_list: + out.append(f"\t\t(void *)&{t},") + out.append("\t\tNULL\n" + "\t}\n" + "};\n") + # output function template if C file being written + cfile_out.append(f"{func_sig}\n{{{PARSE_FN_BODY}}}\n") + + # return the instance structure name + return (f"cmd_{name}", out, cfile_out) + + +def process_commands(infile, hfile, cfile, ctxname): + """Generate boilerplate output for a list of commands from infile.""" + instances = [] + + hfile.write( + f"""/* File autogenerated by {sys.argv[0]} */ +#ifndef GENERATED_COMMANDS_H +#define GENERATED_COMMANDS_H +#include <rte_common.h> +#include <cmdline.h> +#include <cmdline_parse_string.h> +#include <cmdline_parse_num.h> +#include <cmdline_parse_ipaddr.h> + +""" + ) + + for lineno, line in enumerate(infile.readlines()): + if line.lstrip().startswith("#"): + continue + if "#" not in line: + line = line + "#" # ensure split always works, even if no help text + tokens, comment = line.split("#", 1) + cmd_inst, h_out, c_out = process_command(lineno, tokens.strip().split(), comment.strip()) + hfile.write("\n".join(h_out)) + if cfile: + cfile.write("\n".join(c_out)) + instances.append(cmd_inst) + + inst_join_str = ",\n\t&" + hfile.write( + f""" +static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{ +\t&{inst_join_str.join(instances)}, +\tNULL +}}; + +#endif /* GENERATED_COMMANDS_H */ +""" + ) + + +def main(): + """Application main entry point.""" + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument( + "--stubs", + action="store_true", + help="Produce C file with empty function stubs for each command", + ) + ap.add_argument( + "--output-file", + "-o", + default="-", + help="Output header filename [default to stdout]", + ) + ap.add_argument( + "--context-name", + default="ctx", + help="Name given to the cmdline context variable in the output header [default=ctx]", + ) + ap.add_argument("infile", type=argparse.FileType("r"), help="File with list of commands") + args = ap.parse_args() + + if not args.stubs: + if args.output_file == "-": + process_commands(args.infile, sys.stdout, None, args.context_name) + else: + with open(args.output_file, "w") as hfile: + process_commands(args.infile, hfile, None, args.context_name) + else: + if not args.output_file.endswith(".h"): + ap.error( + "-o/--output-file: specify an output filename ending with .h when creating stubs" + ) + + cfilename = args.output_file[:-2] + ".c" + with open(args.output_file, "w") as hfile: + with open(cfilename, "w") as cfile: + cfile.write(f'#include "{args.output_file}"\n\n') + process_commands(args.infile, hfile, cfile, args.context_name) + + +if __name__ == "__main__": + main()
buildtools/meson.build +7 -0
@@ -19,6 +19,13 @@ get_cpu_count_cmd = py3 + files('get-cpu-count.py') get_numa_count_cmd = py3 + files('get-numa-count.py') get_test_suites_cmd = py3 + files('get-test-suites.py') has_hugepages_cmd = py3 + files('has-hugepages.py') +cmdline_gen_cmd = py3 + files('dpdk-cmdline-gen.py') + +# install any build tools that end-users might want also +install_data([ + 'dpdk-cmdline-gen.py', + ], + install_dir: 'bin') # select library and object file format pmdinfo = py3 + files('gen-pmdinfo-cfile.py') + [meson.current_build_dir()]
doc/guides/prog_guide/cmdline.rst +130 -1
137 lines not on this page · raw message
Signature · 1 line
2.39.2
Re: [PATCH v5 2/9] buildtools: script to generate cmdline boilerplate
Bruce Richardson, Oct 17, 2023 at 14:13:
Quoted 27 lines
Provide a "
dpdk-cmdline-gen.py" script for application developers to quickly generate the boilerplate code necessary for using the cmdline library.Example of use:
The script takes an input file with a list of commands the user wants in the app, where the parameter variables are tagged with the type. For example:$ cat commands.list list add <UINT16>x <UINT16>y echo <STRING>message add socket <STRING>path quitWhen run through the script as "./dpdk-cmdline-gen.py commands.list", the output will be the contents of a header file with all the boilerplate necessary for a commandline instance with those commands.
If the flag --stubs is passed, an output header filename must also be passed, in which case both a header file with the definitions and a C file with function stubs in it is written to disk. The separation is so that the header file can be rewritten at any future point to add more commands, while the C file can be kept as-is and extended by the user with any additional functions needed.
Quoted 7 lines
Signed-off-by Bruce Richardson <[email protected]>--- buildtools/dpdk-cmdline-gen.py | 190 ++++++++++++++++++++++++++++++ buildtools/meson.build | 7 ++ doc/guides/prog_guide/cmdline.rst | 131 +++++++++++++++++++- 3 files changed, 327 insertions(+), 1 deletion(-) create mode 100755 buildtools/dpdk-cmdline-gen.py
Hi Bruce,
thanks for the respin! I have some small remarks inline.
Quoted 58 lines
buildtools/dpdk-cmdline-gen.py new file +52
-0@@ -0,0 +1,190 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +""" +Script to automatically generate boilerplate for using DPDK cmdline library. +""" + +import argparse +import sys + +PARSE_FN_PARAMS = "void *parsed_result, struct cmdline *cl, void *data" +PARSE_FN_BODY = """ + /* TODO: command action */ + RTE_SET_USED(parsed_result); + RTE_SET_USED(cl); + RTE_SET_USED(data); +""" +NUMERIC_TYPES = [ + "UINT8", + "UINT16", + "UINT32", + "UINT64", + "INT8", + "INT16", + "INT32", + "INT64", +] + + +def process_command(lineno, tokens, comment): + """Generate the structures and definitions for a single command.""" + out = [] + cfile_out = [] + + if tokens[0].startswith("<"): + raise ValueError(f"Error line {lineno + 1}: command must start with a literal string") + + name_tokens = [] + for t in tokens: + if t.startswith("<"): + break + name_tokens.append(t) + name = "_".join(name_tokens) + + result_struct = [] + initializers = [] + token_list = [] + for t in tokens: + if t.startswith("<"): + t_type, t_name = t[1:].split(">") + t_val = "NULL"
buildtools/dpdk-cmdline-gen.py line 62
Quoted 10 lines
buildtools/dpdk-cmdline-gen.py new file +10
-0+ else: + t_type = "STRING" + t_name = t + t_val = f'"{t}"' + + if t_type == "STRING": + result_struct.append(f"\tcmdline_fixed_string_t {t_name};") + initializers.append( + f"static cmdline_parse_token_string_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_STRING_INITIALIZER(struct cmd_{name}_result, {t_name}, {t_val});"
Since you are now using multiline strings in process_commands(), why not use them everywhere?
It would make the code more readable in my opinion and would avoid inline f-string concatenation.
Quoted 22 lines
buildtools/dpdk-cmdline-gen.py new file +22
-0+ ) + elif t_type in NUMERIC_TYPES: + result_struct.append(f"\t{t_type.lower()}_t {t_name};") + initializers.append( + f"static cmdline_parse_token_num_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_NUM_INITIALIZER(struct cmd_{name}_result, {t_name}, RTE_{t_type});" + ) + elif t_type in ["IP", "IP_ADDR", "IPADDR"]: + result_struct.append(f"\tcmdline_ipaddr_t {t_name};") + initializers.append( + f"cmdline_parse_token_ipaddr_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_IPV4_INITIALIZER(struct cmd_{name}_result, {t_name});" + ) + else: + raise TypeError(f"Error line {lineno + 1}: unknown token type '{t_type}'") + token_list.append(f"cmd_{name}_{t_name}_tok") + + out.append(f'/* Auto-generated handling for command "{" ".join(tokens)}" */') + # output function prototype + func_sig = f"void\ncmd_{name}_parsed({PARSE_FN_PARAMS})" + out.append(f"extern {func_sig};\n") + # output result data structure
buildtools/dpdk-cmdline-gen.py line 94
Quoted 10 lines
buildtools/dpdk-cmdline-gen.py new file +10
-0+ out.append(f"struct cmd_{name}_result {{\n" + "\n".join(result_struct) + "\n};\n") + # output the initializer tokens + out.append("\n".join(initializers) + "\n") + # output the instance structure + out.append( + f"static cmdline_parse_inst_t cmd_{name} = {{\n" + + f"\t.f = cmd_{name}_parsed,\n" + + "\t.data = NULL,\n" + + f'\t.help_str = "{comment}",\n' + + "\t.tokens = {"
Especially here :)
Quoted 40 lines
buildtools/dpdk-cmdline-gen.py new file +40
-0+ ) + for t in token_list: + out.append(f"\t\t(void *)&{t},") + out.append("\t\tNULL\n" + "\t}\n" + "};\n") + # output function template if C file being written + cfile_out.append(f"{func_sig}\n{{{PARSE_FN_BODY}}}\n") + + # return the instance structure name + return (f"cmd_{name}", out, cfile_out) + + +def process_commands(infile, hfile, cfile, ctxname): + """Generate boilerplate output for a list of commands from infile.""" + instances = [] + + hfile.write( + f"""/* File autogenerated by {sys.argv[0]} */ +#ifndef GENERATED_COMMANDS_H +#define GENERATED_COMMANDS_H +#include <rte_common.h> +#include <cmdline.h> +#include <cmdline_parse_string.h> +#include <cmdline_parse_num.h> +#include <cmdline_parse_ipaddr.h> + +""" + ) + + for lineno, line in enumerate(infile.readlines()): + if line.lstrip().startswith("#"): + continue + if "#" not in line: + line = line + "#" # ensure split always works, even if no help text + tokens, comment = line.split("#", 1) + cmd_inst, h_out, c_out = process_command(lineno, tokens.strip().split(), comment.strip()) + hfile.write("\n".join(h_out)) + if cfile: + cfile.write("\n".join(c_out)) + instances.append(cmd_inst) +
buildtools/dpdk-cmdline-gen.py line 144
Quoted 10 lines
buildtools/dpdk-cmdline-gen.py new file +10
-0+ inst_join_str = ",\n\t&" + hfile.write( + f""" +static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{ +\t&{inst_join_str.join(instances)}, +\tNULL +}}; + +#endif /* GENERATED_COMMANDS_H */ +"""
By the way, you can put literal tabs in the multiline strings. That way the indentation will look the same than in the generated C code.
f"""
static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{
&{inst_join_str.join(instances)},
NULL
}};#endif /* GENERATED_COMMANDS_H */
"""
Quoted 46 lines
buildtools/dpdk-cmdline-gen.py new file +46
-0+ ) + + +def main(): + """Application main entry point.""" + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument( + "--stubs", + action="store_true", + help="Produce C file with empty function stubs for each command", + ) + ap.add_argument( + "--output-file", + "-o", + default="-", + help="Output header filename [default to stdout]", + ) + ap.add_argument( + "--context-name", + default="ctx", + help="Name given to the cmdline context variable in the output header [default=ctx]", + ) + ap.add_argument("infile", type=argparse.FileType("r"), help="File with list of commands") + args = ap.parse_args() + + if not args.stubs: + if args.output_file == "-": + process_commands(args.infile, sys.stdout, None, args.context_name) + else: + with open(args.output_file, "w") as hfile: + process_commands(args.infile, hfile, None, args.context_name) + else: + if not args.output_file.endswith(".h"): + ap.error( + "-o/--output-file: specify an output filename ending with .h when creating stubs" + ) + + cfilename = args.output_file[:-2] + ".c" + with open(args.output_file, "w") as hfile: + with open(cfilename, "w") as cfile: + cfile.write(f'#include "{args.output_file}"\n\n') + process_commands(args.infile, hfile, cfile, args.context_name) + + +if __name__ == "__main__": + main()
Signature · 3 lines
Robin Jarry Principal Software Engineer Red Hat, Telco/NFV
Re: [PATCH v5 2/9] buildtools: script to generate cmdline boilerplate
Quoted 112 lines · Robin Jarry
Bruce Richardson, Oct 17, 2023 at 14:13:
Quoted 27 lines
Provide a "
dpdk-cmdline-gen.py" script for application developers to quickly generate the boilerplate code necessary for using the cmdline library.Example of use:
The script takes an input file with a list of commands the user wants in the app, where the parameter variables are tagged with the type. For example:$ cat commands.list list add <UINT16>x <UINT16>y echo <STRING>message add socket <STRING>path quitWhen run through the script as "./dpdk-cmdline-gen.py commands.list", the output will be the contents of a header file with all the boilerplate necessary for a commandline instance with those commands.
If the flag --stubs is passed, an output header filename must also be passed, in which case both a header file with the definitions and a C file with function stubs in it is written to disk. The separation is so that the header file can be rewritten at any future point to add more commands, while the C file can be kept as-is and extended by the user with any additional functions needed.
Quoted 7 lines
Signed-off-by Bruce Richardson <[email protected]>--- buildtools/dpdk-cmdline-gen.py | 190 ++++++++++++++++++++++++++++++ buildtools/meson.build | 7 ++ doc/guides/prog_guide/cmdline.rst | 131 +++++++++++++++++++- 3 files changed, 327 insertions(+), 1 deletion(-) create mode 100755 buildtools/dpdk-cmdline-gen.pyHi Bruce,
thanks for the respin! I have some small remarks inline.
Quoted 58 lines
buildtools/dpdk-cmdline-gen.py new file +52
-0@@ -0,0 +1,190 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +""" +Script to automatically generate boilerplate for using DPDK cmdline library. +""" + +import argparse +import sys + +PARSE_FN_PARAMS = "void *parsed_result, struct cmdline *cl, void *data" +PARSE_FN_BODY = """ + /* TODO: command action */ + RTE_SET_USED(parsed_result); + RTE_SET_USED(cl); + RTE_SET_USED(data); +""" +NUMERIC_TYPES = [ + "UINT8", + "UINT16", + "UINT32", + "UINT64", + "INT8", + "INT16", + "INT32", + "INT64", +] + + +def process_command(lineno, tokens, comment): + """Generate the structures and definitions for a single command.""" + out = [] + cfile_out = [] + + if tokens[0].startswith("<"): + raise ValueError(f"Error line {lineno + 1}: command must start with a literal string") + + name_tokens = [] + for t in tokens: + if t.startswith("<"): + break + name_tokens.append(t) + name = "_".join(name_tokens) + + result_struct = [] + initializers = [] + token_list = [] + for t in tokens: + if t.startswith("<"): + t_type, t_name = t[1:].split(">") + t_val = "NULL"buildtools/dpdk-cmdline-gen.py line 62
Quoted 10 lines
buildtools/dpdk-cmdline-gen.py new file +10
-0+ else: + t_type = "STRING" + t_name = t + t_val = f'"{t}"' + + if t_type == "STRING": + result_struct.append(f"\tcmdline_fixed_string_t {t_name};") + initializers.append( + f"static cmdline_parse_token_string_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_STRING_INITIALIZER(struct cmd_{name}_result, {t_name}, {t_val});"Since you are now using multiline strings in
process_commands(), why not use them everywhere?
Quoted 3 lines
It would make the code more readable in my opinion and would avoid inline f-string concatenation.
I'm a bit unsure about this case. I notice I can at least remove the "+" symbol and have implicit string concat, but I really don't like the way the indentation gets adjusted when we use multi-line strings, since the indent has to match the C-code indent rather than the python indentation levels.
Therefore, I'm going to leave these pairs of lines as they are.
Quoted 33 lines
Quoted 22 lines
buildtools/dpdk-cmdline-gen.py new file +22
-0+ ) + elif t_type in NUMERIC_TYPES: + result_struct.append(f"\t{t_type.lower()}_t {t_name};") + initializers.append( + f"static cmdline_parse_token_num_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_NUM_INITIALIZER(struct cmd_{name}_result, {t_name}, RTE_{t_type});" + ) + elif t_type in ["IP", "IP_ADDR", "IPADDR"]: + result_struct.append(f"\tcmdline_ipaddr_t {t_name};") + initializers.append( + f"cmdline_parse_token_ipaddr_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_IPV4_INITIALIZER(struct cmd_{name}_result, {t_name});" + ) + else: + raise TypeError(f"Error line {lineno + 1}: unknown token type '{t_type}'") + token_list.append(f"cmd_{name}_{t_name}_tok") + + out.append(f'/* Auto-generated handling for command "{" ".join(tokens)}" */') + # output function prototype + func_sig = f"void\ncmd_{name}_parsed({PARSE_FN_PARAMS})" + out.append(f"extern {func_sig};\n") + # output result data structurebuildtools/dpdk-cmdline-gen.py line 94
Quoted 10 lines
buildtools/dpdk-cmdline-gen.py new file +10
-0+ out.append(f"struct cmd_{name}_result {{\n" + "\n".join(result_struct) + "\n};\n") + # output the initializer tokens + out.append("\n".join(initializers) + "\n") + # output the instance structure + out.append( + f"static cmdline_parse_inst_t cmd_{name} = {{\n" + + f"\t.f = cmd_{name}_parsed,\n" + + "\t.data = NULL,\n" + + f'\t.help_str = "{comment}",\n' + + "\t.tokens = {"
Quoted 2 lines
Especially here :)
I'll see about converting this and what it looks like. Maybe see if textwrap.dedent will allow sensible indentation with it.
Quoted 54 lines
Quoted 40 lines
buildtools/dpdk-cmdline-gen.py new file +40
-0+ ) + for t in token_list: + out.append(f"\t\t(void *)&{t},") + out.append("\t\tNULL\n" + "\t}\n" + "};\n") + # output function template if C file being written + cfile_out.append(f"{func_sig}\n{{{PARSE_FN_BODY}}}\n") + + # return the instance structure name + return (f"cmd_{name}", out, cfile_out) + + +def process_commands(infile, hfile, cfile, ctxname): + """Generate boilerplate output for a list of commands from infile.""" + instances = [] + + hfile.write( + f"""/* File autogenerated by {sys.argv[0]} */ +#ifndef GENERATED_COMMANDS_H +#define GENERATED_COMMANDS_H +#include <rte_common.h> +#include <cmdline.h> +#include <cmdline_parse_string.h> +#include <cmdline_parse_num.h> +#include <cmdline_parse_ipaddr.h> + +""" + ) + + for lineno, line in enumerate(infile.readlines()): + if line.lstrip().startswith("#"): + continue + if "#" not in line: + line = line + "#" # ensure split always works, even if no help text + tokens, comment = line.split("#", 1) + cmd_inst, h_out, c_out = process_command(lineno, tokens.strip().split(), comment.strip()) + hfile.write("\n".join(h_out)) + if cfile: + cfile.write("\n".join(c_out)) + instances.append(cmd_inst) +buildtools/dpdk-cmdline-gen.py line 144
Quoted 10 lines
buildtools/dpdk-cmdline-gen.py new file +10
-0+ inst_join_str = ",\n\t&" + hfile.write( + f""" +static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{ +\t&{inst_join_str.join(instances)}, +\tNULL +}}; + +#endif /* GENERATED_COMMANDS_H */ +"""By the way, you can put literal tabs in the multiline strings. That way the indentation will look the same than in the generated C code.
Quoted 9 lines
f""" static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{ &{inst_join_str.join(instances)}, NULL }};#endif /*
GENERATED_COMMANDS_H*/
"""
Trouble with that is that for some editors when using python, the tabs are automatically expanded with spaces. For me using eclipse right now, I physically can't insert leading tabs into the file! I need to open in vim or some other editor to do it (or maybe use copy-paste from a C file), and while that's not a big deal for me, it will be a problem for anyone else editing this in future who has similar settings.
/Bruce
PATCH v5 3/9 ci: allow use of DPDK tools when building examples
In reply to Bruce RichardsonTo allow use of the DPDK python scripts (installed in $(prefix)/bin) from within the makefiles of our examples, we need to export the PATH variable with the location of our installed scripts from within our CI scripts. This matches what is already done for other paths e.g. the PKG_CONFIG_PATH variable.
--- .ci/linux-build.sh | 1 + 1 file changed, 1 insertion(+)
.ci/linux-build.sh +1 -0
@@ -174,6 +174,7 @@ fi if [ "$BUILD_EXAMPLES" = "true" ]; then [ -d install ] || DESTDIR=$(pwd)/install meson install -C build export LD_LIBRARY_PATH=$(dirname $(find $(pwd)/install -name librte_eal.so)):$LD_LIBRARY_PATH + export PATH=$(dirname $(find $(pwd)/install -name dpdk-devbind.py)):$PATH export PKG_CONFIG_PATH=$(dirname $(find $(pwd)/install -name libdpdk.pc)):$PKG_CONFIG_PATH export PKGCONF="pkg-config --define-prefix" find build/examples -maxdepth 1 -type f -name "dpdk-*" |
Signature · 1 line
2.39.2
Re: [PATCH v5 3/9] ci: allow use of DPDK tools when building examples
Quoted 8 lines · Bruce Richardson
To allow use of the DPDK python scripts (installed in $(prefix)/bin) from within the makefiles of our examples, we need to export the PATH variable with the location of our installed scripts from within our CI scripts. This matches what is already done for other paths e.g. the
PKG_CONFIG_PATHvariable.Signed-off-by Bruce Richardson <[email protected]>---
PATCH v5 4/9 examples/simple_mp: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/multi_process/simple_mp/Makefile | 12 +- examples/multi_process/simple_mp/meson.build | 9 ++ .../multi_process/simple_mp/mp_commands.c | 106 ++---------------- .../multi_process/simple_mp/mp_commands.h | 14 --- .../multi_process/simple_mp/mp_commands.list | 3 + 5 files changed, 30 insertions(+), 114 deletions(-) delete mode 100644 examples/multi_process/simple_mp/mp_commands.h create mode 100644 examples/multi_process/simple_mp/mp_commands.list
examples/multi_process/simple_mp/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = simple_mp # all source are stored in SRCS-y SRCS-y := main.c mp_commands.c +SRC-DEPS := build/mp_commands.h PKGCONF ?= pkg-config
@@ -22,10 +23,13 @@ static: build/$(APP)-static ln -sf $(APP)-static build/$(APP) PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/mp_commands.h: mp_commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=simple_mp_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -36,10 +40,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -47,5 +51,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/mp_commands.h test -d build && rmdir -p build || true
examples/multi_process/simple_mp/meson.build +9 -0
@@ -7,7 +7,16 @@ # DPDK instance, use 'make' allow_experimental_apis = true + +cmd_h = custom_target('commands_hdr', + output: 'mp_commands.h', + input: files('mp_commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=simple_mp_ctx', '@INPUT@'] +) + sources = files( 'mp_commands.c', 'main.c', ) +sources += cmd_h
examples/multi_process/simple_mp/mp_commands.c +10 -96
133 lines not on this page · raw message
examples/multi_process/simple_mp/mp_commands.h deleted +0 -14
@@ -1,14 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2010-2014 Intel Corporation -*/ - -#ifndef _SIMPLE_MP_COMMANDS_H_ -#define _SIMPLE_MP_COMMANDS_H_ - -extern struct rte_ring *send_ring; -extern struct rte_mempool *message_pool; -extern volatile int quit; - -extern cmdline_parse_ctx_t simple_mp_ctx[]; - -#endif /* _SIMPLE_MP_COMMANDS_H_ */
examples/multi_process/simple_mp/mp_commands.list new file +3 -0
@@ -0,0 +1,3 @@ +send <STRING>message # send a string to another process +help # show help +quit # close the application
Signature · 1 line
2.39.2
PATCH v5 5/9 examples/hotplug_mp: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/multi_process/hotplug_mp/Makefile | 12 +- examples/multi_process/hotplug_mp/commands.c | 147 ++---------------- examples/multi_process/hotplug_mp/commands.h | 10 -- .../multi_process/hotplug_mp/commands.list | 8 + examples/multi_process/hotplug_mp/meson.build | 9 ++ 5 files changed, 38 insertions(+), 148 deletions(-) delete mode 100644 examples/multi_process/hotplug_mp/commands.h create mode 100644 examples/multi_process/hotplug_mp/commands.list
examples/multi_process/hotplug_mp/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = hotplug_mp # all source are stored in SRCS-y SRCS-y := main.c commands.c +SRC-DEPS := build/commands.h PKGCONF ?= pkg-config
@@ -22,10 +23,13 @@ static: build/$(APP)-static ln -sf $(APP)-static build/$(APP) PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -36,10 +40,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -47,5 +51,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/commands.h test -d build && rmdir -p build || true
examples/multi_process/hotplug_mp/commands.c +13 -134
189 lines not on this page · raw message
examples/multi_process/hotplug_mp/commands.h deleted +0 -10
@@ -1,10 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2018 Intel Corporation -*/ - -#ifndef _COMMANDS_H_ -#define _COMMANDS_H_ - -extern cmdline_parse_ctx_t main_ctx[]; - -#endif /* _COMMANDS_H_ */
examples/multi_process/hotplug_mp/commands.list new file +8 -0
@@ -0,0 +1,8 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +attach <STRING>devargs # attach a device +detach <STRING>devargs # detach a device +list # list all devices +help # show help +quit # quit
examples/multi_process/hotplug_mp/meson.build +9 -0
@@ -7,7 +7,16 @@ # DPDK instance, use 'make' allow_experimental_apis = true + +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) + sources = files( 'commands.c', 'main.c', ) +sources += cmd_h
Signature · 1 line
2.39.2
PATCH v5 6/9 examples/bond: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
---
Note: the original help text on some of the commands in this example
were not useful "this command do not handle any arguments". Therefore, when converting over to the command script, the per-command help info has been updated with reference to the code rather than a literal transfer of the existing help text, as was done with the previous 2 example apps.
--- examples/bond/Makefile | 12 +- examples/bond/commands.list | 6 + examples/bond/main.c | 161 ++---------------- examples/bond/main.h | 10 -- examples/bond/meson.build | 8 + .../multi_process/simple_mp/mp_commands.list | 3 + 6 files changed, 40 insertions(+), 160 deletions(-) create mode 100644 examples/bond/commands.list delete mode 100644 examples/bond/main.h
examples/bond/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = bond_app # all source are stored in SRCS-y SRCS-y := main.c +SRC-DEPS := build/commands.h PKGCONF ?= pkg-config
@@ -24,10 +25,13 @@ static: build/$(APP)-static LDFLAGS += -lrte_net_bond PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -38,10 +42,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -49,5 +53,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/*.h test -d build && rmdir -p build || true
examples/bond/commands.list new file +6 -0
@@ -0,0 +1,6 @@ +send <IP>ip # sends one ARPrequest through bonding for IP +start # starts listening if not started at startup +stop # stops listening +show # shows some bond info, e.g. active members +help # show help +quit # close application
examples/bond/main.c +15 -146
218 lines not on this page · raw message
examples/bond/main.h deleted +0 -10
@@ -1,10 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2010-2015 Intel Corporation -*/ - -#ifndef _MAIN_H_ -#define _MAIN_H_ - -int main (int argc,char *argv[]); - -#endif /* ifndef _MAIN_H_ */
examples/bond/meson.build +8 -0
@@ -11,3 +11,11 @@ allow_experimental_apis = true sources = files( 'main.c', ) + +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) +sources += cmd_h
examples/multi_process/simple_mp/mp_commands.list +3 -0
@@ -1,3 +1,6 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# send <STRING>message # send a string to another process help # show help quit # close the application
Signature · 1 line
2.39.2
PATCH v5 7/9 examples/vdpa: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/vdpa/Makefile | 12 ++-- examples/vdpa/commands.list | 8 +++ examples/vdpa/main.c | 131 ++---------------------------------- examples/vdpa/meson.build | 7 ++ 4 files changed, 30 insertions(+), 128 deletions(-) create mode 100644 examples/vdpa/commands.list
examples/vdpa/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = vdpa # all source are stored in SRCS-y SRCS-y := main.c +SRC-DEPS := build/commands.h CFLAGS += -DALLOW_EXPERIMENTAL_API PKGCONF ?= pkg-config
@@ -23,10 +24,13 @@ static: build/$(APP)-static ln -sf $(APP)-static build/$(APP) PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -35,10 +39,10 @@ $(error "Cannot generate statically-linked binaries with this version of pkg-con endif endif -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -46,5 +50,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/*.h test -d build && rmdir -p build || true
examples/vdpa/commands.list new file +8 -0
@@ -0,0 +1,8 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +help # show help +list # list all available vdpa devices +create <STRING>socket_path <STRING>bdf # create a new vdpa port +stats <STRING>bdf <UINT32>qid # show device statistics +quit # exit application
examples/vdpa/main.c +7 -124
175 lines not on this page · raw message
examples/vdpa/meson.build +7 -0
@@ -16,3 +16,10 @@ allow_experimental_apis = true sources = files( 'main.c', ) +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) +sources += cmd_h
Signature · 1 line
2.39.2
PATCH v5 8/9 buildtools/dpdk-cmdline-gen: support option strings
In reply to Bruce RichardsonAdd support to the commandline generator for option strings, where there are only a limited number of acceptable values to be passed as a parameter.
--- buildtools/dpdk-cmdline-gen.py | 7 +++++++ doc/guides/prog_guide/cmdline.rst | 6 +++++- 2 files changed, 12 insertions(+), 1 deletion(-)
buildtools/dpdk-cmdline-gen.py +7 -0
@@ -73,6 +73,13 @@ def process_command(lineno, tokens, comment): f"cmdline_parse_token_ipaddr_t cmd_{name}_{t_name}_tok =\n" + f"\tTOKEN_IPV4_INITIALIZER(struct cmd_{name}_result, {t_name});" ) + elif t_type.startswith("|") and t_type.endswith("|"): + result_struct.append(f"\tcmdline_fixed_string_t {t_name};") + t_val = f'"{t_type[1:-1].replace("|","#")}"' + initializers.append( + f"static cmdline_parse_token_string_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_STRING_INITIALIZER(struct cmd_{name}_result, {t_name}, {t_val});" + ) else: raise TypeError(f"Error line {lineno + 1}: unknown token type '{t_type}'") token_list.append(f"cmd_{name}_{t_name}_tok")
doc/guides/prog_guide/cmdline.rst +5 -1
@@ -62,7 +62,8 @@ The format of the list file must be: * One command per line -* Variable fields are prefixed by the type-name in angle-brackets, for example: +* Variable fields are prefixed by the type-name, or "|"-delimited option-list, in angle-brackets. + For example: * ``<STRING>message``
@@ -70,6 +71,8 @@ The format of the list file must be: * ``<IP>src_ip`` + * ``<|rx|tx|rxtx|>mode`` + * The help text for a command is given in the form of a comment on the same line as the command An example list file, with a variety of (unrelated) commands, is shown below::
@@ -79,6 +82,7 @@ An example list file, with a variety of (unrelated) commands, is shown below:: add <UINT16>x <UINT16>y # add x and y echo <STRING>message # print message to screen add socket <STRING>path # add unix socket with the given path + set mode <|rx|tx|>rxtx # set Rx-only or Tx-only mode quit # close the application Running the Generator Script
Signature · 1 line
2.39.2
PATCH v5 9/9 examples/ntb: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/ntb/Makefile | 12 ++- examples/ntb/commands.list | 11 ++ examples/ntb/meson.build | 7 ++ examples/ntb/ntb_fwd.c | 200 ++++--------------------------------- 4 files changed, 47 insertions(+), 183 deletions(-) create mode 100644 examples/ntb/commands.list
examples/ntb/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = ntb_fwd # all source are stored in SRCS-y SRCS-y := ntb_fwd.c +SRC-DEPS := build/commands.h PKGCONF ?= pkg-config
@@ -25,10 +26,13 @@ CFLAGS += -D_FILE_OFFSET_BITS=64 LDFLAGS += -pthread PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -39,10 +43,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -50,5 +54,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/*.h test -d build && rmdir -p build || true
examples/ntb/commands.list new file +11 -0
@@ -0,0 +1,11 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +help # show help +quit # exit application +send <STRING>filepath # send <file_path> +start # start pkt fwd between ntb and ethdev +stop # stop packet forwarding +show port stats # show statistics for all ports +clear port stats # clear all port statistics +set fwd <|file-trans|iofwd|txonly|rxonly|>mode # set forwarding mode as file-trans|rxonly|txonly|iofwd
examples/ntb/meson.build +7 -0
@@ -17,3 +17,10 @@ cflags += ['-D_FILE_OFFSET_BITS=64'] sources = files( 'ntb_fwd.c', ) +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) +sources += cmd_h
examples/ntb/ntb_fwd.c +21 -179
272 lines not on this page · raw message
Signature · 1 line
2.39.2
v6 cover document and simplify use of cmdline
In reply to Bruce RichardsonThe DPDK commandline library is widely used by apps and examples within DPDK, but it is not documented in our programmers guide and it requires a lot of boilerplate code definitions in order to used. We can improve this situation by creating a simple python script to automatically generate the boilerplate from a list of commands.
This patchset contains a new documentation chapter on cmdline library, going through step-by-step how to add commands and create the necessary token lists and parse contexts.
Following that initial doc patch, the set then contains a boilerplate-generating script, as well as a set of four patches showing its use, by converting four examples to use the script instead of having the hard-coded boilerplate. Once the script is used, adding a new command becomes as simple as adding the desired command to the .list file, and then writing the required function which will be called for that command. No other boilerplate coding is necessary.
Final two patches, from V5 onwards, add support for option-lists in values, and then use that support to convert over a fifth sample app - ntb.
Cmdline script obviously does not cover the full range of capabilities of the commandline lib, but does cover the most used parts. The code-saving to each of the examples by auto-generating the boilerplate is significant, and probably more examples with commandlines can be converted over in future.
The "cmdline" example itself, is not converted over, as it should probably remain as a simple example of direct library use without the script.
v6:
* rework syntax of the option lists following feedback from David. Now use "(x,y,z)" instead of "|x|y|z|", to avoid giving impression of regex support
V5:
* Added copyright headers to command list files
* Add support for option lists
* Convert examples/ntb to use script
V4:
* Reworked script following feedback from Robin J.
- formatted code with black
- used multi-line strings
- replaced sys.exit(1) with proper error handling
- per-command function returns lists rather than printing directly
- other small cleanups
* Added change to CI script so the cmdline script is in PATH
* Converted VDPA example to script, saving another 100 LOC
V3:
* Added lots of documentation
* Added support for help text for each command
* Cleaned up script a little so it passes pycodestyle and most flake8 checks, when line-length is set to max 100.
* Removed RFC tag, as I consider this patchset stable enough for consideration in a release.
V2-RFC:
* Add support for IP addresses in commands
* Move to buildtools directory and make installable
* Convert 3 examples to use script, and eliminate their boilerplate *** SUBJECT HERE ***
*** BLURB HERE ***
Bruce Richardson (9):
doc/prog_guide: new chapter on cmdline library
buildtools: script to generate cmdline boilerplate
ci: allow use of DPDK tools when building examples examples/simple_mp: auto-generate cmdline boilerplate examples/hotplug_mp: auto-generate cmdline boilerplate examples/bond: auto-generate cmdline boilerplate examples/vdpa: auto-generate cmdline boilerplate buildtools/dpdk-cmdline-gen: support option strings examples/ntb: auto-generate cmdline boilerplate
.ci/linux-build.sh | 1 + app/test/commands.c | 2 + buildtools/dpdk-cmdline-gen.py | 197 ++++++++ buildtools/meson.build | 7 + doc/guides/prog_guide/cmdline.rst | 473 ++++++++++++++++++ doc/guides/prog_guide/index.rst | 1 + examples/bond/Makefile | 12 +- examples/bond/commands.list | 6 + examples/bond/main.c | 161 +----- examples/bond/main.h | 10 - examples/bond/meson.build | 8 + examples/multi_process/hotplug_mp/Makefile | 12 +- examples/multi_process/hotplug_mp/commands.c | 147 +----- examples/multi_process/hotplug_mp/commands.h | 10 - .../multi_process/hotplug_mp/commands.list | 8 + examples/multi_process/hotplug_mp/meson.build | 9 + examples/multi_process/simple_mp/Makefile | 12 +- examples/multi_process/simple_mp/meson.build | 9 + .../multi_process/simple_mp/mp_commands.c | 106 +--- .../multi_process/simple_mp/mp_commands.h | 14 - .../multi_process/simple_mp/mp_commands.list | 6 + examples/ntb/Makefile | 12 +- examples/ntb/commands.list | 11 + examples/ntb/meson.build | 7 + examples/ntb/ntb_fwd.c | 200 +------- examples/vdpa/Makefile | 12 +- examples/vdpa/commands.list | 8 + examples/vdpa/main.c | 131 +---- examples/vdpa/meson.build | 7 + 29 files changed, 866 insertions(+), 733 deletions(-) create mode 100755 buildtools/dpdk-cmdline-gen.py create mode 100644 doc/guides/prog_guide/cmdline.rst create mode 100644 examples/bond/commands.list delete mode 100644 examples/bond/main.h delete mode 100644 examples/multi_process/hotplug_mp/commands.h create mode 100644 examples/multi_process/hotplug_mp/commands.list delete mode 100644 examples/multi_process/simple_mp/mp_commands.h create mode 100644 examples/multi_process/simple_mp/mp_commands.list create mode 100644 examples/ntb/commands.list create mode 100644 examples/vdpa/commands.list
--
2.39.2
PATCH v6 1/9 doc/prog_guide: new chapter on cmdline library
The cmdline library was not documented in our programmers guide, so add a new chapter on it. This chapter covers step-by-step how to use the library, rather than focusing on the library internals. This complements the existing cmdline example app document, providing more details on the process of using the library.
--- app/test/commands.c | 2 + doc/guides/prog_guide/cmdline.rst | 337 ++++++++++++++++++++++++++++++ doc/guides/prog_guide/index.rst | 1 + 3 files changed, 340 insertions(+) create mode 100644 doc/guides/prog_guide/cmdline.rst
app/test/commands.c +2 -0
@@ -108,6 +108,7 @@ dump_struct_sizes(void)#undef DUMP_SIZE } +/* Add the dump_* tests cases 8< */ static void cmd_dump_parsed (void *parsed_result, __rte_unused struct cmdline *cl, __rte_unused void *data)
@@ -155,6 +156,7 @@ cmdline_parse_inst_t cmd_dump = { NULL, }, }; +/* >8 End of add the dump_* tests cases */ /****************/
doc/guides/prog_guide/cmdline.rst new file +337 -0
337 lines not on this page · raw message
doc/guides/prog_guide/index.rst +1 -0
@@ -13,6 +13,7 @@ Programmer's Guide source_org env_abstraction_layer log_lib + cmdline service_cores trace_lib rcu_lib
Signature · 1 line
2.39.2
PATCH v6 2/9 buildtools: script to generate cmdline boilerplate
In reply to Bruce RichardsonProvide a "dpdk-cmdline-gen.py" script for application developers to quickly generate the boilerplate code necessary for using the cmdline library.
Example of use:
The script takes an input file with a list of commands the user wants in the app, where the parameter variables are tagged with the type. For example:
$ cat commands.list list add <UINT16>x <UINT16>y echo <STRING>message add socket <STRING>path quit
When run through the script as "./dpdk-cmdline-gen.py commands.list", the output will be the contents of a header file with all the boilerplate necessary for a commandline instance with those commands.
If the flag --stubs is passed, an output header filename must also be passed, in which case both a header file with the definitions and a C file with function stubs in it is written to disk. The separation is so that the header file can be rewritten at any future point to add more commands, while the C file can be kept as-is and extended by the user with any additional functions needed.
--- buildtools/dpdk-cmdline-gen.py | 190 ++++++++++++++++++++++++++++++ buildtools/meson.build | 7 ++ doc/guides/prog_guide/cmdline.rst | 131 +++++++++++++++++++- 3 files changed, 327 insertions(+), 1 deletion(-) create mode 100755 buildtools/dpdk-cmdline-gen.py
buildtools/dpdk-cmdline-gen.py new file +190 -0
@@ -0,0 +1,190 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +""" +Script to automatically generate boilerplate for using DPDK cmdline library. +""" + +import argparse +import sys + +PARSE_FN_PARAMS = "void *parsed_result, struct cmdline *cl, void *data" +PARSE_FN_BODY = """ + /* TODO: command action */ + RTE_SET_USED(parsed_result); + RTE_SET_USED(cl); + RTE_SET_USED(data); +""" +NUMERIC_TYPES = [ + "UINT8", + "UINT16", + "UINT32", + "UINT64", + "INT8", + "INT16", + "INT32", + "INT64", +] + + +def process_command(lineno, tokens, comment): + """Generate the structures and definitions for a single command.""" + out = [] + cfile_out = [] + + if tokens[0].startswith("<"): + raise ValueError(f"Error line {lineno + 1}: command must start with a literal string") + + name_tokens = [] + for t in tokens: + if t.startswith("<"): + break + name_tokens.append(t) + name = "_".join(name_tokens) + + result_struct = [] + initializers = [] + token_list = [] + for t in tokens: + if t.startswith("<"): + t_type, t_name = t[1:].split(">") + t_val = "NULL" + else: + t_type = "STRING" + t_name = t + t_val = f'"{t}"' + + if t_type == "STRING": + result_struct.append(f"\tcmdline_fixed_string_t {t_name};") + initializers.append( + f"static cmdline_parse_token_string_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_STRING_INITIALIZER(struct cmd_{name}_result, {t_name}, {t_val});" + ) + elif t_type in NUMERIC_TYPES: + result_struct.append(f"\t{t_type.lower()}_t {t_name};") + initializers.append( + f"static cmdline_parse_token_num_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_NUM_INITIALIZER(struct cmd_{name}_result, {t_name}, RTE_{t_type});" + ) + elif t_type in ["IP", "IP_ADDR", "IPADDR"]: + result_struct.append(f"\tcmdline_ipaddr_t {t_name};") + initializers.append( + f"cmdline_parse_token_ipaddr_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_IPV4_INITIALIZER(struct cmd_{name}_result, {t_name});" + ) + else: + raise TypeError(f"Error line {lineno + 1}: unknown token type '{t_type}'") + token_list.append(f"cmd_{name}_{t_name}_tok") + + out.append(f'/* Auto-generated handling for command "{" ".join(tokens)}" */') + # output function prototype + func_sig = f"void\ncmd_{name}_parsed({PARSE_FN_PARAMS})" + out.append(f"extern {func_sig};\n") + # output result data structure + out.append(f"struct cmd_{name}_result {{\n" + "\n".join(result_struct) + "\n};\n") + # output the initializer tokens + out.append("\n".join(initializers) + "\n") + # output the instance structure + out.append( + f"static cmdline_parse_inst_t cmd_{name} = {{\n" + + f"\t.f = cmd_{name}_parsed,\n" + + "\t.data = NULL,\n" + + f'\t.help_str = "{comment}",\n' + + "\t.tokens = {" + ) + for t in token_list: + out.append(f"\t\t(void *)&{t},") + out.append("\t\tNULL\n" + "\t}\n" + "};\n") + # output function template if C file being written + cfile_out.append(f"{func_sig}\n{{{PARSE_FN_BODY}}}\n") + + # return the instance structure name + return (f"cmd_{name}", out, cfile_out) + + +def process_commands(infile, hfile, cfile, ctxname): + """Generate boilerplate output for a list of commands from infile.""" + instances = [] + + hfile.write( + f"""/* File autogenerated by {sys.argv[0]} */ +#ifndef GENERATED_COMMANDS_H +#define GENERATED_COMMANDS_H +#include <rte_common.h> +#include <cmdline.h> +#include <cmdline_parse_string.h> +#include <cmdline_parse_num.h> +#include <cmdline_parse_ipaddr.h> + +""" + ) + + for lineno, line in enumerate(infile.readlines()): + if line.lstrip().startswith("#"): + continue + if "#" not in line: + line = line + "#" # ensure split always works, even if no help text + tokens, comment = line.split("#", 1) + cmd_inst, h_out, c_out = process_command(lineno, tokens.strip().split(), comment.strip()) + hfile.write("\n".join(h_out)) + if cfile: + cfile.write("\n".join(c_out)) + instances.append(cmd_inst) + + inst_join_str = ",\n\t&" + hfile.write( + f""" +static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{ +\t&{inst_join_str.join(instances)}, +\tNULL +}}; + +#endif /* GENERATED_COMMANDS_H */ +""" + ) + + +def main(): + """Application main entry point.""" + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument( + "--stubs", + action="store_true", + help="Produce C file with empty function stubs for each command", + ) + ap.add_argument( + "--output-file", + "-o", + default="-", + help="Output header filename [default to stdout]", + ) + ap.add_argument( + "--context-name", + default="ctx", + help="Name given to the cmdline context variable in the output header [default=ctx]", + ) + ap.add_argument("infile", type=argparse.FileType("r"), help="File with list of commands") + args = ap.parse_args() + + if not args.stubs: + if args.output_file == "-": + process_commands(args.infile, sys.stdout, None, args.context_name) + else: + with open(args.output_file, "w") as hfile: + process_commands(args.infile, hfile, None, args.context_name) + else: + if not args.output_file.endswith(".h"): + ap.error( + "-o/--output-file: specify an output filename ending with .h when creating stubs" + ) + + cfilename = args.output_file[:-2] + ".c" + with open(args.output_file, "w") as hfile: + with open(cfilename, "w") as cfile: + cfile.write(f'#include "{args.output_file}"\n\n') + process_commands(args.infile, hfile, cfile, args.context_name) + + +if __name__ == "__main__": + main()
buildtools/meson.build +7 -0
@@ -19,6 +19,13 @@ get_cpu_count_cmd = py3 + files('get-cpu-count.py') get_numa_count_cmd = py3 + files('get-numa-count.py') get_test_suites_cmd = py3 + files('get-test-suites.py') has_hugepages_cmd = py3 + files('has-hugepages.py') +cmdline_gen_cmd = py3 + files('dpdk-cmdline-gen.py') + +# install any build tools that end-users might want also +install_data([ + 'dpdk-cmdline-gen.py', + ], + install_dir: 'bin') # select library and object file format pmdinfo = py3 + files('gen-pmdinfo-cfile.py') + [meson.current_build_dir()]
doc/guides/prog_guide/cmdline.rst +130 -1
137 lines not on this page · raw message
Signature · 1 line
2.39.2
PATCH v6 3/9 ci: allow use of DPDK tools when building examples
In reply to Bruce RichardsonTo allow use of the DPDK python scripts (installed in $(prefix)/bin) from within the makefiles of our examples, we need to export the PATH variable with the location of our installed scripts from within our CI scripts. This matches what is already done for other paths e.g. the PKG_CONFIG_PATH variable.
--- .ci/linux-build.sh | 1 + 1 file changed, 1 insertion(+)
.ci/linux-build.sh +1 -0
@@ -174,6 +174,7 @@ fi if [ "$BUILD_EXAMPLES" = "true" ]; then [ -d install ] || DESTDIR=$(pwd)/install meson install -C build export LD_LIBRARY_PATH=$(dirname $(find $(pwd)/install -name librte_eal.so)):$LD_LIBRARY_PATH + export PATH=$(dirname $(find $(pwd)/install -name dpdk-devbind.py)):$PATH export PKG_CONFIG_PATH=$(dirname $(find $(pwd)/install -name libdpdk.pc)):$PKG_CONFIG_PATH export PKGCONF="pkg-config --define-prefix" find build/examples -maxdepth 1 -type f -name "dpdk-*" |
Signature · 1 line
2.39.2
PATCH v6 4/9 examples/simple_mp: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/multi_process/simple_mp/Makefile | 12 +- examples/multi_process/simple_mp/meson.build | 9 ++ .../multi_process/simple_mp/mp_commands.c | 106 ++---------------- .../multi_process/simple_mp/mp_commands.h | 14 --- .../multi_process/simple_mp/mp_commands.list | 3 + 5 files changed, 30 insertions(+), 114 deletions(-) delete mode 100644 examples/multi_process/simple_mp/mp_commands.h create mode 100644 examples/multi_process/simple_mp/mp_commands.list
examples/multi_process/simple_mp/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = simple_mp # all source are stored in SRCS-y SRCS-y := main.c mp_commands.c +SRC-DEPS := build/mp_commands.h PKGCONF ?= pkg-config
@@ -22,10 +23,13 @@ static: build/$(APP)-static ln -sf $(APP)-static build/$(APP) PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/mp_commands.h: mp_commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=simple_mp_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -36,10 +40,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -47,5 +51,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/mp_commands.h test -d build && rmdir -p build || true
examples/multi_process/simple_mp/meson.build +9 -0
@@ -7,7 +7,16 @@ # DPDK instance, use 'make' allow_experimental_apis = true + +cmd_h = custom_target('commands_hdr', + output: 'mp_commands.h', + input: files('mp_commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=simple_mp_ctx', '@INPUT@'] +) + sources = files( 'mp_commands.c', 'main.c', ) +sources += cmd_h
examples/multi_process/simple_mp/mp_commands.c +10 -96
133 lines not on this page · raw message
examples/multi_process/simple_mp/mp_commands.h deleted +0 -14
@@ -1,14 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2010-2014 Intel Corporation -*/ - -#ifndef _SIMPLE_MP_COMMANDS_H_ -#define _SIMPLE_MP_COMMANDS_H_ - -extern struct rte_ring *send_ring; -extern struct rte_mempool *message_pool; -extern volatile int quit; - -extern cmdline_parse_ctx_t simple_mp_ctx[]; - -#endif /* _SIMPLE_MP_COMMANDS_H_ */
examples/multi_process/simple_mp/mp_commands.list new file +3 -0
@@ -0,0 +1,3 @@ +send <STRING>message # send a string to another process +help # show help +quit # close the application
Signature · 1 line
2.39.2
PATCH v6 5/9 examples/hotplug_mp: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/multi_process/hotplug_mp/Makefile | 12 +- examples/multi_process/hotplug_mp/commands.c | 147 ++---------------- examples/multi_process/hotplug_mp/commands.h | 10 -- .../multi_process/hotplug_mp/commands.list | 8 + examples/multi_process/hotplug_mp/meson.build | 9 ++ 5 files changed, 38 insertions(+), 148 deletions(-) delete mode 100644 examples/multi_process/hotplug_mp/commands.h create mode 100644 examples/multi_process/hotplug_mp/commands.list
examples/multi_process/hotplug_mp/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = hotplug_mp # all source are stored in SRCS-y SRCS-y := main.c commands.c +SRC-DEPS := build/commands.h PKGCONF ?= pkg-config
@@ -22,10 +23,13 @@ static: build/$(APP)-static ln -sf $(APP)-static build/$(APP) PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -36,10 +40,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -47,5 +51,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/commands.h test -d build && rmdir -p build || true
examples/multi_process/hotplug_mp/commands.c +13 -134
189 lines not on this page · raw message
examples/multi_process/hotplug_mp/commands.h deleted +0 -10
@@ -1,10 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2018 Intel Corporation -*/ - -#ifndef _COMMANDS_H_ -#define _COMMANDS_H_ - -extern cmdline_parse_ctx_t main_ctx[]; - -#endif /* _COMMANDS_H_ */
examples/multi_process/hotplug_mp/commands.list new file +8 -0
@@ -0,0 +1,8 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +attach <STRING>devargs # attach a device +detach <STRING>devargs # detach a device +list # list all devices +help # show help +quit # quit
examples/multi_process/hotplug_mp/meson.build +9 -0
@@ -7,7 +7,16 @@ # DPDK instance, use 'make' allow_experimental_apis = true + +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) + sources = files( 'commands.c', 'main.c', ) +sources += cmd_h
Signature · 1 line
2.39.2
PATCH v6 6/9 examples/bond: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
---
Note: the original help text on some of the commands in this example
were not useful "this command do not handle any arguments". Therefore, when converting over to the command script, the per-command help info has been updated with reference to the code rather than a literal transfer of the existing help text, as was done with the previous 2 example apps.
--- examples/bond/Makefile | 12 +- examples/bond/commands.list | 6 + examples/bond/main.c | 161 ++---------------- examples/bond/main.h | 10 -- examples/bond/meson.build | 8 + .../multi_process/simple_mp/mp_commands.list | 3 + 6 files changed, 40 insertions(+), 160 deletions(-) create mode 100644 examples/bond/commands.list delete mode 100644 examples/bond/main.h
examples/bond/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = bond_app # all source are stored in SRCS-y SRCS-y := main.c +SRC-DEPS := build/commands.h PKGCONF ?= pkg-config
@@ -24,10 +25,13 @@ static: build/$(APP)-static LDFLAGS += -lrte_net_bond PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -38,10 +42,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -49,5 +53,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/*.h test -d build && rmdir -p build || true
examples/bond/commands.list new file +6 -0
@@ -0,0 +1,6 @@ +send <IP>ip # sends one ARPrequest through bonding for IP +start # starts listening if not started at startup +stop # stops listening +show # shows some bond info, e.g. active members +help # show help +quit # close application
examples/bond/main.c +15 -146
218 lines not on this page · raw message
examples/bond/main.h deleted +0 -10
@@ -1,10 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2010-2015 Intel Corporation -*/ - -#ifndef _MAIN_H_ -#define _MAIN_H_ - -int main (int argc,char *argv[]); - -#endif /* ifndef _MAIN_H_ */
examples/bond/meson.build +8 -0
@@ -11,3 +11,11 @@ allow_experimental_apis = true sources = files( 'main.c', ) + +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) +sources += cmd_h
examples/multi_process/simple_mp/mp_commands.list +3 -0
@@ -1,3 +1,6 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# send <STRING>message # send a string to another process help # show help quit # close the application
Signature · 1 line
2.39.2
PATCH v6 7/9 examples/vdpa: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/vdpa/Makefile | 12 ++-- examples/vdpa/commands.list | 8 +++ examples/vdpa/main.c | 131 ++---------------------------------- examples/vdpa/meson.build | 7 ++ 4 files changed, 30 insertions(+), 128 deletions(-) create mode 100644 examples/vdpa/commands.list
examples/vdpa/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = vdpa # all source are stored in SRCS-y SRCS-y := main.c +SRC-DEPS := build/commands.h CFLAGS += -DALLOW_EXPERIMENTAL_API PKGCONF ?= pkg-config
@@ -23,10 +24,13 @@ static: build/$(APP)-static ln -sf $(APP)-static build/$(APP) PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -35,10 +39,10 @@ $(error "Cannot generate statically-linked binaries with this version of pkg-con endif endif -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -46,5 +50,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/*.h test -d build && rmdir -p build || true
examples/vdpa/commands.list new file +8 -0
@@ -0,0 +1,8 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +help # show help +list # list all available vdpa devices +create <STRING>socket_path <STRING>bdf # create a new vdpa port +stats <STRING>bdf <UINT32>qid # show device statistics +quit # exit application
examples/vdpa/main.c +7 -124
175 lines not on this page · raw message
examples/vdpa/meson.build +7 -0
@@ -16,3 +16,10 @@ allow_experimental_apis = true sources = files( 'main.c', ) +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) +sources += cmd_h
Signature · 1 line
2.39.2
PATCH v6 8/9 buildtools/dpdk-cmdline-gen: support option strings
In reply to Bruce RichardsonAdd support to the commandline generator for option strings, where there are only a limited number of acceptable values to be passed as a parameter.
--- buildtools/dpdk-cmdline-gen.py | 7 +++++++ doc/guides/prog_guide/cmdline.rst | 7 +++++++ 2 files changed, 14 insertions(+)
buildtools/dpdk-cmdline-gen.py +7 -0
@@ -73,6 +73,13 @@ def process_command(lineno, tokens, comment): f"cmdline_parse_token_ipaddr_t cmd_{name}_{t_name}_tok =\n" + f"\tTOKEN_IPV4_INITIALIZER(struct cmd_{name}_result, {t_name});" ) + elif t_type.startswith("(") and t_type.endswith(")"): + result_struct.append(f"\tcmdline_fixed_string_t {t_name};") + t_val = f'"{t_type[1:-1].replace(",","#")}"' + initializers.append( + f"static cmdline_parse_token_string_t cmd_{name}_{t_name}_tok =\n" + + f"\tTOKEN_STRING_INITIALIZER(struct cmd_{name}_result, {t_name}, {t_val});" + ) else: raise TypeError(f"Error line {lineno + 1}: unknown token type '{t_type}'") token_list.append(f"cmd_{name}_{t_name}_tok")
doc/guides/prog_guide/cmdline.rst +7 -0
@@ -70,6 +70,12 @@ The format of the list file must be: * ``<IP>src_ip`` +* Variable fields, which take their values from a list of options, + have the comma-separated option list placed in braces, rather than a the type name. + For example, + + * ``<(rx,tx,rxtx)>mode`` + * The help text for a command is given in the form of a comment on the same line as the command An example list file, with a variety of (unrelated) commands, is shown below::
@@ -79,6 +85,7 @@ An example list file, with a variety of (unrelated) commands, is shown below:: add <UINT16>x <UINT16>y # add x and y echo <STRING>message # print message to screen add socket <STRING>path # add unix socket with the given path + set mode <(rx,tx)>rxtx # set Rx-only or Tx-only mode quit # close the application Running the Generator Script
Signature · 1 line
2.39.2
PATCH v6 9/9 examples/ntb: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/ntb/Makefile | 12 ++- examples/ntb/commands.list | 11 ++ examples/ntb/meson.build | 7 ++ examples/ntb/ntb_fwd.c | 200 ++++--------------------------------- 4 files changed, 47 insertions(+), 183 deletions(-) create mode 100644 examples/ntb/commands.list
examples/ntb/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = ntb_fwd # all source are stored in SRCS-y SRCS-y := ntb_fwd.c +SRC-DEPS := build/commands.h PKGCONF ?= pkg-config
@@ -25,10 +26,13 @@ CFLAGS += -D_FILE_OFFSET_BITS=64 LDFLAGS += -pthread PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -39,10 +43,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -50,5 +54,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/*.h test -d build && rmdir -p build || true
examples/ntb/commands.list new file +11 -0
@@ -0,0 +1,11 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +help # show help +quit # exit application +send <STRING>filepath # send <file_path> +start # start pkt fwd between ntb and ethdev +stop # stop packet forwarding +show port stats # show statistics for all ports +clear port stats # clear all port statistics +set fwd <(file-trans,iofwd,txonly,rxonly)>mode # set forwarding mode as file-trans|rxonly|txonly|iofwd
examples/ntb/meson.build +7 -0
@@ -17,3 +17,10 @@ cflags += ['-D_FILE_OFFSET_BITS=64'] sources = files( 'ntb_fwd.c', ) +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) +sources += cmd_h
examples/ntb/ntb_fwd.c +21 -179
272 lines not on this page · raw message
Signature · 1 line
2.39.2
v7 cover document and simplify use of cmdline
In reply to Bruce RichardsonThe DPDK commandline library is widely used by apps and examples within DPDK, but it is not documented in our programmers guide and it requires a lot of boilerplate code definitions in order to used. We can improve this situation by creating a simple python script to automatically generate the boilerplate from a list of commands.
This patchset contains a new documentation chapter on cmdline library, going through step-by-step how to add commands and create the necessary token lists and parse contexts.
Following that initial doc patch, the set then contains a boilerplate-generating script, as well as a set of four patches showing its use, by converting four examples to use the script instead of having the hard-coded boilerplate. Once the script is used, adding a new command becomes as simple as adding the desired command to the .list file, and then writing the required function which will be called for that command. No other boilerplate coding is necessary.
Final two patches, from V5 onwards, add support for option-lists in values, and then use that support to convert over a fifth sample app - ntb.
Cmdline script obviously does not cover the full range of capabilities of the commandline lib, but does cover the most used parts. The code-saving to each of the examples by auto-generating the boilerplate is significant, and probably more examples with commandlines can be converted over in future.
The "cmdline" example itself, is not converted over, as it should probably remain as a simple example of direct library use without the script.
v7:
* Increased use of multi-line strings in python script, following feedback.
v6:
* rework syntax of the option lists following feedback from David. Now use "(x,y,z)" instead of "|x|y|z|", to avoid giving impression of regex support
V5:
* Added copyright headers to command list files
* Add support for option lists
* Convert examples/ntb to use script
V4:
* Reworked script following feedback from Robin J.
- formatted code with black
- used multi-line strings
- replaced sys.exit(1) with proper error handling
- per-command function returns lists rather than printing directly
- other small cleanups
* Added change to CI script so the cmdline script is in PATH
* Converted VDPA example to script, saving another 100 LOC
V3:
* Added lots of documentation
* Added support for help text for each command
* Cleaned up script a little so it passes pycodestyle and most flake8 checks, when line-length is set to max 100.
* Removed RFC tag, as I consider this patchset stable enough for consideration in a release.
V2-RFC:
* Add support for IP addresses in commands
* Move to buildtools directory and make installable
* Convert 3 examples to use script, and eliminate their boilerplate
Bruce Richardson (9):
doc/prog_guide: new chapter on cmdline library
buildtools: script to generate cmdline boilerplate
ci: allow use of DPDK tools when building examples examples/simple_mp: auto-generate cmdline boilerplate examples/hotplug_mp: auto-generate cmdline boilerplate examples/bond: auto-generate cmdline boilerplate examples/vdpa: auto-generate cmdline boilerplate buildtools/dpdk-cmdline-gen: support option strings examples/ntb: auto-generate cmdline boilerplate
.ci/linux-build.sh | 1 + app/test/commands.c | 2 + buildtools/dpdk-cmdline-gen.py | 202 ++++++++ buildtools/meson.build | 7 + doc/guides/prog_guide/cmdline.rst | 473 ++++++++++++++++++ doc/guides/prog_guide/index.rst | 1 + examples/bond/Makefile | 12 +- examples/bond/commands.list | 6 + examples/bond/main.c | 161 +----- examples/bond/main.h | 10 - examples/bond/meson.build | 8 + examples/multi_process/hotplug_mp/Makefile | 12 +- examples/multi_process/hotplug_mp/commands.c | 147 +----- examples/multi_process/hotplug_mp/commands.h | 10 - .../multi_process/hotplug_mp/commands.list | 8 + examples/multi_process/hotplug_mp/meson.build | 9 + examples/multi_process/simple_mp/Makefile | 12 +- examples/multi_process/simple_mp/meson.build | 9 + .../multi_process/simple_mp/mp_commands.c | 106 +--- .../multi_process/simple_mp/mp_commands.h | 14 - .../multi_process/simple_mp/mp_commands.list | 6 + examples/ntb/Makefile | 12 +- examples/ntb/commands.list | 11 + examples/ntb/meson.build | 7 + examples/ntb/ntb_fwd.c | 200 +------- examples/vdpa/Makefile | 12 +- examples/vdpa/commands.list | 8 + examples/vdpa/main.c | 131 +---- examples/vdpa/meson.build | 7 + 29 files changed, 871 insertions(+), 733 deletions(-) create mode 100755 buildtools/dpdk-cmdline-gen.py create mode 100644 doc/guides/prog_guide/cmdline.rst create mode 100644 examples/bond/commands.list delete mode 100644 examples/bond/main.h delete mode 100644 examples/multi_process/hotplug_mp/commands.h create mode 100644 examples/multi_process/hotplug_mp/commands.list delete mode 100644 examples/multi_process/simple_mp/mp_commands.h create mode 100644 examples/multi_process/simple_mp/mp_commands.list create mode 100644 examples/ntb/commands.list create mode 100644 examples/vdpa/commands.list
--
2.39.2
PATCH v7 1/9 doc/prog_guide: new chapter on cmdline library
The cmdline library was not documented in our programmers guide, so add a new chapter on it. This chapter covers step-by-step how to use the library, rather than focusing on the library internals. This complements the existing cmdline example app document, providing more details on the process of using the library.
--- app/test/commands.c | 2 + doc/guides/prog_guide/cmdline.rst | 337 ++++++++++++++++++++++++++++++ doc/guides/prog_guide/index.rst | 1 + 3 files changed, 340 insertions(+) create mode 100644 doc/guides/prog_guide/cmdline.rst
app/test/commands.c +2 -0
@@ -108,6 +108,7 @@ dump_struct_sizes(void)#undef DUMP_SIZE } +/* Add the dump_* tests cases 8< */ static void cmd_dump_parsed (void *parsed_result, __rte_unused struct cmdline *cl, __rte_unused void *data)
@@ -155,6 +156,7 @@ cmdline_parse_inst_t cmd_dump = { NULL, }, }; +/* >8 End of add the dump_* tests cases */ /****************/
doc/guides/prog_guide/cmdline.rst new file +337 -0
337 lines not on this page · raw message
doc/guides/prog_guide/index.rst +1 -0
@@ -13,6 +13,7 @@ Programmer's Guide source_org env_abstraction_layer log_lib + cmdline service_cores trace_lib rcu_lib
Signature · 1 line
2.39.2
PATCH v7 2/9 buildtools: script to generate cmdline boilerplate
In reply to Bruce RichardsonProvide a "dpdk-cmdline-gen.py" script for application developers to quickly generate the boilerplate code necessary for using the cmdline library.
Example of use:
The script takes an input file with a list of commands the user wants in the app, where the parameter variables are tagged with the type. For example:
$ cat commands.list list add <UINT16>x <UINT16>y echo <STRING>message add socket <STRING>path quit
When run through the script as "./dpdk-cmdline-gen.py commands.list", the output will be the contents of a header file with all the boilerplate necessary for a commandline instance with those commands.
If the flag --stubs is passed, an output header filename must also be passed, in which case both a header file with the definitions and a C file with function stubs in it is written to disk. The separation is so that the header file can be rewritten at any future point to add more commands, while the C file can be kept as-is and extended by the user with any additional functions needed.
--- buildtools/dpdk-cmdline-gen.py | 195 ++++++++++++++++++++++++++++++ buildtools/meson.build | 7 ++ doc/guides/prog_guide/cmdline.rst | 131 +++++++++++++++++++- 3 files changed, 332 insertions(+), 1 deletion(-) create mode 100755 buildtools/dpdk-cmdline-gen.py
buildtools/dpdk-cmdline-gen.py new file +195 -0
@@ -0,0 +1,195 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +""" +Script to automatically generate boilerplate for using DPDK cmdline library. +""" + +import argparse +import sys + +PARSE_FN_PARAMS = "void *parsed_result, struct cmdline *cl, void *data" +PARSE_FN_BODY = """ + /* TODO: command action */ + RTE_SET_USED(parsed_result); + RTE_SET_USED(cl); + RTE_SET_USED(data); +""" +NUMERIC_TYPES = [ + "UINT8", + "UINT16", + "UINT32", + "UINT64", + "INT8", + "INT16", + "INT32", + "INT64", +] + + +def process_command(lineno, tokens, comment): + """Generate the structures and definitions for a single command.""" + out = [] + cfile_out = [] + + if tokens[0].startswith("<"): + raise ValueError(f"Error line {lineno + 1}: command must start with a literal string") + + name_tokens = [] + for t in tokens: + if t.startswith("<"): + break + name_tokens.append(t) + name = "_".join(name_tokens) + + result_struct = [] + initializers = [] + token_list = [] + for t in tokens: + if t.startswith("<"): + t_type, t_name = t[1:].split(">") + t_val = "NULL" + else: + t_type = "STRING" + t_name = t + t_val = f'"{t}"' + + if t_type == "STRING": + result_struct.append(f"\tcmdline_fixed_string_t {t_name};") + initializers.append( + f"static cmdline_parse_token_string_t cmd_{name}_{t_name}_tok =\n" + f"\tTOKEN_STRING_INITIALIZER(struct cmd_{name}_result, {t_name}, {t_val});" + ) + elif t_type in NUMERIC_TYPES: + result_struct.append(f"\t{t_type.lower()}_t {t_name};") + initializers.append( + f"static cmdline_parse_token_num_t cmd_{name}_{t_name}_tok =\n" + f"\tTOKEN_NUM_INITIALIZER(struct cmd_{name}_result, {t_name}, RTE_{t_type});" + ) + elif t_type in ["IP", "IP_ADDR", "IPADDR"]: + result_struct.append(f"\tcmdline_ipaddr_t {t_name};") + initializers.append( + f"cmdline_parse_token_ipaddr_t cmd_{name}_{t_name}_tok =\n" + f"\tTOKEN_IPV4_INITIALIZER(struct cmd_{name}_result, {t_name});" + ) + else: + raise TypeError(f"Error line {lineno + 1}: unknown token type '{t_type}'") + token_list.append(f"cmd_{name}_{t_name}_tok") + + out.append(f'/* Auto-generated handling for command "{" ".join(tokens)}" */') + # output function prototype + func_sig = f"void\ncmd_{name}_parsed({PARSE_FN_PARAMS})" + out.append(f"extern {func_sig};\n") + # output result data structure + out.append(f"struct cmd_{name}_result {{\n" + "\n".join(result_struct) + "\n};\n") + # output the initializer tokens + out.append("\n".join(initializers) + "\n") + # output the instance structure + inst_elems = "\n".join([f"\t\t(void *)&{t}," for t in token_list]) + out.append( + f"""\ +static cmdline_parse_inst_t cmd_{name} = {{ +\t.f = cmd_{name}_parsed, +\t.data = NULL, +\t.help_str = "{comment}", +\t.tokens = {{ +{inst_elems} +\t\tNULL, +\t}} +}}; +""" + ) + # output function template if C file being written + cfile_out.append(f"{func_sig}\n{{{PARSE_FN_BODY}}}\n") + + # return the instance structure name + return (f"cmd_{name}", out, cfile_out) + + +def process_commands(infile, hfile, cfile, ctxname): + """Generate boilerplate output for a list of commands from infile.""" + instances = [] + + hfile.write( + f"""\ +/* File autogenerated by {sys.argv[0]} */ +#ifndef GENERATED_COMMANDS_H +#define GENERATED_COMMANDS_H +#include <rte_common.h> +#include <cmdline.h> +#include <cmdline_parse_string.h> +#include <cmdline_parse_num.h> +#include <cmdline_parse_ipaddr.h> + +""" + ) + + for lineno, line in enumerate(infile.readlines()): + if line.lstrip().startswith("#"): + continue + if "#" not in line: + line = line + "#" # ensure split always works, even if no help text + tokens, comment = line.split("#", 1) + cmd_inst, h_out, c_out = process_command(lineno, tokens.strip().split(), comment.strip()) + hfile.write("\n".join(h_out)) + if cfile: + cfile.write("\n".join(c_out)) + instances.append(cmd_inst) + + inst_join_str = ",\n\t&" + hfile.write( + f""" +static __rte_used cmdline_parse_ctx_t {ctxname}[] = {{ +\t&{inst_join_str.join(instances)}, +\tNULL +}}; + +#endif /* GENERATED_COMMANDS_H */ +""" + ) + + +def main(): + """Application main entry point.""" + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument( + "--stubs", + action="store_true", + help="Produce C file with empty function stubs for each command", + ) + ap.add_argument( + "--output-file", + "-o", + default="-", + help="Output header filename [default to stdout]", + ) + ap.add_argument( + "--context-name", + default="ctx", + help="Name given to the cmdline context variable in the output header [default=ctx]", + ) + ap.add_argument("infile", type=argparse.FileType("r"), help="File with list of commands") + args = ap.parse_args() + + if not args.stubs: + if args.output_file == "-": + process_commands(args.infile, sys.stdout, None, args.context_name) + else: + with open(args.output_file, "w") as hfile: + process_commands(args.infile, hfile, None, args.context_name) + else: + if not args.output_file.endswith(".h"): + ap.error( + "-o/--output-file: specify an output filename ending with .h when creating stubs" + ) + + cfilename = args.output_file[:-2] + ".c" + with open(args.output_file, "w") as hfile: + with open(cfilename, "w") as cfile: + cfile.write(f'#include "{args.output_file}"\n\n') + process_commands(args.infile, hfile, cfile, args.context_name) + + +if __name__ == "__main__": + main()
buildtools/meson.build +7 -0
@@ -19,6 +19,13 @@ get_cpu_count_cmd = py3 + files('get-cpu-count.py') get_numa_count_cmd = py3 + files('get-numa-count.py') get_test_suites_cmd = py3 + files('get-test-suites.py') has_hugepages_cmd = py3 + files('has-hugepages.py') +cmdline_gen_cmd = py3 + files('dpdk-cmdline-gen.py') + +# install any build tools that end-users might want also +install_data([ + 'dpdk-cmdline-gen.py', + ], + install_dir: 'bin') # select library and object file format pmdinfo = py3 + files('gen-pmdinfo-cfile.py') + [meson.current_build_dir()]
doc/guides/prog_guide/cmdline.rst +130 -1
137 lines not on this page · raw message
Signature · 1 line
2.39.2
PATCH v7 3/9 ci: allow use of DPDK tools when building examples
In reply to Bruce RichardsonTo allow use of the DPDK python scripts (installed in $(prefix)/bin) from within the makefiles of our examples, we need to export the PATH variable with the location of our installed scripts from within our CI scripts. This matches what is already done for other paths e.g. the PKG_CONFIG_PATH variable.
--- .ci/linux-build.sh | 1 + 1 file changed, 1 insertion(+)
.ci/linux-build.sh +1 -0
@@ -178,6 +178,7 @@ fi if [ "$BUILD_EXAMPLES" = "true" ]; then [ -d install ] || DESTDIR=$(pwd)/install meson install -C build export LD_LIBRARY_PATH=$(dirname $(find $(pwd)/install -name librte_eal.so)):$LD_LIBRARY_PATH + export PATH=$(dirname $(find $(pwd)/install -name dpdk-devbind.py)):$PATH export PKG_CONFIG_PATH=$(dirname $(find $(pwd)/install -name libdpdk.pc)):$PKG_CONFIG_PATH export PKGCONF="pkg-config --define-prefix" find build/examples -maxdepth 1 -type f -name "dpdk-*" |
Signature · 1 line
2.39.2
PATCH v7 4/9 examples/simple_mp: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/multi_process/simple_mp/Makefile | 12 +- examples/multi_process/simple_mp/meson.build | 9 ++ .../multi_process/simple_mp/mp_commands.c | 106 ++---------------- .../multi_process/simple_mp/mp_commands.h | 14 --- .../multi_process/simple_mp/mp_commands.list | 3 + 5 files changed, 30 insertions(+), 114 deletions(-) delete mode 100644 examples/multi_process/simple_mp/mp_commands.h create mode 100644 examples/multi_process/simple_mp/mp_commands.list
examples/multi_process/simple_mp/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = simple_mp # all source are stored in SRCS-y SRCS-y := main.c mp_commands.c +SRC-DEPS := build/mp_commands.h PKGCONF ?= pkg-config
@@ -22,10 +23,13 @@ static: build/$(APP)-static ln -sf $(APP)-static build/$(APP) PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/mp_commands.h: mp_commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=simple_mp_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -36,10 +40,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -47,5 +51,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/mp_commands.h test -d build && rmdir -p build || true
examples/multi_process/simple_mp/meson.build +9 -0
@@ -7,7 +7,16 @@ # DPDK instance, use 'make' allow_experimental_apis = true + +cmd_h = custom_target('commands_hdr', + output: 'mp_commands.h', + input: files('mp_commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=simple_mp_ctx', '@INPUT@'] +) + sources = files( 'mp_commands.c', 'main.c', ) +sources += cmd_h
examples/multi_process/simple_mp/mp_commands.c +10 -96
133 lines not on this page · raw message
examples/multi_process/simple_mp/mp_commands.h deleted +0 -14
@@ -1,14 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2010-2014 Intel Corporation -*/ - -#ifndef _SIMPLE_MP_COMMANDS_H_ -#define _SIMPLE_MP_COMMANDS_H_ - -extern struct rte_ring *send_ring; -extern struct rte_mempool *message_pool; -extern volatile int quit; - -extern cmdline_parse_ctx_t simple_mp_ctx[]; - -#endif /* _SIMPLE_MP_COMMANDS_H_ */
examples/multi_process/simple_mp/mp_commands.list new file +3 -0
@@ -0,0 +1,3 @@ +send <STRING>message # send a string to another process +help # show help +quit # close the application
Signature · 1 line
2.39.2
PATCH v7 5/9 examples/hotplug_mp: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/multi_process/hotplug_mp/Makefile | 12 +- examples/multi_process/hotplug_mp/commands.c | 147 ++---------------- examples/multi_process/hotplug_mp/commands.h | 10 -- .../multi_process/hotplug_mp/commands.list | 8 + examples/multi_process/hotplug_mp/meson.build | 9 ++ 5 files changed, 38 insertions(+), 148 deletions(-) delete mode 100644 examples/multi_process/hotplug_mp/commands.h create mode 100644 examples/multi_process/hotplug_mp/commands.list
examples/multi_process/hotplug_mp/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = hotplug_mp # all source are stored in SRCS-y SRCS-y := main.c commands.c +SRC-DEPS := build/commands.h PKGCONF ?= pkg-config
@@ -22,10 +23,13 @@ static: build/$(APP)-static ln -sf $(APP)-static build/$(APP) PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -36,10 +40,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -47,5 +51,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/commands.h test -d build && rmdir -p build || true
examples/multi_process/hotplug_mp/commands.c +13 -134
189 lines not on this page · raw message
examples/multi_process/hotplug_mp/commands.h deleted +0 -10
@@ -1,10 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2018 Intel Corporation -*/ - -#ifndef _COMMANDS_H_ -#define _COMMANDS_H_ - -extern cmdline_parse_ctx_t main_ctx[]; - -#endif /* _COMMANDS_H_ */
examples/multi_process/hotplug_mp/commands.list new file +8 -0
@@ -0,0 +1,8 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +attach <STRING>devargs # attach a device +detach <STRING>devargs # detach a device +list # list all devices +help # show help +quit # quit
examples/multi_process/hotplug_mp/meson.build +9 -0
@@ -7,7 +7,16 @@ # DPDK instance, use 'make' allow_experimental_apis = true + +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) + sources = files( 'commands.c', 'main.c', ) +sources += cmd_h
Signature · 1 line
2.39.2
PATCH v7 6/9 examples/bond: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
---
Note: the original help text on some of the commands in this example
were not useful "this command do not handle any arguments". Therefore, when converting over to the command script, the per-command help info has been updated with reference to the code rather than a literal transfer of the existing help text, as was done with the previous 2 example apps.
--- examples/bond/Makefile | 12 +- examples/bond/commands.list | 6 + examples/bond/main.c | 161 ++---------------- examples/bond/main.h | 10 -- examples/bond/meson.build | 8 + .../multi_process/simple_mp/mp_commands.list | 3 + 6 files changed, 40 insertions(+), 160 deletions(-) create mode 100644 examples/bond/commands.list delete mode 100644 examples/bond/main.h
examples/bond/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = bond_app # all source are stored in SRCS-y SRCS-y := main.c +SRC-DEPS := build/commands.h PKGCONF ?= pkg-config
@@ -24,10 +25,13 @@ static: build/$(APP)-static LDFLAGS += -lrte_net_bond PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -38,10 +42,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -49,5 +53,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/*.h test -d build && rmdir -p build || true
examples/bond/commands.list new file +6 -0
@@ -0,0 +1,6 @@ +send <IP>ip # sends one ARPrequest through bonding for IP +start # starts listening if not started at startup +stop # stops listening +show # shows some bond info, e.g. active members +help # show help +quit # close application
examples/bond/main.c +15 -146
218 lines not on this page · raw message
examples/bond/main.h deleted +0 -10
@@ -1,10 +0,0 @@ -/* SPDX-License-Identifier: BSD-3-Clause -* Copyright(c) 2010-2015 Intel Corporation -*/ - -#ifndef _MAIN_H_ -#define _MAIN_H_ - -int main (int argc,char *argv[]); - -#endif /* ifndef _MAIN_H_ */
examples/bond/meson.build +8 -0
@@ -11,3 +11,11 @@ allow_experimental_apis = true sources = files( 'main.c', ) + +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) +sources += cmd_h
examples/multi_process/simple_mp/mp_commands.list +3 -0
@@ -1,3 +1,6 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# send <STRING>message # send a string to another process help # show help quit # close the application
Signature · 1 line
2.39.2
PATCH v7 7/9 examples/vdpa: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/vdpa/Makefile | 12 ++-- examples/vdpa/commands.list | 8 +++ examples/vdpa/main.c | 131 ++---------------------------------- examples/vdpa/meson.build | 7 ++ 4 files changed, 30 insertions(+), 128 deletions(-) create mode 100644 examples/vdpa/commands.list
examples/vdpa/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = vdpa # all source are stored in SRCS-y SRCS-y := main.c +SRC-DEPS := build/commands.h CFLAGS += -DALLOW_EXPERIMENTAL_API PKGCONF ?= pkg-config
@@ -23,10 +24,13 @@ static: build/$(APP)-static ln -sf $(APP)-static build/$(APP) PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -35,10 +39,10 @@ $(error "Cannot generate statically-linked binaries with this version of pkg-con endif endif -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -46,5 +50,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/*.h test -d build && rmdir -p build || true
examples/vdpa/commands.list new file +8 -0
@@ -0,0 +1,8 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +help # show help +list # list all available vdpa devices +create <STRING>socket_path <STRING>bdf # create a new vdpa port +stats <STRING>bdf <UINT32>qid # show device statistics +quit # exit application
examples/vdpa/main.c +7 -124
175 lines not on this page · raw message
examples/vdpa/meson.build +7 -0
@@ -16,3 +16,10 @@ allow_experimental_apis = true sources = files( 'main.c', ) +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) +sources += cmd_h
Signature · 1 line
2.39.2
PATCH v7 8/9 buildtools/dpdk-cmdline-gen: support option strings
In reply to Bruce RichardsonAdd support to the commandline generator for option strings, where there are only a limited number of acceptable values to be passed as a parameter.
--- buildtools/dpdk-cmdline-gen.py | 7 +++++++ doc/guides/prog_guide/cmdline.rst | 7 +++++++ 2 files changed, 14 insertions(+)
buildtools/dpdk-cmdline-gen.py +7 -0
@@ -73,6 +73,13 @@ def process_command(lineno, tokens, comment): f"cmdline_parse_token_ipaddr_t cmd_{name}_{t_name}_tok =\n" f"\tTOKEN_IPV4_INITIALIZER(struct cmd_{name}_result, {t_name});" ) + elif t_type.startswith("(") and t_type.endswith(")"): + result_struct.append(f"\tcmdline_fixed_string_t {t_name};") + t_val = f'"{t_type[1:-1].replace(",","#")}"' + initializers.append( + f"static cmdline_parse_token_string_t cmd_{name}_{t_name}_tok =\n" + f"\tTOKEN_STRING_INITIALIZER(struct cmd_{name}_result, {t_name}, {t_val});" + ) else: raise TypeError(f"Error line {lineno + 1}: unknown token type '{t_type}'") token_list.append(f"cmd_{name}_{t_name}_tok")
doc/guides/prog_guide/cmdline.rst +7 -0
@@ -70,6 +70,12 @@ The format of the list file must be: * ``<IP>src_ip`` +* Variable fields, which take their values from a list of options, + have the comma-separated option list placed in braces, rather than a the type name. + For example, + + * ``<(rx,tx,rxtx)>mode`` + * The help text for a command is given in the form of a comment on the same line as the command An example list file, with a variety of (unrelated) commands, is shown below::
@@ -79,6 +85,7 @@ An example list file, with a variety of (unrelated) commands, is shown below:: add <UINT16>x <UINT16>y # add x and y echo <STRING>message # print message to screen add socket <STRING>path # add unix socket with the given path + set mode <(rx,tx)>rxtx # set Rx-only or Tx-only mode quit # close the application Running the Generator Script
Signature · 1 line
2.39.2
PATCH v7 9/9 examples/ntb: auto-generate cmdline boilerplate
In reply to Bruce RichardsonUse the dpdk-cmdline-gen script to autogenerate all the boilerplate structs and defines for the commandline part of the app.
--- examples/ntb/Makefile | 12 ++- examples/ntb/commands.list | 11 ++ examples/ntb/meson.build | 7 ++ examples/ntb/ntb_fwd.c | 200 ++++--------------------------------- 4 files changed, 47 insertions(+), 183 deletions(-) create mode 100644 examples/ntb/commands.list
examples/ntb/Makefile +8 -4
@@ -6,6 +6,7 @@ APP = ntb_fwd # all source are stored in SRCS-y SRCS-y := ntb_fwd.c +SRC-DEPS := build/commands.h PKGCONF ?= pkg-config
@@ -25,10 +26,13 @@ CFLAGS += -D_FILE_OFFSET_BITS=64 LDFLAGS += -pthread PC_FILE := $(shell $(PKGCONF) --path libdpdk 2>/dev/null) -CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) +CFLAGS += -O3 $(shell $(PKGCONF) --cflags libdpdk) -I build/ LDFLAGS_SHARED = $(shell $(PKGCONF) --libs libdpdk) LDFLAGS_STATIC = $(shell $(PKGCONF) --static --libs libdpdk) +build/commands.h: commands.list Makefile + dpdk-cmdline-gen.py -o $@ --context-name=main_ctx $< + ifeq ($(MAKECMDGOALS),static) # check for broken pkg-config ifeq ($(shell echo $(LDFLAGS_STATIC) | grep 'whole-archive.*l:lib.*no-whole-archive'),)
@@ -39,10 +43,10 @@ endif CFLAGS += -DALLOW_EXPERIMENTAL_API -build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-shared: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_SHARED) -build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build +build/$(APP)-static: $(SRCS-y) Makefile $(PC_FILE) | build $(SRC-DEPS) $(CC) $(CFLAGS) $(SRCS-y) -o $@ $(LDFLAGS) $(LDFLAGS_STATIC) build:
@@ -50,5 +54,5 @@ build: .PHONY: clean clean: - rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared + rm -f build/$(APP) build/$(APP)-static build/$(APP)-shared build/*.h test -d build && rmdir -p build || true
examples/ntb/commands.list new file +11 -0
@@ -0,0 +1,11 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright(c) 2023 Intel Corporation +# +help # show help +quit # exit application +send <STRING>filepath # send <file_path> +start # start pkt fwd between ntb and ethdev +stop # stop packet forwarding +show port stats # show statistics for all ports +clear port stats # clear all port statistics +set fwd <(file-trans,iofwd,txonly,rxonly)>mode # set forwarding mode as file-trans|rxonly|txonly|iofwd
examples/ntb/meson.build +7 -0
@@ -17,3 +17,10 @@ cflags += ['-D_FILE_OFFSET_BITS=64'] sources = files( 'ntb_fwd.c', ) +cmd_h = custom_target('commands_hdr', + output: 'commands.h', + input: files('commands.list'), + capture: true, + command: [cmdline_gen_cmd, '--context-name=main_ctx', '@INPUT@'] +) +sources += cmd_h
examples/ntb/ntb_fwd.c +21 -179
272 lines not on this page · raw message
Signature · 1 line
2.39.2
Re: [PATCH v7 0/9] document and simplify use of cmdline
In reply to Bruce RichardsonQuoted 112 lines · Bruce Richardson
The DPDK commandline library is widely used by apps and examples within DPDK, but it is not documented in our programmers guide and it requires a lot of boilerplate code definitions in order to used. We can improve this situation by creating a simple python script to automatically generate the boilerplate from a list of commands.
This patchset contains a new documentation chapter on cmdline library, going through step-by-step how to add commands and create the necessary token lists and parse contexts.
Following that initial doc patch, the set then contains a boilerplate-generating script, as well as a set of four patches showing its use, by converting four examples to use the script instead of having the hard-coded boilerplate. Once the script is used, adding a new command becomes as simple as adding the desired command to the .list file, and then writing the required function which will be called for that command. No other boilerplate coding is necessary.
Final two patches, from V5 onwards, add support for option-lists in values, and then use that support to convert over a fifth sample app - ntb.
Cmdline script obviously does not cover the full range of capabilities of the commandline lib, but does cover the most used parts. The code-saving to each of the examples by auto-generating the boilerplate is significant, and probably more examples with commandlines can be converted over in future.
The "cmdline" example itself, is not converted over, as it should probably remain as a simple example of direct library use without the script.
v7:
* Increased use of multi-line strings in python script, following feedback.v6:
* rework syntax of the option lists following feedback from David. Now use "(x,y,z)" instead of "|x|y|z|", to avoid giving impression of regex supportV5:
* Added copyright headers to command list files
* Add support for option lists
* Convert examples/ntb to use scriptV4:
* Reworked script following feedback from Robin J.
- formatted code with black
- used multi-line strings
- replacedsys.exit(1)with proper error handling
- per-command function returns lists rather than printing directly
- other small cleanups
* Added change to CI script so the cmdline script is in PATH
* Converted VDPA example to script, saving another 100 LOCV3:
* Added lots of documentation
* Added support for help text for each command
* Cleaned up script a little so it passes pycodestyle and most flake8 checks, when line-length is set to max 100.
* Removed RFC tag, as I consider this patchset stable enough for consideration in a release.V2-RFC:
* Add support for IP addresses in commands
* Move to buildtools directory and make installable
* Convert 3 examples to use script, and eliminate their boilerplateBruce Richardson (9):
doc/prog_guide: new chapter on cmdline library
buildtools: script to generate cmdline boilerplate
ci: allow use of DPDK tools when building examples examples/simple_mp: auto-generate cmdline boilerplate examples/hotplug_mp: auto-generate cmdline boilerplate examples/bond: auto-generate cmdline boilerplate examples/vdpa: auto-generate cmdline boilerplate buildtools/dpdk-cmdline-gen: support option strings examples/ntb: auto-generate cmdline boilerplate.ci/linux-build.sh | 1 + app/test/commands.c | 2 + buildtools/dpdk-cmdline-gen.py | 202 ++++++++ buildtools/meson.build | 7 + doc/guides/prog_guide/cmdline.rst | 473 ++++++++++++++++++ doc/guides/prog_guide/index.rst | 1 + examples/bond/Makefile | 12 +- examples/bond/commands.list | 6 + examples/bond/main.c | 161 +----- examples/bond/main.h | 10 - examples/bond/meson.build | 8 + examples/multi_process/hotplug_mp/Makefile | 12 +- examples/multi_process/hotplug_mp/commands.c | 147 +----- examples/multi_process/hotplug_mp/commands.h | 10 - .../multi_process/hotplug_mp/commands.list | 8 + examples/multi_process/hotplug_mp/meson.build | 9 + examples/multi_process/simple_mp/Makefile | 12 +- examples/multi_process/simple_mp/meson.build | 9 + .../multi_process/simple_mp/mp_commands.c | 106 +--- .../multi_process/simple_mp/mp_commands.h | 14 - .../multi_process/simple_mp/mp_commands.list | 6 + examples/ntb/Makefile | 12 +- examples/ntb/commands.list | 11 + examples/ntb/meson.build | 7 + examples/ntb/ntb_fwd.c | 200 +------- examples/vdpa/Makefile | 12 +- examples/vdpa/commands.list | 8 + examples/vdpa/main.c | 131 +---- examples/vdpa/meson.build | 7 + 29 files changed, 871 insertions(+), 733 deletions(-) create mode 100755 buildtools/dpdk-cmdline-gen.py create mode 100644 doc/guides/prog_guide/cmdline.rst
Quoted 8 lines
create mode 100644 examples/bond/commands.list delete mode 100644 examples/bond/main.h delete mode 100644 examples/multi_process/hotplug_mp/commands.h create mode 100644 examples/multi_process/hotplug_mp/commands.list delete mode 100644 examples/multi_process/simple_mp/mp_commands.h create mode 100644 examples/multi_process/simple_mp/mp_commands.list create mode 100644 examples/ntb/commands.list create mode 100644 examples/vdpa/commands.list
I fixed a few issues:
- devtools/test-meson.builds.sh was missing some update so the new script is used when building examples out of dpdk tree,
- the examples/bond patch contained a change belonging to a previous patch,
- some meson.build updates contained tabs,
- the documentation and the new script were not referenced in the MAINTAINERS file,
- the cmdline documentation used explicitly numbered items while the coding style for the doc recommends use of #.,
For the series,
Series applied, thanks for this nice cleanup/improvement.
Signature · 1 line
David Marchand