summaryrefslogtreecommitdiff
path: root/targetcli/ui_node.py
blob: bd7848f799570f18086cd74010d60285fcb14ccc (plain)
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
'''
Implements the targetcli base UI node.

This file is part of targetcli.
Copyright (c) 2011 by RisingTide Systems LLC

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, version 3 (AGPLv3).

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

from configshell import ConfigNode, ExecutionError
from rtslib import RTSLibError, RTSRoot
from subprocess import PIPE, Popen
from os.path import isfile
from os import getuid

def exec3(cmd):
    '''
    Executes a shell command **cmd** and returns
    **(retcode, stdout, stderr)**.
    '''
    process = Popen(cmd, shell=True, bufsize=1024*1024,
                    stdin=PIPE,
                    stdout=PIPE, stderr=PIPE,
                    close_fds=True)
    (out, err) = process.communicate()
    retcode = process.returncode
    return (retcode, out, err)

class UINode(ConfigNode):
    '''
    Our targetcli basic UI node.
    '''
    def __init__(self, name, parent=None, shell=None):
        ConfigNode.__init__(self, name, parent, shell)
        self.cfs_cwd = RTSRoot.configfs_dir
        self.define_config_group_param(
            'global', 'auto_enable_tpgt', 'bool',
            'If true, automatically enables TPGTs upon creation.')
        self.define_config_group_param(
            'global', 'auto_add_mapped_luns', 'bool',
            'If true, automatically create node ACLs mapped LUNs '
            + 'after creating a new target LUN or a new node ACL')
        self.define_config_group_param(
            'global', 'legacy_hba_view', 'bool',
            'If true, use legacy HBA view, allowing to create more '
            + 'than one storage object per HBA.')
        self.define_config_group_param(
            'global', 'auto_cd_after_create', 'bool',
            'If true, changes current path to newly created objects.')

    def assert_root(self):
        '''
        For commands requiring root privileges, disable command if not the root
        node's as_root attribute is False.
        '''
        root_node = self.get_root()
        if hasattr(root_node, 'as_root') and not self.get_root().as_root:
            raise ExecutionError("This privileged command is disabled: "
                                 + "you are not root.")

    def new_node(self, new_node):
        '''
        Used to honor global 'auto_cd_after_create'.
        Either returns None if the global is False, or the new_node if the
        global is True. In both cases, set the @last bookmark to last_node.
        '''
        self.shell.prefs['bookmarks']['last'] = new_node.path
        self.shell.prefs.save()
        if self.shell.prefs['auto_cd_after_create']:
            self.shell.log.info("Entering new node %s" % new_node.path)
            # Piggy backs on cd instead of just returning new_node,
            # so we update navigation history.
            return self.ui_command_cd(new_node.path)
        else:
            return None

    def refresh(self):
        '''
        Refreshes and updates the objects tree from the current path.
        '''
        for child in self.children:
            child.refresh()

    def execute_command(self, command, pparams=[], kparams={}):
        '''
        We overload this one in order to handle our own exceptions cleanly,
        and not just configshell's ExecutionError.
        '''
        try:
            result = ConfigNode.execute_command(self, command,
                                                pparams, kparams)
        except RTSLibError, msg:
            self.shell.log.error(msg)
        else:
            self.shell.log.debug("Command %s succeeded." % command)
            return result

    def ui_command_exit(self):
        '''
        Exits the command line interface.
        '''
        config_needs_save = False
        config_paths = {'tcm': "/etc/target/tcm_start.sh",
                        'lio': "/etc/target/lio_start.sh"}
        for mod_name, config_path in config_paths.items():
            saved_config = ''
            live_config = exec3("%s_dump --stdout" % mod_name)[1]
            if isfile(config_path):
                with open(config_path) as config_fh:
                    saved_config = config_fh.read()
            if saved_config != live_config:
                config_needs_save = True
                break

        if config_needs_save and getuid() == 0:
            self.shell.con.display("There are unsaved configuration changes.\n"
                                   "If you exit now, configuration will not "
                                   "be updated and changes will be lost upon "
                                   "reboot.")
            try:
                input = raw_input("Type 'exit' if you want to exit anyway: ")
            except EOFError:
                input = None
                self.shell.con.display('')
            if input == "exit":
                return 'EXIT'
            else:
                self.shell.log.warning("Aborted exit, use 'saveconfig' to "
                                       "save the current configuration.")
        else:
            return 'EXIT'

    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}
        '''
        description, is_healthy = self.summary()
        self.shell.log.info("Status for %s: %s" % (self.path, description))

    def ui_setgroup_global(self, parameter, value):
        ConfigNode.ui_setgroup_global(self, parameter, value)
        self.get_root().refresh()


class UIRTSLibNode(UINode):
    '''
    A subclass of UINode for nodes with an underlying RTSLib object.
    '''
    def __init__(self, name, rtslib_object, parent):
        '''
        Call from the class that inherits this, with the rtslib object that
        should be checked upon.
        '''
        UINode.__init__(self, name, parent)
        self.rtsnode = rtslib_object

        # If the rtsnode has parameters, use them
        parameters = self.rtsnode.list_parameters()
        parameters_ro = self.rtsnode.list_parameters(writable=False)
        for parameter in parameters:
            writable = parameter not in parameters_ro
            description = "The %s parameter." % parameter
            self.define_config_group_param(
                'parameter', parameter, 'string', description, writable)

        # If the rtsnode has attributes, enable them
        attributes = self.rtsnode.list_attributes()
        attributes_ro = self.rtsnode.list_attributes(writable=False)
        for attribute in attributes:
            writable = attribute not in attributes_ro
            description = "The %s attribute." % attribute
            self.define_config_group_param(
                'attribute', attribute, 'string', description, writable)

        # If the rtsnode has auth_attrs, use them
        auth_attrs = self.rtsnode.list_auth_attrs()
        auth_attrs_ro = self.rtsnode.list_auth_attrs(writable=False)
        for auth_attr in auth_attrs:
            writable = auth_attr not in auth_attrs_ro
            description = "The %s auth_attr." % auth_attr
            self.define_config_group_param(
                'auth', auth_attr, 'string', description, writable)

    def execute_command(self, command, pparams=[], kparams={}):
        '''
        Overrides the parent's execute_command() to check if the underlying
        RTSLib object still exists before returning.
        '''
        if not self.rtsnode.exists:
            self.shell.log.error("The underlying rtslib object for "
                                 + "%s does not exist." % self.path)
            root = self.get_root()
            root.refresh()
            return root
        else:
            return UINode.execute_command(self, command, pparams, kparams)

    def ui_getgroup_attribute(self, attribute):
        '''
        This is the backend method for getting attributes.
        @param attribute: The attribute to get the value of.
        @type attribute: str
        @return: The attribute's value
        @rtype: arbitrary
        '''
        return self.rtsnode.get_attribute(attribute)

    def ui_setgroup_attribute(self, attribute, value):
        '''
        This is the backend method for setting attributes.
        @param attribute: The attribute to set the value of.
        @type attribute: str
        @param value: The attribute's value
        @type value: arbitrary
        '''
        self.assert_root()
        self.rtsnode.set_attribute(attribute, value)

    def ui_getgroup_parameter(self, parameter):
        '''
        This is the backend method for getting parameters.
        @param parameter: The parameter to get the value of.
        @type parameter: str
        @return: The parameter's value
        @rtype: arbitrary
        '''
        return self.rtsnode.get_parameter(parameter)

    def ui_setgroup_parameter(self, parameter, value):
        '''
        This is the backend method for setting parameters.
        @param parameter: The parameter to set the value of.
        @type parameter: str
        @param value: The parameter's value
        @type value: arbitrary
        '''
        self.assert_root()
        self.rtsnode.set_parameter(parameter, value)

    def ui_getgroup_auth(self, auth_attr):
        '''
        This is the backend method for getting auth_attrs.
        @param auth_attr: The auth_attr to get the value of.
        @type auth_attr: str
        @return: The auth_attr's value
        @rtype: arbitrary
        '''
        return self.rtsnode.get_auth_attr(auth_attr)

    def ui_setgroup_auth(self, auth_attr, value):
        '''
        This is the backend method for setting auth_attrs.
        @param auth_attr: The auth_attr to set the value of.
        @type auth_attr: str
        @param value: The auth_attr's value
        @type value: arbitrary
        '''
        self.assert_root()
        self.rtsnode.set_auth_attr(auth_attr, value)