#!/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|--tcp]" % 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(" \t\tEnter configuration shell", file=err) print(" --tcp CMD\t\tPass targetcli command to targetclid", file=err) print(" --tcp \tEnter multi-line command mode for targetclid", 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')) 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(): 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") argstart = 1 if len(sys.argv) > 1 and sys.argv[1] in ("tcp", "--tcp", "-t"): argstart = 2 if len(sys.argv[argstart - 1:]) > 1: command = " ".join(sys.argv[argstart:]) else: inputs = [] while True: 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 if len(sys.argv) > 1: usage_version(sys.argv[1]) if sys.argv[1] in ("tcp", "--tcp", "-t"): use_daemon = True if use_daemon: call_daemon(shell, get_arguments().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: 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()