]> git.proxmox.com Git - ceph.git/blame - ceph/src/ceph.in
update sources to v12.1.1
[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',
267 help='input file')
268 parser.add_argument('-o', '--out-file', dest='output_file',
269 help='output file')
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')
279 parser.add_argument('--admin-socket', dest='admin_socket_nope',
280 help='you probably mean --admin-daemon')
281
282 parser.add_argument('-s', '--status', action='store_true',
283 help='show cluster status')
284
285 parser.add_argument('-w', '--watch', action='store_true',
286 help='watch live cluster changes')
287 parser.add_argument('--watch-debug', action='store_true',
288 help='watch debug events')
289 parser.add_argument('--watch-info', action='store_true',
290 help='watch info events')
291 parser.add_argument('--watch-sec', action='store_true',
292 help='watch security events')
293 parser.add_argument('--watch-warn', action='store_true',
294 help='watch warn events')
295 parser.add_argument('--watch-error', action='store_true',
296 help='watch error events')
297
224ce89b
WB
298 parser.add_argument('--watch-channel', dest="watch_channel",
299 help="which log channel to follow " \
300 "when using -w/--watch. One of ['cluster', 'audit', '*'",
301 default='cluster')
302
7c673cae
FG
303 parser.add_argument('--version', '-v', action="store_true", help="display version")
304 parser.add_argument('--verbose', action="store_true", help="make verbose")
305 parser.add_argument('--concise', dest='verbose', action="store_false",
306 help="make less verbose")
307
308 parser.add_argument('-f', '--format', choices=['json', 'json-pretty',
309 'xml', 'xml-pretty', 'plain'], dest='output_format')
310
311 parser.add_argument('--connect-timeout', dest='cluster_timeout',
312 type=int,
313 help='set a timeout for connecting to the cluster')
314
315 # returns a Namespace with the parsed args, and a list of all extras
316 parsed_args, extras = parser.parse_known_args(args)
317
318 return parser, parsed_args, extras
319
320
321def hdr(s):
322 print('\n', s, '\n', '=' * len(s))
323
31f18b77 324
7c673cae
FG
325def do_basic_help(parser, args):
326 """
327 Print basic parser help
328 If the cluster is available, get and print monitor help
329 """
330 hdr('General usage:')
331 parser.print_help()
332 print_locally_handled_command_help()
333
31f18b77 334
7c673cae
FG
335def print_locally_handled_command_help():
336 hdr("Local commands:")
337 print("""
338ping <mon.id> Send simple presence/life test to a mon
339 <mon.id> may be 'mon.*' for all mons
340daemon {type.id|path} <cmd>
341 Same as --admin-daemon, but auto-find admin socket
342daemonperf {type.id | path} [stat-pats] [priority] [<interval>] [<count>]
343daemonperf {type.id | path} list|ls [stat-pats] [priority]
344 Get selected perf stats from daemon/admin socket
345 Optional shell-glob comma-delim match string stat-pats
346 Optional selection priority (can abbreviate name):
347 critical, interesting, useful, noninteresting, debug
348 List shows a table of all available stats
349 Run <count> times (default forever),
350 once per <interval> seconds (default 1)
351 """, file=sys.stdout)
352
353
31f18b77 354def do_extended_help(parser, args, target, partial):
7c673cae
FG
355 def help_for_sigs(sigs, partial=None):
356 sys.stdout.write(format_help(parse_json_funcsigs(sigs, 'cli'),
357 partial=partial))
358
359 def help_for_target(target, partial=None):
360 ret, outbuf, outs = json_command(cluster_handle, target=target,
361 prefix='get_command_descriptions',
362 timeout=10)
363 if ret:
31f18b77
FG
364 print("couldn't get command descriptions for {0}: {1} ({2})".
365 format(target, outs, ret), file=sys.stderr)
366 return ret
7c673cae 367 else:
31f18b77 368 return help_for_sigs(outbuf.decode('utf-8'), partial)
7c673cae 369
31f18b77
FG
370 assert(cluster_handle.state == "connected")
371 return help_for_target(target, partial)
7c673cae
FG
372
373DONTSPLIT = string.ascii_letters + '{[<>]}'
374
31f18b77 375
7c673cae
FG
376def wrap(s, width, indent):
377 """
378 generator to transform s into a sequence of strings width or shorter,
379 for wrapping text to a specific column width.
380 Attempt to break on anything but DONTSPLIT characters.
381 indent is amount to indent 2nd-through-nth lines.
382
383 so "long string long string long string" width=11 indent=1 becomes
384 'long string', ' long string', ' long string' so that it can be printed
385 as
386 long string
387 long string
388 long string
389
390 Consumes s.
391 """
392 result = ''
393 leader = ''
394 while len(s):
395
31f18b77 396 if len(s) <= width:
7c673cae
FG
397 # no splitting; just possibly indent
398 result = leader + s
399 s = ''
400 yield result
401
402 else:
403 splitpos = width
404 while (splitpos > 0) and (s[splitpos-1] in DONTSPLIT):
405 splitpos -= 1
406
407 if splitpos == 0:
408 splitpos = width
409
410 if result:
411 # prior result means we're mid-iteration, indent
412 result = leader
413 else:
414 # first time, set leader and width for next
415 leader = ' ' * indent
416 width -= 1 # for subsequent space additions
417
418 # remove any leading spaces in this chunk of s
419 result += s[:splitpos].lstrip()
420 s = s[splitpos:]
421
422 yield result
423
424 raise StopIteration
425
31f18b77 426
7c673cae
FG
427def format_help(cmddict, partial=None):
428 """
429 Formats all the cmdsigs and helptexts from cmddict into a sorted-by-
430 cmdsig 2-column display, with each column wrapped and indented to
31f18b77 431 fit into (terminal_width / 2) characters.
7c673cae
FG
432 """
433
434 fullusage = ''
435 for cmd in sorted(cmddict.values(), key=descsort_key):
436
437 if not cmd['help']:
438 continue
31f18b77
FG
439 flags = cmd.get('flags', 0)
440 if flags & (FLAG_OBSOLETE | FLAG_DEPRECATED):
7c673cae
FG
441 continue
442 concise = concise_sig(cmd['sig'])
443 if partial and not concise.startswith(partial):
444 continue
31f18b77
FG
445 width = Termsize().cols - 1 # 1 for the line between sig and help
446 sig_width = int(width / 2)
447 # make sure width == sig_width + help_width, even (width % 2 > 0)
448 help_width = int(width / 2) + (width % 2)
449 siglines = [l for l in wrap(concise, sig_width, 1)]
450 helplines = [l for l in wrap(cmd['help'], help_width, 1)]
7c673cae
FG
451
452 # make lists the same length
453 maxlen = max(len(siglines), len(helplines))
454 siglines.extend([''] * (maxlen - len(siglines)))
455 helplines.extend([''] * (maxlen - len(helplines)))
456
457 # so we can zip them for output
31f18b77
FG
458 for s, h in zip(siglines, helplines):
459 fullusage += '{s:{w}s} {h}\n'.format(s=s, h=h, w=sig_width)
7c673cae
FG
460
461 return fullusage
462
463
464def ceph_conf(parsed_args, field, name):
31f18b77 465 args = ['ceph-conf']
7c673cae
FG
466
467 if name:
468 args.extend(['--name', name])
469
470 # add any args in GLOBAL_ARGS
471 for key, val in GLOBAL_ARGS.items():
472 # ignore name in favor of argument name, if any
473 if name and key == 'client_name':
474 continue
475 if getattr(parsed_args, key):
476 args.extend([val, getattr(parsed_args, key)])
477
478 args.extend(['--show-config-value', field])
479 p = subprocess.Popen(
480 args,
481 stdout=subprocess.PIPE,
482 stderr=subprocess.PIPE)
483 outdata, errdata = p.communicate()
31f18b77 484 if len(errdata):
7c673cae
FG
485 raise RuntimeError('unable to get conf option %s for %s: %s' % (field, name, errdata))
486 return outdata.rstrip()
487
488PROMPT = 'ceph> '
489
490if sys.stdin.isatty():
491 def read_input():
492 while True:
493 line = input(PROMPT).rstrip()
494 if line in ['q', 'quit', 'Q', 'exit']:
495 return None
496 if line:
497 return line
498else:
499 def read_input():
500 while True:
501 line = sys.stdin.readline()
502 if not line:
503 return None
504 line = line.rstrip()
505 if line:
506 return line
507
508
509def new_style_command(parsed_args, cmdargs, target, sigdict, inbuf, verbose):
510 """
511 Do new-style command dance.
512 target: daemon to receive command: mon (any) or osd.N
513 sigdict - the parsed output from the new monitor describing commands
514 inbuf - any -i input file data
515 verbose - bool
516 """
517 if verbose:
518 for cmdtag in sorted(sigdict.keys()):
519 cmd = sigdict[cmdtag]
520 sig = cmd['sig']
521 print('{0}: {1}'.format(cmdtag, concise_sig(sig)))
522
523 if True:
524 if cmdargs:
525 # Validate input args against list of sigs
526 valid_dict = validate_command(sigdict, cmdargs, verbose)
527 if valid_dict:
528 if parsed_args.output_format:
529 valid_dict['format'] = parsed_args.output_format
530 else:
531 return -errno.EINVAL, '', 'invalid command'
532 else:
533 if sys.stdin.isatty():
534 # do the command-interpreter looping
535 # for input to do readline cmd editing
536 import readline # noqa
537
538 while True:
539 interactive_input = read_input()
540 if interactive_input is None:
541 return 0, '', ''
542 cmdargs = parse_cmdargs(shlex.split(interactive_input))[2]
543 try:
544 target = find_cmd_target(cmdargs)
545 except Exception as e:
31f18b77
FG
546 print('error handling command target: {0}'.format(e),
547 file=sys.stderr)
7c673cae
FG
548 continue
549 if len(cmdargs) and cmdargs[0] == 'tell':
31f18b77
FG
550 print('Can not use \'tell\' in interactive mode.',
551 file=sys.stderr)
7c673cae
FG
552 continue
553 valid_dict = validate_command(sigdict, cmdargs, verbose)
554 if valid_dict:
555 if parsed_args.output_format:
556 valid_dict['format'] = parsed_args.output_format
557 if verbose:
558 print("Submitting command: ", valid_dict, file=sys.stderr)
559 ret, outbuf, outs = json_command(cluster_handle,
560 target=target,
561 argdict=valid_dict)
562 if ret:
563 ret = abs(ret)
31f18b77
FG
564 print('Error: {0} {1}'.format(ret, errno.errorcode.get(ret, 'Unknown')),
565 file=sys.stderr)
7c673cae
FG
566 if outbuf:
567 print(outbuf)
568 if outs:
569 print('Status:\n', outs, file=sys.stderr)
570 else:
571 print("Invalid command", file=sys.stderr)
572
573 if verbose:
574 print("Submitting command: ", valid_dict, file=sys.stderr)
575 return json_command(cluster_handle, target=target, argdict=valid_dict,
576 inbuf=inbuf)
577
578
579def complete(sigdict, args, target):
580 """
581 Command completion. Match as much of [args] as possible,
582 and print every possible match separated by newlines.
583 Return exitcode.
584 """
585 # XXX this looks a lot like the front of validate_command(). Refactor?
586
587 complete_verbose = 'COMPVERBOSE' in os.environ
588
589 # Repulsive hack to handle tell: lop off 'tell' and target
590 # and validate the rest of the command. 'target' is already
591 # determined in our callers, so it's ok to remove it here.
592 if len(args) and args[0] == 'tell':
593 args = args[2:]
594 # look for best match, accumulate possibles in bestcmds
595 # (so we can maybe give a more-useful error message)
596
597 match_count = 0
598 comps = []
599 for cmdtag, cmd in sigdict.items():
600 sig = cmd['sig']
601 j = 0
602 # iterate over all arguments, except last one
603 for arg in args[0:-1]:
604 if j > len(sig)-1:
605 # an out of argument definitions
606 break
607 found_match = arg in sig[j].complete(arg)
608 if not found_match and sig[j].req:
609 # no elements that match
610 break
611 if not sig[j].N:
612 j += 1
613 else:
614 # successfully matched all - except last one - arguments
615 if j < len(sig) and len(args) > 0:
616 comps += sig[j].complete(args[-1])
617
618 match_count += 1
619 match_cmd = cmd
620
621 if match_count == 1 and len(comps) == 0:
622 # only one command matched and no hints yet => add help
623 comps = comps + [' ', '#'+match_cmd['help']]
624 print('\n'.join(sorted(set(comps))))
625 return 0
626
627
7c673cae
FG
628def ping_monitor(cluster_handle, name, timeout):
629 if 'mon.' not in name:
630 print('"ping" expects a monitor to ping; try "ping mon.<id>"', file=sys.stderr)
631 return 1
632
633 mon_id = name[len('mon.'):]
31f18b77 634 if mon_id == '*':
7c673cae 635 run_in_thread(cluster_handle.connect, timeout=timeout)
31f18b77 636 for m in monids():
7c673cae
FG
637 s = run_in_thread(cluster_handle.ping_monitor, m)
638 if s is None:
639 print("mon.{0}".format(m) + '\n' + "Error connecting to monitor.")
640 else:
641 print("mon.{0}".format(m) + '\n' + s)
31f18b77 642 else:
7c673cae
FG
643 s = run_in_thread(cluster_handle.ping_monitor, mon_id)
644 print(s)
645 return 0
646
647
648def maybe_daemon_command(parsed_args, childargs):
649 """
650 Check if --admin-socket, daemon, or daemonperf command
651 if it is, returns (boolean handled, return code if handled == True)
652 """
653
654 daemon_perf = False
655 sockpath = None
656 if parsed_args.admin_socket:
657 sockpath = parsed_args.admin_socket
658 elif len(childargs) > 0 and childargs[0] in ["daemon", "daemonperf"]:
659 daemon_perf = (childargs[0] == "daemonperf")
660 # Treat "daemon <path>" or "daemon <name>" like --admin_daemon <path>
661 # Handle "daemonperf <path>" the same but requires no trailing args
662 require_args = 2 if daemon_perf else 3
663 if len(childargs) >= require_args:
664 if childargs[1].find('/') >= 0:
665 sockpath = childargs[1]
666 else:
667 # try resolve daemon name
668 try:
669 sockpath = ceph_conf(parsed_args, 'admin_socket',
670 childargs[1])
671 except Exception as e:
672 print('Can\'t get admin socket path: ' + str(e), file=sys.stderr)
673 return True, errno.EINVAL
674 # for both:
675 childargs = childargs[2:]
676 else:
31f18b77
FG
677 print('{0} requires at least {1} arguments'.format(childargs[0], require_args),
678 file=sys.stderr)
7c673cae
FG
679 return True, errno.EINVAL
680
681 if sockpath and daemon_perf:
682 return True, daemonperf(childargs, sockpath)
683 elif sockpath:
684 try:
685 raw_write(admin_socket(sockpath, childargs, parsed_args.output_format))
686 except Exception as e:
687 print('admin_socket: {0}'.format(e), file=sys.stderr)
688 return True, errno.EINVAL
689 return True, 0
690
691 return False, 0
692
693
694def isnum(s):
695 try:
696 float(s)
697 return True
698 except ValueError:
699 return False
700
31f18b77 701
7c673cae
FG
702def daemonperf(childargs, sockpath):
703 """
704 Handle daemonperf command; returns errno or 0
705
706 daemonperf <daemon> [priority string] [statpats] [interval] [count]
707 daemonperf <daemon> list|ls [statpats]
708 """
709
710 interval = 1
711 count = None
712 statpats = None
713 priority = None
714 do_list = False
715
716 def prio_from_name(arg):
717
718 PRIOMAP = {
719 'critical': PRIO_CRITICAL,
720 'interesting': PRIO_INTERESTING,
721 'useful': PRIO_USEFUL,
722 'uninteresting': PRIO_UNINTERESTING,
723 'debugonly': PRIO_DEBUGONLY,
724 }
725
726 if arg in PRIOMAP:
727 return PRIOMAP[arg]
728 # allow abbreviation
729 for name, val in PRIOMAP.items():
730 if name.startswith(arg):
731 return val
732 return None
733
734 # consume and analyze non-numeric args
735 while len(childargs) and not isnum(childargs[0]):
736 arg = childargs.pop(0)
737 # 'list'?
738 if arg in ['list', 'ls']:
31f18b77 739 do_list = True
7c673cae
FG
740 continue
741 # prio?
742 prio = prio_from_name(arg)
743 if prio is not None:
744 priority = prio
745 continue
746 # statpats
747 statpats = arg.split(',')
748
749 if priority is None:
750 priority = PRIO_DEFAULT
751
752 if len(childargs) > 0:
753 try:
754 interval = float(childargs.pop(0))
755 if interval < 0:
756 raise ValueError
757 except ValueError:
758 print('daemonperf: interval should be a positive number', file=sys.stderr)
759 return errno.EINVAL
760
761 if len(childargs) > 0:
762 arg = childargs.pop(0)
763 if (not isnum(arg)) or (int(arg) < 0):
764 print('daemonperf: count should be a positive integer', file=sys.stderr)
765 return errno.EINVAL
766 count = int(arg)
767
768 watcher = DaemonWatcher(sockpath, statpats, priority)
769 if do_list:
770 watcher.list()
771 else:
772 watcher.run(interval, count)
773
774 return 0
775
7c673cae
FG
776
777def main():
778 ceph_args = os.environ.get('CEPH_ARGS')
779 if ceph_args:
780 if "injectargs" in sys.argv:
781 i = sys.argv.index("injectargs")
782 sys.argv = sys.argv[:i] + ceph_args.split() + sys.argv[i:]
783 else:
784 sys.argv.extend(ceph_args.split())
785 parser, parsed_args, childargs = parse_cmdargs()
786
787 if parsed_args.version:
31f18b77
FG
788 print('ceph version {0} ({1}) {2} ({3})'.format(
789 CEPH_GIT_NICE_VER,
790 CEPH_GIT_VER,
791 CEPH_RELEASE_NAME,
792 CEPH_RELEASE_TYPE)) # noqa
7c673cae
FG
793 return 0
794
795 global verbose
796 verbose = parsed_args.verbose
797
798 if verbose:
799 print("parsed_args: {0}, childargs: {1}".format(parsed_args, childargs), file=sys.stderr)
800
801 if parsed_args.admin_socket_nope:
31f18b77
FG
802 print('--admin-socket is used by daemons; '
803 'you probably mean --admin-daemon/daemon', file=sys.stderr)
7c673cae
FG
804 return 1
805
806 # pass on --id, --name, --conf
807 name = 'client.admin'
808 if parsed_args.client_id:
809 name = 'client.' + parsed_args.client_id
810 if parsed_args.client_name:
811 name = parsed_args.client_name
812
813 # default '' means default conf search
814 conffile = ''
815 if parsed_args.cephconf:
816 conffile = parsed_args.cephconf
817 # For now, --admin-daemon is handled as usual. Try it
818 # first in case we can't connect() to the cluster
819
820 format = parsed_args.output_format
821
822 done, ret = maybe_daemon_command(parsed_args, childargs)
823 if done:
824 return ret
825
826 timeout = None
827 if parsed_args.cluster_timeout:
828 timeout = parsed_args.cluster_timeout
829
830 # basic help
831 if parsed_args.help:
832 do_basic_help(parser, childargs)
833
834 # handle any 'generic' ceph arguments that we didn't parse here
835 global cluster_handle
836
837 # rados.Rados() will call rados_create2, and then read the conf file,
838 # and then set the keys from the dict. So we must do these
839 # "pre-file defaults" first (see common_preinit in librados)
840 conf_defaults = {
31f18b77
FG
841 'log_to_stderr': 'true',
842 'err_to_stderr': 'true',
843 'log_flush_on_exit': 'true',
7c673cae
FG
844 }
845
846 if 'injectargs' in childargs:
847 position = childargs.index('injectargs')
848 injectargs = childargs[position:]
849 childargs = childargs[:position]
850 if verbose:
31f18b77
FG
851 print('Separate childargs {0} from injectargs {1}'.format(childargs, injectargs),
852 file=sys.stderr)
7c673cae
FG
853 else:
854 injectargs = None
855
856 clustername = None
857 if parsed_args.cluster:
858 clustername = parsed_args.cluster
859
860 try:
861 cluster_handle = run_in_thread(rados.Rados,
862 name=name, clustername=clustername,
863 conf_defaults=conf_defaults,
864 conffile=conffile)
865 retargs = run_in_thread(cluster_handle.conf_parse_argv, childargs)
866 except rados.Error as e:
867 print('Error initializing cluster client: {0!r}'.format(e), file=sys.stderr)
868 return 1
869
870 childargs = retargs
871 if not childargs:
872 childargs = []
873
874 # -- means "stop parsing args", but we don't want to see it either
875 if '--' in childargs:
876 childargs.remove('--')
877 if injectargs and '--' in injectargs:
878 injectargs.remove('--')
879
880 # special deprecation warning for 'ceph <type> tell'
881 # someday 'mds' will be here too
31f18b77
FG
882 if (len(childargs) >= 2 and
883 childargs[0] in ['mon', 'osd'] and
884 childargs[1] == 'tell'):
885 print('"{0} tell" is deprecated; try "tell {0}.<id> <command> [options...]" instead (id can be "*") '.format(childargs[0]),
886 file=sys.stderr)
7c673cae
FG
887 return 1
888
889 if parsed_args.help:
890 # short default timeout for -h
891 if not timeout:
892 timeout = 5
893
224ce89b 894 if childargs and childargs[0] == 'ping' and not parsed_args.help:
7c673cae
FG
895 if len(childargs) < 2:
896 print('"ping" requires a monitor name as argument: "ping mon.<id>"', file=sys.stderr)
897 return 1
898 if parsed_args.completion:
31f18b77 899 # for completion let timeout be really small
7c673cae
FG
900 timeout = 3
901 try:
224ce89b 902 if childargs and childargs[0] == 'ping' and not parsed_args.help:
7c673cae 903 return ping_monitor(cluster_handle, childargs[1], timeout)
224ce89b
WB
904 result = run_in_thread(cluster_handle.connect, timeout=timeout)
905 if type(result) is tuple and result[0] == -errno.EINTR:
906 print('Cluster connection interrupted or timed out', file=sys.stderr)
907 return 1
7c673cae
FG
908 except KeyboardInterrupt:
909 print('Cluster connection aborted', file=sys.stderr)
910 return 1
911 except rados.PermissionDeniedError as e:
912 print(str(e), file=sys.stderr)
913 return errno.EACCES
914 except Exception as e:
915 print(str(e), file=sys.stderr)
916 return 1
224ce89b 917
7c673cae 918 if parsed_args.help:
224ce89b
WB
919 hdr('Monitor commands:')
920 if verbose:
921 print('[Contacting monitor, timeout after %d seconds]' % timeout)
922
31f18b77 923 return do_extended_help(parser, childargs, ('mon', ''), ' '.join(childargs))
7c673cae 924
31f18b77
FG
925 # implement "tell service.id help"
926 if len(childargs) >= 3 and childargs[0] == 'tell' and childargs[2] == 'help':
927 target = childargs[1].split('.')
928 if validate_target(target):
929 return do_extended_help(parser, childargs, target, None)
930 else:
931 print('target {0} doesn\'t exists, please pass correct target to tell command, such as mon.a/'
932 'osd.1/mds.a/mgr'.format(childargs[1]), file=sys.stderr)
933 return 1
7c673cae
FG
934 # implement -w/--watch_*
935 # This is ugly, but Namespace() isn't quite rich enough.
936 level = ''
937 for k, v in parsed_args._get_kwargs():
938 if k.startswith('watch') and v:
939 if k == 'watch':
940 level = 'info'
224ce89b 941 elif k != "watch_channel":
7c673cae
FG
942 level = k.replace('watch_', '')
943 if level:
7c673cae 944 # an awfully simple callback
224ce89b
WB
945 def watch_cb(arg, line, channel, name, who, stamp_sec, stamp_nsec, seq, level, msg):
946 # Filter on channel
947 if (channel == parsed_args.watch_channel or \
948 parsed_args.watch_channel == "*"):
949 print(line)
950 sys.stdout.flush()
7c673cae
FG
951
952 # first do a ceph status
953 ret, outbuf, outs = json_command(cluster_handle, prefix='status')
7c673cae
FG
954 if ret:
955 print("status query failed: ", outs, file=sys.stderr)
956 return ret
957 print(outbuf)
958
959 # this instance keeps the watch connection alive, but is
960 # otherwise unused
224ce89b 961 run_in_thread(cluster_handle.monitor_log2, level, watch_cb, 0)
7c673cae
FG
962
963 # loop forever letting watch_cb print lines
964 try:
965 signal.pause()
966 except KeyboardInterrupt:
967 # or until ^C, at least
968 return 0
969
970 # read input file, if any
971 inbuf = b''
972 if parsed_args.input_file:
973 try:
974 with open(parsed_args.input_file, 'rb') as f:
975 inbuf = f.read()
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:
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)
986 return 1
987
988 # -s behaves like a command (ceph status).
989 if parsed_args.status:
990 childargs.insert(0, 'status')
991
992 try:
993 target = find_cmd_target(childargs)
994 except Exception as e:
995 print('error handling command target: {0}'.format(e), file=sys.stderr)
996 return 1
997
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.
1001 is_tell = False
1002 if len(childargs) and childargs[0] == 'tell':
1003 childargs = childargs[2:]
1004 is_tell = True
1005
1006 if is_tell:
1007 if injectargs:
1008 childargs = injectargs
1009 if not len(childargs):
1010 print('"{0} tell" requires additional arguments.'.format(sys.argv[0]),
31f18b77
FG
1011 'Try "{0} tell <name> <command> [options...]" instead.'.format(sys.argv[0]),
1012 file=sys.stderr)
7c673cae
FG
1013 return errno.EINVAL
1014
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
1019
1020 targets = [target]
1021
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()]
1027
1028 final_ret = 0
1029 for target in targets:
1030 # prettify? prefix output with target, if there was a wildcard used
1031 prefix = ''
1032 suffix = ''
1033 if not parsed_args.output_file and len(targets) > 1:
1034 prefix = '{0}.{1}: '.format(*target)
1035 suffix = '\n'
1036
1037 ret, outbuf, outs = json_command(cluster_handle, target=target,
1038 prefix='get_command_descriptions')
31f18b77
FG
1039 if ret:
1040 where = '{0}.{1}'.format(*target)
1041 if ret > 0:
1042 raise RuntimeError('Unexpeceted return code from {0}: {1}'.
1043 format(where, ret))
1044 outs = 'problem getting command descriptions from {0}'.format(where)
1045 else:
1046 sigdict = parse_json_funcsigs(outbuf.decode('utf-8'), 'cli')
7c673cae 1047
31f18b77
FG
1048 if parsed_args.completion:
1049 return complete(sigdict, childargs, target)
7c673cae 1050
31f18b77
FG
1051 ret, outbuf, outs = new_style_command(parsed_args, childargs,
1052 target, sigdict, inbuf,
1053 verbose)
7c673cae 1054
31f18b77
FG
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,
1060 verbose)
1061 if ret < 0:
1062 ret = -ret
1063 print(prefix +
1064 'Second attempt of previously successful command '
1065 'failed with {0}: {1}'.format(
1066 errno.errorcode.get(ret, 'Unknown'), outs),
1067 file=sys.stderr)
7c673cae
FG
1068
1069 if ret < 0:
1070 ret = -ret
31f18b77
FG
1071 errstr = errno.errorcode.get(ret, 'Unknown')
1072 print(u'Error {0}: {1}'.format(errstr, outs), file=sys.stderr)
7c673cae
FG
1073 if len(targets) > 1:
1074 final_ret = ret
1075 else:
1076 return ret
1077
31f18b77
FG
1078 if outs:
1079 print(prefix + outs, file=sys.stderr)
7c673cae
FG
1080
1081 sys.stdout.flush()
1082
31f18b77 1083 if parsed_args.output_file:
7c673cae
FG
1084 outf.write(outbuf)
1085 else:
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 \
31f18b77 1091 parsed_args.output_format.startswith('json'):
7c673cae
FG
1092 print()
1093
1094 # if we are prettifying things, normalize newlines. sigh.
1095 if suffix:
1096 outbuf = outbuf.rstrip()
1097 if outbuf:
1098 try:
1099 print(prefix, end='')
1100 # Write directly to binary stdout
1101 raw_write(outbuf)
1102 print(suffix, end='')
1103 except IOError as e:
1104 if e.errno != errno.EPIPE:
1105 raise e
1106
1107 sys.stdout.flush()
1108
31f18b77 1109 if parsed_args.output_file:
7c673cae
FG
1110 outf.close()
1111
1112 if final_ret:
1113 return final_ret
1114
1115 return 0
1116
1117if __name__ == '__main__':
1118 retval = main()
1119 # shutdown explicitly; Rados() does not
1120 if cluster_handle:
1121 run_in_thread(cluster_handle.shutdown)
1122 sys.exit(retval)