-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathcli.py
2795 lines (2514 loc) · 116 KB
/
cli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (c) 2021 International Business Machines
# All rights reserved.
#
# SPDX-License-Identifier: LGPL-3.0-or-later
#
# Authors: [email protected], [email protected]
#
import argparse
import grpc
import json
import logging
import sys
import errno
import os
import yaml
import ipaddress
from functools import wraps
from google.protobuf import json_format
from tabulate import tabulate
from .proto import gateway_pb2_grpc as pb2_grpc
from .proto import gateway_pb2 as pb2
from .utils import GatewayUtils
from .utils import GatewayEnumUtils
BASE_GATEWAY_VERSION = "1.1.0"
def errprint(msg):
print(msg, file=sys.stderr)
def argument(*name_or_flags, **kwargs):
"""Helper function to format arguments for argparse command decorator."""
return (list(name_or_flags), kwargs)
def get_enum_keys_list(e_type, include_first=True):
k_list = []
for k in e_type.keys():
k_list.append(k.lower())
k_list.append(k.upper())
if not include_first:
k_list = k_list[2:]
return k_list
def break_string(s, delim, count):
start = 0
for i in range(count):
ind = s.find(delim, start)
if ind < 0:
return s
start = ind + 1
return s[0:ind + 1] + "\n" + s[ind + 1:]
class ErrorCatchingArgumentParser(argparse.ArgumentParser):
def __init__(self, *args, **kwargs):
self.logger = logging.getLogger(__name__)
super(ErrorCatchingArgumentParser, self).__init__(*args, **kwargs)
def exit(self, status=0, message=None):
if status != 0:
if message:
self.logger.error(message)
else:
if message:
self.logger.info(message)
exit(status)
def error(self, message):
self.print_usage()
if message:
self.logger.error(f"error: {message}")
exit(2)
class Parser:
"""Class to simplify creation of client CLI.
Instance attributes:
parser: ArgumentParser object.
subparsers: Action object to add subcommands to main argument parser.
"""
def __init__(self):
self.parser = ErrorCatchingArgumentParser(
prog="python3 -m control.cli",
description="CLI to manage NVMe gateways")
self.parser.add_argument(
"--format",
help="CLI output format",
type=str,
default="text",
choices=["text", "json", "yaml", "plain", "python"],
required=False)
self.parser.add_argument(
"--output",
help="CLI output method",
type=str,
default="log",
choices=["log", "stdio"],
required=False)
self.parser.add_argument(
"--log-level",
help="CLI log level",
type=str,
default="info",
choices=get_enum_keys_list(pb2.GwLogLevel, False),
required=False)
self.parser.add_argument(
"--server-address",
default=(os.getenv('CEPH_NVMEOF_SERVER_ADDRESS') or "localhost"),
type=str,
help="Server address (default: CEPH_NVMEOF_SERVER_ADDRESS env variable or 'localhost')",
)
self.parser.add_argument(
"--server-port",
default=int(os.getenv('CEPH_NVMEOF_SERVER_PORT') or "5500"),
type=int,
help="Server port (default: CEPH_NVMEOF_SERVER_PORT env variable or '5500')",
)
self.parser.add_argument(
"--client-key",
type=argparse.FileType("rb"),
help="Path to the client key file")
self.parser.add_argument(
"--client-cert",
type=argparse.FileType("rb"),
help="Path to the client certificate file")
self.parser.add_argument(
"--server-cert",
type=argparse.FileType("rb"),
help="Path to the server certificate file"
)
self.parser.add_argument(
"--verbose",
help="Run CLI in verbose mode",
action='store_true')
self.subparsers = self.parser.add_subparsers(title="Commands", dest="subcommand")
def cmd(self, actions=[], aliases=[], hlp=None):
"""Decorator to create an argparse command.
The arguments to this decorator are used as arguments for the argparse
command.
"""
def decorator(func):
helpstr = func.__doc__
if hlp:
helpstr = hlp
parser = self.subparsers.add_parser(func.__name__,
description=helpstr, aliases=aliases, help=helpstr)
subp = parser.add_subparsers(title="Action", dest="action")
for act in actions:
act_name = act["name"]
act_args = act["args"]
act_help = act["help"]
pr = subp.add_parser(act_name, description=act_help, help=act_help)
for arg in act_args:
pr.add_argument(*arg[0], **arg[1])
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except grpc.RpcError as e:
self.parser.error(
f"{func.__name__} failed: code={e.code()} message={e.details()}")
parser.set_defaults(func=wrapper)
return wrapper
return decorator
class GatewayClient:
"""Client for gRPC functionality with a gateway server.
Contains methods to send RPC calls to the server and specifications for the
associated command line arguments.
Class attributes:
cli: Parser object
Instance attributes: * Must be initialized with GatewayClient.connect *
stub: Object on which to call server methods
logger: Logger instance to track client events
"""
SIZE_UNITS = ["K", "M", "G", "T", "P"]
MAX_MB_PER_SECOND = int(0xffffffffffffffff / (1024 * 1024))
cli = Parser()
def __init__(self):
self._stub = None
logging.basicConfig(format='%(message)s')
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.INFO)
@property
def stub(self):
"""Object on which to call server methods."""
if self._stub is None:
raise AttributeError("stub is None. Set with connect method.")
return self._stub
def connect(self, args, host, port, client_key, client_cert, server_cert):
"""Connects to server and sets stub."""
out_func, err_func, _ = self.get_output_functions(args)
if args.format == "json" or args.format == "yaml" or args.format == "python":
out_func = None
# We need to enclose IPv6 addresses in brackets before
# concatenating a colon and port number to it
host = GatewayUtils.escape_address_if_ipv6(host)
server = f"{host}:{port}"
if client_key and client_cert:
# Create credentials for mutual TLS and a secure channel
if out_func:
out_func("Enable server auth since both --client-key and "
"--client-cert are provided")
with client_cert as f:
client_cert = f.read()
with client_key as f:
client_key = f.read()
if server_cert:
with server_cert as f:
server_cert = f.read()
else:
err_func("No server certificate file was provided")
credentials = grpc.ssl_channel_credentials(
root_certificates=server_cert,
private_key=client_key,
certificate_chain=client_cert,
)
channel = grpc.secure_channel(server, credentials)
else:
# Instantiate a channel without credentials
channel = grpc.insecure_channel(server)
# Bind the client and the server
self._stub = pb2_grpc.GatewayStub(channel)
def get_actions(act_list):
acts = ""
for a in act_list:
acts += ", '" + a["name"] + "'"
return acts[2:]
def format_adrfam(self, adrfam):
adrfam = adrfam.upper()
if adrfam == "IPV4":
adrfam = "IPv4"
elif adrfam == "IPV6":
adrfam = "IPv6"
return adrfam
def get_output_functions(self, args):
if args.output == "log":
return (self.logger.info, self.logger.error, self.logger.warning)
elif args.output == "stdio":
return (print, errprint, errprint)
else:
self.cli.parser.error("invalid --output value")
def validate_ip_address(self, addr, family):
ipaddr = None
try:
ipaddr = ipaddress.ip_address(addr)
except ValueError:
ipaddr = None
if ipaddr is None:
self.cli.parser.error(f"invalid IP address {addr}")
if not family or family.lower() == "ipv4":
if ipaddr.version != 4:
self.cli.parser.error(f"IP address {addr} is not an IPv4 address")
elif family.lower() == "ipv6":
if ipaddr.version != 6:
self.cli.parser.error(f"IP address {addr} is not an IPv6 address")
else:
self.cli.parser.error(f"invalid address family {family}")
@cli.cmd()
def version(self, args):
"""Get CLI version"""
rc = 0
out_func, err_func, _ = self.get_output_functions(args)
errmsg = ""
ver = os.getenv("NVMEOF_VERSION")
if not ver:
rc = errno.ENOKEY
errmsg = "Can't get CLI version"
else:
rc = 0
errmsg = os.strerror(0)
if args.format == "text" or args.format == "plain":
if not ver:
err_func(errmsg)
else:
out_func(f"CLI version: {ver}")
elif args.format == "json" or args.format == "yaml":
cli_ver = pb2.cli_version(status=rc, error_message=errmsg, version=ver)
out_ver = json_format.MessageToJson(cli_ver,
indent=4,
including_default_value_fields=True,
preserving_proto_field_name=True)
if args.format == "json":
out_func(f"{out_ver}")
elif args.format == "yaml":
obj = json.loads(out_ver)
out_func(yaml.dump(obj))
elif args.format == "python":
return pb2.cli_version(status=rc, error_message=errmsg, version=ver)
else:
assert False
return rc
def parse_version_string(self, version):
if not version:
return None
try:
vlist = version.split(".")
if len(vlist) != 3:
raise Exception
v1 = int(vlist[0])
v2 = int(vlist[1])
v3 = int(vlist[2])
except Exception:
return None
return (v1, v2, v3)
def gw_get_info(self):
ver = os.getenv("NVMEOF_VERSION")
req = pb2.get_gateway_info_req(cli_version=ver)
gw_info = self.stub.get_gateway_info(req)
if gw_info.status == 0:
base_ver = self.parse_version_string(BASE_GATEWAY_VERSION)
assert base_ver is not None
gw_ver = self.parse_version_string(gw_info.version)
if gw_ver is None:
gw_info.status = errno.EINVAL
gw_info.bool_status = False
gw_info.error_message = f"Can't parse gateway version \"{gw_info.version}\"."
elif gw_ver < base_ver:
gw_info.status = errno.EINVAL
gw_info.bool_status = False
gw_info.error_message = f"Can't work with gateway version older " \
f"than {BASE_GATEWAY_VERSION}"
return gw_info
def gw_info(self, args):
"""Get gateway's information"""
out_func, err_func, _ = self.get_output_functions(args)
try:
gw_info = self.gw_get_info()
except Exception as ex:
gw_info = pb2.gateway_info(
status=errno.EINVAL,
error_message=f"Failure getting gateway's information:\n{ex}")
if args.format == "text" or args.format == "plain":
if gw_info.status == 0:
if gw_info.cli_version:
out_func(f"CLI's version: {gw_info.cli_version}")
if gw_info.version:
out_func(f"Gateway's version: {gw_info.version}")
if gw_info.name:
out_func(f"Gateway's name: {gw_info.name}")
if gw_info.group:
out_func(f"Gateway's group: {gw_info.group}")
if gw_info.hostname:
out_func(f"Gateway's host name: {gw_info.hostname}")
out_func(f"Gateway's load balancing group: {gw_info.load_balancing_group}")
out_func(f"Gateway's address: {gw_info.addr}")
out_func(f"Gateway's port: {gw_info.port}")
if gw_info.max_subsystems:
out_func(f"Gateway's max subsystems: {gw_info.max_subsystems}")
if gw_info.max_hosts:
out_func(f"Gateway's max hosts: {gw_info.max_hosts}")
if gw_info.max_namespaces:
out_func(f"Gateway's max namespaces: {gw_info.max_namespaces}")
if gw_info.max_namespaces_per_subsystem:
out_func(f"Gateway's max namespaces per subsystem: "
f"{gw_info.max_namespaces_per_subsystem}")
if gw_info.max_hosts_per_subsystem:
out_func(f"Gateway's max hosts per subsystem: "
f"{gw_info.max_hosts_per_subsystem}")
if gw_info.spdk_version:
out_func(f"SPDK version: {gw_info.spdk_version}")
if not gw_info.bool_status:
err_func("Getting gateway's information returned status mismatch")
else:
err_func(gw_info.error_message)
if gw_info.bool_status:
err_func("Getting gateway's information returned status mismatch")
elif args.format == "json" or args.format == "yaml":
gw_info_str = json_format.MessageToJson(gw_info, indent=4,
including_default_value_fields=True,
preserving_proto_field_name=True)
if args.format == "json":
out_func(gw_info_str)
elif args.format == "yaml":
obj = json.loads(gw_info_str)
out_func(yaml.dump(obj))
elif args.format == "python":
return gw_info
else:
assert False
return gw_info.status
def gw_version(self, args):
"""Get gateway's version"""
out_func, err_func, _ = self.get_output_functions(args)
try:
gw_info = self.gw_get_info()
except Exception as ex:
gw_info = pb2.gateway_info(status=errno.EINVAL,
error_message=f"Failure getting gateway's version:\n{ex}")
if args.format == "text" or args.format == "plain":
if gw_info.status == 0:
out_func(f"Gateway's version: {gw_info.version}")
else:
err_func(f"{gw_info.error_message}")
elif args.format == "json" or args.format == "yaml":
gw_ver = pb2.gw_version(status=gw_info.status,
error_message=gw_info.error_message,
version=gw_info.version)
out_ver = json_format.MessageToJson(gw_ver,
indent=4,
including_default_value_fields=True,
preserving_proto_field_name=True)
if args.format == "json":
out_func(f"{out_ver}")
elif args.format == "yaml":
obj = json.loads(out_ver)
out_func(yaml.dump(obj))
elif args.format == "python":
return pb2.gw_version(status=gw_info.status,
error_message=gw_info.error_message,
version=gw_info.version)
else:
assert False
return gw_info.status
def gw_get_log_level(self, args):
"""Get gateway's log level"""
out_func, err_func, _ = self.get_output_functions(args)
req = pb2.get_gateway_log_level_req()
try:
ret = self.stub.get_gateway_log_level(req)
except Exception as ex:
ret = pb2.req_status(status=errno.EINVAL,
error_message=f"Failure getting gateway log level:\n{ex}")
if args.format == "text" or args.format == "plain":
if ret.status == 0:
level = GatewayEnumUtils.get_key_from_value(pb2.GwLogLevel, ret.log_level)
out_func(f"Gateway log level is \"{level}\"")
else:
err_func(f"{ret.error_message}")
elif args.format == "json" or args.format == "yaml":
out_log_level = json_format.MessageToJson(ret, indent=4,
including_default_value_fields=True,
preserving_proto_field_name=True)
if args.format == "json":
out_func(out_log_level)
elif args.format == "yaml":
obj = json.loads(out_log_level)
out_func(yaml.dump(obj))
elif args.format == "python":
return ret
else:
assert False
return ret.status
def gw_set_log_level(self, args):
"""Set gateway's log level"""
out_func, err_func, _ = self.get_output_functions(args)
log_level = None
if args.level:
log_level = args.level.lower()
try:
req = pb2.set_gateway_log_level_req(log_level=log_level)
except ValueError as err:
self.cli.parser.error(f"invalid log level {log_level}, error {err}")
try:
ret = self.stub.set_gateway_log_level(req)
except Exception as ex:
ret = pb2.req_status(status=errno.EINVAL,
error_message=f"Failure setting gateway log level:\n{ex}")
if args.format == "text" or args.format == "plain":
if ret.status == 0:
out_func(f"Set gateway log level to \"{log_level}\": Successful")
else:
err_func(f"{ret.error_message}")
elif args.format == "json" or args.format == "yaml":
ret_str = json_format.MessageToJson(ret, indent=4,
including_default_value_fields=True,
preserving_proto_field_name=True)
if args.format == "json":
out_func(ret_str)
elif args.format == "yaml":
obj = json.loads(ret_str)
out_func(yaml.dump(obj))
elif args.format == "python":
return ret
else:
assert False
def gw_listener_info(self, args):
"""Show gateway's listeners info"""
out_func, err_func, _ = self.get_output_functions(args)
listeners_info = None
try:
list_req = pb2.show_gateway_listeners_info_req(subsystem_nqn=args.subsystem)
listeners_info = self.stub.show_gateway_listeners_info(list_req)
except Exception as ex:
listeners_info = pb2.gateway_listeners_info(status=errno.EINVAL,
error_message=f"Failure listing gateway "
f"listeners info:\n{ex}",
gw_listeners=[])
if args.format == "text" or args.format == "plain":
if listeners_info.status == 0:
listeners_list = []
for lstnr in listeners_info.gw_listeners:
ana_states = ""
for ana in lstnr.lb_states:
if not args.verbose and ana.state != pb2.ana_state.OPTIMIZED:
continue
state_str = GatewayEnumUtils.get_key_from_value(pb2.ana_state, ana.state)
if state_str is None:
ana_states += str(ana.grp_id) + ": " + str(ana.state) + "\n"
else:
ana_states += str(ana.grp_id) + ": " + state_str.title() + "\n"
adrfam = GatewayEnumUtils.get_key_from_value(pb2.AddressFamily,
lstnr.listener.adrfam)
adrfam = self.format_adrfam(adrfam)
secure = "Yes" if lstnr.listener.secure else "No"
ana_states = ana_states.removesuffix("\n")
listeners_list.append([lstnr.listener.host_name,
lstnr.listener.trtype,
adrfam,
f"{lstnr.listener.traddr}:{lstnr.listener.trsvcid}",
secure,
ana_states])
if len(listeners_list) > 0:
if args.format == "text":
table_format = "fancy_grid"
else:
table_format = "plain"
listeners_out = tabulate(listeners_list,
headers=["Host",
"Transport",
"Address Family",
"Address",
"Secure",
"Load Balancing Group ID/State"],
tablefmt=table_format)
out_func(f"Gateway listeners for {args.subsystem}:\n{listeners_out}")
else:
out_func(f"No gateway listeners for {args.subsystem}")
else:
err_func(f"{listeners_info.error_message}")
elif args.format == "json" or args.format == "yaml":
ret_str = json_format.MessageToJson(listeners_info, indent=4,
including_default_value_fields=True,
preserving_proto_field_name=True)
if args.format == "json":
out_func(ret_str)
elif args.format == "yaml":
obj = json.loads(ret_str)
out_func(yaml.dump(obj))
elif args.format == "python":
return listeners_info
else:
assert False
return listeners_info.status
gw_set_log_level_args = [
argument("--level", "-l", help="Gateway log level", required=True,
type=str, choices=get_enum_keys_list(pb2.GwLogLevel, False)),
]
gw_listener_info_args = [
argument("--subsystem",
"-n",
help="Subsystem NQN",
required=True),
]
gw_actions = []
gw_actions.append({"name": "version",
"args": [],
"help": "Display gateway's version"})
gw_actions.append({"name": "info",
"args": [],
"help": "Display gateway's information"})
gw_actions.append({"name": "get_log_level",
"args": [],
"help": "Get gateway's log level"})
gw_actions.append({"name": "set_log_level",
"args": gw_set_log_level_args,
"help": "Set gateway's log level"})
gw_actions.append({"name": "listener_info",
"args": gw_listener_info_args,
"help": "Show listeners information for the gateway"})
gw_choices = get_actions(gw_actions)
@cli.cmd(gw_actions)
def gw(self, args):
"""Gateway commands"""
if args.action == "info":
return self.gw_info(args)
elif args.action == "version":
return self.gw_version(args)
elif args.action == "get_log_level":
return self.gw_get_log_level(args)
elif args.action == "set_log_level":
return self.gw_set_log_level(args)
elif args.action == "listener_info":
return self.gw_listener_info(args)
if not args.action:
self.cli.parser.error(f"missing action for gw command (choose from "
f"{GatewayClient.gw_choices})")
def spdk_log_level_disable(self, args):
"""Disable SPDK nvmf log flags"""
out_func, err_func, _ = self.get_output_functions(args)
req = pb2.disable_spdk_nvmf_logs_req()
try:
ret = self.stub.disable_spdk_nvmf_logs(req)
except Exception as ex:
ret = pb2.req_status(status=errno.EINVAL,
error_message=f"Failure disabling SPDK nvmf log flags:\n{ex}")
if args.format == "text" or args.format == "plain":
if ret.status == 0:
out_func("Disable SPDK nvmf log flags: Successful")
else:
err_func(f"{ret.error_message}")
elif args.format == "json" or args.format == "yaml":
ret_str = json_format.MessageToJson(ret, indent=4,
including_default_value_fields=True,
preserving_proto_field_name=True)
if args.format == "json":
out_func(ret_str)
elif args.format == "yaml":
obj = json.loads(ret_str)
out_func(yaml.dump(obj))
elif args.format == "python":
return ret
else:
assert False
return ret.status
def spdk_log_level_get(self, args):
"""Get SPDK log levels and nvmf log flags"""
out_func, err_func, _ = self.get_output_functions(args)
req = pb2.get_spdk_nvmf_log_flags_and_level_req()
try:
ret = self.stub.get_spdk_nvmf_log_flags_and_level(req)
except Exception as ex:
ret = pb2.req_status(
status=errno.EINVAL,
error_message=f"Failure getting SPDK log levels and nvmf log flags:\n{ex}")
if args.format == "text" or args.format == "plain":
if ret.status == 0:
for flag in ret.nvmf_log_flags:
enabled_str = "enabled" if flag.enabled else "disabled"
out_func(f"SPDK nvmf log flag \"{flag.name}\" is {enabled_str}")
level = GatewayEnumUtils.get_key_from_value(pb2.LogLevel, ret.log_level)
out_func(f"SPDK log level is {level}")
level = GatewayEnumUtils.get_key_from_value(pb2.LogLevel, ret.log_print_level)
out_func(f"SPDK log print level is {level}")
else:
err_func(f"{ret.error_message}")
elif args.format == "json" or args.format == "yaml":
out_log_level = json_format.MessageToJson(ret, indent=4,
including_default_value_fields=True,
preserving_proto_field_name=True)
if args.format == "json":
out_func(out_log_level)
elif args.format == "yaml":
obj = json.loads(out_log_level)
out_func(yaml.dump(obj))
elif args.format == "python":
return ret
else:
assert False
return ret.status
def spdk_log_level_set(self, args):
"""Set SPDK log levels and nvmf log flags"""
out_func, err_func, _ = self.get_output_functions(args)
log_level = None
print_level = None
if args.level:
log_level = args.level.upper()
if args.print:
print_level = args.print.upper()
try:
req = pb2.set_spdk_nvmf_logs_req(log_level=log_level, print_level=print_level)
except ValueError as err:
self.cli.parser.error(f"invalid log level {log_level}, error {err}")
try:
ret = self.stub.set_spdk_nvmf_logs(req)
except Exception as ex:
ret = pb2.req_status(
status=errno.EINVAL,
error_message=f"Failure setting SPDK log levels and nvmf log flags:\n{ex}")
if args.format == "text" or args.format == "plain":
if ret.status == 0:
out_func("Set SPDK log levels and nvmf log flags: Successful")
else:
err_func(f"{ret.error_message}")
elif args.format == "json" or args.format == "yaml":
ret_str = json_format.MessageToJson(ret, indent=4,
including_default_value_fields=True,
preserving_proto_field_name=True)
if args.format == "json":
out_func(ret_str)
elif args.format == "yaml":
obj = json.loads(ret_str)
out_func(yaml.dump(obj))
elif args.format == "python":
return ret
else:
assert False
return ret.status
spdk_log_get_args = []
spdk_log_set_args = [
argument("--level", "-l", help="SPDK nvmf log level", required=False,
type=str, choices=get_enum_keys_list(pb2.LogLevel)),
argument("--print", "-p", help="SPDK nvmf log print level", required=False,
type=str, choices=get_enum_keys_list(pb2.LogLevel)),
]
spdk_log_disable_args = []
spdk_log_actions = []
spdk_log_actions.append({"name": "get",
"args": spdk_log_get_args,
"help": "Get SPDK log levels and nvmf log flags"})
spdk_log_actions.append({"name": "set",
"args": spdk_log_set_args,
"help": "Set SPDK log levels and nvmf log flags"})
spdk_log_actions.append({"name": "disable",
"args": spdk_log_disable_args,
"help": "Disable SPDK nvmf log flags"})
spdk_log_choices = get_actions(spdk_log_actions)
@cli.cmd(spdk_log_actions)
def spdk_log_level(self, args):
"""SPDK nvmf log level commands"""
if args.action == "get":
return self.spdk_log_level_get(args)
elif args.action == "set":
return self.spdk_log_level_set(args)
elif args.action == "disable":
return self.spdk_log_level_disable(args)
if not args.action:
self.cli.parser.error(f"missing action for spdk_log_level command "
f"(choose from {GatewayClient.spdk_log_choices})")
def subsystem_add(self, args):
"""Create a subsystem"""
out_func, err_func, _ = self.get_output_functions(args)
if args.max_namespaces is not None and args.max_namespaces <= 0:
self.cli.parser.error("--max-namespaces value must be positive")
if args.subsystem == GatewayUtils.DISCOVERY_NQN:
self.cli.parser.error("Can't add a discovery subsystem")
if args.dhchap_key == "":
self.cli.parser.error("DH-HMAC-CHAP key can't be empty")
req = pb2.create_subsystem_req(subsystem_nqn=args.subsystem,
serial_number=args.serial_number,
max_namespaces=args.max_namespaces,
enable_ha=True,
no_group_append=args.no_group_append,
dhchap_key=args.dhchap_key)
try:
ret = self.stub.create_subsystem(req)
except Exception as ex:
ret = pb2.subsys_status(
status=errno.EINVAL,
error_message=f"Failure adding subsystem {args.subsystem}:\n{ex}",
nqn=args.subsystem)
new_nqn = ""
try:
new_nqn = ret.nqn
except Exception:
# In case of an old gateway the returned value wouldn't have the nqn field
pass
if not new_nqn:
new_nqn = args.subsystem
if args.format == "text" or args.format == "plain":
if ret.status == 0:
out_func(f"Adding subsystem {new_nqn}: Successful")
else:
err_func(f"{ret.error_message}")
elif args.format == "json" or args.format == "yaml":
ret_str = json_format.MessageToJson(ret, indent=4,
including_default_value_fields=True,
preserving_proto_field_name=True)
if args.format == "json":
out_func(ret_str)
elif args.format == "yaml":
obj = json.loads(ret_str)
out_func(yaml.dump(obj))
elif args.format == "python":
return ret
else:
assert False
return ret.status
def subsystem_del(self, args):
"""Delete a subsystem"""
out_func, err_func, _ = self.get_output_functions(args)
if args.subsystem == GatewayUtils.DISCOVERY_NQN:
self.cli.parser.error("Can't delete a discovery subsystem")
req = pb2.delete_subsystem_req(subsystem_nqn=args.subsystem, force=args.force)
try:
ret = self.stub.delete_subsystem(req)
except Exception as ex:
ret = pb2.req_status(
status=errno.EINVAL,
error_message=f"Failure deleting subsystem {args.subsystem}:\n{ex}")
if args.format == "text" or args.format == "plain":
if ret.status == 0:
out_func(f"Deleting subsystem {args.subsystem}: Successful")
else:
err_func(f"{ret.error_message}")
elif args.format == "json" or args.format == "yaml":
ret_str = json_format.MessageToJson(ret, indent=4,
including_default_value_fields=True,
preserving_proto_field_name=True)
if args.format == "json":
out_func(ret_str)
elif args.format == "yaml":
obj = json.loads(ret_str)
out_func(yaml.dump(obj))
elif args.format == "python":
return ret
else:
assert False
return ret.status
def subsystem_list(self, args):
"""List subsystems"""
out_func, err_func, _ = self.get_output_functions(args)
subsystems = None
try:
list_req = pb2.list_subsystems_req(subsystem_nqn=args.subsystem,
serial_number=args.serial_number)
subsystems = self.stub.list_subsystems(list_req)
except Exception as ex:
subsystems = pb2.subsystems_info_cli(
status=errno.EINVAL,
error_message=f"Failure listing subsystems:\n{ex}")
if args.format == "text" or args.format == "plain":
if subsystems.status == 0:
subsys_list = []
created_without_key = False
for s in subsystems.subsystems:
if s.created_without_key:
created_without_key = True
break
for s in subsystems.subsystems:
if args.subsystem and args.subsystem != s.nqn:
err_func(f"Failure listing subsystem {args.subsystem}: "
f"Got subsystem {s.nqn} instead")
return errno.ENODEV
if args.serial_number and args.serial_number != s.serial_number:
err_func(f"Failure listing subsystem with serial number "
f"{args.serial_number}: Got serial number "
f"{s.serial_number} instead")
return errno.ENODEV
ctrls_id = f"{s.min_cntlid}-{s.max_cntlid}"
has_dhchap = "Yes" if s.has_dhchap_key else "No"
allow_any = "Yes" if s.allow_any_host else "No"
one_subsys = [s.subtype,
s.nqn,
s.serial_number,
ctrls_id,
s.namespace_count,
s.max_namespaces,
allow_any,
has_dhchap]
if created_without_key:
one_subsys.append("Yes" if s.created_without_key else "No")
subsys_list.append(one_subsys)
if len(subsys_list) > 0:
if args.format == "text":
table_format = "fancy_grid"
else:
table_format = "plain"
headers_list = ["Subtype", "NQN", "Serial\nNumber", "Controller IDs",
"Namespace\nCount", "Max\nNamespaces", "Allow\nAny Host",
"DHCHAP\nKey"]
if created_without_key:
headers_list.append("Created\nWithout Key")
subsys_out = tabulate(subsys_list,
headers=headers_list,
tablefmt=table_format)
prefix = "Subsystems"
if args.subsystem:
prefix = f"Subsystem {args.subsystem}"
if args.serial_number:
prefix = prefix + f" with serial number {args.serial_number}"
out_func(f"{prefix}:\n{subsys_out}")
else:
if args.subsystem:
out_func(f"No subsystem {args.subsystem}")
elif args.serial_number:
out_func(f"No subsystem with serial number {args.serial_number}")
else:
out_func("No subsystems")
else:
err_func(f"{subsystems.error_message}")
elif args.format == "json" or args.format == "yaml":
ret_str = json_format.MessageToJson(subsystems, indent=4,
including_default_value_fields=True,
preserving_proto_field_name=True)
if args.format == "json":
out_func(ret_str)
elif args.format == "yaml":
obj = json.loads(ret_str)
out_func(yaml.dump(obj))
elif args.format == "python":
return subsystems
else:
assert False
return subsystems.status
def subsystem_change_key(self, args):
"""Change subsystem's inband authentication key."""
out_func, err_func, _ = self.get_output_functions(args)
if args.dhchap_key == "":
self.cli.parser.error("DH-HMAC-CHAP key can't be empty")
req = pb2.change_subsystem_key_req(subsystem_nqn=args.subsystem, dhchap_key=args.dhchap_key)
try:
ret = self.stub.change_subsystem_key(req)
except Exception as ex:
errmsg = f"Failure changing key for subsystem {args.subsystem}"
ret = pb2.req_status(status=errno.EINVAL, error_message=f"{errmsg}:\n{ex}")