summaryrefslogtreecommitdiff
path: root/scripts/targetcli
blob: 04e5aba30bf379e45b787c152581cca7e2b9bea4 (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
#!/usr/bin/python
'''
Starts the targetcli CLI shell.

This file is part of targetcli.
Copyright (c) 2011-2013 by Datera, Inc

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

from os import getuid, getenv
from targetcli import UIRoot
from rtslib_fb import RTSLibError
from configshell_fb import ConfigShell, ExecutionError
from targetcli import __version__ as targetcli_version

import sys
import socket
import struct
import readline
import six
import fcntl

err = sys.stderr
# lockfile for serializing multiple targetcli requests
lock_file = '/var/run/targetcli.lock'
socket_path = '/var/run/targetclid.sock'
hints = ['/', 'backstores/', 'iscsi/', 'loopback/', 'vhost/', 'xen-pvscsi/',
         'cd', 'pwd', 'ls', 'set', 'get', 'help', 'refresh', 'status',
         'clearconfig', 'restoreconfig', 'saveconfig', 'exit']

class TargetCLI(ConfigShell):
    default_prefs = {'color_path': 'magenta',
                     'color_command': 'cyan',
                     'color_parameter': 'magenta',
                     'color_keyword': 'cyan',
                     'completions_in_columns': True,
                     'logfile': None,
                     'loglevel_console': 'info',
                     'loglevel_file': 'debug9',
                     'color_mode': True,
                     'prompt_length': 30,
                     'tree_max_depth': 0,
                     'tree_status_mode': True,
                     'tree_round_nodes': True,
                     'tree_show_root': True,
                     'export_backstore_name_as_model': True,
                     'auto_enable_tpgt': True,
                     'auto_add_mapped_luns': True,
                     'auto_cd_after_create': False,
                     'auto_save_on_exit': True,
                     'max_backup_files': '10',
                     'auto_add_default_portal': True,
                     'auto_use_daemon': False,
                    }

def usage():
    print("Usage: %s [--version|--help|CMD|--disable-daemon]" % sys.argv[0], file=err)
    print("  --version\t\tPrint version", file=err)
    print("  --help\t\tPrint this information", file=err)
    print("  CMD\t\t\tRun targetcli shell command and exit", file=err)
    print("  <nothing>\t\tEnter configuration shell", file=err)
    print("  --disable-daemon\tTurn-off the global auto use daemon flag", file=err)
    print("See man page for more information.", file=err)
    sys.exit(-1)

def version():
    print("%s version %s" % (sys.argv[0], targetcli_version), file=err)
    sys.exit(0)

def usage_version(cmd):
    if cmd in ("help", "--help", "-h"):
        usage()

    if cmd in ("version", "--version", "-v"):
        version()

def try_op_lock(shell, lkfd):
    '''
    acquire a blocking lock on lockfile, to serialize multiple requests
    '''
    try:
        fcntl.flock(lkfd, fcntl.LOCK_EX)  # wait here until ongoing request is finished
    except Exception as e:
        shell.con.display(
            shell.con.render_text(
                "taking lock on lockfile failed: %s" %str(e),
                'red'))
        sys.exit(1)

def release_op_lock(shell, lkfd):
    '''
    release blocking lock on lockfile, which can allow other requests process
    '''
    try:
        fcntl.flock(lkfd, fcntl.LOCK_UN)  # allow other requests now
    except Exception as e:
        shell.con.display(
            shell.con.render_text(
                "unlock on lockfile failed: %s" %str(e),
                'red'))
        sys.exit(1)
    lkfd.close()

def completer(text, state):
    options = [x for x in hints if x.startswith(text)]
    try:
        return options[state]
    except IndexError:
        return None

def call_daemon(shell, req):
    try:
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    except socket.error as err:
        shell.con.display(shell.con.render_text(err, 'red'))
        sys.exit(1)

    try:
        sock.connect(socket_path)
    except socket.error as err:
        shell.con.display(shell.con.render_text(err, 'red'))
        shell.con.display(
            shell.con.render_text("Currently auto_use_daemon is true, "
                "hence please make sure targetclid daemon is running ...\n"
                "(or)\nIncase if you wish to turn auto_use_daemon to false "
                "then run '#targetcli --disable-daemon'", 'red'))
        sys.exit(1)

    try:
        # send request
        sock.sendall(req)
    except socket.error as err:
        shell.con.display(shell.con.render_text(err, 'red'))
        sys.exit(1)

    var = sock.recv(4) # get length of data
    sending = struct.unpack('i', var)
    amount_expected = sending[0]
    amount_received = 0

    # get the actual data in chunks
    while amount_received < amount_expected:
        data = sock.recv(1024)
        amount_received += len(data)
        print(data.decode(), end ="")

    sock.send(b'-END@OF@DATA-')
    sock.close()
    sys.exit(0)

def get_arguments(shell):
    readline.set_completer(completer)
    readline.set_completer_delims('')

    if 'libedit' in readline.__doc__:
        readline.parse_and_bind("bind ^I rl_complete")
    else:
        readline.parse_and_bind("tab: complete")

    if len(sys.argv) > 1:
        command = " ".join(sys.argv[1:])
    else:
        inputs = []
        shell.con.display("targetcli shell version %s\n"
                        "Entering targetcli batch mode for daemonized approach.\n"
                        "Enter multiple commands separated by newline and "
                        "type 'exit' to run them all in one go.\n"
                        % targetcli_version)
        while True:
            shell.con.raw_write("/> ")
            command = six.moves.input()
            if command.lower() == "exit":
                break
            inputs.append(command)
        command = '%'.join(inputs)  # delimit multiple commands with '%'

    if not command:
        sys.exit(1)

    usage_version(command);

    return command

def main():
    '''
    Start the targetcli shell.
    '''
    shell = TargetCLI(getenv("TARGETCLI_HOME", '~/.targetcli'))

    is_root = False
    if getuid() == 0:
        is_root = True

    try:
        lkfd = open(lock_file, 'w+');
    except IOError as e:
        shell.con.display(
                shell.con.render_text("opening lockfile failed: %s" %str(e),
                    'red'))
        sys.exit(1)

    try_op_lock(shell, lkfd)

    use_daemon = False
    if shell.prefs['auto_use_daemon']:
        use_daemon = True

    disable_daemon=False
    if len(sys.argv) > 1:
        usage_version(sys.argv[1])
        if sys.argv[1] in ("disable-daemon", "--disable-daemon"):
            disable_daemon=True

    if use_daemon and not disable_daemon:
        call_daemon(shell, get_arguments(shell).encode())
        # does not return

    try:
        root_node = UIRoot(shell, as_root=is_root)
        root_node.refresh()
    except Exception as error:
        shell.con.display(shell.con.render_text(str(error), 'red'))
        if not is_root:
            shell.con.display(shell.con.render_text("Retry as root.", 'red'))
        sys.exit(-1)

    if len(sys.argv) > 1:
        try:
            if disable_daemon:
                shell.run_cmdline('set global auto_use_daemon=false')
            else:
                shell.run_cmdline(" ".join(sys.argv[1:]))
        except Exception as e:
            print(str(e), file=sys.stderr)
            sys.exit(1)
        sys.exit(0)

    shell.con.display("targetcli shell version %s\n"
                      "Copyright 2011-2013 by Datera, Inc and others.\n"
                      "For help on commands, type 'help'.\n"
                      % targetcli_version)
    if not is_root:
        shell.con.display("You are not root, disabling privileged commands.\n")

    while not shell._exit:
        try:
            shell.run_interactive()
        except (RTSLibError, ExecutionError) as msg:
            shell.log.error(str(msg))

    if shell.prefs['auto_save_on_exit'] and is_root:
        shell.log.info("Global pref auto_save_on_exit=true")
        root_node.ui_command_saveconfig()

    release_op_lock(shell, lkfd)


if __name__ == "__main__":
    main()