3 # vim: ts=4 sw=4 smarttab expandtab
5 # Processed in Makefile to add python #! line and version variable
11 ceph.in becomes ceph, the command-line management tool for Ceph clusters.
12 This is a replacement for tools/ceph.cc and tools/common.cc.
14 Copyright (C) 2013 Inktank Storage, Inc.
16 This is free software; you can redistribute it and/or
17 modify it under the terms of the GNU General Public
18 License version 2, as published by the Free Software
19 Foundation. See file COPYING.
22 from __future__ import print_function
33 CEPH_GIT_VER = "@CEPH_GIT_VER@"
34 CEPH_GIT_NICE_VER = "@CEPH_GIT_NICE_VER@"
35 CEPH_RELEASE = "@CEPH_RELEASE@"
36 CEPH_RELEASE_NAME = "@CEPH_RELEASE_NAME@"
37 CEPH_RELEASE_TYPE = "@CEPH_RELEASE_TYPE@"
39 # Flags from src/mon/Monitor.h
40 FLAG_NOFORWARD = (1 << 0)
41 FLAG_OBSOLETE = (1 << 1)
42 FLAG_DEPRECATED = (1 << 2)
44 # priorities from src/common/perf_counters.h
48 PRIO_UNINTERESTING = 2
51 PRIO_DEFAULT = PRIO_USEFUL
53 # Make life easier on developers:
54 # If our parent dir contains CMakeCache.txt and bin/init-ceph,
55 # assume we're running from a build dir (i.e. src/build/bin/ceph)
56 # and tweak sys.path and LD_LIBRARY_PATH to use built files.
57 # Since this involves re-execing, if CEPH_DBG is set in the environment
58 # re-exec with -mpdb. Also, if CEPH_DEV is in the env, suppress
59 # the warning message about the DEVELOPER MODE.
61 MYPATH = os.path.abspath(__file__)
62 MYDIR = os.path.dirname(MYPATH)
63 MYPDIR = os.path.dirname(MYDIR)
64 DEVMODEMSG = '*** DEVELOPER MODE: setting PATH, PYTHONPATH and LD_LIBRARY_PATH ***'
67 def respawn_in_path(lib_path, pybind_path, pythonlib_path):
68 execv_cmd = ['python']
69 if 'CEPH_DBG' in os.environ:
70 execv_cmd += ['-mpdb']
72 if platform.system() == "Darwin":
73 lib_path_var = "DYLD_LIBRARY_PATH"
75 lib_path_var = "LD_LIBRARY_PATH"
77 py_binary = os.environ.get("PYTHON", "python")
79 if lib_path_var in os.environ:
80 if lib_path not in os.environ[lib_path_var]:
81 os.environ[lib_path_var] += ':' + lib_path
82 if "CEPH_DEV" not in os.environ:
83 print(DEVMODEMSG, file=sys.stderr)
84 os.execvp(py_binary, execv_cmd + sys.argv)
86 os.environ[lib_path_var] = lib_path
87 if "CEPH_DEV" not in os.environ:
88 print(DEVMODEMSG, file=sys.stderr)
89 os.execvp(py_binary, execv_cmd + sys.argv)
90 sys.path.insert(0, os.path.join(MYDIR, pybind_path))
91 sys.path.insert(0, os.path.join(MYDIR, pythonlib_path))
94 def get_pythonlib_dir():
95 """Returns the name of a distutils build directory"""
96 return "lib.{version[0]}".format(version=sys.version_info)
98 if os.path.exists(os.path.join(MYPDIR, "CMakeCache.txt")) \
99 and os.path.exists(os.path.join(MYPDIR, "bin/init-ceph")):
101 for l in open(os.path.join(MYPDIR, "CMakeCache.txt")):
102 if l.startswith("ceph_SOURCE_DIR:STATIC="):
103 src_path = l.split("=")[1].strip()
106 # Huh, maybe we're not really in a cmake environment?
109 # Developer mode, but in a cmake build dir instead of the src dir
110 lib_path = os.path.join(MYPDIR, "lib")
111 bin_path = os.path.join(MYPDIR, "bin")
112 pybind_path = os.path.join(src_path, "src", "pybind")
113 pythonlib_path = os.path.join(lib_path,
117 respawn_in_path(lib_path, pybind_path, pythonlib_path)
119 if 'PATH' in os.environ and bin_path not in os.environ['PATH']:
120 os.environ['PATH'] += ':' + bin_path
131 from ceph_argparse import \
132 concise_sig, descsort_key, parse_json_funcsigs, \
133 matchnum, validate_command, find_cmd_target, \
134 send_command, json_command, run_in_thread
136 from ceph_daemon import admin_socket, DaemonWatcher, Termsize
138 # just a couple of globals
141 cluster_handle = None
143 # Always use Unicode (UTF-8) for stdout
144 if sys.version_info[0] >= 3:
145 raw_stdout = sys.stdout.buffer
146 raw_stderr = sys.stderr.buffer
148 raw_stdout = sys.__stdout__
149 raw_stderr = sys.__stderr__
150 sys.stdout = codecs.getwriter('utf-8')(raw_stdout)
151 sys.stderr = codecs.getwriter('utf-8')(raw_stderr)
156 raw_stdout.write(buf)
160 ret, outbuf, outs = json_command(cluster_handle, prefix='osd ls')
162 raise RuntimeError('Can\'t contact mon for osd list')
163 return [line.decode('utf-8') for line in outbuf.split(b'\n') if line]
167 ret, outbuf, outs = json_command(cluster_handle, prefix='mon dump',
168 argdict={'format': 'json'})
170 raise RuntimeError('Can\'t contact mon for mon list')
171 d = json.loads(outbuf.decode('utf-8'))
172 return [m['name'] for m in d['mons']]
176 ret, outbuf, outs = json_command(cluster_handle, prefix='mds dump',
177 argdict={'format': 'json'})
179 raise RuntimeError('Can\'t contact mon for mds list')
180 d = json.loads(outbuf.decode('utf-8'))
183 for mdsdict in infodict.values():
184 l.append(mdsdict['name'])
189 ret, outbuf, outs = json_command(cluster_handle, prefix='mgr dump',
190 argdict={'format': 'json'})
192 raise RuntimeError('Can\'t contact mon for mgr list')
194 d = json.loads(outbuf.decode('utf-8'))
196 l.append(d['active_name'])
197 for i in d['standbys']:
202 def validate_target(target):
204 this function will return true iff target is a correct
205 target, such as mon.a/osd.2/mds.a/mgr.
207 target: array, likes ['osd', '2']
208 return: bool, or raise RuntimeError
212 # for case "service.id"
213 service_name, service_id = target[0], target[1]
215 if service_name == "mon":
217 elif service_name == "osd":
219 elif service_name == "mds":
221 elif service_name == "mgr":
224 print('WARN: {0} is not a legal service name, should be one of mon/osd/mds/mgr'.format(service_name),
228 if service_id in exist_ids:
231 print('WARN: the service id you provided does not exist. service id should '
232 'be one of {0}.'.format('/'.join(exist_ids)), file=sys.stderr)
235 elif len(target) == 1 and target[0] in ['mgr', 'mon']:
238 print('WARN: \"{0}\" is not a legal target. it should be one of mon.<id>/osd.<int>/mds.<id>/mgr'.format('.'.join(target)), file=sys.stderr)
242 # these args must be passed to all child programs
245 'client_name': '--name',
246 'cluster': '--cluster',
247 'cephconf': '--conf',
251 def parse_cmdargs(args=None, target=''):
252 # alias: let the line-wrapping be sane
253 AP = argparse.ArgumentParser
255 # format our own help
256 parser = AP(description='Ceph administration tool', add_help=False)
258 parser.add_argument('--completion', action='store_true',
259 help=argparse.SUPPRESS)
261 parser.add_argument('-h', '--help', help='request mon help',
264 parser.add_argument('-c', '--conf', dest='cephconf',
265 help='ceph configuration file')
266 parser.add_argument('-i', '--in-file', dest='input_file',
267 help='input file, or "-" for stdin')
268 parser.add_argument('-o', '--out-file', dest='output_file',
269 help='output file, or "-" for stdout')
271 parser.add_argument('--id', '--user', dest='client_id',
272 help='client id for authentication')
273 parser.add_argument('--name', '-n', dest='client_name',
274 help='client name for authentication')
275 parser.add_argument('--cluster', help='cluster name')
277 parser.add_argument('--admin-daemon', dest='admin_socket',
278 help='submit admin-socket commands (\"help\" for help')
280 parser.add_argument('-s', '--status', action='store_true',
281 help='show cluster status')
283 parser.add_argument('-w', '--watch', action='store_true',
284 help='watch live cluster changes')
285 parser.add_argument('--watch-debug', action='store_true',
286 help='watch debug events')
287 parser.add_argument('--watch-info', action='store_true',
288 help='watch info events')
289 parser.add_argument('--watch-sec', action='store_true',
290 help='watch security events')
291 parser.add_argument('--watch-warn', action='store_true',
292 help='watch warn events')
293 parser.add_argument('--watch-error', action='store_true',
294 help='watch error events')
296 parser.add_argument('--watch-channel', dest="watch_channel",
297 help="which log channel to follow " \
298 "when using -w/--watch. One of ['cluster', 'audit', '*'",
301 parser.add_argument('--version', '-v', action="store_true", help="display version")
302 parser.add_argument('--verbose', action="store_true", help="make verbose")
303 parser.add_argument('--concise', dest='verbose', action="store_false",
304 help="make less verbose")
306 parser.add_argument('-f', '--format', choices=['json', 'json-pretty',
307 'xml', 'xml-pretty', 'plain'], dest='output_format')
309 parser.add_argument('--connect-timeout', dest='cluster_timeout',
311 help='set a timeout for connecting to the cluster')
313 # returns a Namespace with the parsed args, and a list of all extras
314 parsed_args, extras = parser.parse_known_args(args)
316 return parser, parsed_args, extras
320 print('\n', s, '\n', '=' * len(s))
323 def do_basic_help(parser, args):
325 Print basic parser help
326 If the cluster is available, get and print monitor help
328 hdr('General usage:')
330 print_locally_handled_command_help()
333 def print_locally_handled_command_help():
334 hdr("Local commands:")
336 ping <mon.id> Send simple presence/life test to a mon
337 <mon.id> may be 'mon.*' for all mons
338 daemon {type.id|path} <cmd>
339 Same as --admin-daemon, but auto-find admin socket
340 daemonperf {type.id | path} [stat-pats] [priority] [<interval>] [<count>]
341 daemonperf {type.id | path} list|ls [stat-pats] [priority]
342 Get selected perf stats from daemon/admin socket
343 Optional shell-glob comma-delim match string stat-pats
344 Optional selection priority (can abbreviate name):
345 critical, interesting, useful, noninteresting, debug
346 List shows a table of all available stats
347 Run <count> times (default forever),
348 once per <interval> seconds (default 1)
349 """, file=sys.stdout)
352 def do_extended_help(parser, args, target, partial):
353 def help_for_sigs(sigs, partial=None):
354 sys.stdout.write(format_help(parse_json_funcsigs(sigs, 'cli'),
357 def help_for_target(target, partial=None):
358 ret, outbuf, outs = json_command(cluster_handle, target=target,
359 prefix='get_command_descriptions',
362 print("couldn't get command descriptions for {0}: {1} ({2})".
363 format(target, outs, ret), file=sys.stderr)
366 return help_for_sigs(outbuf.decode('utf-8'), partial)
368 assert(cluster_handle.state == "connected")
369 return help_for_target(target, partial)
371 DONTSPLIT = string.ascii_letters + '{[<>]}'
374 def wrap(s, width, indent):
376 generator to transform s into a sequence of strings width or shorter,
377 for wrapping text to a specific column width.
378 Attempt to break on anything but DONTSPLIT characters.
379 indent is amount to indent 2nd-through-nth lines.
381 so "long string long string long string" width=11 indent=1 becomes
382 'long string', ' long string', ' long string' so that it can be printed
395 # no splitting; just possibly indent
402 while (splitpos > 0) and (s[splitpos-1] in DONTSPLIT):
409 # prior result means we're mid-iteration, indent
412 # first time, set leader and width for next
413 leader = ' ' * indent
414 width -= 1 # for subsequent space additions
416 # remove any leading spaces in this chunk of s
417 result += s[:splitpos].lstrip()
425 def format_help(cmddict, partial=None):
427 Formats all the cmdsigs and helptexts from cmddict into a sorted-by-
428 cmdsig 2-column display, with each column wrapped and indented to
429 fit into (terminal_width / 2) characters.
433 for cmd in sorted(cmddict.values(), key=descsort_key):
437 flags = cmd.get('flags', 0)
438 if flags & (FLAG_OBSOLETE | FLAG_DEPRECATED):
440 concise = concise_sig(cmd['sig'])
441 if partial and not concise.startswith(partial):
443 width = Termsize().cols - 1 # 1 for the line between sig and help
444 sig_width = int(width / 2)
445 # make sure width == sig_width + help_width, even (width % 2 > 0)
446 help_width = int(width / 2) + (width % 2)
447 siglines = [l for l in wrap(concise, sig_width, 1)]
448 helplines = [l for l in wrap(cmd['help'], help_width, 1)]
450 # make lists the same length
451 maxlen = max(len(siglines), len(helplines))
452 siglines.extend([''] * (maxlen - len(siglines)))
453 helplines.extend([''] * (maxlen - len(helplines)))
455 # so we can zip them for output
456 for s, h in zip(siglines, helplines):
457 fullusage += '{s:{w}s} {h}\n'.format(s=s, h=h, w=sig_width)
462 def ceph_conf(parsed_args, field, name):
466 args.extend(['--name', name])
468 # add any args in GLOBAL_ARGS
469 for key, val in GLOBAL_ARGS.items():
470 # ignore name in favor of argument name, if any
471 if name and key == 'client_name':
473 if getattr(parsed_args, key):
474 args.extend([val, getattr(parsed_args, key)])
476 args.extend(['--show-config-value', field])
477 p = subprocess.Popen(
479 stdout=subprocess.PIPE,
480 stderr=subprocess.PIPE)
481 outdata, errdata = p.communicate()
483 raise RuntimeError('unable to get conf option %s for %s: %s' % (field, name, errdata))
484 return outdata.rstrip()
488 if sys.stdin.isatty():
491 line = input(PROMPT).rstrip()
492 if line in ['q', 'quit', 'Q', 'exit']:
499 line = sys.stdin.readline()
507 def new_style_command(parsed_args, cmdargs, target, sigdict, inbuf, verbose):
509 Do new-style command dance.
510 target: daemon to receive command: mon (any) or osd.N
511 sigdict - the parsed output from the new monitor describing commands
512 inbuf - any -i input file data
516 for cmdtag in sorted(sigdict.keys()):
517 cmd = sigdict[cmdtag]
519 print('{0}: {1}'.format(cmdtag, concise_sig(sig)))
523 # Validate input args against list of sigs
524 valid_dict = validate_command(sigdict, cmdargs, verbose)
526 if parsed_args.output_format:
527 valid_dict['format'] = parsed_args.output_format
529 return -errno.EINVAL, '', 'invalid command'
531 if sys.stdin.isatty():
532 # do the command-interpreter looping
533 # for input to do readline cmd editing
534 import readline # noqa
537 interactive_input = read_input()
538 if interactive_input is None:
540 cmdargs = parse_cmdargs(shlex.split(interactive_input))[2]
542 target = find_cmd_target(cmdargs)
543 except Exception as e:
544 print('error handling command target: {0}'.format(e),
547 if len(cmdargs) and cmdargs[0] == 'tell':
548 print('Can not use \'tell\' in interactive mode.',
551 valid_dict = validate_command(sigdict, cmdargs, verbose)
553 if parsed_args.output_format:
554 valid_dict['format'] = parsed_args.output_format
556 print("Submitting command: ", valid_dict, file=sys.stderr)
557 ret, outbuf, outs = json_command(cluster_handle,
562 print('Error: {0} {1}'.format(ret, errno.errorcode.get(ret, 'Unknown')),
567 print('Status:\n', outs, file=sys.stderr)
569 print("Invalid command", file=sys.stderr)
572 print("Submitting command: ", valid_dict, file=sys.stderr)
573 return json_command(cluster_handle, target=target, argdict=valid_dict,
577 def complete(sigdict, args, target):
579 Command completion. Match as much of [args] as possible,
580 and print every possible match separated by newlines.
583 # XXX this looks a lot like the front of validate_command(). Refactor?
585 complete_verbose = 'COMPVERBOSE' in os.environ
587 # Repulsive hack to handle tell: lop off 'tell' and target
588 # and validate the rest of the command. 'target' is already
589 # determined in our callers, so it's ok to remove it here.
590 if len(args) and args[0] == 'tell':
592 # look for best match, accumulate possibles in bestcmds
593 # (so we can maybe give a more-useful error message)
597 for cmdtag, cmd in sigdict.items():
600 # iterate over all arguments, except last one
601 for arg in args[0:-1]:
603 # an out of argument definitions
605 found_match = arg in sig[j].complete(arg)
606 if not found_match and sig[j].req:
607 # no elements that match
612 # successfully matched all - except last one - arguments
613 if j < len(sig) and len(args) > 0:
614 comps += sig[j].complete(args[-1])
619 if match_count == 1 and len(comps) == 0:
620 # only one command matched and no hints yet => add help
621 comps = comps + [' ', '#'+match_cmd['help']]
622 print('\n'.join(sorted(set(comps))))
626 def ping_monitor(cluster_handle, name, timeout):
627 if 'mon.' not in name:
628 print('"ping" expects a monitor to ping; try "ping mon.<id>"', file=sys.stderr)
631 mon_id = name[len('mon.'):]
633 run_in_thread(cluster_handle.connect, timeout=timeout)
635 s = run_in_thread(cluster_handle.ping_monitor, m)
637 print("mon.{0}".format(m) + '\n' + "Error connecting to monitor.")
639 print("mon.{0}".format(m) + '\n' + s)
641 s = run_in_thread(cluster_handle.ping_monitor, mon_id)
646 def maybe_daemon_command(parsed_args, childargs):
648 Check if --admin-socket, daemon, or daemonperf command
649 if it is, returns (boolean handled, return code if handled == True)
654 if parsed_args.admin_socket:
655 sockpath = parsed_args.admin_socket
656 elif len(childargs) > 0 and childargs[0] in ["daemon", "daemonperf"]:
657 daemon_perf = (childargs[0] == "daemonperf")
658 # Treat "daemon <path>" or "daemon <name>" like --admin_daemon <path>
659 # Handle "daemonperf <path>" the same but requires no trailing args
660 require_args = 2 if daemon_perf else 3
661 if len(childargs) >= require_args:
662 if childargs[1].find('/') >= 0:
663 sockpath = childargs[1]
665 # try resolve daemon name
667 sockpath = ceph_conf(parsed_args, 'admin_socket',
669 except Exception as e:
670 print('Can\'t get admin socket path: ' + str(e), file=sys.stderr)
671 return True, errno.EINVAL
673 childargs = childargs[2:]
675 print('{0} requires at least {1} arguments'.format(childargs[0], require_args),
677 return True, errno.EINVAL
679 if sockpath and daemon_perf:
680 return True, daemonperf(childargs, sockpath)
683 raw_write(admin_socket(sockpath, childargs, parsed_args.output_format))
684 except Exception as e:
685 print('admin_socket: {0}'.format(e), file=sys.stderr)
686 return True, errno.EINVAL
700 def daemonperf(childargs, sockpath):
702 Handle daemonperf command; returns errno or 0
704 daemonperf <daemon> [priority string] [statpats] [interval] [count]
705 daemonperf <daemon> list|ls [statpats]
714 def prio_from_name(arg):
717 'critical': PRIO_CRITICAL,
718 'interesting': PRIO_INTERESTING,
719 'useful': PRIO_USEFUL,
720 'uninteresting': PRIO_UNINTERESTING,
721 'debugonly': PRIO_DEBUGONLY,
727 for name, val in PRIOMAP.items():
728 if name.startswith(arg):
732 # consume and analyze non-numeric args
733 while len(childargs) and not isnum(childargs[0]):
734 arg = childargs.pop(0)
736 if arg in ['list', 'ls']:
740 prio = prio_from_name(arg)
745 statpats = arg.split(',')
748 priority = PRIO_DEFAULT
750 if len(childargs) > 0:
752 interval = float(childargs.pop(0))
756 print('daemonperf: interval should be a positive number', file=sys.stderr)
759 if len(childargs) > 0:
760 arg = childargs.pop(0)
761 if (not isnum(arg)) or (int(arg) < 0):
762 print('daemonperf: count should be a positive integer', file=sys.stderr)
766 watcher = DaemonWatcher(sockpath, statpats, priority)
770 watcher.run(interval, count)
776 ceph_args = os.environ.get('CEPH_ARGS')
778 if "injectargs" in sys.argv:
779 i = sys.argv.index("injectargs")
780 sys.argv = sys.argv[:i] + ceph_args.split() + sys.argv[i:]
782 sys.argv.extend([arg for arg in ceph_args.split()
783 if '--admin-socket' not in arg])
784 parser, parsed_args, childargs = parse_cmdargs()
786 if parsed_args.version:
787 print('ceph version {0} ({1}) {2} ({3})'.format(
791 CEPH_RELEASE_TYPE)) # noqa
795 verbose = parsed_args.verbose
798 print("parsed_args: {0}, childargs: {1}".format(parsed_args, childargs), file=sys.stderr)
800 # pass on --id, --name, --conf
801 name = 'client.admin'
802 if parsed_args.client_id:
803 name = 'client.' + parsed_args.client_id
804 if parsed_args.client_name:
805 name = parsed_args.client_name
807 # default '' means default conf search
809 if parsed_args.cephconf:
810 conffile = parsed_args.cephconf
811 # For now, --admin-daemon is handled as usual. Try it
812 # first in case we can't connect() to the cluster
814 format = parsed_args.output_format
816 done, ret = maybe_daemon_command(parsed_args, childargs)
821 if parsed_args.cluster_timeout:
822 timeout = parsed_args.cluster_timeout
826 do_basic_help(parser, childargs)
828 # handle any 'generic' ceph arguments that we didn't parse here
829 global cluster_handle
831 # rados.Rados() will call rados_create2, and then read the conf file,
832 # and then set the keys from the dict. So we must do these
833 # "pre-file defaults" first (see common_preinit in librados)
835 'log_to_stderr': 'true',
836 'err_to_stderr': 'true',
837 'log_flush_on_exit': 'true',
840 if 'injectargs' in childargs:
841 position = childargs.index('injectargs')
842 injectargs = childargs[position:]
843 childargs = childargs[:position]
845 print('Separate childargs {0} from injectargs {1}'.format(childargs, injectargs),
851 if parsed_args.cluster:
852 clustername = parsed_args.cluster
855 cluster_handle = run_in_thread(rados.Rados,
856 name=name, clustername=clustername,
857 conf_defaults=conf_defaults,
859 retargs = run_in_thread(cluster_handle.conf_parse_argv, childargs)
860 except rados.Error as e:
861 print('Error initializing cluster client: {0!r}'.format(e), file=sys.stderr)
868 # -- means "stop parsing args", but we don't want to see it either
869 if '--' in childargs:
870 childargs.remove('--')
871 if injectargs and '--' in injectargs:
872 injectargs.remove('--')
874 # special deprecation warning for 'ceph <type> tell'
875 # someday 'mds' will be here too
876 if (len(childargs) >= 2 and
877 childargs[0] in ['mon', 'osd'] and
878 childargs[1] == 'tell'):
879 print('"{0} tell" is deprecated; try "tell {0}.<id> <command> [options...]" instead (id can be "*") '.format(childargs[0]),
884 # short default timeout for -h
888 if childargs and childargs[0] == 'ping' and not parsed_args.help:
889 if len(childargs) < 2:
890 print('"ping" requires a monitor name as argument: "ping mon.<id>"', file=sys.stderr)
892 if parsed_args.completion:
893 # for completion let timeout be really small
896 if childargs and childargs[0] == 'ping' and not parsed_args.help:
897 return ping_monitor(cluster_handle, childargs[1], timeout)
898 result = run_in_thread(cluster_handle.connect, timeout=timeout)
899 if type(result) is tuple and result[0] == -errno.EINTR:
900 print('Cluster connection interrupted or timed out', file=sys.stderr)
902 except KeyboardInterrupt:
903 print('Cluster connection aborted', file=sys.stderr)
905 except rados.PermissionDeniedError as e:
906 print(str(e), file=sys.stderr)
908 except Exception as e:
909 print(str(e), file=sys.stderr)
913 hdr('Monitor commands:')
915 print('[Contacting monitor, timeout after %d seconds]' % timeout)
917 return do_extended_help(parser, childargs, ('mon', ''), ' '.join(childargs))
919 # implement "tell service.id help"
920 if len(childargs) >= 3 and childargs[0] == 'tell' and childargs[2] == 'help':
921 target = childargs[1].split('.')
922 if validate_target(target):
923 return do_extended_help(parser, childargs, target, None)
925 print('target {0} doesn\'t exists, please pass correct target to tell command, such as mon.a/'
926 'osd.1/mds.a/mgr'.format(childargs[1]), file=sys.stderr)
928 # implement -w/--watch_*
929 # This is ugly, but Namespace() isn't quite rich enough.
931 for k, v in parsed_args._get_kwargs():
932 if k.startswith('watch') and v:
935 elif k != "watch_channel":
936 level = k.replace('watch_', '')
938 # an awfully simple callback
939 def watch_cb(arg, line, channel, name, who, stamp_sec, stamp_nsec, seq, level, msg):
941 if (channel == parsed_args.watch_channel or \
942 parsed_args.watch_channel == "*"):
946 # first do a ceph status
947 ret, outbuf, outs = json_command(cluster_handle, prefix='status')
949 print("status query failed: ", outs, file=sys.stderr)
953 # this instance keeps the watch connection alive, but is
955 run_in_thread(cluster_handle.monitor_log2, level, watch_cb, 0)
957 # loop forever letting watch_cb print lines
960 except KeyboardInterrupt:
961 # or until ^C, at least
964 # read input file, if any
966 if parsed_args.input_file:
968 if parsed_args.input_file == '-':
969 inbuf = sys.stdin.read()
971 with open(parsed_args.input_file, 'rb') as f:
973 except Exception as e:
974 print('Can\'t open input file {0}: {1}'.format(parsed_args.input_file, e), file=sys.stderr)
977 # prepare output file, if any
978 if parsed_args.output_file:
980 if parsed_args.output_file == '-':
983 outf = open(parsed_args.output_file, 'wb')
984 except Exception as e:
985 print('Can\'t open output file {0}: {1}'.format(parsed_args.output_file, e), file=sys.stderr)
988 # -s behaves like a command (ceph status).
989 if parsed_args.status:
990 childargs.insert(0, 'status')
993 target = find_cmd_target(childargs)
994 except Exception as e:
995 print('error handling command target: {0}'.format(e), file=sys.stderr)
998 # Repulsive hack to handle tell: lop off 'tell' and target
999 # and validate the rest of the command. 'target' is already
1000 # determined in our callers, so it's ok to remove it here.
1002 if len(childargs) and childargs[0] == 'tell':
1003 childargs = childargs[2:]
1008 childargs = injectargs
1009 if not len(childargs):
1010 print('"{0} tell" requires additional arguments.'.format(sys.argv[0]),
1011 'Try "{0} tell <name> <command> [options...]" instead.'.format(sys.argv[0]),
1015 # fetch JSON sigs from command
1016 # each line contains one command signature (a placeholder name
1017 # of the form 'cmdNNN' followed by an array of argument descriptors)
1018 # as part of the validated argument JSON object
1022 if target[1] == '*':
1023 if target[0] == 'osd':
1024 targets = [(target[0], o) for o in osdids()]
1025 elif target[0] == 'mon':
1026 targets = [(target[0], m) for m in monids()]
1029 for target in targets:
1030 # prettify? prefix output with target, if there was a wildcard used
1033 if not parsed_args.output_file and len(targets) > 1:
1034 prefix = '{0}.{1}: '.format(*target)
1037 ret, outbuf, outs = json_command(cluster_handle, target=target,
1038 prefix='get_command_descriptions')
1040 where = '{0}.{1}'.format(*target)
1042 raise RuntimeError('Unexpeceted return code from {0}: {1}'.
1044 outs = 'problem getting command descriptions from {0}'.format(where)
1046 sigdict = parse_json_funcsigs(outbuf.decode('utf-8'), 'cli')
1048 if parsed_args.completion:
1049 return complete(sigdict, childargs, target)
1051 ret, outbuf, outs = new_style_command(parsed_args, childargs,
1052 target, sigdict, inbuf,
1055 # debug tool: send any successful command *again* to
1056 # verify that it is idempotent.
1057 if not ret and 'CEPH_CLI_TEST_DUP_COMMAND' in os.environ:
1058 ret, outbuf, outs = new_style_command(parsed_args, childargs,
1059 target, sigdict, inbuf,
1064 'Second attempt of previously successful command '
1065 'failed with {0}: {1}'.format(
1066 errno.errorcode.get(ret, 'Unknown'), outs),
1071 errstr = errno.errorcode.get(ret, 'Unknown')
1072 print(u'Error {0}: {1}'.format(errstr, outs), file=sys.stderr)
1073 if len(targets) > 1:
1079 print(prefix + outs, file=sys.stderr)
1083 if parsed_args.output_file:
1086 # hack: old code printed status line before many json outputs
1087 # (osd dump, etc.) that consumers know to ignore. Add blank line
1088 # to satisfy consumers that skip the first line, but not annoy
1089 # consumers that don't.
1090 if parsed_args.output_format and \
1091 parsed_args.output_format.startswith('json'):
1094 # if we are prettifying things, normalize newlines. sigh.
1096 outbuf = outbuf.rstrip()
1099 print(prefix, end='')
1100 # Write directly to binary stdout
1102 print(suffix, end='')
1103 except IOError as e:
1104 if e.errno != errno.EPIPE:
1109 if parsed_args.output_file and parsed_args.output_file != '-':
1117 if __name__ == '__main__':
1119 # shutdown explicitly; Rados() does not
1121 run_in_thread(cluster_handle.shutdown)