xref: /linux/tools/net/ynl/pyynl/cli.py (revision bcdd8ea73f750a4a6c38859a3f06027aa40b84c5)
1#!/usr/bin/env python3
2# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
3
4"""
5YNL cli tool
6"""
7
8import argparse
9import json
10import os
11import pathlib
12import pprint
13import sys
14import textwrap
15
16# pylint: disable=no-name-in-module,wrong-import-position
17sys.path.append(pathlib.Path(__file__).resolve().parent.as_posix())
18from lib import YnlFamily, Netlink, NlError, SpecFamily
19
20SYS_SCHEMA_DIR='/usr/share/ynl'
21RELATIVE_SCHEMA_DIR='../../../../Documentation/netlink'
22
23def schema_dir():
24    """
25    Return the effective schema directory, preferring in-tree before
26    system schema directory.
27    """
28    script_dir = os.path.dirname(os.path.abspath(__file__))
29    schema_dir_ = os.path.abspath(f"{script_dir}/{RELATIVE_SCHEMA_DIR}")
30    if not os.path.isdir(schema_dir_):
31        schema_dir_ = SYS_SCHEMA_DIR
32    if not os.path.isdir(schema_dir_):
33        raise Exception(f"Schema directory {schema_dir_} does not exist")
34    return schema_dir_
35
36def spec_dir():
37    """
38    Return the effective spec directory, relative to the effective
39    schema directory.
40    """
41    spec_dir_ = schema_dir() + '/specs'
42    if not os.path.isdir(spec_dir_):
43        raise Exception(f"Spec directory {spec_dir_} does not exist")
44    return spec_dir_
45
46
47class YnlEncoder(json.JSONEncoder):
48    """A custom encoder for emitting JSON with ynl-specific instance types"""
49    def default(self, o):
50        if isinstance(o, bytes):
51            return bytes.hex(o)
52        if isinstance(o, set):
53            return list(o)
54        return json.JSONEncoder.default(self, o)
55
56
57def print_attr_list(ynl, attr_names, attr_set, indent=2):
58    """Print a list of attributes with their types and documentation."""
59    prefix = ' ' * indent
60    for attr_name in attr_names:
61        if attr_name in attr_set.attrs:
62            attr = attr_set.attrs[attr_name]
63            attr_info = f'{prefix}- {attr_name}: {attr.type}'
64            if 'enum' in attr.yaml:
65                enum_name = attr.yaml['enum']
66                attr_info += f" (enum: {enum_name})"
67                # Print enum values if available
68                if enum_name in ynl.consts:
69                    const = ynl.consts[enum_name]
70                    enum_values = list(const.entries.keys())
71                    attr_info += f"\n{prefix}  {const.type.capitalize()}: {', '.join(enum_values)}"
72
73            # Show nested attributes reference and recursively display them
74            nested_set_name = None
75            if attr.type == 'nest' and 'nested-attributes' in attr.yaml:
76                nested_set_name = attr.yaml['nested-attributes']
77                attr_info += f" -> {nested_set_name}"
78
79            if attr.yaml.get('doc'):
80                doc_text = textwrap.indent(attr.yaml['doc'], prefix + '  ')
81                attr_info += f"\n{doc_text}"
82            print(attr_info)
83
84            # Recursively show nested attributes
85            if nested_set_name in ynl.attr_sets:
86                nested_set = ynl.attr_sets[nested_set_name]
87                # Filter out 'unspec' and other unused attrs
88                nested_names = [n for n in nested_set.attrs.keys()
89                                if nested_set.attrs[n].type != 'unused']
90                if nested_names:
91                    print_attr_list(ynl, nested_names, nested_set, indent + 4)
92
93
94def print_mode_attrs(ynl, mode, mode_spec, attr_set, print_request=True):
95    """Print a given mode (do/dump/event/notify)."""
96    mode_title = mode.capitalize()
97
98    if print_request and 'request' in mode_spec and 'attributes' in mode_spec['request']:
99        print(f'\n{mode_title} request attributes:')
100        print_attr_list(ynl, mode_spec['request']['attributes'], attr_set)
101
102    if 'reply' in mode_spec and 'attributes' in mode_spec['reply']:
103        print(f'\n{mode_title} reply attributes:')
104        print_attr_list(ynl, mode_spec['reply']['attributes'], attr_set)
105
106    if 'attributes' in mode_spec:
107        print(f'\n{mode_title} attributes:')
108        print_attr_list(ynl, mode_spec['attributes'], attr_set)
109
110
111# pylint: disable=too-many-locals,too-many-branches,too-many-statements
112def main():
113    """YNL cli tool"""
114
115    description = """
116    YNL CLI utility - a general purpose netlink utility that uses YAML
117    specs to drive protocol encoding and decoding.
118    """
119    epilog = """
120    The --multi option can be repeated to include several do operations
121    in the same netlink payload.
122    """
123
124    parser = argparse.ArgumentParser(description=description,
125                                     epilog=epilog)
126    spec_group = parser.add_mutually_exclusive_group(required=True)
127    spec_group.add_argument('--family', dest='family', type=str,
128                            help='name of the netlink FAMILY')
129    spec_group.add_argument('--list-families', action='store_true',
130                            help='list all netlink families supported by YNL (has spec)')
131    spec_group.add_argument('--spec', dest='spec', type=str,
132                            help='choose the family by SPEC file path')
133
134    parser.add_argument('--schema', dest='schema', type=str)
135    parser.add_argument('--no-schema', action='store_true')
136    parser.add_argument('--json', dest='json_text', type=str)
137
138    group = parser.add_mutually_exclusive_group()
139    group.add_argument('--do', dest='do', metavar='DO-OPERATION', type=str)
140    group.add_argument('--multi', dest='multi', nargs=2, action='append',
141                       metavar=('DO-OPERATION', 'JSON_TEXT'), type=str)
142    group.add_argument('--dump', dest='dump', metavar='DUMP-OPERATION', type=str)
143    group.add_argument('--list-ops', action='store_true')
144    group.add_argument('--list-msgs', action='store_true')
145    group.add_argument('--list-attrs', dest='list_attrs', metavar='OPERATION', type=str,
146                       help='List attributes for an operation')
147    group.add_argument('--validate', action='store_true')
148
149    parser.add_argument('--duration', dest='duration', type=int,
150                        help='when subscribed, watch for DURATION seconds')
151    parser.add_argument('--sleep', dest='duration', type=int,
152                        help='alias for duration')
153    parser.add_argument('--subscribe', dest='ntf', type=str)
154    parser.add_argument('--replace', dest='flags', action='append_const',
155                        const=Netlink.NLM_F_REPLACE)
156    parser.add_argument('--excl', dest='flags', action='append_const',
157                        const=Netlink.NLM_F_EXCL)
158    parser.add_argument('--create', dest='flags', action='append_const',
159                        const=Netlink.NLM_F_CREATE)
160    parser.add_argument('--append', dest='flags', action='append_const',
161                        const=Netlink.NLM_F_APPEND)
162    parser.add_argument('--process-unknown', action=argparse.BooleanOptionalAction)
163    parser.add_argument('--output-json', action='store_true')
164    parser.add_argument('--dbg-small-recv', default=0, const=4000,
165                        action='store', nargs='?', type=int)
166    args = parser.parse_args()
167
168    def output(msg):
169        if args.output_json:
170            print(json.dumps(msg, cls=YnlEncoder))
171        else:
172            pprint.PrettyPrinter().pprint(msg)
173
174    if args.list_families:
175        for filename in sorted(os.listdir(spec_dir())):
176            if filename.endswith('.yaml'):
177                print(filename.removesuffix('.yaml'))
178        return
179
180    if args.no_schema:
181        args.schema = ''
182
183    attrs = {}
184    if args.json_text:
185        attrs = json.loads(args.json_text)
186
187    if args.family:
188        spec = f"{spec_dir()}/{args.family}.yaml"
189    else:
190        spec = args.spec
191    if not os.path.isfile(spec):
192        raise Exception(f"Spec file {spec} does not exist")
193
194    if args.validate:
195        try:
196            SpecFamily(spec, args.schema)
197        except Exception as error:
198            print(error)
199            sys.exit(1)
200        return
201
202    if args.family: # set behaviour when using installed specs
203        if args.schema is None and spec.startswith(SYS_SCHEMA_DIR):
204            args.schema = '' # disable schema validation when installed
205        if args.process_unknown is None:
206            args.process_unknown = True
207
208    ynl = YnlFamily(spec, args.schema, args.process_unknown,
209                    recv_size=args.dbg_small_recv)
210    if args.dbg_small_recv:
211        ynl.set_recv_dbg(True)
212
213    if args.ntf:
214        ynl.ntf_subscribe(args.ntf)
215
216    if args.list_ops:
217        for op_name, op in ynl.ops.items():
218            print(op_name, " [", ", ".join(op.modes), "]")
219    if args.list_msgs:
220        for op_name, op in ynl.msgs.items():
221            print(op_name, " [", ", ".join(op.modes), "]")
222
223    if args.list_attrs:
224        op = ynl.msgs.get(args.list_attrs)
225        if not op:
226            print(f'Operation {args.list_attrs} not found')
227            sys.exit(1)
228
229        print(f'Operation: {op.name}')
230        print(op.yaml['doc'])
231
232        for mode in ['do', 'dump', 'event']:
233            if mode in op.yaml:
234                print_mode_attrs(ynl, mode, op.yaml[mode], op.attr_set, True)
235
236        if 'notify' in op.yaml:
237            mode_spec = op.yaml['notify']
238            ref_spec = ynl.msgs.get(mode_spec).yaml.get('do')
239            if ref_spec:
240                print_mode_attrs(ynl, 'notify', ref_spec, op.attr_set, False)
241
242        if 'mcgrp' in op.yaml:
243            print(f"\nMulticast group: {op.yaml['mcgrp']}")
244
245    try:
246        if args.do:
247            reply = ynl.do(args.do, attrs, args.flags)
248            output(reply)
249        if args.dump:
250            reply = ynl.dump(args.dump, attrs)
251            output(reply)
252        if args.multi:
253            ops = [ (item[0], json.loads(item[1]), args.flags or []) for item in args.multi ]
254            reply = ynl.do_multi(ops)
255            output(reply)
256
257        if args.ntf:
258            for msg in ynl.poll_ntf(duration=args.duration):
259                output(msg)
260    except NlError as e:
261        print(e)
262        sys.exit(1)
263    except KeyboardInterrupt:
264        pass
265    except BrokenPipeError:
266        pass
267
268
269if __name__ == "__main__":
270    main()
271