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
|
#!/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 Console, 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,
'daemon_use_batch_mode': 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(console, 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:
text = "taking lock on lockfile failed: %s" %str(e)
console.display(console.render_text(text, 'red'))
sys.exit(1)
def release_op_lock(console, 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:
text = "unlock on lockfile failed: %s" %str(e)
console.display(console.render_text(text, 'red'))
lkfd.close()
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, interactive):
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)
# Two cases where we want to get pwd:
# 1. Before starting shell in interactive mode, needed for setting terminal
# 2. And only in Interactive mode, having command 'cd'
get_pwd = False
if interactive:
if not req:
req = "pwd"
get_pwd = True
elif "cd " in req:
req += "%pwd"
get_pwd = True
else:
req = "cd /%" + req # Non-interactive modes always consider start at '/'
try:
# send request
sock.sendall(req.encode())
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
output = ""
path = ""
while amount_received < amount_expected:
data = sock.recv(1024)
data = data.decode()
amount_received += len(data)
output += data
if get_pwd:
output_split = output.splitlines()
lines = len(output_split)
for i in range(0, lines):
if i == lines-1:
path = str(output_split[i])
else:
print(str(output_split[i]), end ="\n")
else:
print(output, end ="")
sock.send(b'-END@OF@DATA-')
sock.close()
return path
def switch_to_daemon(shell, interactive):
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:])
call_daemon(shell, command, False)
sys.exit(0)
if interactive:
shell.con.display("targetcli shell version %s\n"
"Entering targetcli interactive mode for daemonized approach.\n"
"Type 'exit' to quit.\n"
% targetcli_version)
else:
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)
prompt_path = "/"
if interactive:
prompt_path = call_daemon(shell, None, interactive) # get the initial path
inputs = []
real_exit=False
while True:
command = six.moves.input("%s> " %prompt_path)
if command.lower() == "exit":
real_exit=True
elif not command:
continue
if not interactive:
inputs.append(command)
if real_exit:
command = '%'.join(inputs) # delimit multiple commands with '%'
call_daemon(shell, command, interactive)
break
else:
if real_exit:
break
path = call_daemon(shell, command, interactive)
if path:
if path[0] == "/":
prompt_path = path
else:
print(path) # Error No Path ...
sys.exit(0)
def main():
'''
Start the targetcli shell.
'''
console = Console()
is_root = False
if getuid() == 0:
is_root = True
try:
lkfd = open(lock_file, 'w+')
except IOError as e:
text = "opening lockfile failed: %s" %str(e)
console.display(console.render_text(text, 'red'))
sys.exit(1)
try_op_lock(console, lkfd)
targetcli_dir = getenv("TARGETCLI_HOME", '~/.targetcli')
shell = TargetCLI(targetcli_dir, console)
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
interactive_mode = True
if shell.prefs['daemon_use_batch_mode']:
interactive_mode = False
if use_daemon and not disable_daemon:
switch_to_daemon(shell, interactive_mode)
# 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'))
release_op_lock(console, lkfd)
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)
release_op_lock(console, lkfd)
sys.exit(1)
release_op_lock(console, lkfd)
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(console, lkfd)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass
|