]> git.proxmox.com Git - ceph.git/blame - ceph/src/ceph.in
update sources to v12.1.3
[ceph.git] / ceph / src / ceph.in
CommitLineData
7c673cae
FG
1#!@PYTHON_EXECUTABLE@
2# -*- mode:python -*-
3# vim: ts=4 sw=4 smarttab expandtab
4#
5# Processed in Makefile to add python #! line and version variable
6#
7#
8
9
10"""
11ceph.in becomes ceph, the command-line management tool for Ceph clusters.
12This is a replacement for tools/ceph.cc and tools/common.cc.
13
14Copyright (C) 2013 Inktank Storage, Inc.
15
16This is free software; you can redistribute it and/or
17modify it under the terms of the GNU General Public
18License version 2, as published by the Free Software
19Foundation. See file COPYING.
20"""
21
22from __future__ import print_function
23import codecs
24import os
25import sys
26import platform
27
28try:
29 input = raw_input
30except NameError:
31 pass
32
31f18b77
FG
33CEPH_GIT_VER = "@CEPH_GIT_VER@"
34CEPH_GIT_NICE_VER = "@CEPH_GIT_NICE_VER@"
35CEPH_RELEASE = "@CEPH_RELEASE@"
36CEPH_RELEASE_NAME = "@CEPH_RELEASE_NAME@"
37CEPH_RELEASE_TYPE = "@CEPH_RELEASE_TYPE@"
7c673cae
FG
38
39# Flags from src/mon/Monitor.h
31f18b77
FG
40FLAG_NOFORWARD = (1 << 0)
41FLAG_OBSOLETE = (1 << 1)
7c673cae
FG
42FLAG_DEPRECATED = (1 << 2)
43
44# priorities from src/common/perf_counters.h
45PRIO_CRITICAL = 10
46PRIO_INTERESTING = 8
47PRIO_USEFUL = 5
48PRIO_UNINTERESTING = 2
49PRIO_DEBUGONLY = 0
50
51PRIO_DEFAULT = PRIO_USEFUL
52
53# Make life easier on developers:
224ce89b
WB
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.
7c673cae
FG
60
61MYPATH = os.path.abspath(__file__)
62MYDIR = os.path.dirname(MYPATH)
224ce89b 63MYPDIR = os.path.dirname(MYDIR)
7c673cae
FG
64DEVMODEMSG = '*** DEVELOPER MODE: setting PATH, PYTHONPATH and LD_LIBRARY_PATH ***'
65
31f18b77 66
7c673cae
FG
67def respawn_in_path(lib_path, pybind_path, pythonlib_path):
68 execv_cmd = ['python']
69 if 'CEPH_DBG' in os.environ:
70 execv_cmd += ['-mpdb']
71
72 if platform.system() == "Darwin":
73 lib_path_var = "DYLD_LIBRARY_PATH"
74 else:
75 lib_path_var = "LD_LIBRARY_PATH"
76
77 py_binary = os.environ.get("PYTHON", "python")
78
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
31f18b77
FG
82 if "CEPH_DEV" not in os.environ:
83 print(DEVMODEMSG, file=sys.stderr)
7c673cae
FG
84 os.execvp(py_binary, execv_cmd + sys.argv)
85 else:
86 os.environ[lib_path_var] = lib_path
31f18b77
FG
87 if "CEPH_DEV" not in os.environ:
88 print(DEVMODEMSG, file=sys.stderr)
7c673cae
FG
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))
92
31f18b77 93
7c673cae
FG
94def get_pythonlib_dir():
95 """Returns the name of a distutils build directory"""
96 return "lib.{version[0]}".format(version=sys.version_info)
97
224ce89b
WB
98if os.path.exists(os.path.join(MYPDIR, "CMakeCache.txt")) \
99 and os.path.exists(os.path.join(MYPDIR, "bin/init-ceph")):
7c673cae 100 src_path = None
224ce89b 101 for l in open(os.path.join(MYPDIR, "CMakeCache.txt")):
7c673cae
FG
102 if l.startswith("ceph_SOURCE_DIR:STATIC="):
103 src_path = l.split("=")[1].strip()
104
7c673cae
FG
105 if src_path is None:
106 # Huh, maybe we're not really in a cmake environment?
107 pass
108 else:
109 # Developer mode, but in a cmake build dir instead of the src dir
224ce89b
WB
110 lib_path = os.path.join(MYPDIR, "lib")
111 bin_path = os.path.join(MYPDIR, "bin")
7c673cae
FG
112 pybind_path = os.path.join(src_path, "src", "pybind")
113 pythonlib_path = os.path.join(lib_path,
114 "cython_modules",
115 get_pythonlib_dir())
116
117 respawn_in_path(lib_path, pybind_path, pythonlib_path)
118
119 if 'PATH' in os.environ and bin_path not in os.environ['PATH']:
120 os.environ['PATH'] += ':' + bin_path
121
122import argparse
123import errno
124import json
125import rados
126import shlex
127import signal
128import string
129import subprocess
130
131from 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
135
31f18b77 136from ceph_daemon import admin_socket, DaemonWatcher, Termsize
7c673cae
FG
137
138# just a couple of globals
139
140verbose = False
141cluster_handle = None
142
143# Always use Unicode (UTF-8) for stdout
144if sys.version_info[0] >= 3:
145 raw_stdout = sys.stdout.buffer
146 raw_stderr = sys.stderr.buffer
147else:
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)
152
31f18b77 153
7c673cae
FG
154def raw_write(buf):
155 sys.stdout.flush()
156 raw_stdout.write(buf)
157
7c673cae
FG
158
159def osdids():
160 ret, outbuf, outs = json_command(cluster_handle, prefix='osd ls')
7c673cae
FG
161 if ret:
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]
164
31f18b77 165
7c673cae
FG
166def monids():
167 ret, outbuf, outs = json_command(cluster_handle, prefix='mon dump',
31f18b77 168 argdict={'format': 'json'})
7c673cae
FG
169 if ret:
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']]
173
31f18b77 174
7c673cae
FG
175def mdsids():
176 ret, outbuf, outs = json_command(cluster_handle, prefix='mds dump',
31f18b77 177 argdict={'format': 'json'})
7c673cae
FG
178 if ret:
179 raise RuntimeError('Can\'t contact mon for mds list')
180 d = json.loads(outbuf.decode('utf-8'))
181 l = []
182 infodict = d['info']
183 for mdsdict in infodict.values():
184 l.append(mdsdict['name'])
185 return l
186
31f18b77
FG
187
188def mgrids():
189 ret, outbuf, outs = json_command(cluster_handle, prefix='mgr dump',
190 argdict={'format': 'json'})
191 if ret:
192 raise RuntimeError('Can\'t contact mon for mgr list')
193
194 d = json.loads(outbuf.decode('utf-8'))
195 l = []
196 l.append(d['active_name'])
197 for i in d['standbys']:
198 l.append(i['name'])
199 return l
200
201
202def validate_target(target):
203 """
204 this function will return true iff target is a correct
205 target, such as mon.a/osd.2/mds.a/mgr.
206
207 target: array, likes ['osd', '2']
208 return: bool, or raise RuntimeError
209 """
210
211 if len(target) == 2:
212 # for case "service.id"
213 service_name, service_id = target[0], target[1]
214 exist_ids = []
215 if service_name == "mon":
216 exist_ids = monids()
217 elif service_name == "osd":
218 exist_ids = osdids()
219 elif service_name == "mds":
220 exist_ids = mdsids()
221 elif service_name == "mgr":
222 exist_ids = mgrids()
223 else:
224 print('WARN: {0} is not a legal service name, should be one of mon/osd/mds/mgr'.format(service_name),
225 file=sys.stderr)
226 return False
227
228 if service_id in exist_ids:
229 return True
230 else:
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)
233 return False
234
235 elif len(target) == 1 and target[0] in ['mgr', 'mon']:
236 return True
237 else:
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)
239 return False
240
241
7c673cae
FG
242# these args must be passed to all child programs
243GLOBAL_ARGS = {
244 'client_id': '--id',
245 'client_name': '--name',
246 'cluster': '--cluster',
247 'cephconf': '--conf',
248}
249
31f18b77 250
7c673cae
FG
251def parse_cmdargs(args=None, target=''):
252 # alias: let the line-wrapping be sane
253 AP = argparse.ArgumentParser
254
255 # format our own help
256 parser = AP(description='Ceph administration tool', add_help=False)
257
258 parser.add_argument('--completion', action='store_true',
259 help=argparse.SUPPRESS)
260
261 parser.add_argument('-h', '--help', help='request mon help',
262 action='store_true')
263
264 parser.add_argument('-c', '--conf', dest='cephconf',
265 help='ceph configuration file')
266 parser.add_argument('-i', '--in-file', dest='input_file',
c07f9fc5 267 help='input file, or "-" for stdin')
7c673cae 268 parser.add_argument('-o', '--out-file', dest='output_file',
c07f9fc5 269 help='output file, or "-" for stdout')
7c673cae
FG
270
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')
276
277 parser.add_argument('--admin-daemon', dest='admin_socket',
278 help='submit admin-socket commands (\"help\" for help')
7c673cae
FG
279
280 parser.add_argument('-s', '--status', action='store_true',
281 help='show cluster status')
282
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')
295
224ce89b
WB
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', '*'",
299 default='cluster')
300
7c673cae
FG
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")
305
306 parser.add_argument('-f', '--format', choices=['json', 'json-pretty',
307 'xml', 'xml-pretty', 'plain'], dest='output_format')
308
309 parser.add_argument('--connect-timeout', dest='cluster_timeout',
310 type=int,
311 help='set a timeout for connecting to the cluster')
312
313 # returns a Namespace with the parsed args, and a list of all extras
314 parsed_args, extras = parser.parse_known_args(args)
315
316 return parser, parsed_args, extras
317
318
319def hdr(s):
320 print('\n', s, '\n', '=' * len(s))
321
31f18b77 322
7c673cae
FG
323def do_basic_help(parser, args):
324 """
325 Print basic parser help
326 If the cluster is available, get and print monitor help
327 """
328 hdr('General usage:')
329 parser.print_help()
330 print_locally_handled_command_help()
331
31f18b77 332
7c673cae
FG
333def print_locally_handled_command_help():
334 hdr("Local commands:")
335 print("""
336ping <mon.id> Send simple presence/life test to a mon
337 <mon.id> may be 'mon.*' for all mons
338daemon {type.id|path} <cmd>
339 Same as --admin-daemon, but auto-find admin socket
340daemonperf {type.id | path} [stat-pats] [priority] [<interval>] [<count>]
341daemonperf {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)
350
351
31f18b77 352def do_extended_help(parser, args, target, partial):
7c673cae
FG
353 def help_for_sigs(sigs, partial=None):
354 sys.stdout.write(format_help(parse_json_funcsigs(sigs, 'cli'),
355 partial=partial))
356
357 def help_for_target(target, partial=None):
d2e6a577
FG
358 # wait for osdmap because we know this is sent after the mgrmap
359 # and monmap (it's alphabetical).
360 cluster_handle.wait_for_latest_osdmap()
7c673cae
FG
361 ret, outbuf, outs = json_command(cluster_handle, target=target,
362 prefix='get_command_descriptions',
363 timeout=10)
364 if ret:
31f18b77
FG
365 print("couldn't get command descriptions for {0}: {1} ({2})".
366 format(target, outs, ret), file=sys.stderr)
367 return ret
7c673cae 368 else:
31f18b77 369 return help_for_sigs(outbuf.decode('utf-8'), partial)
7c673cae 370
31f18b77
FG
371 assert(cluster_handle.state == "connected")
372 return help_for_target(target, partial)
7c673cae
FG
373
374DONTSPLIT = string.ascii_letters + '{[<>]}'
375
31f18b77 376
7c673cae
FG
377def wrap(s, width, indent):
378 """
379 generator to transform s into a sequence of strings width or shorter,
380 for wrapping text to a specific column width.
381 Attempt to break on anything but DONTSPLIT characters.
382 indent is amount to indent 2nd-through-nth lines.
383
384 so "long string long string long string" width=11 indent=1 becomes
385 'long string', ' long string', ' long string' so that it can be printed
386 as
387 long string
388 long string
389 long string
390
391 Consumes s.
392 """
393 result = ''
394 leader = ''
395 while len(s):
396
31f18b77 397 if len(s) <= width:
7c673cae
FG
398 # no splitting; just possibly indent
399 result = leader + s
400 s = ''
401 yield result
402
403 else:
404 splitpos = width
405 while (splitpos > 0) and (s[splitpos-1] in DONTSPLIT):
406 splitpos -= 1
407
408 if splitpos == 0:
409 splitpos = width
410
411 if result:
412 # prior result means we're mid-iteration, indent
413 result = leader
414 else:
415 # first time, set leader and width for next
416 leader = ' ' * indent
417 width -= 1 # for subsequent space additions
418
419 # remove any leading spaces in this chunk of s
420 result += s[:splitpos].lstrip()
421 s = s[splitpos:]
422
423 yield result
424
425 raise StopIteration
426
31f18b77 427
7c673cae
FG
428def format_help(cmddict, partial=None):
429 """
430 Formats all the cmdsigs and helptexts from cmddict into a sorted-by-
431 cmdsig 2-column display, with each column wrapped and indented to
31f18b77 432 fit into (terminal_width / 2) characters.
7c673cae
FG
433 """
434
435 fullusage = ''
436 for cmd in sorted(cmddict.values(), key=descsort_key):
437
438 if not cmd['help']:
439 continue
31f18b77
FG
440 flags = cmd.get('flags', 0)
441 if flags & (FLAG_OBSOLETE | FLAG_DEPRECATED):
7c673cae
FG
442 continue
443 concise = concise_sig(cmd['sig'])
444 if partial and not concise.startswith(partial):
445 continue
31f18b77
FG
446 width = Termsize().cols - 1 # 1 for the line between sig and help
447 sig_width = int(width / 2)
448 # make sure width == sig_width + help_width, even (width % 2 > 0)
449 help_width = int(width / 2) + (width % 2)
450 siglines = [l for l in wrap(concise, sig_width, 1)]
451 helplines = [l for l in wrap(cmd['help'], help_width, 1)]
7c673cae
FG
452
453 # make lists the same length
454 maxlen = max(len(siglines), len(helplines))
455 siglines.extend([''] * (maxlen - len(siglines)))
456 helplines.extend([''] * (maxlen - len(helplines)))
457
458 # so we can zip them for output
31f18b77
FG
459 for s, h in zip(siglines, helplines):
460 fullusage += '{s:{w}s} {h}\n'.format(s=s, h=h, w=sig_width)
7c673cae
FG
461
462 return fullusage
463
464
465def ceph_conf(parsed_args, field, name):
31f18b77 466 args = ['ceph-conf']
7c673cae
FG
467
468 if name:
469 args.extend(['--name', name])
470
471 # add any args in GLOBAL_ARGS
472 for key, val in GLOBAL_ARGS.items():
473 # ignore name in favor of argument name, if any
474 if name and key == 'client_name':
475 continue
476 if getattr(parsed_args, key):
477 args.extend([val, getattr(parsed_args, key)])
478
479 args.extend(['--show-config-value', field])
480 p = subprocess.Popen(
481 args,
482 stdout=subprocess.PIPE,
483 stderr=subprocess.PIPE)
484 outdata, errdata = p.communicate()
31f18b77 485 if len(errdata):
7c673cae
FG
486 raise RuntimeError('unable to get conf option %s for %s: %s' % (field, name, errdata))
487 return outdata.rstrip()
488
489PROMPT = 'ceph> '
490
491if sys.stdin.isatty():
492 def read_input():
493 while True:
494 line = input(PROMPT).rstrip()
495 if line in ['q', 'quit', 'Q', 'exit']:
496 return None
497 if line:
498 return line
499else:
500 def read_input():
501 while True:
502 line = sys.stdin.readline()
503 if not line:
504 return None
505 line = line.rstrip()
506 if line:
507 return line
508
509
510def new_style_command(parsed_args, cmdargs, target, sigdict, inbuf, verbose):
511 """
512 Do new-style command dance.
513 target: daemon to receive command: mon (any) or osd.N
514 sigdict - the parsed output from the new monitor describing commands
515 inbuf - any -i input file data
516 verbose - bool
517 """
518 if verbose:
519 for cmdtag in sorted(sigdict.keys()):
520 cmd = sigdict[cmdtag]
521 sig = cmd['sig']
522 print('{0}: {1}'.format(cmdtag, concise_sig(sig)))
523
524 if True:
525 if cmdargs:
526 # Validate input args against list of sigs
527 valid_dict = validate_command(sigdict, cmdargs, verbose)
528 if valid_dict:
529 if parsed_args.output_format:
530 valid_dict['format'] = parsed_args.output_format
531 else:
532 return -errno.EINVAL, '', 'invalid command'
533 else:
534 if sys.stdin.isatty():
535 # do the command-interpreter looping
536 # for input to do readline cmd editing
537 import readline # noqa
538
539 while True:
540 interactive_input = read_input()
541 if interactive_input is None:
542 return 0, '', ''
543 cmdargs = parse_cmdargs(shlex.split(interactive_input))[2]
544 try:
545 target = find_cmd_target(cmdargs)
546 except Exception as e:
31f18b77
FG
547 print('error handling command target: {0}'.format(e),
548 file=sys.stderr)
7c673cae
FG
549 continue
550 if len(cmdargs) and cmdargs[0] == 'tell':
31f18b77
FG
551 print('Can not use \'tell\' in interactive mode.',
552 file=sys.stderr)
7c673cae
FG
553 continue
554 valid_dict = validate_command(sigdict, cmdargs, verbose)
555 if valid_dict:
556 if parsed_args.output_format:
557 valid_dict['format'] = parsed_args.output_format
558 if verbose:
559 print("Submitting command: ", valid_dict, file=sys.stderr)
560 ret, outbuf, outs = json_command(cluster_handle,
561 target=target,
562 argdict=valid_dict)
563 if ret:
564 ret = abs(ret)
31f18b77
FG
565 print('Error: {0} {1}'.format(ret, errno.errorcode.get(ret, 'Unknown')),
566 file=sys.stderr)
7c673cae
FG
567 if outbuf:
568 print(outbuf)
569 if outs:
570 print('Status:\n', outs, file=sys.stderr)
571 else:
572 print("Invalid command", file=sys.stderr)
573
574 if verbose:
575 print("Submitting command: ", valid_dict, file=sys.stderr)
576 return json_command(cluster_handle, target=target, argdict=valid_dict,
577 inbuf=inbuf)
578
579
580def complete(sigdict, args, target):
581 """
582 Command completion. Match as much of [args] as possible,
583 and print every possible match separated by newlines.
584 Return exitcode.
585 """
586 # XXX this looks a lot like the front of validate_command(). Refactor?
587
588 complete_verbose = 'COMPVERBOSE' in os.environ
589
590 # Repulsive hack to handle tell: lop off 'tell' and target
591 # and validate the rest of the command. 'target' is already
592 # determined in our callers, so it's ok to remove it here.
593 if len(args) and args[0] == 'tell':
594 args = args[2:]
595 # look for best match, accumulate possibles in bestcmds
596 # (so we can maybe give a more-useful error message)
597
598 match_count = 0
599 comps = []
600 for cmdtag, cmd in sigdict.items():
601 sig = cmd['sig']
602 j = 0
603 # iterate over all arguments, except last one
604 for arg in args[0:-1]:
605 if j > len(sig)-1:
606 # an out of argument definitions
607 break
608 found_match = arg in sig[j].complete(arg)
609 if not found_match and sig[j].req:
610 # no elements that match
611 break
612 if not sig[j].N:
613 j += 1
614 else:
615 # successfully matched all - except last one - arguments
616 if j < len(sig) and len(args) > 0:
617 comps += sig[j].complete(args[-1])
618
619 match_count += 1
620 match_cmd = cmd
621
622 if match_count == 1 and len(comps) == 0:
623 # only one command matched and no hints yet => add help
624 comps = comps + [' ', '#'+match_cmd['help']]
625 print('\n'.join(sorted(set(comps))))
626 return 0
627
628
7c673cae
FG
629def ping_monitor(cluster_handle, name, timeout):
630 if 'mon.' not in name:
631 print('"ping" expects a monitor to ping; try "ping mon.<id>"', file=sys.stderr)
632 return 1
633
634 mon_id = name[len('mon.'):]
31f18b77 635 if mon_id == '*':
7c673cae 636 run_in_thread(cluster_handle.connect, timeout=timeout)
31f18b77 637 for m in monids():
7c673cae
FG
638 s = run_in_thread(cluster_handle.ping_monitor, m)
639 if s is None:
640 print("mon.{0}".format(m) + '\n' + "Error connecting to monitor.")
641 else:
642 print("mon.{0}".format(m) + '\n' + s)
31f18b77 643 else:
7c673cae
FG
644 s = run_in_thread(cluster_handle.ping_monitor, mon_id)
645 print(s)
646 return 0
647
648
649def maybe_daemon_command(parsed_args, childargs):
650 """
651 Check if --admin-socket, daemon, or daemonperf command
652 if it is, returns (boolean handled, return code if handled == True)
653 """
654
655 daemon_perf = False
656 sockpath = None
657 if parsed_args.admin_socket:
658 sockpath = parsed_args.admin_socket
659 elif len(childargs) > 0 and childargs[0] in ["daemon", "daemonperf"]:
660 daemon_perf = (childargs[0] == "daemonperf")
661 # Treat "daemon <path>" or "daemon <name>" like --admin_daemon <path>
662 # Handle "daemonperf <path>" the same but requires no trailing args
663 require_args = 2 if daemon_perf else 3
664 if len(childargs) >= require_args:
665 if childargs[1].find('/') >= 0:
666 sockpath = childargs[1]
667 else:
668 # try resolve daemon name
669 try:
670 sockpath = ceph_conf(parsed_args, 'admin_socket',
671 childargs[1])
672 except Exception as e:
673 print('Can\'t get admin socket path: ' + str(e), file=sys.stderr)
674 return True, errno.EINVAL
675 # for both:
676 childargs = childargs[2:]
677 else:
31f18b77
FG
678 print('{0} requires at least {1} arguments'.format(childargs[0], require_args),
679 file=sys.stderr)
7c673cae
FG
680 return True, errno.EINVAL
681
682 if sockpath and daemon_perf:
683 return True, daemonperf(childargs, sockpath)
684 elif sockpath:
685 try:
686 raw_write(admin_socket(sockpath, childargs, parsed_args.output_format))
687 except Exception as e:
688 print('admin_socket: {0}'.format(e), file=sys.stderr)
689 return True, errno.EINVAL
690 return True, 0
691
692 return False, 0
693
694
695def isnum(s):
696 try:
697 float(s)
698 return True
699 except ValueError:
700 return False
701
31f18b77 702
7c673cae
FG
703def daemonperf(childargs, sockpath):
704 """
705 Handle daemonperf command; returns errno or 0
706
707 daemonperf <daemon> [priority string] [statpats] [interval] [count]
708 daemonperf <daemon> list|ls [statpats]
709 """
710
711 interval = 1
712 count = None
713 statpats = None
714 priority = None
715 do_list = False
716
717 def prio_from_name(arg):
718
719 PRIOMAP = {
720 'critical': PRIO_CRITICAL,
721 'interesting': PRIO_INTERESTING,
722 'useful': PRIO_USEFUL,
723 'uninteresting': PRIO_UNINTERESTING,
724 'debugonly': PRIO_DEBUGONLY,
725 }
726
727 if arg in PRIOMAP:
728 return PRIOMAP[arg]
729 # allow abbreviation
730 for name, val in PRIOMAP.items():
731 if name.startswith(arg):
732 return val
733 return None
734
735 # consume and analyze non-numeric args
736 while len(childargs) and not isnum(childargs[0]):
737 arg = childargs.pop(0)
738 # 'list'?
739 if arg in ['list', 'ls']:
31f18b77 740 do_list = True
7c673cae
FG
741 continue
742 # prio?
743 prio = prio_from_name(arg)
744 if prio is not None:
745 priority = prio
746 continue
747 # statpats
748 statpats = arg.split(',')
749
750 if priority is None:
751 priority = PRIO_DEFAULT
752
753 if len(childargs) > 0:
754 try:
755 interval = float(childargs.pop(0))
756 if interval < 0:
757 raise ValueError
758 except ValueError:
759 print('daemonperf: interval should be a positive number', file=sys.stderr)
760 return errno.EINVAL
761
762 if len(childargs) > 0:
763 arg = childargs.pop(0)
764 if (not isnum(arg)) or (int(arg) < 0):
765 print('daemonperf: count should be a positive integer', file=sys.stderr)
766 return errno.EINVAL
767 count = int(arg)
768
769 watcher = DaemonWatcher(sockpath, statpats, priority)
770 if do_list:
771 watcher.list()
772 else:
773 watcher.run(interval, count)
774
775 return 0
776
7c673cae
FG
777
778def main():
779 ceph_args = os.environ.get('CEPH_ARGS')
780 if ceph_args:
781 if "injectargs" in sys.argv:
782 i = sys.argv.index("injectargs")
783 sys.argv = sys.argv[:i] + ceph_args.split() + sys.argv[i:]
784 else:
c07f9fc5
FG
785 sys.argv.extend([arg for arg in ceph_args.split()
786 if '--admin-socket' not in arg])
7c673cae
FG
787 parser, parsed_args, childargs = parse_cmdargs()
788
789 if parsed_args.version:
31f18b77
FG
790 print('ceph version {0} ({1}) {2} ({3})'.format(
791 CEPH_GIT_NICE_VER,
792 CEPH_GIT_VER,
793 CEPH_RELEASE_NAME,
794 CEPH_RELEASE_TYPE)) # noqa
7c673cae
FG
795 return 0
796
797 global verbose
798 verbose = parsed_args.verbose
799
800 if verbose:
801 print("parsed_args: {0}, childargs: {1}".format(parsed_args, childargs), file=sys.stderr)
802
7c673cae
FG
803 # pass on --id, --name, --conf
804 name = 'client.admin'
805 if parsed_args.client_id:
806 name = 'client.' + parsed_args.client_id
807 if parsed_args.client_name:
808 name = parsed_args.client_name
809
810 # default '' means default conf search
811 conffile = ''
812 if parsed_args.cephconf:
813 conffile = parsed_args.cephconf
814 # For now, --admin-daemon is handled as usual. Try it
815 # first in case we can't connect() to the cluster
816
817 format = parsed_args.output_format
818
819 done, ret = maybe_daemon_command(parsed_args, childargs)
820 if done:
821 return ret
822
823 timeout = None
824 if parsed_args.cluster_timeout:
825 timeout = parsed_args.cluster_timeout
826
827 # basic help
828 if parsed_args.help:
829 do_basic_help(parser, childargs)
830
831 # handle any 'generic' ceph arguments that we didn't parse here
832 global cluster_handle
833
834 # rados.Rados() will call rados_create2, and then read the conf file,
835 # and then set the keys from the dict. So we must do these
836 # "pre-file defaults" first (see common_preinit in librados)
837 conf_defaults = {
31f18b77
FG
838 'log_to_stderr': 'true',
839 'err_to_stderr': 'true',
840 'log_flush_on_exit': 'true',
7c673cae
FG
841 }
842
843 if 'injectargs' in childargs:
844 position = childargs.index('injectargs')
845 injectargs = childargs[position:]
846 childargs = childargs[:position]
847 if verbose:
31f18b77
FG
848 print('Separate childargs {0} from injectargs {1}'.format(childargs, injectargs),
849 file=sys.stderr)
7c673cae
FG
850 else:
851 injectargs = None
852
853 clustername = None
854 if parsed_args.cluster:
855 clustername = parsed_args.cluster
856
857 try:
858 cluster_handle = run_in_thread(rados.Rados,
859 name=name, clustername=clustername,
860 conf_defaults=conf_defaults,
861 conffile=conffile)
862 retargs = run_in_thread(cluster_handle.conf_parse_argv, childargs)
863 except rados.Error as e:
864 print('Error initializing cluster client: {0!r}'.format(e), file=sys.stderr)
865 return 1
866
867 childargs = retargs
868 if not childargs:
869 childargs = []
870
871 # -- means "stop parsing args", but we don't want to see it either
872 if '--' in childargs:
873 childargs.remove('--')
874 if injectargs and '--' in injectargs:
875 injectargs.remove('--')
876
877 # special deprecation warning for 'ceph <type> tell'
878 # someday 'mds' will be here too
31f18b77
FG
879 if (len(childargs) >= 2 and
880 childargs[0] in ['mon', 'osd'] and
881 childargs[1] == 'tell'):
882 print('"{0} tell" is deprecated; try "tell {0}.<id> <command> [options...]" instead (id can be "*") '.format(childargs[0]),
883 file=sys.stderr)
7c673cae
FG
884 return 1
885
886 if parsed_args.help:
887 # short default timeout for -h
888 if not timeout:
889 timeout = 5
890
224ce89b 891 if childargs and childargs[0] == 'ping' and not parsed_args.help:
7c673cae
FG
892 if len(childargs) < 2:
893 print('"ping" requires a monitor name as argument: "ping mon.<id>"', file=sys.stderr)
894 return 1
895 if parsed_args.completion:
31f18b77 896 # for completion let timeout be really small
7c673cae
FG
897 timeout = 3
898 try:
224ce89b 899 if childargs and childargs[0] == 'ping' and not parsed_args.help:
7c673cae 900 return ping_monitor(cluster_handle, childargs[1], timeout)
224ce89b
WB
901 result = run_in_thread(cluster_handle.connect, timeout=timeout)
902 if type(result) is tuple and result[0] == -errno.EINTR:
903 print('Cluster connection interrupted or timed out', file=sys.stderr)
904 return 1
7c673cae
FG
905 except KeyboardInterrupt:
906 print('Cluster connection aborted', file=sys.stderr)
907 return 1
908 except rados.PermissionDeniedError as e:
909 print(str(e), file=sys.stderr)
910 return errno.EACCES
911 except Exception as e:
912 print(str(e), file=sys.stderr)
913 return 1
224ce89b 914
7c673cae 915 if parsed_args.help:
224ce89b
WB
916 hdr('Monitor commands:')
917 if verbose:
918 print('[Contacting monitor, timeout after %d seconds]' % timeout)
919
31f18b77 920 return do_extended_help(parser, childargs, ('mon', ''), ' '.join(childargs))
7c673cae 921
31f18b77
FG
922 # implement "tell service.id help"
923 if len(childargs) >= 3 and childargs[0] == 'tell' and childargs[2] == 'help':
924 target = childargs[1].split('.')
925 if validate_target(target):
926 return do_extended_help(parser, childargs, target, None)
927 else:
928 print('target {0} doesn\'t exists, please pass correct target to tell command, such as mon.a/'
929 'osd.1/mds.a/mgr'.format(childargs[1]), file=sys.stderr)
930 return 1
7c673cae
FG
931 # implement -w/--watch_*
932 # This is ugly, but Namespace() isn't quite rich enough.
933 level = ''
934 for k, v in parsed_args._get_kwargs():
935 if k.startswith('watch') and v:
936 if k == 'watch':
937 level = 'info'
224ce89b 938 elif k != "watch_channel":
7c673cae
FG
939 level = k.replace('watch_', '')
940 if level:
7c673cae 941 # an awfully simple callback
224ce89b
WB
942 def watch_cb(arg, line, channel, name, who, stamp_sec, stamp_nsec, seq, level, msg):
943 # Filter on channel
944 if (channel == parsed_args.watch_channel or \
945 parsed_args.watch_channel == "*"):
946 print(line)
947 sys.stdout.flush()
7c673cae
FG
948
949 # first do a ceph status
950 ret, outbuf, outs = json_command(cluster_handle, prefix='status')
7c673cae
FG
951 if ret:
952 print("status query failed: ", outs, file=sys.stderr)
953 return ret
954 print(outbuf)
955
956 # this instance keeps the watch connection alive, but is
957 # otherwise unused
224ce89b 958 run_in_thread(cluster_handle.monitor_log2, level, watch_cb, 0)
7c673cae
FG
959
960 # loop forever letting watch_cb print lines
961 try:
962 signal.pause()
963 except KeyboardInterrupt:
964 # or until ^C, at least
965 return 0
966
967 # read input file, if any
968 inbuf = b''
969 if parsed_args.input_file:
970 try:
c07f9fc5
FG
971 if parsed_args.input_file == '-':
972 inbuf = sys.stdin.read()
973 else:
974 with open(parsed_args.input_file, 'rb') as f:
975 inbuf = f.read()
7c673cae
FG
976 except Exception as e:
977 print('Can\'t open input file {0}: {1}'.format(parsed_args.input_file, e), file=sys.stderr)
978 return 1
979
980 # prepare output file, if any
981 if parsed_args.output_file:
982 try:
c07f9fc5
FG
983 if parsed_args.output_file == '-':
984 outf = sys.stdout
985 else:
986 outf = open(parsed_args.output_file, 'wb')
7c673cae
FG
987 except Exception as e:
988 print('Can\'t open output file {0}: {1}'.format(parsed_args.output_file, e), file=sys.stderr)
989 return 1
990
991 # -s behaves like a command (ceph status).
992 if parsed_args.status:
993 childargs.insert(0, 'status')
994
995 try:
996 target = find_cmd_target(childargs)
997 except Exception as e:
998 print('error handling command target: {0}'.format(e), file=sys.stderr)
999 return 1
1000
1001 # Repulsive hack to handle tell: lop off 'tell' and target
1002 # and validate the rest of the command. 'target' is already
1003 # determined in our callers, so it's ok to remove it here.
1004 is_tell = False
1005 if len(childargs) and childargs[0] == 'tell':
1006 childargs = childargs[2:]
1007 is_tell = True
1008
1009 if is_tell:
1010 if injectargs:
1011 childargs = injectargs
1012 if not len(childargs):
1013 print('"{0} tell" requires additional arguments.'.format(sys.argv[0]),
31f18b77
FG
1014 'Try "{0} tell <name> <command> [options...]" instead.'.format(sys.argv[0]),
1015 file=sys.stderr)
7c673cae
FG
1016 return errno.EINVAL
1017
1018 # fetch JSON sigs from command
1019 # each line contains one command signature (a placeholder name
1020 # of the form 'cmdNNN' followed by an array of argument descriptors)
1021 # as part of the validated argument JSON object
1022
1023 targets = [target]
1024
1025 if target[1] == '*':
1026 if target[0] == 'osd':
1027 targets = [(target[0], o) for o in osdids()]
1028 elif target[0] == 'mon':
1029 targets = [(target[0], m) for m in monids()]
1030
1031 final_ret = 0
1032 for target in targets:
1033 # prettify? prefix output with target, if there was a wildcard used
1034 prefix = ''
1035 suffix = ''
1036 if not parsed_args.output_file and len(targets) > 1:
1037 prefix = '{0}.{1}: '.format(*target)
1038 suffix = '\n'
1039
1040 ret, outbuf, outs = json_command(cluster_handle, target=target,
1041 prefix='get_command_descriptions')
31f18b77
FG
1042 if ret:
1043 where = '{0}.{1}'.format(*target)
1044 if ret > 0:
1045 raise RuntimeError('Unexpeceted return code from {0}: {1}'.
1046 format(where, ret))
1047 outs = 'problem getting command descriptions from {0}'.format(where)
1048 else:
1049 sigdict = parse_json_funcsigs(outbuf.decode('utf-8'), 'cli')
7c673cae 1050
31f18b77
FG
1051 if parsed_args.completion:
1052 return complete(sigdict, childargs, target)
7c673cae 1053
31f18b77
FG
1054 ret, outbuf, outs = new_style_command(parsed_args, childargs,
1055 target, sigdict, inbuf,
1056 verbose)
7c673cae 1057
31f18b77
FG
1058 # debug tool: send any successful command *again* to
1059 # verify that it is idempotent.
1060 if not ret and 'CEPH_CLI_TEST_DUP_COMMAND' in os.environ:
1061 ret, outbuf, outs = new_style_command(parsed_args, childargs,
1062 target, sigdict, inbuf,
1063 verbose)
1064 if ret < 0:
1065 ret = -ret
1066 print(prefix +
1067 'Second attempt of previously successful command '
1068 'failed with {0}: {1}'.format(
1069 errno.errorcode.get(ret, 'Unknown'), outs),
1070 file=sys.stderr)
7c673cae
FG
1071
1072 if ret < 0:
1073 ret = -ret
31f18b77
FG
1074 errstr = errno.errorcode.get(ret, 'Unknown')
1075 print(u'Error {0}: {1}'.format(errstr, outs), file=sys.stderr)
7c673cae
FG
1076 if len(targets) > 1:
1077 final_ret = ret
1078 else:
1079 return ret
1080
31f18b77
FG
1081 if outs:
1082 print(prefix + outs, file=sys.stderr)
7c673cae
FG
1083
1084 sys.stdout.flush()
1085
31f18b77 1086 if parsed_args.output_file:
7c673cae
FG
1087 outf.write(outbuf)
1088 else:
1089 # hack: old code printed status line before many json outputs
1090 # (osd dump, etc.) that consumers know to ignore. Add blank line
1091 # to satisfy consumers that skip the first line, but not annoy
1092 # consumers that don't.
1093 if parsed_args.output_format and \
31f18b77 1094 parsed_args.output_format.startswith('json'):
7c673cae
FG
1095 print()
1096
1097 # if we are prettifying things, normalize newlines. sigh.
1098 if suffix:
1099 outbuf = outbuf.rstrip()
1100 if outbuf:
1101 try:
1102 print(prefix, end='')
1103 # Write directly to binary stdout
1104 raw_write(outbuf)
1105 print(suffix, end='')
1106 except IOError as e:
1107 if e.errno != errno.EPIPE:
1108 raise e
1109
1110 sys.stdout.flush()
1111
c07f9fc5 1112 if parsed_args.output_file and parsed_args.output_file != '-':
7c673cae
FG
1113 outf.close()
1114
1115 if final_ret:
1116 return final_ret
1117
1118 return 0
1119
1120if __name__ == '__main__':
1121 retval = main()
1122 # shutdown explicitly; Rados() does not
1123 if cluster_handle:
1124 run_in_thread(cluster_handle.shutdown)
1125 sys.exit(retval)