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(ynl, attr_names, attr_set, indent=2): 44 """Print a list of attributes with their types and documentation.""" 45 prefix = ' ' * indent 46 for attr_name in attr_names: 47 if attr_name in attr_set.attrs: 48 attr = attr_set.attrs[attr_name] 49 attr_info = f'{prefix}- {attr_name}: {attr.type}' 50 if 'enum' in attr.yaml: 51 attr_info += f" (enum: {attr.yaml['enum']})" 52 53 # Show nested attributes reference and recursively display them 54 nested_set_name = None 55 if attr.type == 'nest' and 'nested-attributes' in attr.yaml: 56 nested_set_name = attr.yaml['nested-attributes'] 57 attr_info += f" -> {nested_set_name}" 58 59 if attr.yaml.get('doc'): 60 doc_text = textwrap.indent(attr.yaml['doc'], prefix + ' ') 61 attr_info += f"\n{doc_text}" 62 print(attr_info) 63 64 # Recursively show nested attributes 65 if nested_set_name in ynl.attr_sets: 66 nested_set = ynl.attr_sets[nested_set_name] 67 # Filter out 'unspec' and other unused attrs 68 nested_names = [n for n in nested_set.attrs.keys() 69 if nested_set.attrs[n].type != 'unused'] 70 if nested_names: 71 print_attr_list(ynl, nested_names, nested_set, indent + 4) 72 73 74def print_mode_attrs(ynl, mode, mode_spec, attr_set, print_request=True): 75 """Print a given mode (do/dump/event/notify).""" 76 mode_title = mode.capitalize() 77 78 if print_request and 'request' in mode_spec and 'attributes' in mode_spec['request']: 79 print(f'\n{mode_title} request attributes:') 80 print_attr_list(ynl, mode_spec['request']['attributes'], attr_set) 81 82 if 'reply' in mode_spec and 'attributes' in mode_spec['reply']: 83 print(f'\n{mode_title} reply attributes:') 84 print_attr_list(ynl, mode_spec['reply']['attributes'], attr_set) 85 86 if 'attributes' in mode_spec: 87 print(f'\n{mode_title} attributes:') 88 print_attr_list(ynl, mode_spec['attributes'], attr_set) 89 90 91def main(): 92 description = """ 93 YNL CLI utility - a general purpose netlink utility that uses YAML 94 specs to drive protocol encoding and decoding. 95 """ 96 epilog = """ 97 The --multi option can be repeated to include several do operations 98 in the same netlink payload. 99 """ 100 101 parser = argparse.ArgumentParser(description=description, 102 epilog=epilog) 103 spec_group = parser.add_mutually_exclusive_group(required=True) 104 spec_group.add_argument('--family', dest='family', type=str, 105 help='name of the netlink FAMILY') 106 spec_group.add_argument('--list-families', action='store_true', 107 help='list all netlink families supported by YNL (has spec)') 108 spec_group.add_argument('--spec', dest='spec', type=str, 109 help='choose the family by SPEC file path') 110 111 parser.add_argument('--schema', dest='schema', type=str) 112 parser.add_argument('--no-schema', action='store_true') 113 parser.add_argument('--json', dest='json_text', type=str) 114 115 group = parser.add_mutually_exclusive_group() 116 group.add_argument('--do', dest='do', metavar='DO-OPERATION', type=str) 117 group.add_argument('--multi', dest='multi', nargs=2, action='append', 118 metavar=('DO-OPERATION', 'JSON_TEXT'), type=str) 119 group.add_argument('--dump', dest='dump', metavar='DUMP-OPERATION', type=str) 120 group.add_argument('--list-ops', action='store_true') 121 group.add_argument('--list-msgs', action='store_true') 122 group.add_argument('--list-attrs', dest='list_attrs', metavar='OPERATION', type=str, 123 help='List attributes for an operation') 124 125 parser.add_argument('--duration', dest='duration', type=int, 126 help='when subscribed, watch for DURATION seconds') 127 parser.add_argument('--sleep', dest='duration', type=int, 128 help='alias for duration') 129 parser.add_argument('--subscribe', dest='ntf', type=str) 130 parser.add_argument('--replace', dest='flags', action='append_const', 131 const=Netlink.NLM_F_REPLACE) 132 parser.add_argument('--excl', dest='flags', action='append_const', 133 const=Netlink.NLM_F_EXCL) 134 parser.add_argument('--create', dest='flags', action='append_const', 135 const=Netlink.NLM_F_CREATE) 136 parser.add_argument('--append', dest='flags', action='append_const', 137 const=Netlink.NLM_F_APPEND) 138 parser.add_argument('--process-unknown', action=argparse.BooleanOptionalAction) 139 parser.add_argument('--output-json', action='store_true') 140 parser.add_argument('--dbg-small-recv', default=0, const=4000, 141 action='store', nargs='?', type=int) 142 args = parser.parse_args() 143 144 def output(msg): 145 if args.output_json: 146 print(json.dumps(msg, cls=YnlEncoder)) 147 else: 148 pprint.PrettyPrinter().pprint(msg) 149 150 if args.list_families: 151 for filename in sorted(os.listdir(spec_dir())): 152 if filename.endswith('.yaml'): 153 print(filename.removesuffix('.yaml')) 154 return 155 156 if args.no_schema: 157 args.schema = '' 158 159 attrs = {} 160 if args.json_text: 161 attrs = json.loads(args.json_text) 162 163 if args.family: 164 spec = f"{spec_dir()}/{args.family}.yaml" 165 if args.schema is None and spec.startswith(sys_schema_dir): 166 args.schema = '' # disable schema validation when installed 167 if args.process_unknown is None: 168 args.process_unknown = True 169 else: 170 spec = args.spec 171 if not os.path.isfile(spec): 172 raise Exception(f"Spec file {spec} does not exist") 173 174 ynl = YnlFamily(spec, args.schema, args.process_unknown, 175 recv_size=args.dbg_small_recv) 176 if args.dbg_small_recv: 177 ynl.set_recv_dbg(True) 178 179 if args.ntf: 180 ynl.ntf_subscribe(args.ntf) 181 182 if args.list_ops: 183 for op_name, op in ynl.ops.items(): 184 print(op_name, " [", ", ".join(op.modes), "]") 185 if args.list_msgs: 186 for op_name, op in ynl.msgs.items(): 187 print(op_name, " [", ", ".join(op.modes), "]") 188 189 if args.list_attrs: 190 op = ynl.msgs.get(args.list_attrs) 191 if not op: 192 print(f'Operation {args.list_attrs} not found') 193 exit(1) 194 195 print(f'Operation: {op.name}') 196 print(op.yaml['doc']) 197 198 for mode in ['do', 'dump', 'event']: 199 if mode in op.yaml: 200 print_mode_attrs(ynl, mode, op.yaml[mode], op.attr_set, True) 201 202 if 'notify' in op.yaml: 203 mode_spec = op.yaml['notify'] 204 ref_spec = ynl.msgs.get(mode_spec).yaml.get('do') 205 if ref_spec: 206 print_mode_attrs(ynl, 'notify', ref_spec, op.attr_set, False) 207 208 if 'mcgrp' in op.yaml: 209 print(f"\nMulticast group: {op.yaml['mcgrp']}") 210 211 try: 212 if args.do: 213 reply = ynl.do(args.do, attrs, args.flags) 214 output(reply) 215 if args.dump: 216 reply = ynl.dump(args.dump, attrs) 217 output(reply) 218 if args.multi: 219 ops = [ (item[0], json.loads(item[1]), args.flags or []) for item in args.multi ] 220 reply = ynl.do_multi(ops) 221 output(reply) 222 223 if args.ntf: 224 for msg in ynl.poll_ntf(duration=args.duration): 225 output(msg) 226 except NlError as e: 227 print(e) 228 exit(1) 229 except KeyboardInterrupt: 230 pass 231 except BrokenPipeError: 232 pass 233 234 235if __name__ == "__main__": 236 main() 237