targetcli 3.0.0__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_node.py ADDED
@@ -0,0 +1,212 @@
1
+ '''
2
+ Implements the targetcli base UI node.
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
+
20
+
21
+ from configshell_fb import ConfigNode, ExecutionError
22
+
23
+
24
+ class UINode(ConfigNode):
25
+ '''
26
+ Our targetcli basic UI node.
27
+ '''
28
+ def __init__(self, name, parent=None, shell=None):
29
+ ConfigNode.__init__(self, name, parent, shell)
30
+ self.define_config_group_param(
31
+ 'global', 'export_backstore_name_as_model', 'bool',
32
+ 'If true, the backstore name is used for the scsi inquiry model name.')
33
+ self.define_config_group_param(
34
+ 'global', 'auto_enable_tpgt', 'bool',
35
+ 'If true, automatically enables TPGTs upon creation.')
36
+ self.define_config_group_param(
37
+ 'global', 'auto_add_mapped_luns', 'bool',
38
+ 'If true, automatically create node ACLs mapped LUNs after creating a new target LUN or a new node ACL')
39
+ self.define_config_group_param(
40
+ 'global', 'auto_cd_after_create', 'bool',
41
+ 'If true, changes current path to newly created objects.')
42
+ self.define_config_group_param(
43
+ 'global', 'auto_save_on_exit', 'bool',
44
+ 'If true, saves configuration on exit.')
45
+ self.define_config_group_param(
46
+ 'global', 'auto_add_default_portal', 'bool',
47
+ 'If true, adds a portal listening on all IPs to new targets.')
48
+ self.define_config_group_param(
49
+ 'global', 'max_backup_files', 'string',
50
+ 'Max no. of configurations to be backed up in /etc/target/backup/ directory.')
51
+ self.define_config_group_param(
52
+ 'global', 'auto_use_daemon', 'bool',
53
+ 'If true, commands will be sent to targetclid.')
54
+ self.define_config_group_param(
55
+ 'global', 'daemon_use_batch_mode', 'bool',
56
+ 'If true, use batch mode for daemonized approach.')
57
+
58
+ def assert_root(self):
59
+ '''
60
+ For commands requiring root privileges, disable command if not the root
61
+ node's as_root attribute is False.
62
+ '''
63
+ root_node = self.get_root()
64
+ if hasattr(root_node, 'as_root') and not self.get_root().as_root:
65
+ raise ExecutionError("This privileged command is disabled: you are not root.")
66
+
67
+ def new_node(self, new_node):
68
+ '''
69
+ Used to honor global 'auto_cd_after_create'.
70
+ Either returns None if the global is False, or the new_node if the
71
+ global is True. In both cases, set the @last bookmark to last_node.
72
+ '''
73
+ self.shell.prefs['bookmarks']['last'] = new_node.path
74
+ self.shell.prefs.save()
75
+ if self.shell.prefs['auto_cd_after_create']:
76
+ self.shell.log.info(f"Entering new node {new_node.path}")
77
+ # Piggy backs on cd instead of just returning new_node,
78
+ # so we update navigation history.
79
+ return self.ui_command_cd(new_node.path)
80
+ return None
81
+
82
+ def refresh(self):
83
+ '''
84
+ Refreshes and updates the objects tree from the current path.
85
+ '''
86
+ for child in self.children:
87
+ child.refresh()
88
+
89
+ def ui_command_refresh(self):
90
+ '''
91
+ Refreshes and updates the objects tree from the current path.
92
+ '''
93
+ self.refresh()
94
+
95
+ def ui_command_status(self):
96
+ '''
97
+ Displays the current node's status summary.
98
+
99
+ SEE ALSO
100
+ ========
101
+ ls
102
+ '''
103
+ description, _is_healthy = self.summary()
104
+ self.shell.log.info(f"Status for {self.path}: {description}")
105
+
106
+ def ui_setgroup_global(self, parameter, value):
107
+ ConfigNode.ui_setgroup_global(self, parameter, value)
108
+ self.get_root().refresh()
109
+
110
+ def ui_type_yesno(self, value=None, enum=False, reverse=False):
111
+ '''
112
+ UI parameter type helper for "Yes" and "No" boolean values.
113
+ "Yes" and "No" are used for boolean iSCSI session parameters.
114
+ '''
115
+ if reverse:
116
+ if value is not None:
117
+ return value
118
+ return 'n/a'
119
+ type_enum = ('Yes', 'No')
120
+ syntax = '|'.join(type_enum)
121
+ if value is None:
122
+ if enum:
123
+ return type_enum
124
+ return syntax
125
+ if value in type_enum:
126
+ return value
127
+ raise ValueError(f"Syntax error, '{value}' is not {syntax}.")
128
+
129
+
130
+ class UIRTSLibNode(UINode):
131
+ '''
132
+ A subclass of UINode for nodes with an underlying RTSLib object.
133
+ '''
134
+ def __init__(self, name, rtslib_object, parent, late_params=False):
135
+ '''
136
+ Call from the class that inherits this, with the rtslib object that
137
+ should be checked upon.
138
+ '''
139
+ UINode.__init__(self, name, parent)
140
+ self.rtsnode = rtslib_object
141
+
142
+ if late_params:
143
+ return
144
+
145
+ # If the rtsnode has parameters, use them
146
+ parameters = self.rtsnode.list_parameters()
147
+ parameters_ro = self.rtsnode.list_parameters(writable=False)
148
+ for parameter in parameters:
149
+ writable = parameter not in parameters_ro
150
+ param_type, desc = getattr(self.__class__, 'ui_desc_parameters', {}).get(parameter, ('string', ''))
151
+ self.define_config_group_param(
152
+ 'parameter', parameter, param_type, desc, writable)
153
+
154
+ # If the rtsnode has attributes, enable them
155
+ attributes = self.rtsnode.list_attributes()
156
+ attributes_ro = self.rtsnode.list_attributes(writable=False)
157
+ for attribute in attributes:
158
+ writable = attribute not in attributes_ro
159
+ param_type, desc = getattr(self.__class__, 'ui_desc_attributes', {}).get(attribute, ('string', ''))
160
+ self.define_config_group_param(
161
+ 'attribute', attribute, param_type, desc, writable)
162
+
163
+ def ui_getgroup_attribute(self, attribute):
164
+ '''
165
+ This is the backend method for getting attributes.
166
+ @param attribute: The attribute to get the value of.
167
+ @type attribute: str
168
+ @return: The attribute's value
169
+ @rtype: arbitrary
170
+ '''
171
+ return self.rtsnode.get_attribute(attribute)
172
+
173
+ def ui_setgroup_attribute(self, attribute, value):
174
+ '''
175
+ This is the backend method for setting attributes.
176
+ @param attribute: The attribute to set the value of.
177
+ @type attribute: str
178
+ @param value: The attribute's value
179
+ @type value: arbitrary
180
+ '''
181
+ self.assert_root()
182
+ self.rtsnode.set_attribute(attribute, value)
183
+
184
+ def ui_getgroup_parameter(self, parameter):
185
+ '''
186
+ This is the backend method for getting parameters.
187
+ @param parameter: The parameter to get the value of.
188
+ @type parameter: str
189
+ @return: The parameter's value
190
+ @rtype: arbitrary
191
+ '''
192
+ return self.rtsnode.get_parameter(parameter)
193
+
194
+ def ui_setgroup_parameter(self, parameter, value):
195
+ '''
196
+ This is the backend method for setting parameters.
197
+ @param parameter: The parameter to set the value of.
198
+ @type parameter: str
199
+ @param value: The parameter's value
200
+ @type value: arbitrary
201
+ '''
202
+ self.assert_root()
203
+ self.rtsnode.set_parameter(parameter, value)
204
+
205
+ def ui_command_info(self):
206
+ info = self.rtsnode.dump()
207
+ for item in ('attributes', 'parameters'):
208
+ if item in info:
209
+ del info[item]
210
+ for name, value in sorted(info.items()):
211
+ if not isinstance(value, (dict, list)):
212
+ self.shell.log.info(f"{name}: {value}")
targetcli/ui_root.py ADDED
@@ -0,0 +1,329 @@
1
+ '''
2
+ Implements the targetcli root 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
+
20
+ import gzip
21
+ import os
22
+ import re
23
+ import shutil
24
+ import stat
25
+ from datetime import datetime
26
+ from glob import glob
27
+ from pathlib import Path, PurePosixPath
28
+
29
+ from configshell_fb import ExecutionError
30
+ from rtslib_fb import RTSRoot
31
+ from rtslib_fb.utils import ignored
32
+
33
+ from targetcli import __version__
34
+
35
+ from .ui_backstore import UIBackstores, complete_path
36
+ from .ui_node import UINode
37
+ from .ui_target import UIFabricModule
38
+
39
+ default_target_dir = "/etc/target"
40
+ default_save_file = os.path.join(default_target_dir, "saveconfig.json")
41
+ universal_prefs_file = os.path.join(default_target_dir, "targetcli.conf")
42
+
43
+ class UIRoot(UINode):
44
+ '''
45
+ The targetcli hierarchy root node.
46
+ '''
47
+ def __init__(self, shell, as_root=False):
48
+ UINode.__init__(self, '/', shell=shell)
49
+ self.as_root = as_root
50
+ self.rtsroot = RTSRoot()
51
+
52
+ def refresh(self):
53
+ '''
54
+ Refreshes the tree of target fabric modules.
55
+ '''
56
+ self._children = set()
57
+
58
+ # Invalidate any rtslib caches
59
+ if 'invalidate_caches' in dir(RTSRoot):
60
+ self.rtsroot.invalidate_caches()
61
+
62
+ UIBackstores(self)
63
+
64
+ # only show fabrics present in the system
65
+ for fm in self.rtsroot.fabric_modules:
66
+ if fm.wwns is None or any(fm.wwns):
67
+ UIFabricModule(fm, self)
68
+
69
+ def _compare_files(self, backupfile, savefile):
70
+ '''
71
+ Compare backfile and saveconfig file
72
+ '''
73
+ backupfilepath = Path(backupfile)
74
+ if PurePosixPath(backupfile).suffix == '.gz':
75
+ try:
76
+ with gzip.open(backupfilepath, 'rb') as fbkp:
77
+ fdata_bkp = fbkp.read()
78
+ except OSError as e:
79
+ self.shell.log.warning(f"Could not gzip open backupfile {backupfile}: {e.strerror}")
80
+
81
+ else:
82
+ try:
83
+ fdata_bkp = backupfilepath.read_bytes()
84
+ except OSError as e:
85
+ self.shell.log.warning(f"Could not open backupfile {backupfile}: {e.strerror}")
86
+
87
+ try:
88
+ fdata = Path(savefile).read_bytes()
89
+ except OSError as e:
90
+ self.shell.log.warning(f"Could not open saveconfig file {savefile}: {e.strerror}")
91
+
92
+ return fdata_bkp == fdata
93
+
94
+ def _create_dir(self, dirname):
95
+ '''
96
+ create directory with permissions 0o600 set
97
+ if directory already exists, set right perms
98
+ '''
99
+ mode = stat.S_IRUSR | stat.S_IWUSR # 0o600
100
+ dir_path = Path(dirname)
101
+ if not dir_path.exists():
102
+ umask = 0o777 ^ mode # Prevents always downgrading umask to 0
103
+ umask_original = os.umask(umask)
104
+ try:
105
+ dir_path.mkdir(mode=mode)
106
+ except OSError as exe:
107
+ raise ExecutionError(f"Cannot create directory [{dirname}] {exe.strerror}.")
108
+ finally:
109
+ os.umask(umask_original)
110
+ elif dirname == default_target_dir and (os.stat(dirname).st_mode & 0o777) != mode:
111
+ os.chmod(dirname, mode)
112
+
113
+ def _save_backups(self, savefile):
114
+ '''
115
+ Take backup of config-file if needed.
116
+ '''
117
+ # Only save backups if saving to default location
118
+ if savefile != default_save_file:
119
+ return
120
+
121
+ backup_dir = os.path.dirname(savefile) + "/backup/"
122
+ backup_name = "saveconfig-" + \
123
+ datetime.now().strftime("%Y%m%d-%H:%M:%S") + "-json.gz"
124
+ backupfile = backup_dir + backup_name
125
+ backup_error = None
126
+
127
+ self._create_dir(backup_dir)
128
+
129
+ # Only save backups if savefile exits
130
+ if not Path(savefile).exists():
131
+ return
132
+
133
+ backed_files_list = sorted(glob(os.path.dirname(savefile) + \
134
+ "/backup/saveconfig-*json*"))
135
+
136
+ # Save backup if backup dir is empty, or savefile is differnt from recent backup copy
137
+ if not backed_files_list or not self._compare_files(backed_files_list[-1], savefile):
138
+ mode = stat.S_IRUSR | stat.S_IWUSR # 0o600
139
+ umask = 0o777 ^ mode # Prevents always downgrading umask to 0
140
+ umask_original = os.umask(umask)
141
+ try:
142
+ with open(savefile, 'rb') as f_in, gzip.open(backupfile, 'wb') as f_out:
143
+ shutil.copyfileobj(f_in, f_out)
144
+ f_out.flush()
145
+ except OSError as ioe:
146
+ backup_error = ioe.strerror or "Unknown error"
147
+ finally:
148
+ os.umask(umask_original)
149
+
150
+ if backup_error is None:
151
+ # remove excess backups
152
+ max_backup_files = int(self.shell.prefs['max_backup_files'])
153
+
154
+ try:
155
+ prefs = Path(universal_prefs_file).read_text()
156
+ backups = [line for line in prefs.splitlines() if re.match(
157
+ r'^max_backup_files\s*=', line)]
158
+ if max_backup_files < int(backups[0].split('=')[1].strip()):
159
+ max_backup_files = int(backups[0].split('=')[1].strip())
160
+ except:
161
+ self.shell.log.debug(f"No universal prefs file '{universal_prefs_file}'.")
162
+
163
+ files_to_unlink = list(reversed(backed_files_list))[max_backup_files - 1:]
164
+ for f in files_to_unlink:
165
+ with ignored(IOError):
166
+ Path(f).unlink()
167
+
168
+ self.shell.log.info("Last %d configs saved in %s."
169
+ % (max_backup_files, backup_dir))
170
+ else:
171
+ self.shell.log.warning(f"Could not create backup file {backupfile}: {backup_error}.")
172
+
173
+ def ui_command_saveconfig(self, savefile=default_save_file):
174
+ '''
175
+ Saves the current configuration to a file so that it can be restored
176
+ on next boot.
177
+ '''
178
+ self.assert_root()
179
+
180
+ if not savefile:
181
+ savefile = default_save_file
182
+
183
+ savefile = os.path.expanduser(savefile)
184
+
185
+ save_dir = os.path.dirname(savefile)
186
+ self._create_dir(save_dir)
187
+ self._save_backups(savefile)
188
+
189
+ self.rtsroot.save_to_file(savefile)
190
+
191
+ self.shell.log.info(f"Configuration saved to {savefile}")
192
+
193
+ def ui_command_restoreconfig(self, savefile=default_save_file, clear_existing=False,
194
+ target=None, storage_object=None):
195
+ '''
196
+ Restores configuration from a file.
197
+ '''
198
+ self.assert_root()
199
+
200
+ savefile = os.path.expanduser(savefile)
201
+
202
+ if not os.path.isfile(savefile):
203
+ self.shell.log.info(f"Restore file {savefile} not found")
204
+ return
205
+
206
+ target = self.ui_eval_param(target, 'string', None)
207
+ storage_object = self.ui_eval_param(storage_object, 'string', None)
208
+ errors = self.rtsroot.restore_from_file(savefile, clear_existing,
209
+ target, storage_object)
210
+
211
+ self.refresh()
212
+
213
+ if errors:
214
+ raise ExecutionError("Configuration restored, %d recoverable errors:\n%s" % \
215
+ (len(errors), "\n".join(errors)))
216
+
217
+ self.shell.log.info(f"Configuration restored from {savefile}")
218
+
219
+ def ui_complete_saveconfig(self, parameters, text, current_param):
220
+ '''
221
+ Auto-completes the file name
222
+ '''
223
+ if current_param != 'savefile':
224
+ return []
225
+ completions = complete_path(text, stat.S_ISREG)
226
+ if len(completions) == 1 and not completions[0].endswith('/'):
227
+ completions = [completions[0] + ' ']
228
+ return completions
229
+
230
+ ui_complete_restoreconfig = ui_complete_saveconfig
231
+
232
+ def ui_command_clearconfig(self, confirm=None):
233
+ '''
234
+ Removes entire configuration of backstores and targets
235
+ '''
236
+ self.assert_root()
237
+
238
+ confirm = self.ui_eval_param(confirm, 'bool', False)
239
+
240
+ self.rtsroot.clear_existing(confirm=confirm)
241
+
242
+ self.shell.log.info("All configuration cleared")
243
+
244
+ self.refresh()
245
+
246
+ def ui_command_version(self):
247
+ '''
248
+ Displays the targetcli and support libraries versions.
249
+ '''
250
+ self.shell.log.info(f"targetcli version {__version__}")
251
+
252
+ def ui_command_sessions(self, action="list", sid=None):
253
+ '''
254
+ Displays a detailed list of all open sessions.
255
+
256
+ PARAMETERS
257
+ ==========
258
+
259
+ action
260
+ ------
261
+ The action is one of:
262
+ - `list`` gives a short session list
263
+ - `detail` gives a detailed list
264
+
265
+ sid
266
+ ---
267
+ You can specify an "sid" to only list this one,
268
+ with or without details.
269
+
270
+ SEE ALSO
271
+ ========
272
+ status
273
+ '''
274
+
275
+ indent_step = 4
276
+ base_steps = 0
277
+ action_list = ("list", "detail")
278
+
279
+ if action not in action_list:
280
+ raise ExecutionError(f"action must be one of: {', '.join(action_list)}")
281
+ if sid is not None:
282
+ try:
283
+ int(sid)
284
+ except ValueError:
285
+ raise ExecutionError(f"sid must be a number, '{sid}' given")
286
+
287
+ def indent_print(text, steps):
288
+ console = self.shell.con
289
+ console.display(console.indent(text, indent_step * steps),
290
+ no_lf=True)
291
+
292
+ def print_session(session):
293
+ acl = session['parent_nodeacl']
294
+ indent_print("alias: %(alias)s\tsid: %(id)i type: %(type)s session-state: %(state)s" % session,
295
+ base_steps)
296
+
297
+ if action == 'detail':
298
+ if self.as_root:
299
+ auth = " (authenticated)" if acl.authenticate_target else " (NOT AUTHENTICATED)"
300
+ else:
301
+ auth = ""
302
+
303
+ indent_print(f"name: {acl.node_wwn}{auth}",
304
+ base_steps + 1)
305
+
306
+ for mlun in acl.mapped_luns:
307
+ plugin = mlun.tpg_lun.storage_object.plugin
308
+ name = mlun.tpg_lun.storage_object.name
309
+ mode = "r" if mlun.write_protect else "rw"
310
+ indent_print("mapped-lun: %d backstore: %s/%s mode: %s" %
311
+ (mlun.mapped_lun, plugin, name, mode),
312
+ base_steps + 1)
313
+
314
+ for connection in session['connections']:
315
+ indent_print("address: %(address)s (%(transport)s) cid: %(cid)i connection-state: %(cstate)s"
316
+ % connection, base_steps + 1)
317
+
318
+ if sid:
319
+ printed_sessions = [x for x in self.rtsroot.sessions if x['id'] == int(sid)]
320
+ else:
321
+ printed_sessions = list(self.rtsroot.sessions)
322
+
323
+ if len(printed_sessions):
324
+ for session in printed_sessions:
325
+ print_session(session)
326
+ elif sid is None:
327
+ indent_print("(no open sessions)", base_steps)
328
+ else:
329
+ raise ExecutionError("no session found with sid %i" % int(sid))