forked from JunxiongGuan/nvmetcli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnvmetcli
executable file
·617 lines (486 loc) · 16.7 KB
/
nvmetcli
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
#!/usr/bin/python
'''
Frontend to access to the NVMe target configfs hierarchy
Copyright (c) 2016 by HGST, a Western Digital Company.
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
'''
from __future__ import print_function
import os
import sys
import configshell_fb as configshell
import nvmet as nvme
class UINode(configshell.node.ConfigNode):
def __init__(self, name, parent=None, cfnode=None, shell=None):
configshell.node.ConfigNode.__init__(self, name, parent, shell)
self.cfnode = cfnode
if self.cfnode:
if self.cfnode.attr_groups:
for group in self.cfnode.attr_groups:
self._init_group(group)
self.refresh()
def _init_group(self, group):
setattr(self.__class__, "ui_getgroup_%s" % group,
lambda self, attr:
self.cfnode.get_attr(group, attr))
setattr(self.__class__, "ui_setgroup_%s" % group,
lambda self, attr, value:
self.cfnode.set_attr(group, attr, value))
attrs = self.cfnode.list_attrs(group)
attrs_ro = self.cfnode.list_attrs(group, writable=False)
for attr in attrs:
writable = attr not in attrs_ro
name = "ui_desc_%s" % group
t, d = getattr(self.__class__, name, {}).get(attr, ('string', ''))
self.define_config_group_param(group, attr, t, d, writable)
def refresh(self):
self._children = set([])
def status(self):
return "None"
def ui_command_refresh(self):
'''
Refreshes and updates the objects tree from the current path.
'''
self.refresh()
def ui_command_status(self):
'''
Displays the current node's status summary.
SEE ALSO
========
B{ls}
'''
self.shell.log.info("Status for %s: %s" % (self.path, self.status()))
def ui_command_saveconfig(self, savefile=None):
'''
Saves the current configuration to a file so that it can be restored
on next boot.
'''
node = self
while node.parent is not None:
node = node.parent
node.cfnode.save_to_file(savefile)
class UIRootNode(UINode):
def __init__(self, shell):
UINode.__init__(self, '/', parent=None, cfnode=nvme.Root(),
shell=shell)
def refresh(self):
self._children = set([])
UISubsystemsNode(self)
UIPortsNode(self)
UIHostsNode(self)
def ui_command_restoreconfig(self, savefile=None, clear_existing=False):
'''
Restores configuration from a file.
'''
errors = self.cfnode.restore_from_file(savefile, clear_existing)
self.refresh()
if errors:
raise configshell.ExecutionError(
"Configuration restored, %d errors:\n%s" %
(len(errors), "\n".join(errors)))
class UISubsystemsNode(UINode):
def __init__(self, parent):
UINode.__init__(self, 'subsystems', parent)
def refresh(self):
self._children = set([])
for subsys in self.parent.cfnode.subsystems:
UISubsystemNode(self, subsys)
def ui_command_create(self, nqn=None):
'''
Creates a new target. If I{nqn} is ommited, then the new Subsystem
will be created using a randomly generated NQN.
SEE ALSO
========
B{delete}
'''
subsystem = nvme.Subsystem(nqn, mode='create')
UISubsystemNode(self, subsystem)
def ui_command_delete(self, nqn):
'''
Recursively deletes the subsystem with the specified I{nqn}, and all
objects hanging under it.
SEE ALSO
========
B{create}
'''
subsystem = nvme.Subsystem(nqn, mode='lookup')
subsystem.delete()
self.refresh()
class UISubsystemNode(UINode):
ui_desc_attr = {
'allow_any_host': ('string', 'Allow access by any host if set to 1'),
}
def __init__(self, parent, cfnode):
UINode.__init__(self, cfnode.nqn, parent, cfnode)
def refresh(self):
self._children = set([])
UINamespacesNode(self)
UIAllowedHostsNode(self)
class UINamespacesNode(UINode):
def __init__(self, parent):
UINode.__init__(self, 'namespaces', parent)
def refresh(self):
self._children = set([])
for ns in self.parent.cfnode.namespaces:
UINamespaceNode(self, ns)
def ui_command_create(self, nsid=None):
'''
Creates a new namespace. If I{nsid} is ommited, then the next
available namespace id will be used.
SEE ALSO
========
B{delete}
'''
namespace = nvme.Namespace(self.parent.cfnode, nsid, mode='create')
UINamespaceNode(self, namespace)
def ui_command_delete(self, nsid):
'''
Recursively deletes the namespace with the specified I{nsid}, and all
objects hanging under it.
SEE ALSO
========
B{create}
'''
namespace = nvme.Namespace(self.parent.cfnode, nsid, mode='lookup')
namespace.delete()
self.refresh()
class UINamespaceNode(UINode):
ui_desc_device = {
'path': ('string', 'Backing device path.'),
'nguid': ('string', 'Namspace Global Unique Identifier.'),
}
def __init__(self, parent, cfnode):
UINode.__init__(self, str(cfnode.nsid), parent, cfnode)
def status(self):
if self.cfnode.get_enable():
return "enabled"
return "disabled"
def ui_command_enable(self):
'''
Enables the current Namespace.
SEE ALSO
========
B{disable}
'''
if self.cfnode.get_enable():
self.shell.log.info("The Namespace is already enabled.")
else:
try:
self.cfnode.set_enable(1)
self.shell.log.info("The Namespace has been enabled.")
except Exception as e:
raise configshell.ExecutionError(
"The Namespace could not be enabled.")
def ui_command_disable(self):
'''
Disables the current Namespace.
SEE ALSO
========
B{enable}
'''
if not self.cfnode.get_enable():
self.shell.log.info("The Namespace is already disabled.")
else:
try:
self.cfnode.set_enable(0)
self.shell.log.info("The Namespace has been disabled.")
except Exception as e:
raise configshell.ExecutionError(
"The Namespace could not be disabled.")
class UIAllowedHostsNode(UINode):
def __init__(self, parent):
UINode.__init__(self, 'allowed_hosts', parent)
def refresh(self):
self._children = set([])
for host in self.parent.cfnode.allowed_hosts:
UIAllowedHostNode(self, host)
def ui_command_create(self, nqn):
'''
Grants access to parent subsystems to the host specified by I{nqn}.
SEE ALSO
========
B{delete}
'''
self.parent.cfnode.add_allowed_host(nqn)
UIAllowedHostNode(self, nqn)
def ui_complete_create(self, parameters, text, current_param):
completions = []
if current_param == 'nqn':
for host in self.get_node('/hosts').children:
completions.append(host.cfnode.nqn)
if len(completions) == 1:
return [completions[0] + ' ']
else:
return completions
def ui_command_delete(self, nqn):
'''
Recursively deletes the namespace with the specified I{nsid}, and all
objects hanging under it.
SEE ALSO
========
B{create}
'''
self.parent.cfnode.remove_allowed_host(nqn)
self.refresh()
def ui_complete_delete(self, parameters, text, current_param):
completions = []
if current_param == 'nqn':
for nqn in self.parent.cfnode.allowed_hosts:
completions.append(nqn)
if len(completions) == 1:
return [completions[0] + ' ']
else:
return completions
class UIAllowedHostNode(UINode):
def __init__(self, parent, nqn):
UINode.__init__(self, nqn, parent)
class UIPortsNode(UINode):
def __init__(self, parent):
UINode.__init__(self, 'ports', parent)
def refresh(self):
self._children = set([])
for port in self.parent.cfnode.ports:
UIPortNode(self, port)
def ui_command_create(self, portid=None):
'''
Creates a new NVMe port with portid I{portid}.
SEE ALSO
========
B{delete}
'''
port = nvme.Port(portid, mode='create')
UIPortNode(self, port)
def ui_command_delete(self, portid):
'''
Recursively deletes the NVMe Port with the specified I{port}, and all
objects hanging under it.
SEE ALSO
========
B{create}
'''
port = nvme.Port(portid, mode='lookup')
port.delete()
self.refresh()
class UIPortNode(UINode):
ui_desc_addr = {
'adrfam': ('string', 'Address Family (e.g. ipv4 or fc)'),
'treq': ('string', 'Transport Security Requirements'),
'traddr': ('string', 'Transport Address (e.g. IP Address or FC wwnn:wwpn)'),
'trsvcid': ('string', 'Transport Service ID (e.g. IP Port)'),
'trtype': ('string', 'Transport Type (e.g. rdma or loop or fc)'),
}
def __init__(self, parent, cfnode):
UINode.__init__(self, str(cfnode.portid), parent, cfnode)
UIPortSubsystemsNode(self)
UIReferralsNode(self)
def status(self):
if self.cfnode.get_enable():
return "enabled"
return "disabled"
class UIPortSubsystemsNode(UINode):
def __init__(self, parent):
UINode.__init__(self, 'subsystems', parent)
def refresh(self):
self._children = set([])
for host in self.parent.cfnode.subsystems:
UIPortSubsystemNode(self, host)
def ui_command_create(self, nqn):
'''
Grants access to the subsystem specified by I{nqn} through the
parent port.
SEE ALSO
========
B{delete}
'''
self.parent.cfnode.add_subsystem(nqn)
UIPortSubsystemNode(self, nqn)
def ui_complete_create(self, parameters, text, current_param):
completions = []
if current_param == 'nqn':
for subsys in self.get_node('/subsystems').children:
completions.append(subsys.cfnode.nqn)
if len(completions) == 1:
return [completions[0] + ' ']
else:
return completions
def ui_command_delete(self, nqn):
'''
Removes access to the subsystem specified by I{nqn} through the
parent port.
SEE ALSO
========
B{create}
'''
self.parent.cfnode.remove_subsystem(nqn)
self.refresh()
def ui_complete_delete(self, parameters, text, current_param):
completions = []
if current_param == 'nqn':
for nqn in self.parent.cfnode.subsystems:
completions.append(nqn)
if len(completions) == 1:
return [completions[0] + ' ']
else:
return completions
class UIPortSubsystemNode(UINode):
def __init__(self, parent, nqn):
UINode.__init__(self, nqn, parent)
class UIReferralsNode(UINode):
def __init__(self, parent):
UINode.__init__(self, 'referrals', parent)
def refresh(self):
self._children = set([])
for r in self.parent.cfnode.referrals:
UIReferralNode(self, r)
def ui_command_create(self, name):
'''
Creates a new referral.
SEE ALSO
========
B{delete}
'''
r = nvme.Referral(self.parent.cfnode, name, mode='create')
UIReferralNode(self, r)
def ui_command_delete(self, name):
'''
Deletes the referral with the specified I{name}.
SEE ALSO
========
B{create}
'''
r = nvme.Referral(self.parent.cfnode, name, mode='lookup')
r.delete()
self.refresh()
class UIReferralNode(UINode):
ui_desc_addr = {
'adrfam': ('string', 'Address Family (e.g. ipv4 or fc)'),
'treq': ('string', 'Transport Security Requirements'),
'traddr': ('string', 'Transport Address (e.g. IP Address or FC wwnn:wwpn)'),
'trsvcid': ('string', 'Transport Service ID (e.g. IP Port)'),
'trtype': ('string', 'Transport Type (e.g. rdma or loop or fc)'),
'portid': ('number', 'Port identifier'),
}
def __init__(self, parent, cfnode):
UINode.__init__(self, cfnode.name, parent, cfnode)
def status(self):
if self.cfnode.get_enable():
return "enabled"
return "disabled"
def ui_command_enable(self):
'''
Enables the current Referral.
SEE ALSO
========
B{disable}
'''
if self.cfnode.get_enable():
self.shell.log.info("The Referral is already enabled.")
else:
try:
self.cfnode.set_enable(1)
self.shell.log.info("The Referral has been enabled.")
except Exception as e:
raise configshell.ExecutionError(
"The Referral could not be enabled.")
def ui_command_disable(self):
'''
Disables the current Referral.
SEE ALSO
========
B{enable}
'''
if not self.cfnode.get_enable():
self.shell.log.info("The Referral is already disabled.")
else:
try:
self.cfnode.set_enable(0)
self.shell.log.info("The Referral has been disabled.")
except Exception as e:
raise configshell.ExecutionError(
"The Referral could not be disabled.")
class UIHostsNode(UINode):
def __init__(self, parent):
UINode.__init__(self, 'hosts', parent)
def refresh(self):
self._children = set([])
for host in self.parent.cfnode.hosts:
UIHostNode(self, host)
def ui_command_create(self, nqn):
'''
Creates a new NVMe host.
SEE ALSO
========
B{delete}
'''
host = nvme.Host(nqn, mode='create')
UIHostNode(self, host)
def ui_command_delete(self, nqn):
'''
Recursively deletes the NVMe Host with the specified I{nqn}, and all
objects hanging under it.
SEE ALSO
========
B{create}
'''
host = nvme.Host(nqn, mode='lookup')
host.delete()
self.refresh()
class UIHostNode(UINode):
def __init__(self, parent, cfnode):
UINode.__init__(self, cfnode.nqn, parent, cfnode)
def usage():
print("syntax: %s save [file_to_save_to]" % sys.argv[0])
print(" %s restore [file_to_restore_from]" % sys.argv[0])
print(" %s clear" % sys.argv[0])
sys.exit(-1)
def save(to_file):
nvme.Root().save_to_file(to_file)
def restore(from_file):
try:
errors = nvme.Root().restore_from_file(from_file)
except IOError:
# Not an error if the restore file is not present
print("No saved config file at %s, ok, exiting" % from_file)
sys.exit(0)
for error in errors:
print(error)
def clear(unused):
nvme.Root().clear_existing()
funcs = dict(save=save, restore=restore, clear=clear)
def main():
if os.geteuid() != 0:
print("%s: must run as root." % sys.argv[0], file=sys.stderr)
sys.exit(-1)
if len(sys.argv) > 3:
usage()
if len(sys.argv) == 2 or len(sys.argv) == 3:
if sys.argv[1] == "--help":
usage()
if sys.argv[1] not in funcs.keys():
usage()
if len(sys.argv) == 3:
savefile = sys.argv[2]
else:
savefile = None
funcs[sys.argv[1]](savefile)
return
try:
shell = configshell.shell.ConfigShell('~/.nvmetcli')
UIRootNode(shell)
except Exception as msg:
shell.log.error(str(msg))
return
while not shell._exit:
try:
shell.run_interactive()
except Exception as msg:
shell.log.error(str(msg))
if __name__ == "__main__":
main()