1#!/usr/bin/env python3 2# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause 3 4import argparse 5import json 6import pprint 7import time 8 9from lib import YnlFamily, Netlink, NlError 10 11 12class YnlEncoder(json.JSONEncoder): 13 def default(self, obj): 14 if isinstance(obj, bytes): 15 return bytes.hex(obj) 16 if isinstance(obj, set): 17 return list(obj) 18 return json.JSONEncoder.default(self, obj) 19 20 21def main(): 22 parser = argparse.ArgumentParser(description='YNL CLI sample') 23 parser.add_argument('--spec', dest='spec', type=str, required=True) 24 parser.add_argument('--schema', dest='schema', type=str) 25 parser.add_argument('--no-schema', action='store_true') 26 parser.add_argument('--json', dest='json_text', type=str) 27 parser.add_argument('--do', dest='do', type=str) 28 parser.add_argument('--dump', dest='dump', type=str) 29 parser.add_argument('--sleep', dest='sleep', type=int) 30 parser.add_argument('--subscribe', dest='ntf', type=str) 31 parser.add_argument('--replace', dest='flags', action='append_const', 32 const=Netlink.NLM_F_REPLACE) 33 parser.add_argument('--excl', dest='flags', action='append_const', 34 const=Netlink.NLM_F_EXCL) 35 parser.add_argument('--create', dest='flags', action='append_const', 36 const=Netlink.NLM_F_CREATE) 37 parser.add_argument('--append', dest='flags', action='append_const', 38 const=Netlink.NLM_F_APPEND) 39 parser.add_argument('--process-unknown', action=argparse.BooleanOptionalAction) 40 parser.add_argument('--output-json', action='store_true') 41 parser.add_argument('--dbg-small-recv', default=0, const=4000, 42 action='store', nargs='?', type=int) 43 args = parser.parse_args() 44 45 def output(msg): 46 if args.output_json: 47 print(json.dumps(msg, cls=YnlEncoder)) 48 else: 49 pprint.PrettyPrinter().pprint(msg) 50 51 if args.no_schema: 52 args.schema = '' 53 54 attrs = {} 55 if args.json_text: 56 attrs = json.loads(args.json_text) 57 58 ynl = YnlFamily(args.spec, args.schema, args.process_unknown, 59 recv_size=args.dbg_small_recv) 60 if args.dbg_small_recv: 61 ynl.set_recv_dbg(True) 62 63 if args.ntf: 64 ynl.ntf_subscribe(args.ntf) 65 66 if args.sleep: 67 time.sleep(args.sleep) 68 69 try: 70 if args.do: 71 reply = ynl.do(args.do, attrs, args.flags) 72 output(reply) 73 if args.dump: 74 reply = ynl.dump(args.dump, attrs) 75 output(reply) 76 except NlError as e: 77 print(e) 78 exit(1) 79 80 if args.ntf: 81 ynl.check_ntf() 82 output(ynl.async_msg_queue) 83 84 85if __name__ == "__main__": 86 main() 87