targetcli 3.0.0.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
targetcli/ui_target.py ADDED
@@ -0,0 +1,1450 @@
1
+ '''
2
+ Implements the targetcli target related UI.
3
+
4
+ This file is part of targetcli.
5
+ Copyright (c) 2011-2013 by Datera, Inc
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License"); you may
8
+ not use this file except in compliance with the License. You may obtain
9
+ a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16
+ License for the specific language governing permissions and limitations
17
+ under the License.
18
+ '''
19
+ from pathlib import Path
20
+
21
+ try:
22
+ import ethtool
23
+ except ImportError:
24
+ ethtool = None
25
+ import stat
26
+
27
+ from configshell_fb import ExecutionError
28
+ from rtslib_fb import (
29
+ LUN,
30
+ TPG,
31
+ MappedLUN,
32
+ NetworkPortal,
33
+ NodeACL,
34
+ RTSLibBrokenLink,
35
+ RTSLibError,
36
+ StorageObjectFactory,
37
+ Target,
38
+ )
39
+
40
+ from .ui_backstore import complete_path
41
+ from .ui_node import UINode, UIRTSLibNode
42
+
43
+ auth_params = ('userid', 'password', 'mutual_userid', 'mutual_password')
44
+ int_params = ('enable',)
45
+ discovery_params = auth_params + int_params
46
+
47
+ class UIFabricModule(UIRTSLibNode):
48
+ '''
49
+ A fabric module UI.
50
+ '''
51
+ def __init__(self, fabric_module, parent):
52
+ super().__init__(fabric_module.name,
53
+ fabric_module, parent,
54
+ late_params=True)
55
+ self.refresh()
56
+ if self.rtsnode.has_feature('discovery_auth'):
57
+ for param in discovery_params:
58
+ if param in int_params:
59
+ self.define_config_group_param('discovery_auth',
60
+ param, 'number')
61
+ else:
62
+ self.define_config_group_param('discovery_auth',
63
+ param, 'string')
64
+ self.refresh()
65
+
66
+ # Support late params
67
+ #
68
+ # By default the base class will call list_parameters and list_attributes
69
+ # in init. This stops us from being able to lazy-load fabric modules.
70
+ # We declare we support "late_params" to stop this, and then
71
+ # this code overrides the base class methods that involve enumerating
72
+ # this stuff, so we don't need to call list_parameters/attrs (which
73
+ # would cause the module to load) until the ui is actually asking for
74
+ # them from us.
75
+ # Currently fabricmodules don't have these anyways, this is all a CYA thing.
76
+ def list_config_groups(self):
77
+ groups = super().list_config_groups()
78
+ if len(self.rtsnode.list_parameters()):
79
+ groups.append('parameter')
80
+ if len(self.rtsnode.list_attributes()):
81
+ groups.append('attribute')
82
+ return groups
83
+
84
+ # Support late params (see above)
85
+ def list_group_params(self, group, writable=None):
86
+ if group not in {"parameter", "attribute"}:
87
+ return super().list_group_params(group,
88
+ writable)
89
+
90
+ params_func = getattr(self.rtsnode, f"list_{group}s")
91
+ params = params_func()
92
+ params_ro = params_func(writable=False)
93
+
94
+ ret_list = []
95
+ for param in params:
96
+ p_writable = param not in params_ro
97
+ if writable is not None and p_writable != writable:
98
+ continue
99
+ ret_list.append(param)
100
+
101
+ ret_list.sort()
102
+ return ret_list
103
+
104
+ # Support late params (see above)
105
+ def get_group_param(self, group, param):
106
+ if group not in {"parameter", "attribute"}:
107
+ return super().get_group_param(group, param)
108
+
109
+ if param not in self.list_group_params(group):
110
+ raise ValueError(f"Not such parameter {param} in configuration group {group}")
111
+
112
+ description = f"The {param} {group}."
113
+ writable = param in self.list_group_params(group, writable=True)
114
+
115
+ return {'name': param, 'group': group, 'type': "string",
116
+ 'description': description, 'writable': writable}
117
+
118
+ def ui_getgroup_discovery_auth(self, auth_attr):
119
+ '''
120
+ This is the backend method for getting discovery_auth attributes.
121
+ @param auth_attr: The auth attribute to get the value of.
122
+ @type auth_attr: str
123
+ @return: The auth attribute's value
124
+ @rtype: str
125
+ '''
126
+ if auth_attr == 'enable':
127
+ return self.rtsnode.discovery_enable_auth
128
+ return getattr(self.rtsnode, "discovery_" + auth_attr)
129
+
130
+ def ui_setgroup_discovery_auth(self, auth_attr, value):
131
+ '''
132
+ This is the backend method for setting discovery auth attributes.
133
+ @param auth_attr: The auth attribute to set the value of.
134
+ @type auth_attr: str
135
+ @param value: The auth's value
136
+ @type value: str
137
+ '''
138
+ self.assert_root()
139
+
140
+ if value is None:
141
+ value = ''
142
+
143
+ if auth_attr == 'enable':
144
+ self.rtsnode.discovery_enable_auth = value
145
+ else:
146
+ setattr(self.rtsnode, "discovery_" + auth_attr, value)
147
+
148
+ def refresh(self):
149
+ self._children = set()
150
+ for target in self.rtsnode.targets:
151
+ self.shell.log.debug(f"Found target {target.wwn} under fabric module {target.fabric_module}.")
152
+ if target.has_feature('tpgts'):
153
+ UIMultiTPGTarget(target, self)
154
+ else:
155
+ UITarget(target, self)
156
+
157
+ def summary(self):
158
+ status = None
159
+ msg = []
160
+
161
+ fm = self.rtsnode
162
+ if fm.has_feature('discovery_auth') and fm.discovery_enable_auth:
163
+ status = bool(fm.discovery_password and fm.discovery_userid)
164
+
165
+ if fm.discovery_authenticate_target:
166
+ msg.append("mutual disc auth")
167
+ else:
168
+ msg.append("1-way disc auth")
169
+
170
+ msg.append(f"Targets: {len(self._children)}")
171
+
172
+ return (", ".join(msg), status)
173
+
174
+ def ui_command_create(self, wwn=None):
175
+ '''
176
+ Creates a new target. The "wwn" format depends on the transport(s)
177
+ supported by the fabric module. If "wwn" is omitted, then a
178
+ target will be created using either a randomly generated WWN of the
179
+ proper type, or the first unused WWN in the list of possible WWNs if
180
+ one is available. If WWNs are constrained to a list (i.e. for hardware
181
+ targets addresses) and all WWNs are in use, the target creation will
182
+ fail. Use the `info` command to get more information abour WWN type
183
+ and possible values.
184
+
185
+ SEE ALSO
186
+ ========
187
+ info
188
+ '''
189
+ self.assert_root()
190
+
191
+ target = Target(self.rtsnode, wwn, mode='create')
192
+ wwn = target.wwn
193
+ if self.rtsnode.wwns is not None and wwn not in self.rtsnode.wwns:
194
+ self.shell.log.warning("Hardware missing for this WWN")
195
+
196
+ if target.has_feature('tpgts'):
197
+ ui_target = UIMultiTPGTarget(target, self)
198
+ self.shell.log.info(f"Created target {wwn}.")
199
+ return ui_target.ui_command_create()
200
+
201
+ ui_target = UITarget(target, self)
202
+ self.shell.log.info(f"Created target {wwn}.")
203
+ return self.new_node(ui_target)
204
+
205
+ def ui_complete_create(self, parameters, text, current_param):
206
+ '''
207
+ Parameter auto-completion method for user command create.
208
+ @param parameters: Parameters on the command line.
209
+ @type parameters: dict
210
+ @param text: Current text of parameter being typed by the user.
211
+ @type text: str
212
+ @param current_param: Name of parameter to complete.
213
+ @type current_param: str
214
+ @return: Possible completions
215
+ @rtype: list of str
216
+ '''
217
+ if current_param == 'wwn' and self.rtsnode.wwns is not None:
218
+ existing_wwns = [child.wwn for child in self.rtsnode.targets]
219
+ completions = [wwn for wwn in self.rtsnode.wwns
220
+ if wwn.startswith(text)
221
+ if wwn not in existing_wwns]
222
+ else:
223
+ completions = []
224
+
225
+ if len(completions) == 1:
226
+ return [completions[0] + ' ']
227
+ return completions
228
+
229
+ def ui_command_delete(self, wwn):
230
+ '''
231
+ Recursively deletes the target with the specified wwn, and all
232
+ objects hanging under it.
233
+
234
+ SEE ALSO
235
+ ========
236
+ create
237
+ '''
238
+ self.assert_root()
239
+ target = Target(self.rtsnode, wwn, mode='lookup')
240
+ target.delete()
241
+ self.shell.log.info(f"Deleted Target {wwn}.")
242
+ self.refresh()
243
+
244
+ def ui_complete_delete(self, parameters, text, current_param):
245
+ '''
246
+ Parameter auto-completion method for user command delete.
247
+ @param parameters: Parameters on the command line.
248
+ @type parameters: dict
249
+ @param text: Current text of parameter being typed by the user.
250
+ @type text: str
251
+ @param current_param: Name of parameter to complete.
252
+ @type current_param: str
253
+ @return: Possible completions
254
+ @rtype: list of str
255
+ '''
256
+ if current_param == 'wwn':
257
+ wwns = [child.name for child in self.children]
258
+ completions = [wwn for wwn in wwns if wwn.startswith(text)]
259
+ else:
260
+ completions = []
261
+
262
+ if len(completions) == 1:
263
+ return [completions[0] + ' ']
264
+ return completions
265
+
266
+ def ui_command_info(self):
267
+ '''
268
+ Displays information about the fabric module, notably the supported
269
+ transports(s) and accepted wwn format(s), along with supported
270
+ features.
271
+ '''
272
+ fabric = self.rtsnode
273
+ self.shell.log.info(f"Fabric module name: {self.name}")
274
+ self.shell.log.info(f"ConfigFS path: {self.rtsnode.path}")
275
+ self.shell.log.info(f"Allowed WWN types: {', '.join(fabric.wwn_types)}")
276
+ if fabric.wwns is not None:
277
+ self.shell.log.info(f"Allowed WWNs list: {', '.join(fabric.wwns)}")
278
+ self.shell.log.info(f"Fabric module features: {', '.join(fabric.features)}")
279
+ self.shell.log.info(f"Corresponding kernel module: {fabric.kernel_module}")
280
+
281
+ def ui_command_version(self):
282
+ '''
283
+ Displays the target fabric module version.
284
+ '''
285
+ version = f"Target fabric module {self.rtsnode.name}: {self.rtsnode.version}"
286
+ self.shell.con.display(version.strip())
287
+
288
+
289
+ class UIMultiTPGTarget(UIRTSLibNode):
290
+ '''
291
+ A generic target UI that has multiple TPGs.
292
+ '''
293
+ def __init__(self, target, parent):
294
+ super().__init__(target.wwn, target, parent)
295
+ self.refresh()
296
+
297
+ def refresh(self):
298
+ self._children = set()
299
+ for tpg in self.rtsnode.tpgs:
300
+ UITPG(tpg, self)
301
+
302
+ def summary(self):
303
+ try:
304
+ self.rtsnode.fabric_module.to_normalized_wwn(self.rtsnode.wwn)
305
+ except:
306
+ return ("INVALID WWN", False)
307
+
308
+ return (f"TPGs: {len(self._children)}", None)
309
+
310
+ def ui_command_create(self, tag=None):
311
+ '''
312
+ Creates a new Target Portal Group within the target. The
313
+ tag must be a positive integer value, optionally prefaced
314
+ by 'tpg'. If omitted, the next available Target Portal Group
315
+ Tag (TPGT) will be used.
316
+
317
+ SEE ALSO
318
+ ========
319
+ delete
320
+ '''
321
+ self.assert_root()
322
+
323
+ if tag:
324
+ if tag.startswith("tpg"):
325
+ tag = tag.removeprefix("tpg")
326
+
327
+ try:
328
+ tag = int(tag)
329
+ except ValueError:
330
+ raise ExecutionError("Tag argument must be a number.")
331
+
332
+ tpg = TPG(self.rtsnode, tag, mode='create')
333
+ if self.shell.prefs['auto_enable_tpgt']:
334
+ tpg.enable = True
335
+
336
+ if tpg.has_feature("auth"):
337
+ tpg.set_attribute("authentication", 0)
338
+
339
+ self.shell.log.info(f"Created TPG {tpg.tag}.")
340
+
341
+ if tpg.has_feature("nps") and self.shell.prefs['auto_add_default_portal']:
342
+ try:
343
+ NetworkPortal(tpg, "0.0.0.0")
344
+ self.shell.log.info("Global pref auto_add_default_portal=true")
345
+ self.shell.log.info("Created default portal listening on all IPs"
346
+ " (0.0.0.0), port 3260.")
347
+ except RTSLibError:
348
+ self.shell.log.info("Default portal not created, TPGs within a target cannot share ip:port.")
349
+
350
+ ui_tpg = UITPG(tpg, self)
351
+ return self.new_node(ui_tpg)
352
+
353
+ def ui_command_delete(self, tag):
354
+ '''
355
+ Deletes the Target Portal Group with TPGT "tag" from the target. The
356
+ tag must be a positive integer matching an existing TPGT.
357
+
358
+ SEE ALSO
359
+ ========
360
+ create
361
+ '''
362
+ self.assert_root()
363
+ if tag.startswith("tpg"):
364
+ tag = tag.removeprefix("tpg")
365
+ try:
366
+ tag = int(tag)
367
+ except ValueError:
368
+ raise ExecutionError("Tag argument must be a number.")
369
+
370
+ tpg = TPG(self.rtsnode, tag, mode='lookup')
371
+ tpg.delete()
372
+ self.shell.log.info(f"Deleted TPGT {tag}.")
373
+ self.refresh()
374
+
375
+ def ui_complete_delete(self, parameters, text, current_param):
376
+ '''
377
+ Parameter auto-completion method for user command delete.
378
+ @param parameters: Parameters on the command line.
379
+ @type parameters: dict
380
+ @param text: Current text of parameter being typed by the user.
381
+ @type text: str
382
+ @param current_param: Name of parameter to complete.
383
+ @type current_param: str
384
+ @return: Possible completions
385
+ @rtype: list of str
386
+ '''
387
+ if current_param == 'tag':
388
+ tags = [child.name[3:] for child in self.children]
389
+ completions = [tag for tag in tags if tag.startswith(text)]
390
+ else:
391
+ completions = []
392
+
393
+ if len(completions) == 1:
394
+ return [completions[0] + ' ']
395
+ return completions
396
+
397
+
398
+ class UITPG(UIRTSLibNode):
399
+ ui_desc_attributes = {
400
+ 'authentication': ('number', 'If set to 1, enforce authentication for this TPG.'),
401
+ 'cache_dynamic_acls': ('number', 'If set to 1 in demo mode, cache dynamically generated ACLs.'),
402
+ 'default_cmdsn_depth': ('number', 'Default CmdSN (Command Sequence Number) depth.'),
403
+ 'default_erl': ('number', 'Default Error Recovery Level.'),
404
+ 'demo_mode_discovery': ('number', 'If set to 1 in demo mode, enable discovery.'),
405
+ 'demo_mode_write_protect': ('number', 'If set to 1 in demo mode, prevent writes to LUNs.'),
406
+ 'fabric_prot_type': ('number', 'Fabric DIF protection type.'),
407
+ 'generate_node_acls': ('number', 'If set to 1, allow all initiators to login (i.e. demo mode).'),
408
+ 'login_timeout': ('number', 'Login timeout value in seconds.'),
409
+ 'netif_timeout': ('number', 'NIC failure timeout in seconds.'),
410
+ 'prod_mode_write_protect': ('number', 'If set to 1, prevent writes to LUNs.'),
411
+ 't10_pi': ('number', 'If set to 1, enable T10 Protection Information.'),
412
+ 'tpg_enabled_sendtargets': ('number', 'If set to 1, the SendTargets discovery response advertises the TPG only if the TPG is enabled.'),
413
+ }
414
+
415
+ ui_desc_parameters = {
416
+ 'AuthMethod': ('string', 'Authentication method used by the TPG.'),
417
+ 'DataDigest': ('string', 'If set to CRC32C, the integrity of the PDU data part is verified.'),
418
+ 'DataPDUInOrder': ('yesno', 'If set to Yes, the data PDUs within sequences must be in order.'),
419
+ 'DataSequenceInOrder': ('yesno', 'If set to Yes, the data sequences must be in order.'),
420
+ 'DefaultTime2Retain': ('number', 'Maximum time, in seconds, after an initial wait, before which an active task reassignment is still possible after an unexpected connection termination or a connection reset.'),
421
+ 'DefaultTime2Wait': ('number', 'Minimum time, in seconds, to wait before attempting an explicit/implicit logout or an active task reassignment after an unexpected connection termination or a connection reset.'),
422
+ 'ErrorRecoveryLevel': ('number', 'Recovery levels represent a combination of recovery capabilities.'),
423
+ 'FirstBurstLength': ('number', 'Maximum amount in bytes of unsolicited data an initiator may send.'),
424
+ 'HeaderDigest': ('string', 'If set to CRC32C, the integrity of the PDU header part is verified.'),
425
+ 'IFMarker': ('yesno', 'Deprecated according to RFC 7143.'),
426
+ 'IFMarkInt': ('string', 'Deprecated according to RFC 7143.'),
427
+ 'ImmediateData': ('string', 'Immediate data support.'),
428
+ 'InitialR2T': ('yesno', 'If set to No, the default use of R2T (Ready To Transfer) is disabled.'),
429
+ 'MaxBurstLength': ('number', 'Maximum SCSI data payload in bytes in a Data-In or a solicited Data-Out iSCSI sequence.'),
430
+ 'MaxConnections': ('number', 'Maximum number of connections acceptable.'),
431
+ 'MaxOutstandingR2T': ('number', 'Maximum number of outstanding R2Ts per task.'),
432
+ 'MaxRecvDataSegmentLength': ('number', 'Maximum data segment length in bytes the target can receive in an iSCSI PDU.'),
433
+ 'MaxXmitDataSegmentLength': ('number', 'Outgoing MaxRecvDataSegmentLength sent over the wire during iSCSI login response.'),
434
+ 'OFMarker': ('yesno', 'Deprecated according to RFC 7143.'),
435
+ 'OFMarkInt': ('string', 'Deprecated according to RFC 7143.'),
436
+ 'TargetAlias': ('string', 'Human-readable target name or description.'),
437
+ }
438
+
439
+ '''
440
+ A generic TPG UI.
441
+ '''
442
+ def __init__(self, tpg, parent):
443
+ name = "tpg%d" % tpg.tag
444
+ super().__init__(name, tpg, parent)
445
+ self.refresh()
446
+
447
+ UILUNs(tpg, self)
448
+
449
+ if tpg.has_feature('acls'):
450
+ UINodeACLs(self.rtsnode, self)
451
+ if tpg.has_feature('nps'):
452
+ UIPortals(self.rtsnode, self)
453
+
454
+ if self.rtsnode.has_feature('auth') and Path(self.rtsnode.path + "/auth").exists:
455
+ for param in auth_params:
456
+ self.define_config_group_param('auth', param, 'string')
457
+
458
+ def summary(self):
459
+ tpg = self.rtsnode
460
+ status = None
461
+
462
+ msg = []
463
+ if tpg.has_feature('nexus'):
464
+ msg.append(str(self.rtsnode.nexus))
465
+
466
+ if not tpg.enable:
467
+ return ("disabled", False)
468
+
469
+ if tpg.has_feature("acls"):
470
+ if "generate_node_acls" in tpg.list_attributes() and \
471
+ int(tpg.get_attribute("generate_node_acls")):
472
+ msg.append("gen-acls")
473
+ else:
474
+ msg.append("no-gen-acls")
475
+
476
+ # 'auth' feature requires 'acls'
477
+ if tpg.has_feature("auth"):
478
+ if not int(tpg.get_attribute("authentication")):
479
+ msg.append("no-auth")
480
+ if int(tpg.get_attribute("generate_node_acls")):
481
+ # if auth=0, g_n_a=1 is recommended
482
+ status = True
483
+ elif not int(tpg.get_attribute("generate_node_acls")):
484
+ msg.append("auth per-acl")
485
+ else:
486
+ msg.append("tpg-auth")
487
+
488
+ status = True
489
+ if not (tpg.chap_password and tpg.chap_userid):
490
+ status = False
491
+
492
+ if tpg.authenticate_target:
493
+ msg.append("mutual auth")
494
+ else:
495
+ msg.append("1-way auth")
496
+
497
+ return (", ".join(msg), status)
498
+
499
+ def ui_getgroup_auth(self, auth_attr):
500
+ return getattr(self.rtsnode, "chap_" + auth_attr)
501
+
502
+ def ui_setgroup_auth(self, auth_attr, value):
503
+ self.assert_root()
504
+
505
+ if value is None:
506
+ value = ''
507
+
508
+ setattr(self.rtsnode, "chap_" + auth_attr, value)
509
+
510
+ def ui_command_enable(self):
511
+ '''
512
+ Enables the TPG.
513
+
514
+ SEE ALSO
515
+ ========
516
+ disable status
517
+ '''
518
+ self.assert_root()
519
+ if self.rtsnode.enable:
520
+ self.shell.log.info("The TPGT is already enabled.")
521
+ else:
522
+ try:
523
+ self.rtsnode.enable = True
524
+ self.shell.log.info("The TPGT has been enabled.")
525
+ except RTSLibError:
526
+ raise ExecutionError("The TPGT could not be enabled.")
527
+
528
+ def ui_command_disable(self):
529
+ '''
530
+ Disables the TPG.
531
+
532
+ SEE ALSO
533
+ ========
534
+ enable status
535
+ '''
536
+ self.assert_root()
537
+ if self.rtsnode.enable:
538
+ self.rtsnode.enable = False
539
+ self.shell.log.info("The TPGT has been disabled.")
540
+ else:
541
+ self.shell.log.info("The TPGT is already disabled.")
542
+
543
+
544
+ class UITarget(UITPG):
545
+ '''
546
+ A generic target UI merged with its only TPG.
547
+ '''
548
+ def __init__(self, target, parent):
549
+ super().__init__(TPG(target, 1), parent)
550
+ self._name = target.wwn
551
+ self.target = target
552
+ if self.parent.name != "sbp":
553
+ self.rtsnode.enable = True
554
+
555
+ def summary(self):
556
+ try:
557
+ self.target.fabric_module.to_normalized_wwn(self.target.wwn)
558
+ except:
559
+ return ("INVALID WWN", False)
560
+
561
+ return super().summary()
562
+
563
+
564
+ class UINodeACLs(UINode):
565
+ '''
566
+ A generic UI for node ACLs.
567
+ '''
568
+ def __init__(self, tpg, parent):
569
+ super().__init__("acls", parent)
570
+ self.tpg = tpg
571
+ self.refresh()
572
+
573
+ def refresh(self):
574
+ self._children = set()
575
+ for name in self.all_names():
576
+ UINodeACL(name, self)
577
+
578
+ def summary(self):
579
+ return (f"ACLs: {len(self._children)}", None)
580
+
581
+ def ui_command_create(self, wwn, add_mapped_luns=None):
582
+ '''
583
+ Creates a Node ACL for the initiator node with the specified wwn.
584
+ The node's wwn must match the expected WWN Type of the target's
585
+ fabric module.
586
+
587
+ "add_mapped_luns" can be "true" of "false". If true, then
588
+ after creating the ACL, mapped LUNs will be automatically
589
+ created for all existing LUNs. If the parameter is omitted,
590
+ the global parameter "auto_add_mapped_luns" is used.
591
+
592
+ SEE ALSO
593
+ ========
594
+ delete
595
+
596
+ '''
597
+ self.assert_root()
598
+
599
+ add_mapped_luns = self.ui_eval_param(add_mapped_luns, 'bool',
600
+ self.shell.prefs['auto_add_mapped_luns'])
601
+
602
+ node_acl = NodeACL(self.tpg, wwn, mode="create")
603
+ ui_node_acl = UINodeACL(node_acl.node_wwn, self)
604
+ self.shell.log.info(f"Created Node ACL for {node_acl.node_wwn}")
605
+
606
+ if add_mapped_luns:
607
+ for lun in self.tpg.luns:
608
+ MappedLUN(node_acl, lun.lun, lun.lun, write_protect=False)
609
+ self.shell.log.info("Created mapped LUN %d." % lun.lun)
610
+ self.refresh()
611
+
612
+ return self.new_node(ui_node_acl)
613
+
614
+ def ui_command_delete(self, wwn):
615
+ '''
616
+ Deletes the Node ACL with the specified wwn.
617
+
618
+ SEE ALSO
619
+ ========
620
+ create
621
+ '''
622
+ self.assert_root()
623
+ node_acl = NodeACL(self.tpg, wwn, mode='lookup')
624
+ node_acl.delete()
625
+ self.shell.log.info(f"Deleted Node ACL {wwn}.")
626
+ self.refresh()
627
+
628
+ def ui_complete_delete(self, parameters, text, current_param):
629
+ '''
630
+ Parameter auto-completion method for user command delete.
631
+ @param parameters: Parameters on the command line.
632
+ @type parameters: dict
633
+ @param text: Current text of parameter being typed by the user.
634
+ @type text: str
635
+ @param current_param: Name of parameter to complete.
636
+ @type current_param: str
637
+ @return: Possible completions
638
+ @rtype: list of str
639
+ '''
640
+ if current_param == 'wwn':
641
+ wwns = [acl.node_wwn for acl in self.tpg.node_acls]
642
+ completions = [wwn for wwn in wwns if wwn.startswith(text)]
643
+ else:
644
+ completions = []
645
+
646
+ if len(completions) == 1:
647
+ return [completions[0] + ' ']
648
+ return completions
649
+
650
+ def find_tagged(self, name):
651
+ for na in self.tpg.node_acls:
652
+ if name in {na.node_wwn, na.tag}:
653
+ yield na
654
+
655
+ def all_names(self):
656
+ names = set()
657
+
658
+ for na in self.tpg.node_acls:
659
+ if na.tag:
660
+ names.add(na.tag)
661
+ else:
662
+ names.add(na.node_wwn)
663
+
664
+ return names
665
+
666
+ def ui_command_tag(self, wwn_or_tag, new_tag):
667
+ '''
668
+ Tag a NodeACL.
669
+
670
+ Usage: tag <wwn_or_tag> <new_tag>
671
+
672
+ Tags help manage initiator WWNs. A tag can apply to one or
673
+ more WWNs. This can give a more meaningful name to a single
674
+ initiator's configuration, or allow multiple initiators with
675
+ identical settings to be configured en masse.
676
+
677
+ The WWNs described by <wwn_or_tag> will be given the new
678
+ tag. If new_tag already exists, its new members will adopt the
679
+ current tag's configuration.
680
+
681
+ Within a tag, the 'info' command shows the WWNs the tag applies to.
682
+
683
+ Use 'untag' to remove tags.
684
+
685
+ NOTE: tags are only supported in kernel 3.8 and above.
686
+ '''
687
+ if wwn_or_tag == new_tag:
688
+ return
689
+
690
+ # Since all WWNs have a '.' in them, let's avoid confusion.
691
+ if '.' in new_tag:
692
+ raise ExecutionError("'.' not permitted in tag names.")
693
+
694
+ src = list(self.find_tagged(wwn_or_tag))
695
+ if not src:
696
+ raise ExecutionError(f"wwn_or_tag {wwn_or_tag} not found.")
697
+
698
+ old_tag_members = list(self.find_tagged(new_tag))
699
+
700
+ # handle overlap
701
+ src_wwns = [na.node_wwn for na in src]
702
+ old_tag_members = [old for old in old_tag_members if old.node_wwn not in src_wwns]
703
+
704
+ for na in src:
705
+ na.tag = new_tag
706
+
707
+ # if joining a tag, take its config
708
+ if old_tag_members:
709
+ model = old_tag_members[0]
710
+
711
+ for mlun in na.mapped_luns:
712
+ mlun.delete()
713
+
714
+ for mlun in model.mapped_luns:
715
+ MappedLUN(na, mlun.mapped_lun, mlun.tpg_lun, mlun.write_protect)
716
+
717
+ if self.parent.rtsnode.has_feature("auth"):
718
+ for param in auth_params:
719
+ setattr(na, "chap_" + param, getattr(model, "chap_" + param))
720
+
721
+ for item in model.list_attributes(writable=True):
722
+ na.set_attribute(item, model.get_attribute(item))
723
+ for item in model.list_parameters(writable=True):
724
+ na.set_parameter(item, model.get_parameter(item))
725
+
726
+ self.refresh()
727
+
728
+ def ui_command_untag(self, wwn_or_tag):
729
+ '''
730
+ Untag a NodeACL.
731
+
732
+ Usage: untag <tag>
733
+
734
+ Remove the tag given to one or more initiator WWNs. They will
735
+ return to being displayed by WWN in the configuration tree, and
736
+ will maintain settings from when they were tagged.
737
+ '''
738
+ for na in list(self.find_tagged(wwn_or_tag)):
739
+ na.tag = None
740
+
741
+ self.refresh()
742
+
743
+ def ui_complete_tag(self, parameters, text, current_param):
744
+ '''
745
+ Parameter auto-completion method for user command tag
746
+ @param parameters: Parameters on the command line.
747
+ @type parameters: dict
748
+ @param text: Current text of parameter being typed by the user.
749
+ @type text: str
750
+ @param current_param: Name of parameter to complete.
751
+ @type current_param: str
752
+ @return: Possible completions
753
+ @rtype: list of str
754
+ '''
755
+ completions = [n for n in self.all_names() if n.startswith(text)] if current_param == 'wwn_or_tag' else []
756
+
757
+ if len(completions) == 1:
758
+ return [completions[0] + ' ']
759
+ return completions
760
+
761
+ ui_complete_untag = ui_complete_tag
762
+
763
+
764
+ class UINodeACL(UIRTSLibNode):
765
+ '''
766
+ A generic UI for a node ACL.
767
+
768
+ Handles grouping multiple NodeACLs in UI via tags.
769
+ All gets are performed against first NodeACL.
770
+ All sets are performed on all NodeACLs.
771
+ This is to make management of multiple ACLs easier.
772
+ '''
773
+ ui_desc_attributes = {
774
+ 'dataout_timeout': ('number', 'Data-Out timeout in seconds before invoking recovery.'),
775
+ 'dataout_timeout_retries': ('number', 'Number of Data-Out timeout recovery attempts before failing a path.'),
776
+ 'default_erl': ('number', 'Default Error Recovery Level.'),
777
+ 'nopin_response_timeout': ('number', 'Nop-In response timeout in seconds.'),
778
+ 'nopin_timeout': ('number', 'Nop-In timeout in seconds.'),
779
+ 'random_datain_pdu_offsets': ('number', 'If set to 1, request random Data-In PDU offsets.'),
780
+ 'random_datain_seq_offsets': ('number', 'If set to 1, request random Data-In sequence offsets.'),
781
+ 'random_r2t_offsets': ('number', 'If set to 1, request random R2T (Ready To Transfer) offsets.'),
782
+ }
783
+
784
+ ui_desc_parameters = UITPG.ui_desc_parameters
785
+
786
+ def __init__(self, name, parent):
787
+
788
+ # Don't want to duplicate work in UIRTSLibNode, so call it but
789
+ # del self.rtsnode to make sure we always use self.rtsnodes.
790
+ self.rtsnodes = list(parent.find_tagged(name))
791
+ super().__init__(name, self.rtsnodes[0], parent)
792
+ del self.rtsnode
793
+
794
+ if self.parent.parent.rtsnode.has_feature('auth'):
795
+ for parameter in auth_params:
796
+ self.define_config_group_param('auth', parameter, 'string')
797
+
798
+ self.refresh()
799
+
800
+ def ui_getgroup_auth(self, auth_attr):
801
+ '''
802
+ This is the backend method for getting auths attributes.
803
+ @param auth_attr: The auth attribute to get the value of.
804
+ @type auth_attr: str
805
+ @return: The auth attribute's value
806
+ @rtype: str
807
+ '''
808
+ # All should return same, so just return from the first one
809
+ return getattr(self.rtsnodes[0], "chap_" + auth_attr)
810
+
811
+ def ui_setgroup_auth(self, auth_attr, value):
812
+ '''
813
+ This is the backend method for setting auths attributes.
814
+ @param auth_attr: The auth attribute to set the value of.
815
+ @type auth_attr: str
816
+ @param value: The auth's value
817
+ @type value: str
818
+ '''
819
+ self.assert_root()
820
+
821
+ if value is None:
822
+ value = ''
823
+
824
+ for na in self.rtsnodes:
825
+ setattr(na, "chap_" + auth_attr, value)
826
+
827
+ def refresh(self):
828
+ self._children = set()
829
+ for mlun in self.rtsnodes[0].mapped_luns:
830
+ UIMappedLUN(mlun, self)
831
+
832
+ def summary(self):
833
+ msg = []
834
+
835
+ if self.name != self.rtsnodes[0].node_wwn:
836
+ if len(self.rtsnodes) > 1:
837
+ msg.append(f"(group of {len(self.rtsnodes)})")
838
+ else:
839
+ msg.append(f"({self.rtsnodes[0].node_wwn})")
840
+
841
+ status = None
842
+ na = self.rtsnodes[0]
843
+ tpg = self.parent.parent.rtsnode
844
+ if tpg.has_feature("auth") and \
845
+ int(tpg.get_attribute("authentication")):
846
+ if int(tpg.get_attribute("generate_node_acls")):
847
+ msg.append("auth via tpg")
848
+ else:
849
+ status = True
850
+ if not (na.chap_password and na.chap_userid):
851
+ status = False
852
+
853
+ if na.authenticate_target:
854
+ msg.append("mutual auth")
855
+ else:
856
+ msg.append("1-way auth")
857
+
858
+ msg.append(f"Mapped LUNs: {len(self._children)}")
859
+
860
+ return (", ".join(msg), status)
861
+
862
+ def ui_command_create(self, mapped_lun, tpg_lun_or_backstore, write_protect=None):
863
+ '''
864
+ Creates a mapping to one of the TPG LUNs for the initiator referenced
865
+ by the ACL. The provided "tpg_lun_or_backstore" will appear to that
866
+ initiator as LUN "mapped_lun". If the "write_protect" flag is set to
867
+ 1, the initiator will not have write access to the mapped LUN.
868
+
869
+ A storage object may also be given for the "tpg_lun_or_backstore" parameter,
870
+ in which case the TPG LUN will be created for that backstore before
871
+ mapping the LUN to the initiator. If a TPG LUN for the backstore already
872
+ exists, the mapped LUN will map to that TPG LUN.
873
+
874
+ Finally, a path to an existing block device or file can be given. If so,
875
+ a storage object of the appropriate type is created with default parameters,
876
+ followed by the TPG LUN and the Mapped LUN.
877
+
878
+ SEE ALSO
879
+ ========
880
+ delete
881
+ '''
882
+ self.assert_root()
883
+ try:
884
+ mapped_lun = int(mapped_lun)
885
+ except ValueError:
886
+ raise ExecutionError("mapped_lun must be an integer")
887
+
888
+ try:
889
+ if tpg_lun_or_backstore.startswith("lun"):
890
+ tpg_lun_or_backstore = tpg_lun_or_backstore.removeprefix("lun")
891
+ tpg_lun = int(tpg_lun_or_backstore)
892
+ except ValueError:
893
+ try:
894
+ so = self.get_node(tpg_lun_or_backstore).rtsnode
895
+ except ValueError:
896
+ try:
897
+ so = StorageObjectFactory(tpg_lun_or_backstore)
898
+ self.shell.log.info(f"Created storage object {so.name}.")
899
+ except RTSLibError:
900
+ raise ExecutionError("LUN, storage object, or path not valid")
901
+ self.get_node("/backstores").refresh()
902
+
903
+ ui_tpg = self.parent.parent
904
+
905
+ for lun in ui_tpg.rtsnode.luns:
906
+ if so == lun.storage_object:
907
+ tpg_lun = lun.lun
908
+ break
909
+ else:
910
+ lun_object = LUN(ui_tpg.rtsnode, storage_object=so)
911
+ self.shell.log.info(f"Created LUN {lun_object.lun}.")
912
+ ui_lun = UILUN(lun_object, ui_tpg.get_node("luns"))
913
+ tpg_lun = ui_lun.rtsnode.lun
914
+
915
+ if tpg_lun in (ml.tpg_lun.lun for ml in self.rtsnodes[0].mapped_luns):
916
+ self.shell.log.warning(
917
+ "Warning: TPG LUN %d already mapped to this NodeACL" % tpg_lun)
918
+
919
+ for na in self.rtsnodes:
920
+ mlun = MappedLUN(na, mapped_lun, tpg_lun, write_protect)
921
+
922
+ ui_mlun = UIMappedLUN(mlun, self)
923
+ self.shell.log.info(f"Created Mapped LUN {mlun.mapped_lun}.")
924
+ return self.new_node(ui_mlun)
925
+
926
+ def ui_complete_create(self, parameters, text, current_param):
927
+ '''
928
+ Parameter auto-completion method for user command create.
929
+ @param parameters: Parameters on the command line.
930
+ @type parameters: dict
931
+ @param text: Current text of parameter being typed by the user.
932
+ @type text: str
933
+ @param current_param: Name of parameter to complete.
934
+ @type current_param: str
935
+ @return: Possible completions
936
+ @rtype: list of str
937
+ '''
938
+ if current_param == 'tpg_lun_or_backstore':
939
+ completions = []
940
+ for backstore in self.get_node('/backstores').children:
941
+ completions = [storage_object.path for storage_object in backstore.children]
942
+
943
+ completions.extend(lun.name for lun in self.parent.parent.get_node("luns").children)
944
+
945
+ completions.extend(complete_path(text, lambda x: stat.S_ISREG(x) or stat.S_ISBLK(x)))
946
+
947
+ completions = [c for c in completions if c.startswith(text)]
948
+ else:
949
+ completions = []
950
+
951
+ if len(completions) == 1:
952
+ return [completions[0] + ' ']
953
+ return completions
954
+
955
+ def ui_command_delete(self, mapped_lun):
956
+ '''
957
+ Deletes the specified mapped LUN.
958
+
959
+ SEE ALSO
960
+ ========
961
+ create
962
+ '''
963
+ self.assert_root()
964
+ for na in self.rtsnodes:
965
+ mlun = MappedLUN(na, mapped_lun)
966
+ mlun.delete()
967
+ self.shell.log.info(f"Deleted Mapped LUN {mapped_lun}.")
968
+ self.refresh()
969
+
970
+ def ui_complete_delete(self, parameters, text, current_param):
971
+ '''
972
+ Parameter auto-completion method for user command delete.
973
+ @param parameters: Parameters on the command line.
974
+ @type parameters: dict
975
+ @param text: Current text of parameter being typed by the user.
976
+ @type text: str
977
+ @param current_param: Name of parameter to complete.
978
+ @type current_param: str
979
+ @return: Possible completions
980
+ @rtype: list of str
981
+ '''
982
+ if current_param == 'mapped_lun':
983
+ mluns = [str(mlun.mapped_lun) for mlun in self.rtsnodes[0].mapped_luns]
984
+ completions = [mlun for mlun in mluns if mlun.startswith(text)]
985
+ else:
986
+ completions = []
987
+
988
+ if len(completions) == 1:
989
+ return [completions[0] + ' ']
990
+ return completions
991
+
992
+ # Override these four methods to handle multiple NodeACLs
993
+ def ui_getgroup_attribute(self, attribute):
994
+ return self.rtsnodes[0].get_attribute(attribute)
995
+
996
+ def ui_setgroup_attribute(self, attribute, value):
997
+ self.assert_root()
998
+
999
+ for na in self.rtsnodes:
1000
+ na.set_attribute(attribute, value)
1001
+
1002
+ def ui_getgroup_parameter(self, parameter):
1003
+ return self.rtsnodes[0].get_parameter(parameter)
1004
+
1005
+ def ui_setgroup_parameter(self, parameter, value):
1006
+ self.assert_root()
1007
+
1008
+ for na in self.rtsnodes:
1009
+ na.set_parameter(parameter, value)
1010
+
1011
+ def ui_command_info(self):
1012
+ '''
1013
+ Since we don't have a self.rtsnode we can't use the base implementation
1014
+ of this method. We also want to not print node_wwn, but list *all*
1015
+ wwns for this entry.
1016
+ '''
1017
+ info = self.rtsnodes[0].dump()
1018
+ for item in ('attributes', 'parameters', "node_wwn"):
1019
+ if item in info:
1020
+ del info[item]
1021
+ for name, value in sorted(info.items()):
1022
+ if not isinstance(value, (dict, list)):
1023
+ self.shell.log.info(f"{name}: {value}")
1024
+ self.shell.log.info("wwns:")
1025
+ for na in self.parent.find_tagged(self.name):
1026
+ self.shell.log.info(na.node_wwn)
1027
+
1028
+
1029
+ class UIMappedLUN(UIRTSLibNode):
1030
+ '''
1031
+ A generic UI for MappedLUN objects.
1032
+ '''
1033
+ def __init__(self, mapped_lun, parent):
1034
+ name = "mapped_lun%d" % mapped_lun.mapped_lun
1035
+ super().__init__(name, mapped_lun, parent)
1036
+ self.refresh()
1037
+
1038
+ def summary(self):
1039
+ mapped_lun = self.rtsnode
1040
+ is_healthy = True
1041
+ try:
1042
+ tpg_lun = mapped_lun.tpg_lun
1043
+ except RTSLibBrokenLink:
1044
+ description = "BROKEN LUN LINK"
1045
+ is_healthy = False
1046
+ else:
1047
+ access_mode = 'ro' if mapped_lun.write_protect else 'rw'
1048
+ description = "lun%d %s/%s (%s)" \
1049
+ % (tpg_lun.lun, tpg_lun.storage_object.plugin,
1050
+ tpg_lun.storage_object.name, access_mode)
1051
+
1052
+ return (description, is_healthy)
1053
+
1054
+
1055
+ class UILUNs(UINode):
1056
+ '''
1057
+ A generic UI for TPG LUNs.
1058
+ '''
1059
+ def __init__(self, tpg, parent):
1060
+ super().__init__("luns", parent)
1061
+ self.tpg = tpg
1062
+ self.refresh()
1063
+
1064
+ def refresh(self):
1065
+ self._children = set()
1066
+ for lun in self.tpg.luns:
1067
+ UILUN(lun, self)
1068
+
1069
+ def summary(self):
1070
+ return (f"LUNs: {len(self._children)}", None)
1071
+
1072
+ def ui_command_create(self, storage_object, lun=None,
1073
+ add_mapped_luns=None):
1074
+ '''
1075
+ Creates a new LUN in the Target Portal Group, attached to a storage
1076
+ object. If the "lun" parameter is omitted, the first available LUN in
1077
+ the TPG will be used. If present, it must be a number greater than 0.
1078
+ Alternatively, the syntax "lunX" where "X" is a positive number is
1079
+ also accepted.
1080
+
1081
+ The "storage_object" may be the path of an existing storage object,
1082
+ i.e. "/backstore/pscsi0/mydisk" to reference the "mydisk" storage
1083
+ object of the virtual HBA "pscsi0". It also may be the path to an
1084
+ existing block device or image file, in which case a storage object
1085
+ will be created for it first, with default parameters.
1086
+
1087
+ "add_mapped_luns" can be "true" of "false". If true, then
1088
+ after creating the ACL, mapped LUNs will be automatically
1089
+ created for all existing LUNs. If the parameter is omitted,
1090
+ the global parameter "auto_add_mapped_luns" is used.
1091
+
1092
+ SEE ALSO
1093
+ ========
1094
+ delete
1095
+ '''
1096
+ self.assert_root()
1097
+
1098
+ add_mapped_luns = \
1099
+ self.ui_eval_param(add_mapped_luns, 'bool',
1100
+ self.shell.prefs['auto_add_mapped_luns'])
1101
+
1102
+ try:
1103
+ so = self.get_node(storage_object).rtsnode
1104
+ except ValueError:
1105
+ try:
1106
+ so = StorageObjectFactory(storage_object)
1107
+ self.shell.log.info(f"Created storage object {so.name}.")
1108
+ except RTSLibError:
1109
+ raise ExecutionError("storage object or path not valid")
1110
+ self.get_node("/backstores").refresh()
1111
+
1112
+ if so in (lun.storage_object for lun in self.parent.rtsnode.luns):
1113
+ raise ExecutionError(f"lun for storage object {so.plugin}/{so.name} already exists")
1114
+
1115
+ if lun and lun.lower().startswith('lun'):
1116
+ lun = lun[3:]
1117
+ lun_object = LUN(self.tpg, lun, so)
1118
+ self.shell.log.info(f"Created LUN {lun_object.lun}.")
1119
+ ui_lun = UILUN(lun_object, self)
1120
+
1121
+ if add_mapped_luns:
1122
+ for acl in self.tpg.node_acls:
1123
+ mapped_lun = lun or 0
1124
+ existing_mluns = [mlun.mapped_lun for mlun in acl.mapped_luns]
1125
+ if mapped_lun in existing_mluns:
1126
+ possible_mlun = 0
1127
+ while possible_mlun in existing_mluns:
1128
+ possible_mlun += 1
1129
+ mapped_lun = possible_mlun
1130
+
1131
+ mlun = MappedLUN(acl, mapped_lun, lun_object, write_protect=False)
1132
+ self.shell.log.info("Created LUN %d->%d mapping in node ACL %s"
1133
+ % (mlun.tpg_lun.lun, mlun.mapped_lun, acl.node_wwn))
1134
+ self.parent.refresh()
1135
+
1136
+ return self.new_node(ui_lun)
1137
+
1138
+ def ui_complete_create(self, parameters, text, current_param):
1139
+ '''
1140
+ Parameter auto-completion method for user command create.
1141
+ @param parameters: Parameters on the command line.
1142
+ @type parameters: dict
1143
+ @param text: Current text of parameter being typed by the user.
1144
+ @type text: str
1145
+ @param current_param: Name of parameter to complete.
1146
+ @type current_param: str
1147
+ @return: Possible completions
1148
+ @rtype: list of str
1149
+ '''
1150
+ if current_param == 'storage_object':
1151
+ storage_objects = []
1152
+ for backstore in self.get_node('/backstores').children:
1153
+ storage_objects = [storage_object.path for storage_object in backstore.children]
1154
+ completions = [so for so in storage_objects if so.startswith(text)]
1155
+
1156
+ completions.extend(complete_path(text, lambda x: stat.S_ISREG(x) or stat.S_ISBLK(x)))
1157
+ else:
1158
+ completions = []
1159
+
1160
+ if len(completions) == 1:
1161
+ return [completions[0] + ' ']
1162
+ return completions
1163
+
1164
+ def ui_command_delete(self, lun):
1165
+ '''
1166
+ Deletes the supplied LUN from the Target Portal Group. "lun" must
1167
+ be a positive number matching an existing LUN.
1168
+
1169
+ Alternatively, the syntax "lunX" where "X" is a positive number is
1170
+ also accepted.
1171
+
1172
+ SEE ALSO
1173
+ ========
1174
+ create
1175
+ '''
1176
+ self.assert_root()
1177
+ if lun.lower().startswith("lun"):
1178
+ lun = lun[3:]
1179
+ try:
1180
+ lun_object = LUN(self.tpg, lun)
1181
+ except:
1182
+ raise RTSLibError("Invalid LUN")
1183
+ lun_object.delete()
1184
+ self.shell.log.info(f"Deleted LUN {lun}.")
1185
+ # Refresh the TPG as we need to also refresh acls MappedLUNs
1186
+ self.parent.refresh()
1187
+
1188
+ def ui_complete_delete(self, parameters, text, current_param):
1189
+ '''
1190
+ Parameter auto-completion method for user command delete.
1191
+ @param parameters: Parameters on the command line.
1192
+ @type parameters: dict
1193
+ @param text: Current text of parameter being typed by the user.
1194
+ @type text: str
1195
+ @param current_param: Name of parameter to complete.
1196
+ @type current_param: str
1197
+ @return: Possible completions
1198
+ @rtype: list of str
1199
+ '''
1200
+ if current_param == 'lun':
1201
+ luns = [str(lun.lun) for lun in self.tpg.luns]
1202
+ completions = [lun for lun in luns if lun.startswith(text)]
1203
+ else:
1204
+ completions = []
1205
+
1206
+ if len(completions) == 1:
1207
+ return [completions[0] + ' ']
1208
+ return completions
1209
+
1210
+
1211
+ class UILUN(UIRTSLibNode):
1212
+ '''
1213
+ A generic UI for LUN objects.
1214
+ '''
1215
+ def __init__(self, lun, parent):
1216
+ name = "lun%d" % lun.lun
1217
+ super().__init__(name, lun, parent)
1218
+ self.refresh()
1219
+
1220
+ self.define_config_group_param("alua", "alua_tg_pt_gp_name", 'string')
1221
+
1222
+ def summary(self):
1223
+ lun = self.rtsnode
1224
+ is_healthy = True
1225
+ try:
1226
+ storage_object = lun.storage_object
1227
+ except RTSLibBrokenLink:
1228
+ description = "BROKEN STORAGE LINK"
1229
+ is_healthy = False
1230
+ else:
1231
+ description = f"{storage_object.plugin}/{storage_object.name}"
1232
+ if storage_object.udev_path:
1233
+ description += f" ({storage_object.udev_path})"
1234
+
1235
+ description += f" ({lun.alua_tg_pt_gp_name})"
1236
+
1237
+ return (description, is_healthy)
1238
+
1239
+ def ui_getgroup_alua(self, alua_attr):
1240
+ return getattr(self.rtsnode, alua_attr)
1241
+
1242
+ def ui_setgroup_alua(self, alua_attr, value):
1243
+ self.assert_root()
1244
+
1245
+ if value is None:
1246
+ return
1247
+
1248
+ setattr(self.rtsnode, alua_attr, value)
1249
+
1250
+ class UIPortals(UINode):
1251
+ '''
1252
+ A generic UI for TPG network portals.
1253
+ '''
1254
+ def __init__(self, tpg, parent):
1255
+ super().__init__("portals", parent)
1256
+ self.tpg = tpg
1257
+ self.refresh()
1258
+
1259
+ def refresh(self):
1260
+ self._children = set()
1261
+ for portal in self.tpg.network_portals:
1262
+ UIPortal(portal, self)
1263
+
1264
+ def summary(self):
1265
+ return (f"Portals: {len(self._children)}", None)
1266
+
1267
+ def _canonicalize_ip(self, ip_address):
1268
+ """
1269
+ rtslib expects ipv4 addresses as a dotted-quad string, and IPv6
1270
+ addresses surrounded by brackets.
1271
+ """
1272
+
1273
+ # Contains a '.'? Must be ipv4, right?
1274
+ if "." in ip_address:
1275
+ return ip_address
1276
+ return "[" + ip_address + "]"
1277
+
1278
+ def ui_command_create(self, ip_address=None, ip_port=None):
1279
+ '''
1280
+ Creates a Network Portal with the specified IP address and
1281
+ port. If the port is omitted, the default port for
1282
+ the target fabric will be used. If the IP address is omitted,
1283
+ INADDR_ANY (0.0.0.0) will be used.
1284
+
1285
+ Choosing IN6ADDR_ANY (::0) will listen on all IPv6 interfaces
1286
+ as well as IPv4, assuming IPV6_V6ONLY sockopt has not been
1287
+ set.
1288
+
1289
+ Note: Portals on Link-local IPv6 addresses are currently not
1290
+ supported.
1291
+
1292
+ SEE ALSO
1293
+ ========
1294
+ delete
1295
+ '''
1296
+ self.assert_root()
1297
+
1298
+ # FIXME: Add a specfile parameter to determine default port
1299
+ default_port = 3260
1300
+ ip_port = self.ui_eval_param(ip_port, 'number', default_port)
1301
+ ip_address = self.ui_eval_param(ip_address, 'string', "0.0.0.0")
1302
+
1303
+ if ip_port == default_port:
1304
+ self.shell.log.info("Using default IP port %d" % ip_port)
1305
+ if ip_address == "0.0.0.0":
1306
+ self.shell.log.info("Binding to INADDR_ANY (0.0.0.0)")
1307
+
1308
+ portal = NetworkPortal(self.tpg, self._canonicalize_ip(ip_address),
1309
+ ip_port, mode='create')
1310
+ self.shell.log.info("Created network portal %s:%d."
1311
+ % (ip_address, ip_port))
1312
+ ui_portal = UIPortal(portal, self)
1313
+ return self.new_node(ui_portal)
1314
+
1315
+ def ui_complete_create(self, parameters, text, current_param):
1316
+ '''
1317
+ Parameter auto-completion method for user command create.
1318
+ @param parameters: Parameters on the command line.
1319
+ @type parameters: dict
1320
+ @param text: Current text of parameter being typed by the user.
1321
+ @type text: str
1322
+ @param current_param: Name of parameter to complete.
1323
+ @type current_param: str
1324
+ @return: Possible completions
1325
+ @rtype: list of str
1326
+ '''
1327
+
1328
+ def list_eth_ips():
1329
+ if not ethtool:
1330
+ return []
1331
+
1332
+ devcfgs = ethtool.get_interfaces_info(ethtool.get_devices())
1333
+ addrs = set()
1334
+ for d in devcfgs:
1335
+ if d.ipv4_address:
1336
+ addrs.add(d.ipv4_address)
1337
+ addrs.add("0.0.0.0")
1338
+ for ip6 in d.get_ipv6_addresses():
1339
+ addrs.add(ip6.address)
1340
+ addrs.add("::0") # only list ::0 if ipv6 present
1341
+
1342
+ return sorted(addrs)
1343
+
1344
+ if current_param == 'ip_address':
1345
+ completions = [addr for addr in list_eth_ips()
1346
+ if addr.startswith(text)]
1347
+ else:
1348
+ completions = []
1349
+
1350
+ if len(completions) == 1:
1351
+ return [completions[0] + ' ']
1352
+ return completions
1353
+
1354
+ def ui_command_delete(self, ip_address, ip_port):
1355
+ '''
1356
+ Deletes the Network Portal with the specified IP address and port.
1357
+
1358
+ SEE ALSO
1359
+ ========
1360
+ create
1361
+ '''
1362
+ self.assert_root()
1363
+ portal = NetworkPortal(self.tpg, self._canonicalize_ip(ip_address),
1364
+ ip_port, mode='lookup')
1365
+ portal.delete()
1366
+ self.shell.log.info(f"Deleted network portal {ip_address}:{ip_port}")
1367
+ self.refresh()
1368
+
1369
+ def ui_complete_delete(self, parameters, text, current_param):
1370
+ '''
1371
+ Parameter auto-completion method for user command delete.
1372
+ @param parameters: Parameters on the command line.
1373
+ @type parameters: dict
1374
+ @param text: Current text of parameter being typed by the user.
1375
+ @type text: str
1376
+ @param current_param: Name of parameter to complete.
1377
+ @type current_param: str
1378
+ @return: Possible completions
1379
+ @rtype: list of str
1380
+ '''
1381
+ completions = []
1382
+ # TODO: Check if a dict comprehension is acceptable here with supported
1383
+ # XXX: python versions.
1384
+ portals = {}
1385
+ all_ports = set()
1386
+ for portal in self.tpg.network_portals:
1387
+ all_ports.add(str(portal.port))
1388
+ portal_ip = portal.ip_address.strip('[]')
1389
+ if portal_ip not in portals:
1390
+ portals[portal_ip] = []
1391
+ portals[portal_ip].append(str(portal.port))
1392
+
1393
+ if current_param == 'ip_address':
1394
+ completions = [addr for addr in portals if addr.startswith(text)]
1395
+ if 'ip_port' in parameters:
1396
+ port = parameters['ip_port']
1397
+ completions = [addr for addr in completions
1398
+ if port in portals[addr]]
1399
+ elif current_param == 'ip_port':
1400
+ if 'ip_address' in parameters:
1401
+ addr = parameters['ip_address']
1402
+ if addr in portals:
1403
+ completions = [port for port in portals[addr]
1404
+ if port.startswith(text)]
1405
+ else:
1406
+ completions = [port for port in all_ports
1407
+ if port.startswith(text)]
1408
+
1409
+ if len(completions) == 1:
1410
+ return [completions[0] + ' ']
1411
+ return completions
1412
+
1413
+
1414
+ class UIPortal(UIRTSLibNode):
1415
+ '''
1416
+ A generic UI for a network portal.
1417
+ '''
1418
+ def __init__(self, portal, parent):
1419
+ name = f"{portal.ip_address}:{portal.port}"
1420
+ super().__init__(name, portal, parent)
1421
+ self.refresh()
1422
+
1423
+ def summary(self):
1424
+ if self.rtsnode.iser:
1425
+ return ('iser', True)
1426
+ if self.rtsnode.offload:
1427
+ return ('offload', True)
1428
+ return ('', True)
1429
+
1430
+ def ui_command_enable_iser(self, boolean):
1431
+ '''
1432
+ Enables or disables iSER for this NetworkPortal.
1433
+
1434
+ If iSER is not supported by the kernel, this command will do nothing.
1435
+ '''
1436
+
1437
+ boolean = self.ui_eval_param(boolean, 'bool', False)
1438
+ self.rtsnode.iser = boolean
1439
+ self.shell.log.info(f"iSER enable now: {self.rtsnode.iser}")
1440
+
1441
+ def ui_command_enable_offload(self, boolean):
1442
+ '''
1443
+ Enables or disables offload for this NetworkPortal.
1444
+
1445
+ If offload is not supported by the kernel, this command will do nothing.
1446
+ '''
1447
+
1448
+ boolean = self.ui_eval_param(boolean, 'bool', False)
1449
+ self.rtsnode.offload = boolean
1450
+ self.shell.log.info(f"offload enable now: {self.rtsnode.offload}")