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