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 in src/, and .libs and pybind exist here, assume we're running
55 # from a Ceph source dir and tweak PYTHONPATH and LD_LIBRARY_PATH
58 MYPATH = os.path.abspath(__file__)
59 MYDIR = os.path.dirname(MYPATH)
60 DEVMODEMSG = '*** DEVELOPER MODE: setting PATH, PYTHONPATH and LD_LIBRARY_PATH ***'
63 def respawn_in_path(lib_path, pybind_path, pythonlib_path):
64 execv_cmd = ['python']
65 if 'CEPH_DBG' in os.environ:
66 execv_cmd += ['-mpdb']
68 if platform.system() == "Darwin":
69 lib_path_var = "DYLD_LIBRARY_PATH"
71 lib_path_var = "LD_LIBRARY_PATH"
73 py_binary = os.environ.get("PYTHON", "python")
75 if lib_path_var in os.environ:
76 if lib_path not in os.environ[lib_path_var]:
77 os.environ[lib_path_var] += ':' + lib_path
78 if "CEPH_DEV" not in os.environ:
79 print(DEVMODEMSG, file=sys.stderr)
80 os.execvp(py_binary, execv_cmd + sys.argv)
82 os.environ[lib_path_var] = lib_path
83 if "CEPH_DEV" not in os.environ:
84 print(DEVMODEMSG, file=sys.stderr)
85 os.execvp(py_binary, execv_cmd + sys.argv)
86 sys.path.insert(0, os.path.join(MYDIR, pybind_path))
87 sys.path.insert(0, os.path.join(MYDIR, pythonlib_path))
90 def get_pythonlib_dir():
91 """Returns the name of a distutils build directory"""
92 return "lib.{version[0]}".format(version=sys.version_info)
94 if os.path.exists(os.path.join(os.getcwd(), "CMakeCache.txt")) \
95 and os.path.exists(os.path.join(os.getcwd(), "bin/init-ceph")):
97 for l in open("./CMakeCache.txt"):
98 if l.startswith("ceph_SOURCE_DIR:STATIC="):
99 src_path = l.split("=")[1].strip()
102 # Huh, maybe we're not really in a cmake environment?
105 # Developer mode, but in a cmake build dir instead of the src dir
106 lib_path = os.path.join(os.getcwd(), "lib")
107 bin_path = os.path.join(os.getcwd(), "bin")
108 pybind_path = os.path.join(src_path, "src", "pybind")
109 pythonlib_path = os.path.join(lib_path,
113 respawn_in_path(lib_path, pybind_path, pythonlib_path)
115 if 'PATH' in os.environ and bin_path not in os.environ['PATH']:
116 os.environ['PATH'] += ':' + bin_path
127 from ceph_argparse import \
128 concise_sig, descsort_key, parse_json_funcsigs, \
129 matchnum, validate_command, find_cmd_target, \
130 send_command, json_command, run_in_thread
132 from ceph_daemon import admin_socket, DaemonWatcher, Termsize
134 # just a couple of globals
137 cluster_handle = None
139 # Always use Unicode (UTF-8) for stdout
140 if sys.version_info[0] >= 3:
141 raw_stdout = sys.stdout.buffer
142 raw_stderr = sys.stderr.buffer
144 raw_stdout = sys.__stdout__
145 raw_stderr = sys.__stderr__
146 sys.stdout = codecs.getwriter('utf-8')(raw_stdout)
147 sys.stderr = codecs.getwriter('utf-8')(raw_stderr)
152 raw_stdout.write(buf)
156 ret, outbuf, outs = json_command(cluster_handle, prefix='osd ls')
158 raise RuntimeError('Can\'t contact mon for osd list')
159 return [line.decode('utf-8') for line in outbuf.split(b'\n') if line]
163 ret, outbuf, outs = json_command(cluster_handle, prefix='mon dump',
164 argdict={'format': 'json'})
166 raise RuntimeError('Can\'t contact mon for mon list')
167 d = json.loads(outbuf.decode('utf-8'))
168 return [m['name'] for m in d['mons']]
172 ret, outbuf, outs = json_command(cluster_handle, prefix='mds dump',
173 argdict={'format': 'json'})
175 raise RuntimeError('Can\'t contact mon for mds list')
176 d = json.loads(outbuf.decode('utf-8'))
179 for mdsdict in infodict.values():
180 l.append(mdsdict['name'])
185 ret, outbuf, outs = json_command(cluster_handle, prefix='mgr dump',
186 argdict={'format': 'json'})
188 raise RuntimeError('Can\'t contact mon for mgr list')
190 d = json.loads(outbuf.decode('utf-8'))
192 l.append(d['active_name'])
193 for i in d['standbys']:
198 def validate_target(target):
200 this function will return true iff target is a correct
201 target, such as mon.a/osd.2/mds.a/mgr.
203 target: array, likes ['osd', '2']
204 return: bool, or raise RuntimeError
208 # for case "service.id"
209 service_name, service_id = target[0], target[1]
211 if service_name == "mon":
213 elif service_name == "osd":
215 elif service_name == "mds":
217 elif service_name == "mgr":
220 print('WARN: {0} is not a legal service name, should be one of mon/osd/mds/mgr'.format(service_name),
224 if service_id in exist_ids:
227 print('WARN: the service id you provided does not exist. service id should '
228 'be one of {0}.'.format('/'.join(exist_ids)), file=sys.stderr)
231 elif len(target) == 1 and target[0] in ['mgr', 'mon']:
234 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)
238 # these args must be passed to all child programs
241 'client_name': '--name',
242 'cluster': '--cluster',
243 'cephconf': '--conf',
247 def parse_cmdargs(args=None, target=''):
248 # alias: let the line-wrapping be sane
249 AP = argparse.ArgumentParser
251 # format our own help
252 parser = AP(description='Ceph administration tool', add_help=False)
254 parser.add_argument('--completion', action='store_true',
255 help=argparse.SUPPRESS)
257 parser.add_argument('-h', '--help', help='request mon help',
260 parser.add_argument('-c', '--conf', dest='cephconf',
261 help='ceph configuration file')
262 parser.add_argument('-i', '--in-file', dest='input_file',
264 parser.add_argument('-o', '--out-file', dest='output_file',
267 parser.add_argument('--id', '--user', dest='client_id',
268 help='client id for authentication')
269 parser.add_argument('--name', '-n', dest='client_name',
270 help='client name for authentication')
271 parser.add_argument('--cluster', help='cluster name')
273 parser.add_argument('--admin-daemon', dest='admin_socket',
274 help='submit admin-socket commands (\"help\" for help')
275 parser.add_argument('--admin-socket', dest='admin_socket_nope',
276 help='you probably mean --admin-daemon')
278 parser.add_argument('-s', '--status', action='store_true',
279 help='show cluster status')
281 parser.add_argument('-w', '--watch', action='store_true',
282 help='watch live cluster changes')
283 parser.add_argument('--watch-debug', action='store_true',
284 help='watch debug events')
285 parser.add_argument('--watch-info', action='store_true',
286 help='watch info events')
287 parser.add_argument('--watch-sec', action='store_true',
288 help='watch security events')
289 parser.add_argument('--watch-warn', action='store_true',
290 help='watch warn events')
291 parser.add_argument('--watch-error', action='store_true',
292 help='watch error events')
294 parser.add_argument('--version', '-v', action="store_true", help="display version")
295 parser.add_argument('--verbose', action="store_true", help="make verbose")
296 parser.add_argument('--concise', dest='verbose', action="store_false",
297 help="make less verbose")
299 parser.add_argument('-f', '--format', choices=['json', 'json-pretty',
300 'xml', 'xml-pretty', 'plain'], dest='output_format')
302 parser.add_argument('--connect-timeout', dest='cluster_timeout',
304 help='set a timeout for connecting to the cluster')
306 # returns a Namespace with the parsed args, and a list of all extras
307 parsed_args, extras = parser.parse_known_args(args)
309 return parser, parsed_args, extras
313 print('\n', s, '\n', '=' * len(s))
316 def do_basic_help(parser, args):
318 Print basic parser help
319 If the cluster is available, get and print monitor help
321 hdr('General usage:')
323 print_locally_handled_command_help()
326 def print_locally_handled_command_help():
327 hdr("Local commands:")
329 ping <mon.id> Send simple presence/life test to a mon
330 <mon.id> may be 'mon.*' for all mons
331 daemon {type.id|path} <cmd>
332 Same as --admin-daemon, but auto-find admin socket
333 daemonperf {type.id | path} [stat-pats] [priority] [<interval>] [<count>]
334 daemonperf {type.id | path} list|ls [stat-pats] [priority]
335 Get selected perf stats from daemon/admin socket
336 Optional shell-glob comma-delim match string stat-pats
337 Optional selection priority (can abbreviate name):
338 critical, interesting, useful, noninteresting, debug
339 List shows a table of all available stats
340 Run <count> times (default forever),
341 once per <interval> seconds (default 1)
342 """, file=sys.stdout)
345 def do_extended_help(parser, args, target, partial):
346 def help_for_sigs(sigs, partial=None):
347 sys.stdout.write(format_help(parse_json_funcsigs(sigs, 'cli'),
350 def help_for_target(target, partial=None):
351 ret, outbuf, outs = json_command(cluster_handle, target=target,
352 prefix='get_command_descriptions',
355 print("couldn't get command descriptions for {0}: {1} ({2})".
356 format(target, outs, ret), file=sys.stderr)
359 return help_for_sigs(outbuf.decode('utf-8'), partial)
361 assert(cluster_handle.state == "connected")
362 return help_for_target(target, partial)
364 DONTSPLIT = string.ascii_letters + '{[<>]}'
367 def wrap(s, width, indent):
369 generator to transform s into a sequence of strings width or shorter,
370 for wrapping text to a specific column width.
371 Attempt to break on anything but DONTSPLIT characters.
372 indent is amount to indent 2nd-through-nth lines.
374 so "long string long string long string" width=11 indent=1 becomes
375 'long string', ' long string', ' long string' so that it can be printed
388 # no splitting; just possibly indent
395 while (splitpos > 0) and (s[splitpos-1] in DONTSPLIT):
402 # prior result means we're mid-iteration, indent
405 # first time, set leader and width for next
406 leader = ' ' * indent
407 width -= 1 # for subsequent space additions
409 # remove any leading spaces in this chunk of s
410 result += s[:splitpos].lstrip()
418 def format_help(cmddict, partial=None):
420 Formats all the cmdsigs and helptexts from cmddict into a sorted-by-
421 cmdsig 2-column display, with each column wrapped and indented to
422 fit into (terminal_width / 2) characters.
426 for cmd in sorted(cmddict.values(), key=descsort_key):
430 flags = cmd.get('flags', 0)
431 if flags & (FLAG_OBSOLETE | FLAG_DEPRECATED):
433 concise = concise_sig(cmd['sig'])
434 if partial and not concise.startswith(partial):
436 width = Termsize().cols - 1 # 1 for the line between sig and help
437 sig_width = int(width / 2)
438 # make sure width == sig_width + help_width, even (width % 2 > 0)
439 help_width = int(width / 2) + (width % 2)
440 siglines = [l for l in wrap(concise, sig_width, 1)]
441 helplines = [l for l in wrap(cmd['help'], help_width, 1)]
443 # make lists the same length
444 maxlen = max(len(siglines), len(helplines))
445 siglines.extend([''] * (maxlen - len(siglines)))
446 helplines.extend([''] * (maxlen - len(helplines)))
448 # so we can zip them for output
449 for s, h in zip(siglines, helplines):
450 fullusage += '{s:{w}s} {h}\n'.format(s=s, h=h, w=sig_width)
455 def ceph_conf(parsed_args, field, name):
459 args.extend(['--name', name])
461 # add any args in GLOBAL_ARGS
462 for key, val in GLOBAL_ARGS.items():
463 # ignore name in favor of argument name, if any
464 if name and key == 'client_name':
466 if getattr(parsed_args, key):
467 args.extend([val, getattr(parsed_args, key)])
469 args.extend(['--show-config-value', field])
470 p = subprocess.Popen(
472 stdout=subprocess.PIPE,
473 stderr=subprocess.PIPE)
474 outdata, errdata = p.communicate()
476 raise RuntimeError('unable to get conf option %s for %s: %s' % (field, name, errdata))
477 return outdata.rstrip()
481 if sys.stdin.isatty():
484 line = input(PROMPT).rstrip()
485 if line in ['q', 'quit', 'Q', 'exit']:
492 line = sys.stdin.readline()
500 def new_style_command(parsed_args, cmdargs, target, sigdict, inbuf, verbose):
502 Do new-style command dance.
503 target: daemon to receive command: mon (any) or osd.N
504 sigdict - the parsed output from the new monitor describing commands
505 inbuf - any -i input file data
509 for cmdtag in sorted(sigdict.keys()):
510 cmd = sigdict[cmdtag]
512 print('{0}: {1}'.format(cmdtag, concise_sig(sig)))
516 # Validate input args against list of sigs
517 valid_dict = validate_command(sigdict, cmdargs, verbose)
519 if parsed_args.output_format:
520 valid_dict['format'] = parsed_args.output_format
522 return -errno.EINVAL, '', 'invalid command'
524 if sys.stdin.isatty():
525 # do the command-interpreter looping
526 # for input to do readline cmd editing
527 import readline # noqa
530 interactive_input = read_input()
531 if interactive_input is None:
533 cmdargs = parse_cmdargs(shlex.split(interactive_input))[2]
535 target = find_cmd_target(cmdargs)
536 except Exception as e:
537 print('error handling command target: {0}'.format(e),
540 if len(cmdargs) and cmdargs[0] == 'tell':
541 print('Can not use \'tell\' in interactive mode.',
544 valid_dict = validate_command(sigdict, cmdargs, verbose)
546 if parsed_args.output_format:
547 valid_dict['format'] = parsed_args.output_format
549 print("Submitting command: ", valid_dict, file=sys.stderr)
550 ret, outbuf, outs = json_command(cluster_handle,
555 print('Error: {0} {1}'.format(ret, errno.errorcode.get(ret, 'Unknown')),
560 print('Status:\n', outs, file=sys.stderr)
562 print("Invalid command", file=sys.stderr)
565 print("Submitting command: ", valid_dict, file=sys.stderr)
566 return json_command(cluster_handle, target=target, argdict=valid_dict,
570 def complete(sigdict, args, target):
572 Command completion. Match as much of [args] as possible,
573 and print every possible match separated by newlines.
576 # XXX this looks a lot like the front of validate_command(). Refactor?
578 complete_verbose = 'COMPVERBOSE' in os.environ
580 # Repulsive hack to handle tell: lop off 'tell' and target
581 # and validate the rest of the command. 'target' is already
582 # determined in our callers, so it's ok to remove it here.
583 if len(args) and args[0] == 'tell':
585 # look for best match, accumulate possibles in bestcmds
586 # (so we can maybe give a more-useful error message)
590 for cmdtag, cmd in sigdict.items():
593 # iterate over all arguments, except last one
594 for arg in args[0:-1]:
596 # an out of argument definitions
598 found_match = arg in sig[j].complete(arg)
599 if not found_match and sig[j].req:
600 # no elements that match
605 # successfully matched all - except last one - arguments
606 if j < len(sig) and len(args) > 0:
607 comps += sig[j].complete(args[-1])
612 if match_count == 1 and len(comps) == 0:
613 # only one command matched and no hints yet => add help
614 comps = comps + [' ', '#'+match_cmd['help']]
615 print('\n'.join(sorted(set(comps))))
619 def ping_monitor(cluster_handle, name, timeout):
620 if 'mon.' not in name:
621 print('"ping" expects a monitor to ping; try "ping mon.<id>"', file=sys.stderr)
624 mon_id = name[len('mon.'):]
626 run_in_thread(cluster_handle.connect, timeout=timeout)
628 s = run_in_thread(cluster_handle.ping_monitor, m)
630 print("mon.{0}".format(m) + '\n' + "Error connecting to monitor.")
632 print("mon.{0}".format(m) + '\n' + s)
634 s = run_in_thread(cluster_handle.ping_monitor, mon_id)
639 def maybe_daemon_command(parsed_args, childargs):
641 Check if --admin-socket, daemon, or daemonperf command
642 if it is, returns (boolean handled, return code if handled == True)
647 if parsed_args.admin_socket:
648 sockpath = parsed_args.admin_socket
649 elif len(childargs) > 0 and childargs[0] in ["daemon", "daemonperf"]:
650 daemon_perf = (childargs[0] == "daemonperf")
651 # Treat "daemon <path>" or "daemon <name>" like --admin_daemon <path>
652 # Handle "daemonperf <path>" the same but requires no trailing args
653 require_args = 2 if daemon_perf else 3
654 if len(childargs) >= require_args:
655 if childargs[1].find('/') >= 0:
656 sockpath = childargs[1]
658 # try resolve daemon name
660 sockpath = ceph_conf(parsed_args, 'admin_socket',
662 except Exception as e:
663 print('Can\'t get admin socket path: ' + str(e), file=sys.stderr)
664 return True, errno.EINVAL
666 childargs = childargs[2:]
668 print('{0} requires at least {1} arguments'.format(childargs[0], require_args),
670 return True, errno.EINVAL
672 if sockpath and daemon_perf:
673 return True, daemonperf(childargs, sockpath)
676 raw_write(admin_socket(sockpath, childargs, parsed_args.output_format))
677 except Exception as e:
678 print('admin_socket: {0}'.format(e), file=sys.stderr)
679 return True, errno.EINVAL
693 def daemonperf(childargs, sockpath):
695 Handle daemonperf command; returns errno or 0
697 daemonperf <daemon> [priority string] [statpats] [interval] [count]
698 daemonperf <daemon> list|ls [statpats]
707 def prio_from_name(arg):
710 'critical': PRIO_CRITICAL,
711 'interesting': PRIO_INTERESTING,
712 'useful': PRIO_USEFUL,
713 'uninteresting': PRIO_UNINTERESTING,
714 'debugonly': PRIO_DEBUGONLY,
720 for name, val in PRIOMAP.items():
721 if name.startswith(arg):
725 # consume and analyze non-numeric args
726 while len(childargs) and not isnum(childargs[0]):
727 arg = childargs.pop(0)
729 if arg in ['list', 'ls']:
733 prio = prio_from_name(arg)
738 statpats = arg.split(',')
741 priority = PRIO_DEFAULT
743 if len(childargs) > 0:
745 interval = float(childargs.pop(0))
749 print('daemonperf: interval should be a positive number', file=sys.stderr)
752 if len(childargs) > 0:
753 arg = childargs.pop(0)
754 if (not isnum(arg)) or (int(arg) < 0):
755 print('daemonperf: count should be a positive integer', file=sys.stderr)
759 watcher = DaemonWatcher(sockpath, statpats, priority)
763 watcher.run(interval, count)
769 ceph_args = os.environ.get('CEPH_ARGS')
771 if "injectargs" in sys.argv:
772 i = sys.argv.index("injectargs")
773 sys.argv = sys.argv[:i] + ceph_args.split() + sys.argv[i:]
775 sys.argv.extend(ceph_args.split())
776 parser, parsed_args, childargs = parse_cmdargs()
778 if parsed_args.version:
779 print('ceph version {0} ({1}) {2} ({3})'.format(
783 CEPH_RELEASE_TYPE)) # noqa
787 verbose = parsed_args.verbose
790 print("parsed_args: {0}, childargs: {1}".format(parsed_args, childargs), file=sys.stderr)
792 if parsed_args.admin_socket_nope:
793 print('--admin-socket is used by daemons; '
794 'you probably mean --admin-daemon/daemon', file=sys.stderr)
797 # pass on --id, --name, --conf
798 name = 'client.admin'
799 if parsed_args.client_id:
800 name = 'client.' + parsed_args.client_id
801 if parsed_args.client_name:
802 name = parsed_args.client_name
804 # default '' means default conf search
806 if parsed_args.cephconf:
807 conffile = parsed_args.cephconf
808 # For now, --admin-daemon is handled as usual. Try it
809 # first in case we can't connect() to the cluster
811 format = parsed_args.output_format
813 done, ret = maybe_daemon_command(parsed_args, childargs)
818 if parsed_args.cluster_timeout:
819 timeout = parsed_args.cluster_timeout
823 do_basic_help(parser, childargs)
825 # handle any 'generic' ceph arguments that we didn't parse here
826 global cluster_handle
828 # rados.Rados() will call rados_create2, and then read the conf file,
829 # and then set the keys from the dict. So we must do these
830 # "pre-file defaults" first (see common_preinit in librados)
832 'log_to_stderr': 'true',
833 'err_to_stderr': 'true',
834 'log_flush_on_exit': 'true',
837 if 'injectargs' in childargs:
838 position = childargs.index('injectargs')
839 injectargs = childargs[position:]
840 childargs = childargs[:position]
842 print('Separate childargs {0} from injectargs {1}'.format(childargs, injectargs),
848 if parsed_args.cluster:
849 clustername = parsed_args.cluster
852 cluster_handle = run_in_thread(rados.Rados,
853 name=name, clustername=clustername,
854 conf_defaults=conf_defaults,
856 retargs = run_in_thread(cluster_handle.conf_parse_argv, childargs)
857 except rados.Error as e:
858 print('Error initializing cluster client: {0!r}'.format(e), file=sys.stderr)
865 # -- means "stop parsing args", but we don't want to see it either
866 if '--' in childargs:
867 childargs.remove('--')
868 if injectargs and '--' in injectargs:
869 injectargs.remove('--')
871 # special deprecation warning for 'ceph <type> tell'
872 # someday 'mds' will be here too
873 if (len(childargs) >= 2 and
874 childargs[0] in ['mon', 'osd'] and
875 childargs[1] == 'tell'):
876 print('"{0} tell" is deprecated; try "tell {0}.<id> <command> [options...]" instead (id can be "*") '.format(childargs[0]),
881 # short default timeout for -h
885 hdr('Monitor commands:')
886 print('[Contacting monitor, timeout after %d seconds]' % timeout)
888 if childargs and childargs[0] == 'ping':
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':
897 return ping_monitor(cluster_handle, childargs[1], timeout)
898 run_in_thread(cluster_handle.connect, timeout=timeout)
899 except KeyboardInterrupt:
900 print('Cluster connection aborted', file=sys.stderr)
902 except rados.PermissionDeniedError as e:
903 print(str(e), file=sys.stderr)
905 except Exception as e:
906 print(str(e), file=sys.stderr)
909 return do_extended_help(parser, childargs, ('mon', ''), ' '.join(childargs))
911 # implement "tell service.id help"
912 if len(childargs) >= 3 and childargs[0] == 'tell' and childargs[2] == 'help':
913 target = childargs[1].split('.')
914 if validate_target(target):
915 return do_extended_help(parser, childargs, target, None)
917 print('target {0} doesn\'t exists, please pass correct target to tell command, such as mon.a/'
918 'osd.1/mds.a/mgr'.format(childargs[1]), file=sys.stderr)
920 # implement -w/--watch_*
921 # This is ugly, but Namespace() isn't quite rich enough.
923 for k, v in parsed_args._get_kwargs():
924 if k.startswith('watch') and v:
928 level = k.replace('watch_', '')
931 # an awfully simple callback
932 def watch_cb(arg, line, who, stamp_sec, stamp_nsec, seq, level, msg):
936 # first do a ceph status
937 ret, outbuf, outs = json_command(cluster_handle, prefix='status')
939 print("status query failed: ", outs, file=sys.stderr)
943 # this instance keeps the watch connection alive, but is
945 run_in_thread(cluster_handle.monitor_log, level, watch_cb, 0)
947 # loop forever letting watch_cb print lines
950 except KeyboardInterrupt:
951 # or until ^C, at least
954 # read input file, if any
956 if parsed_args.input_file:
958 with open(parsed_args.input_file, 'rb') as f:
960 except Exception as e:
961 print('Can\'t open input file {0}: {1}'.format(parsed_args.input_file, e), file=sys.stderr)
964 # prepare output file, if any
965 if parsed_args.output_file:
967 outf = open(parsed_args.output_file, 'wb')
968 except Exception as e:
969 print('Can\'t open output file {0}: {1}'.format(parsed_args.output_file, e), file=sys.stderr)
972 # -s behaves like a command (ceph status).
973 if parsed_args.status:
974 childargs.insert(0, 'status')
977 target = find_cmd_target(childargs)
978 except Exception as e:
979 print('error handling command target: {0}'.format(e), file=sys.stderr)
982 # Repulsive hack to handle tell: lop off 'tell' and target
983 # and validate the rest of the command. 'target' is already
984 # determined in our callers, so it's ok to remove it here.
986 if len(childargs) and childargs[0] == 'tell':
987 childargs = childargs[2:]
992 childargs = injectargs
993 if not len(childargs):
994 print('"{0} tell" requires additional arguments.'.format(sys.argv[0]),
995 'Try "{0} tell <name> <command> [options...]" instead.'.format(sys.argv[0]),
999 # fetch JSON sigs from command
1000 # each line contains one command signature (a placeholder name
1001 # of the form 'cmdNNN' followed by an array of argument descriptors)
1002 # as part of the validated argument JSON object
1006 if target[1] == '*':
1007 if target[0] == 'osd':
1008 targets = [(target[0], o) for o in osdids()]
1009 elif target[0] == 'mon':
1010 targets = [(target[0], m) for m in monids()]
1013 for target in targets:
1014 # prettify? prefix output with target, if there was a wildcard used
1017 if not parsed_args.output_file and len(targets) > 1:
1018 prefix = '{0}.{1}: '.format(*target)
1021 ret, outbuf, outs = json_command(cluster_handle, target=target,
1022 prefix='get_command_descriptions')
1024 where = '{0}.{1}'.format(*target)
1026 raise RuntimeError('Unexpeceted return code from {0}: {1}'.
1028 outs = 'problem getting command descriptions from {0}'.format(where)
1030 sigdict = parse_json_funcsigs(outbuf.decode('utf-8'), 'cli')
1032 if parsed_args.completion:
1033 return complete(sigdict, childargs, target)
1035 ret, outbuf, outs = new_style_command(parsed_args, childargs,
1036 target, sigdict, inbuf,
1039 # debug tool: send any successful command *again* to
1040 # verify that it is idempotent.
1041 if not ret and 'CEPH_CLI_TEST_DUP_COMMAND' in os.environ:
1042 ret, outbuf, outs = new_style_command(parsed_args, childargs,
1043 target, sigdict, inbuf,
1048 'Second attempt of previously successful command '
1049 'failed with {0}: {1}'.format(
1050 errno.errorcode.get(ret, 'Unknown'), outs),
1055 errstr = errno.errorcode.get(ret, 'Unknown')
1056 print(u'Error {0}: {1}'.format(errstr, outs), file=sys.stderr)
1057 if len(targets) > 1:
1063 print(prefix + outs, file=sys.stderr)
1067 if parsed_args.output_file:
1070 # hack: old code printed status line before many json outputs
1071 # (osd dump, etc.) that consumers know to ignore. Add blank line
1072 # to satisfy consumers that skip the first line, but not annoy
1073 # consumers that don't.
1074 if parsed_args.output_format and \
1075 parsed_args.output_format.startswith('json'):
1078 # if we are prettifying things, normalize newlines. sigh.
1080 outbuf = outbuf.rstrip()
1083 print(prefix, end='')
1084 # Write directly to binary stdout
1086 print(suffix, end='')
1087 except IOError as e:
1088 if e.errno != errno.EPIPE:
1093 if parsed_args.output_file:
1101 if __name__ == '__main__':
1103 # shutdown explicitly; Rados() does not
1105 run_in_thread(cluster_handle.shutdown)