supervisorctl.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296
  1. #!/usr/bin/env python -u
  2. """supervisorctl -- control applications run by supervisord from the cmd line.
  3. Usage: %s [options] [action [arguments]]
  4. Options:
  5. -c/--configuration FILENAME -- configuration file path (default /etc/supervisord.conf)
  6. -h/--help -- print usage message and exit
  7. -i/--interactive -- start an interactive shell after executing commands
  8. -s/--serverurl URL -- URL on which supervisord server is listening
  9. (default "http://localhost:9001").
  10. -u/--username USERNAME -- username to use for authentication with server
  11. -p/--password PASSWORD -- password to use for authentication with server
  12. -r/--history-file -- keep a readline history (if readline is available)
  13. action [arguments] -- see below
  14. Actions are commands like "tail" or "stop". If -i is specified or no action is
  15. specified on the command line, a "shell" interpreting actions typed
  16. interactively is started. Use the action "help" to find out about available
  17. actions.
  18. """
  19. import cmd
  20. import sys
  21. import getpass
  22. import socket
  23. import errno
  24. import threading
  25. from supervisor.compat import xmlrpclib
  26. from supervisor.compat import urlparse
  27. from supervisor.compat import unicode
  28. from supervisor.compat import raw_input
  29. from supervisor.medusa import asyncore_25 as asyncore
  30. from supervisor.options import ClientOptions
  31. from supervisor.options import make_namespec
  32. from supervisor.options import split_namespec
  33. from supervisor import xmlrpc
  34. from supervisor import states
  35. from supervisor import http_client
  36. class fgthread(threading.Thread):
  37. """ A subclass of threading.Thread, with a kill() method.
  38. To be used for foreground output/error streaming.
  39. http://mail.python.org/pipermail/python-list/2004-May/260937.html
  40. """
  41. def __init__(self, program, ctl):
  42. threading.Thread.__init__(self)
  43. self.killed = False
  44. self.program = program
  45. self.ctl = ctl
  46. self.listener = http_client.Listener()
  47. self.output_handler = http_client.HTTPHandler(self.listener,
  48. self.ctl.options.username,
  49. self.ctl.options.password)
  50. self.error_handler = http_client.HTTPHandler(self.listener,
  51. self.ctl.options.username,
  52. self.ctl.options.password)
  53. def start(self): # pragma: no cover
  54. # Start the thread
  55. self.__run_backup = self.run
  56. self.run = self.__run
  57. threading.Thread.start(self)
  58. def run(self): # pragma: no cover
  59. self.output_handler.get(self.ctl.options.serverurl,
  60. '/logtail/%s/stdout'%self.program)
  61. self.error_handler.get(self.ctl.options.serverurl,
  62. '/logtail/%s/stderr'%self.program)
  63. asyncore.loop()
  64. def __run(self): # pragma: no cover
  65. # Hacked run function, which installs the trace
  66. sys.settrace(self.globaltrace)
  67. self.__run_backup()
  68. self.run = self.__run_backup
  69. def globaltrace(self, frame, why, arg):
  70. if why == 'call':
  71. return self.localtrace
  72. else:
  73. return None
  74. def localtrace(self, frame, why, arg):
  75. if self.killed:
  76. if why == 'line':
  77. raise SystemExit()
  78. return self.localtrace
  79. def kill(self):
  80. self.output_handler.close()
  81. self.error_handler.close()
  82. self.killed = True
  83. class Controller(cmd.Cmd):
  84. def __init__(self, options, completekey='tab', stdin=None,
  85. stdout=None):
  86. self.options = options
  87. self.prompt = self.options.prompt + '> '
  88. self.options.plugins = []
  89. self.vocab = ['help']
  90. self._complete_info = None
  91. cmd.Cmd.__init__(self, completekey, stdin, stdout)
  92. for name, factory, kwargs in self.options.plugin_factories:
  93. plugin = factory(self, **kwargs)
  94. for a in dir(plugin):
  95. if a.startswith('do_') and callable(getattr(plugin, a)):
  96. self.vocab.append(a[3:])
  97. self.options.plugins.append(plugin)
  98. plugin.name = name
  99. def emptyline(self):
  100. # We don't want a blank line to repeat the last command.
  101. return
  102. def exec_cmdloop(self, args, options):
  103. try:
  104. import readline
  105. delims = readline.get_completer_delims()
  106. delims = delims.replace(':', '') # "group:process" as one word
  107. delims = delims.replace('*', '') # "group:*" as one word
  108. delims = delims.replace('-', '') # names with "-" as one word
  109. readline.set_completer_delims(delims)
  110. if options.history_file:
  111. try:
  112. readline.read_history_file(options.history_file)
  113. except IOError:
  114. pass
  115. def save():
  116. try:
  117. readline.write_history_file(options.history_file)
  118. except IOError:
  119. pass
  120. import atexit
  121. atexit.register(save)
  122. except ImportError:
  123. pass
  124. try:
  125. self.cmdqueue.append('status')
  126. self.cmdloop()
  127. except KeyboardInterrupt:
  128. self.output('')
  129. pass
  130. def onecmd(self, line):
  131. """ Override the onecmd method to:
  132. - catch and print all exceptions
  133. - allow for composite commands in interactive mode (foo; bar)
  134. - call 'do_foo' on plugins rather than ourself
  135. """
  136. origline = line
  137. lines = line.split(';') # don't filter(None, line.split), as we pop
  138. line = lines.pop(0)
  139. # stuffing the remainder into cmdqueue will cause cmdloop to
  140. # call us again for each command.
  141. self.cmdqueue.extend(lines)
  142. cmd, arg, line = self.parseline(line)
  143. if not line:
  144. return self.emptyline()
  145. if cmd is None:
  146. return self.default(line)
  147. self._complete_info = None
  148. self.lastcmd = line
  149. if cmd == '':
  150. return self.default(line)
  151. else:
  152. do_func = self._get_do_func(cmd)
  153. if do_func is None:
  154. return self.default(line)
  155. try:
  156. try:
  157. return do_func(arg)
  158. except xmlrpclib.ProtocolError as e:
  159. if e.errcode == 401:
  160. if self.options.interactive:
  161. self.output('Server requires authentication')
  162. username = raw_input('Username:')
  163. password = getpass.getpass(prompt='Password:')
  164. self.output('')
  165. self.options.username = username
  166. self.options.password = password
  167. return self.onecmd(origline)
  168. else:
  169. self.options.usage('Server requires authentication')
  170. else:
  171. raise
  172. do_func(arg)
  173. except SystemExit:
  174. raise
  175. except Exception:
  176. (file, fun, line), t, v, tbinfo = asyncore.compact_traceback()
  177. error = 'error: %s, %s: file: %s line: %s' % (t, v, file, line)
  178. self.output(error)
  179. if not self.options.interactive:
  180. sys.exit(2)
  181. def _get_do_func(self, cmd):
  182. func_name = 'do_' + cmd
  183. func = getattr(self, func_name, None)
  184. if not func:
  185. for plugin in self.options.plugins:
  186. func = getattr(plugin, func_name, None)
  187. if func is not None:
  188. break
  189. return func
  190. def output(self, stuff):
  191. if stuff is not None:
  192. if isinstance(stuff, unicode):
  193. stuff = stuff.encode('utf-8')
  194. self.stdout.write(stuff + '\n')
  195. def get_supervisor(self):
  196. return self.get_server_proxy('supervisor')
  197. def get_server_proxy(self, namespace=None):
  198. proxy = self.options.getServerProxy()
  199. if namespace is None:
  200. return proxy
  201. else:
  202. return getattr(proxy, namespace)
  203. def upcheck(self):
  204. try:
  205. supervisor = self.get_supervisor()
  206. api = supervisor.getVersion() # deprecated
  207. from supervisor import rpcinterface
  208. if api != rpcinterface.API_VERSION:
  209. self.output(
  210. 'Sorry, this version of supervisorctl expects to '
  211. 'talk to a server with API version %s, but the '
  212. 'remote version is %s.' % (rpcinterface.API_VERSION, api))
  213. return False
  214. except xmlrpclib.Fault as e:
  215. if e.faultCode == xmlrpc.Faults.UNKNOWN_METHOD:
  216. self.output(
  217. 'Sorry, supervisord responded but did not recognize '
  218. 'the supervisor namespace commands that supervisorctl '
  219. 'uses to control it. Please check that the '
  220. '[rpcinterface:supervisor] section is enabled in the '
  221. 'configuration file (see sample.conf).')
  222. return False
  223. raise
  224. except socket.error as why:
  225. if why.args[0] == errno.ECONNREFUSED:
  226. self.output('%s refused connection' % self.options.serverurl)
  227. return False
  228. elif why.args[0] == errno.ENOENT:
  229. self.output('%s no such file' % self.options.serverurl)
  230. return False
  231. raise
  232. return True
  233. def complete(self, text, state, line=None):
  234. """Completer function that Cmd will register with readline using
  235. readline.set_completer(). This function will be called by readline
  236. as complete(text, state) where text is a fragment to complete and
  237. state is an integer (0..n). Each call returns a string with a new
  238. completion. When no more are available, None is returned."""
  239. if line is None: # line is only set in tests
  240. import readline
  241. line = readline.get_line_buffer()
  242. # take the last phrase from a line like "stop foo; start bar"
  243. phrase = line.split(';')[-1]
  244. matches = []
  245. # blank phrase completes to action list
  246. if not phrase.strip():
  247. matches = self._complete_actions(text)
  248. else:
  249. words = phrase.split()
  250. action = words[0]
  251. # incomplete action completes to action list
  252. if len(words) == 1 and not phrase.endswith(' '):
  253. matches = self._complete_actions(text)
  254. # actions that accept an action name
  255. elif action in ('help'):
  256. matches = self._complete_actions(text)
  257. # actions that accept a group name
  258. elif action in ('add', 'remove', 'update'):
  259. matches = self._complete_groups(text)
  260. # actions that accept a process name
  261. elif action in ('clear', 'fg', 'pid', 'restart', 'signal',
  262. 'start', 'status', 'stop', 'tail'):
  263. matches = self._complete_processes(text)
  264. if len(matches) > state:
  265. return matches[state]
  266. def _complete_actions(self, text):
  267. """Build a completion list of action names matching text"""
  268. return [ a + ' ' for a in self.vocab if a.startswith(text)]
  269. def _complete_groups(self, text):
  270. """Build a completion list of group names matching text"""
  271. groups = []
  272. for info in self._get_complete_info():
  273. if info['group'] not in groups:
  274. groups.append(info['group'])
  275. return [ g + ' ' for g in groups if g.startswith(text) ]
  276. def _complete_processes(self, text):
  277. """Build a completion list of process names matching text"""
  278. processes = []
  279. for info in self._get_complete_info():
  280. if ':' in text or info['name'] != info['group']:
  281. processes.append('%s:%s' % (info['group'], info['name']))
  282. if '%s:*' % info['group'] not in processes:
  283. processes.append('%s:*' % info['group'])
  284. else:
  285. processes.append(info['name'])
  286. return [ p + ' ' for p in processes if p.startswith(text) ]
  287. def _get_complete_info(self):
  288. """Get all process info used for completion. We cache this between
  289. commands to reduce XML-RPC calls because readline may call
  290. complete() many times if the user hits tab only once."""
  291. if self._complete_info is None:
  292. self._complete_info = self.get_supervisor().getAllProcessInfo()
  293. return self._complete_info
  294. def do_help(self, arg):
  295. if arg.strip() == 'help':
  296. self.help_help()
  297. else:
  298. for plugin in self.options.plugins:
  299. plugin.do_help(arg)
  300. def help_help(self):
  301. self.output("help\t\tPrint a list of available actions")
  302. self.output("help <action>\tPrint help for <action>")
  303. def do_EOF(self, arg):
  304. self.output('')
  305. return 1
  306. def help_EOF(self):
  307. self.output("To quit, type ^D or use the quit command")
  308. def get_names(inst):
  309. names = []
  310. classes = [inst.__class__]
  311. while classes:
  312. aclass = classes.pop(0)
  313. if aclass.__bases__:
  314. classes = classes + list(aclass.__bases__)
  315. names = names + dir(aclass)
  316. return names
  317. class ControllerPluginBase:
  318. name = 'unnamed'
  319. def __init__(self, controller):
  320. self.ctl = controller
  321. def _doc_header(self):
  322. return "%s commands (type help <topic>):" % self.name
  323. doc_header = property(_doc_header)
  324. def do_help(self, arg):
  325. if arg:
  326. # XXX check arg syntax
  327. try:
  328. func = getattr(self, 'help_' + arg)
  329. except AttributeError:
  330. try:
  331. doc = getattr(self, 'do_' + arg).__doc__
  332. if doc:
  333. self.ctl.output(doc)
  334. return
  335. except AttributeError:
  336. pass
  337. self.ctl.output(self.ctl.nohelp % (arg,))
  338. return
  339. func()
  340. else:
  341. names = get_names(self)
  342. cmds_doc = []
  343. cmds_undoc = []
  344. help = {}
  345. for name in names:
  346. if name[:5] == 'help_':
  347. help[name[5:]]=1
  348. names.sort()
  349. # There can be duplicates if routines overridden
  350. prevname = ''
  351. for name in names:
  352. if name[:3] == 'do_':
  353. if name == prevname:
  354. continue
  355. prevname = name
  356. cmd=name[3:]
  357. if cmd in help:
  358. cmds_doc.append(cmd)
  359. del help[cmd]
  360. elif getattr(self, name).__doc__:
  361. cmds_doc.append(cmd)
  362. else:
  363. cmds_undoc.append(cmd)
  364. self.ctl.output('')
  365. self.ctl.print_topics(self.doc_header, cmds_doc, 15, 80)
  366. class DefaultControllerPlugin(ControllerPluginBase):
  367. name = 'default'
  368. listener = None # for unit tests
  369. def _tailf(self, path):
  370. self.ctl.output('==> Press Ctrl-C to exit <==')
  371. username = self.ctl.options.username
  372. password = self.ctl.options.password
  373. handler = None
  374. try:
  375. # Python's urllib2 (at least as of Python 2.4.2) isn't up
  376. # to this task; it doesn't actually implement a proper
  377. # HTTP/1.1 client that deals with chunked responses (it
  378. # always sends a Connection: close header). We use a
  379. # homegrown client based on asyncore instead. This makes
  380. # me sad.
  381. if self.listener is None:
  382. listener = http_client.Listener()
  383. else:
  384. listener = self.listener # for unit tests
  385. handler = http_client.HTTPHandler(listener, username, password)
  386. handler.get(self.ctl.options.serverurl, path)
  387. asyncore.loop()
  388. except KeyboardInterrupt:
  389. if handler:
  390. handler.close()
  391. self.ctl.output('')
  392. return
  393. def do_tail(self, arg):
  394. if not self.ctl.upcheck():
  395. return
  396. args = arg.split()
  397. if len(args) < 1:
  398. self.ctl.output('Error: too few arguments')
  399. self.help_tail()
  400. return
  401. elif len(args) > 3:
  402. self.ctl.output('Error: too many arguments')
  403. self.help_tail()
  404. return
  405. modifier = None
  406. if args[0].startswith('-'):
  407. modifier = args.pop(0)
  408. if len(args) == 1:
  409. name = args[-1]
  410. channel = 'stdout'
  411. else:
  412. if args:
  413. name = args[0]
  414. channel = args[-1].lower()
  415. if channel not in ('stderr', 'stdout'):
  416. self.ctl.output('Error: bad channel %r' % channel)
  417. return
  418. else:
  419. self.ctl.output('Error: tail requires process name')
  420. return
  421. bytes = 1600
  422. if modifier is not None:
  423. what = modifier[1:]
  424. if what == 'f':
  425. bytes = None
  426. else:
  427. try:
  428. bytes = int(what)
  429. except:
  430. self.ctl.output('Error: bad argument %s' % modifier)
  431. return
  432. supervisor = self.ctl.get_supervisor()
  433. if bytes is None:
  434. return self._tailf('/logtail/%s/%s' % (name, channel))
  435. else:
  436. try:
  437. if channel is 'stdout':
  438. output = supervisor.readProcessStdoutLog(name,
  439. -bytes, 0)
  440. else: # if channel is 'stderr'
  441. output = supervisor.readProcessStderrLog(name,
  442. -bytes, 0)
  443. except xmlrpclib.Fault as e:
  444. template = '%s: ERROR (%s)'
  445. if e.faultCode == xmlrpc.Faults.NO_FILE:
  446. self.ctl.output(template % (name, 'no log file'))
  447. elif e.faultCode == xmlrpc.Faults.FAILED:
  448. self.ctl.output(template % (name,
  449. 'unknown error reading log'))
  450. elif e.faultCode == xmlrpc.Faults.BAD_NAME:
  451. self.ctl.output(template % (name,
  452. 'no such process name'))
  453. else:
  454. raise
  455. else:
  456. self.ctl.output(output)
  457. def help_tail(self):
  458. self.ctl.output(
  459. "tail [-f] <name> [stdout|stderr] (default stdout)\n"
  460. "Ex:\n"
  461. "tail -f <name>\t\tContinuous tail of named process stdout\n"
  462. "\t\t\tCtrl-C to exit.\n"
  463. "tail -100 <name>\tlast 100 *bytes* of process stdout\n"
  464. "tail <name> stderr\tlast 1600 *bytes* of process stderr"
  465. )
  466. def do_maintail(self, arg):
  467. if not self.ctl.upcheck():
  468. return
  469. args = arg.split()
  470. if len(args) > 1:
  471. self.ctl.output('Error: too many arguments')
  472. self.help_maintail()
  473. return
  474. elif len(args) == 1:
  475. if args[0].startswith('-'):
  476. what = args[0][1:]
  477. if what == 'f':
  478. path = '/mainlogtail'
  479. return self._tailf(path)
  480. try:
  481. what = int(what)
  482. except:
  483. self.ctl.output('Error: bad argument %s' % args[0])
  484. return
  485. else:
  486. bytes = what
  487. else:
  488. self.ctl.output('Error: bad argument %s' % args[0])
  489. return
  490. else:
  491. bytes = 1600
  492. supervisor = self.ctl.get_supervisor()
  493. try:
  494. output = supervisor.readLog(-bytes, 0)
  495. except xmlrpclib.Fault as e:
  496. template = '%s: ERROR (%s)'
  497. if e.faultCode == xmlrpc.Faults.NO_FILE:
  498. self.ctl.output(template % ('supervisord', 'no log file'))
  499. elif e.faultCode == xmlrpc.Faults.FAILED:
  500. self.ctl.output(template % ('supervisord',
  501. 'unknown error reading log'))
  502. else:
  503. raise
  504. else:
  505. self.ctl.output(output)
  506. def help_maintail(self):
  507. self.ctl.output(
  508. "maintail -f \tContinuous tail of supervisor main log file"
  509. " (Ctrl-C to exit)\n"
  510. "maintail -100\tlast 100 *bytes* of supervisord main log file\n"
  511. "maintail\tlast 1600 *bytes* of supervisor main log file\n"
  512. )
  513. def do_quit(self, arg):
  514. sys.exit(0)
  515. def help_quit(self):
  516. self.ctl.output("quit\tExit the supervisor shell.")
  517. do_exit = do_quit
  518. def help_exit(self):
  519. self.ctl.output("exit\tExit the supervisor shell.")
  520. def _show_statuses(self, process_infos):
  521. namespecs, maxlen = [], 30
  522. for i, info in enumerate(process_infos):
  523. namespecs.append(make_namespec(info['group'], info['name']))
  524. if len(namespecs[i]) > maxlen:
  525. maxlen = len(namespecs[i])
  526. template = '%(namespec)-' + str(maxlen+3) + 's%(state)-10s%(desc)s'
  527. for i, info in enumerate(process_infos):
  528. line = template % {'namespec': namespecs[i],
  529. 'state': info['statename'],
  530. 'desc': info['description']}
  531. self.ctl.output(line)
  532. def do_status(self, arg):
  533. if not self.ctl.upcheck():
  534. return
  535. supervisor = self.ctl.get_supervisor()
  536. all_infos = supervisor.getAllProcessInfo()
  537. names = arg.split()
  538. if not names or "all" in names:
  539. matching_infos = all_infos
  540. else:
  541. matching_infos = []
  542. for name in names:
  543. bad_name = True
  544. group_name, process_name = split_namespec(name)
  545. for info in all_infos:
  546. matched = info['group'] == group_name
  547. if process_name is not None:
  548. matched = matched and info['name'] == process_name
  549. if matched:
  550. bad_name = False
  551. matching_infos.append(info)
  552. if bad_name:
  553. if process_name is None:
  554. msg = "%s: ERROR (no such group)" % group_name
  555. else:
  556. msg = "%s: ERROR (no such process)" % name
  557. self.ctl.output(msg)
  558. self._show_statuses(matching_infos)
  559. def help_status(self):
  560. self.ctl.output("status <name>\t\tGet status for a single process")
  561. self.ctl.output("status <gname>:*\tGet status for all "
  562. "processes in a group")
  563. self.ctl.output("status <name> <name>\tGet status for multiple named "
  564. "processes")
  565. self.ctl.output("status\t\t\tGet all process status info")
  566. def do_pid(self, arg):
  567. supervisor = self.ctl.get_supervisor()
  568. if not self.ctl.upcheck():
  569. return
  570. names = arg.split()
  571. if not names:
  572. pid = supervisor.getPID()
  573. self.ctl.output(str(pid))
  574. elif 'all' in names:
  575. for info in supervisor.getAllProcessInfo():
  576. self.ctl.output(str(info['pid']))
  577. else:
  578. for name in names:
  579. try:
  580. info = supervisor.getProcessInfo(name)
  581. except xmlrpclib.Fault as e:
  582. if e.faultCode == xmlrpc.Faults.BAD_NAME:
  583. self.ctl.output('No such process %s' % name)
  584. else:
  585. raise
  586. else:
  587. self.ctl.output(str(info['pid']))
  588. def help_pid(self):
  589. self.ctl.output("pid\t\t\tGet the PID of supervisord.")
  590. self.ctl.output("pid <name>\t\tGet the PID of a single "
  591. "child process by name.")
  592. self.ctl.output("pid all\t\t\tGet the PID of every child "
  593. "process, one per line.")
  594. def _startresult(self, result):
  595. name = make_namespec(result['group'], result['name'])
  596. code = result['status']
  597. template = '%s: ERROR (%s)'
  598. if code == xmlrpc.Faults.BAD_NAME:
  599. return template % (name, 'no such process')
  600. elif code == xmlrpc.Faults.NO_FILE:
  601. return template % (name, 'no such file')
  602. elif code == xmlrpc.Faults.NOT_EXECUTABLE:
  603. return template % (name, 'file is not executable')
  604. elif code == xmlrpc.Faults.ALREADY_STARTED:
  605. return template % (name, 'already started')
  606. elif code == xmlrpc.Faults.SPAWN_ERROR:
  607. return template % (name, 'spawn error')
  608. elif code == xmlrpc.Faults.ABNORMAL_TERMINATION:
  609. return template % (name, 'abnormal termination')
  610. elif code == xmlrpc.Faults.SUCCESS:
  611. return '%s: started' % name
  612. # assertion
  613. raise ValueError('Unknown result code %s for %s' % (code, name))
  614. def do_start(self, arg):
  615. if not self.ctl.upcheck():
  616. return
  617. names = arg.split()
  618. supervisor = self.ctl.get_supervisor()
  619. if not names:
  620. self.ctl.output("Error: start requires a process name")
  621. self.help_start()
  622. return
  623. if 'all' in names:
  624. results = supervisor.startAllProcesses()
  625. for result in results:
  626. result = self._startresult(result)
  627. self.ctl.output(result)
  628. else:
  629. for name in names:
  630. group_name, process_name = split_namespec(name)
  631. if process_name is None:
  632. try:
  633. results = supervisor.startProcessGroup(group_name)
  634. for result in results:
  635. result = self._startresult(result)
  636. self.ctl.output(result)
  637. except xmlrpclib.Fault as e:
  638. if e.faultCode == xmlrpc.Faults.BAD_NAME:
  639. error = "%s: ERROR (no such group)" % group_name
  640. self.ctl.output(error)
  641. else:
  642. raise
  643. else:
  644. try:
  645. result = supervisor.startProcess(name)
  646. except xmlrpclib.Fault as e:
  647. error = self._startresult({'status': e.faultCode,
  648. 'name': process_name,
  649. 'group': group_name,
  650. 'description': e.faultString})
  651. self.ctl.output(error)
  652. else:
  653. name = make_namespec(group_name, process_name)
  654. self.ctl.output('%s: started' % name)
  655. def help_start(self):
  656. self.ctl.output("start <name>\t\tStart a process")
  657. self.ctl.output("start <gname>:*\t\tStart all processes in a group")
  658. self.ctl.output(
  659. "start <name> <name>\tStart multiple processes or groups")
  660. self.ctl.output("start all\t\tStart all processes")
  661. def _signalresult(self, result, success='signalled'):
  662. name = make_namespec(result['group'], result['name'])
  663. code = result['status']
  664. fault_string = result['description']
  665. template = '%s: ERROR (%s)'
  666. if code == xmlrpc.Faults.BAD_NAME:
  667. return template % (name, 'no such process')
  668. elif code == xmlrpc.Faults.BAD_SIGNAL:
  669. return template % (name, 'bad signal name')
  670. elif code == xmlrpc.Faults.NOT_RUNNING:
  671. return template % (name, 'not running')
  672. elif code == xmlrpc.Faults.SUCCESS:
  673. return '%s: %s' % (name, success)
  674. elif code == xmlrpc.Faults.FAILED:
  675. return fault_string
  676. # assertion
  677. raise ValueError('Unknown result code %s for %s' % (code, name))
  678. def _stopresult(self, result):
  679. return self._signalresult(result, success='stopped')
  680. def do_stop(self, arg):
  681. if not self.ctl.upcheck():
  682. return
  683. names = arg.split()
  684. supervisor = self.ctl.get_supervisor()
  685. if not names:
  686. self.ctl.output('Error: stop requires a process name')
  687. self.help_stop()
  688. return
  689. if 'all' in names:
  690. results = supervisor.stopAllProcesses()
  691. for result in results:
  692. result = self._stopresult(result)
  693. self.ctl.output(result)
  694. else:
  695. for name in names:
  696. group_name, process_name = split_namespec(name)
  697. if process_name is None:
  698. try:
  699. results = supervisor.stopProcessGroup(group_name)
  700. for result in results:
  701. result = self._stopresult(result)
  702. self.ctl.output(result)
  703. except xmlrpclib.Fault as e:
  704. if e.faultCode == xmlrpc.Faults.BAD_NAME:
  705. error = "%s: ERROR (no such group)" % group_name
  706. self.ctl.output(error)
  707. else:
  708. raise
  709. else:
  710. try:
  711. supervisor.stopProcess(name)
  712. except xmlrpclib.Fault as e:
  713. error = self._stopresult({'status': e.faultCode,
  714. 'name': process_name,
  715. 'group': group_name,
  716. 'description':e.faultString})
  717. self.ctl.output(error)
  718. else:
  719. name = make_namespec(group_name, process_name)
  720. self.ctl.output('%s: stopped' % name)
  721. def help_stop(self):
  722. self.ctl.output("stop <name>\t\tStop a process")
  723. self.ctl.output("stop <gname>:*\t\tStop all processes in a group")
  724. self.ctl.output("stop <name> <name>\tStop multiple processes or groups")
  725. self.ctl.output("stop all\t\tStop all processes")
  726. def do_signal(self, arg):
  727. if not self.ctl.upcheck():
  728. return
  729. args = arg.split()
  730. if len(args) < 2:
  731. self.ctl.output(
  732. 'Error: signal requires a signal name and a process name')
  733. self.help_signal()
  734. return
  735. sig = args[0]
  736. names = args[1:]
  737. supervisor = self.ctl.get_supervisor()
  738. if 'all' in names:
  739. results = supervisor.signalAllProcesses(sig)
  740. for result in results:
  741. result = self._signalresult(result)
  742. self.ctl.output(result)
  743. else:
  744. for name in names:
  745. group_name, process_name = split_namespec(name)
  746. if process_name is None:
  747. try:
  748. results = supervisor.signalProcessGroup(
  749. group_name, sig
  750. )
  751. for result in results:
  752. result = self._signalresult(result)
  753. self.ctl.output(result)
  754. except xmlrpclib.Fault as e:
  755. if e.faultCode == xmlrpc.Faults.BAD_NAME:
  756. error = "%s: ERROR (no such group)" % group_name
  757. self.ctl.output(error)
  758. else:
  759. raise
  760. else:
  761. try:
  762. supervisor.signalProcess(name, sig)
  763. except xmlrpclib.Fault as e:
  764. error = self._signalresult({'status': e.faultCode,
  765. 'name': process_name,
  766. 'group': group_name,
  767. 'description':e.faultString})
  768. self.ctl.output(error)
  769. else:
  770. name = make_namespec(group_name, process_name)
  771. self.ctl.output('%s: signalled' % name)
  772. def help_signal(self):
  773. self.ctl.output("signal <signal name> <name>\t\tSignal a process")
  774. self.ctl.output("signal <signal name> <gname>:*\t\tSignal all processes in a group")
  775. self.ctl.output("signal <signal name> <name> <name>\tSignal multiple processes or groups")
  776. self.ctl.output("signal <signal name> all\t\tSignal all processes")
  777. def do_restart(self, arg):
  778. if not self.ctl.upcheck():
  779. return
  780. names = arg.split()
  781. if not names:
  782. self.ctl.output('Error: restart requires a process name')
  783. self.help_restart()
  784. return
  785. self.do_stop(arg)
  786. self.do_start(arg)
  787. def help_restart(self):
  788. self.ctl.output("restart <name>\t\tRestart a process")
  789. self.ctl.output("restart <gname>:*\tRestart all processes in a group")
  790. self.ctl.output("restart <name> <name>\tRestart multiple processes or "
  791. "groups")
  792. self.ctl.output("restart all\t\tRestart all processes")
  793. self.ctl.output("Note: restart does not reread config files. For that,"
  794. " see reread and update.")
  795. def do_shutdown(self, arg):
  796. if self.ctl.options.interactive:
  797. yesno = raw_input('Really shut the remote supervisord process '
  798. 'down y/N? ')
  799. really = yesno.lower().startswith('y')
  800. else:
  801. really = 1
  802. if really:
  803. supervisor = self.ctl.get_supervisor()
  804. try:
  805. supervisor.shutdown()
  806. except xmlrpclib.Fault as e:
  807. if e.faultCode == xmlrpc.Faults.SHUTDOWN_STATE:
  808. self.ctl.output('ERROR: already shutting down')
  809. else:
  810. raise
  811. except socket.error as e:
  812. if e.args[0] == errno.ECONNREFUSED:
  813. msg = 'ERROR: %s refused connection (already shut down?)'
  814. self.ctl.output(msg % self.ctl.options.serverurl)
  815. elif e.args[0] == errno.ENOENT:
  816. msg = 'ERROR: %s no such file (already shut down?)'
  817. self.ctl.output(msg % self.ctl.options.serverurl)
  818. else:
  819. raise
  820. else:
  821. self.ctl.output('Shut down')
  822. def help_shutdown(self):
  823. self.ctl.output("shutdown \tShut the remote supervisord down.")
  824. def do_reload(self, arg):
  825. if self.ctl.options.interactive:
  826. yesno = raw_input('Really restart the remote supervisord process '
  827. 'y/N? ')
  828. really = yesno.lower().startswith('y')
  829. else:
  830. really = 1
  831. if really:
  832. supervisor = self.ctl.get_supervisor()
  833. try:
  834. supervisor.restart()
  835. except xmlrpclib.Fault as e:
  836. if e.faultCode == xmlrpc.Faults.SHUTDOWN_STATE:
  837. self.ctl.output('ERROR: already shutting down')
  838. else:
  839. raise
  840. else:
  841. self.ctl.output('Restarted supervisord')
  842. def help_reload(self):
  843. self.ctl.output("reload \t\tRestart the remote supervisord.")
  844. def _formatChanges(self, added_changed_dropped_tuple):
  845. added, changed, dropped = added_changed_dropped_tuple
  846. changedict = {}
  847. for n, t in [(added, 'available'),
  848. (changed, 'changed'),
  849. (dropped, 'disappeared')]:
  850. changedict.update(dict(zip(n, [t] * len(n))))
  851. if changedict:
  852. names = list(changedict.keys())
  853. names.sort()
  854. for name in names:
  855. self.ctl.output("%s: %s" % (name, changedict[name]))
  856. else:
  857. self.ctl.output("No config updates to processes")
  858. def _formatConfigInfo(self, configinfo):
  859. name = make_namespec(configinfo['group'], configinfo['name'])
  860. formatted = { 'name': name }
  861. if configinfo['inuse']:
  862. formatted['inuse'] = 'in use'
  863. else:
  864. formatted['inuse'] = 'avail'
  865. if configinfo['autostart']:
  866. formatted['autostart'] = 'auto'
  867. else:
  868. formatted['autostart'] = 'manual'
  869. formatted['priority'] = "%s:%s" % (configinfo['group_prio'],
  870. configinfo['process_prio'])
  871. template = '%(name)-32s %(inuse)-9s %(autostart)-9s %(priority)s'
  872. return template % formatted
  873. def do_avail(self, arg):
  874. supervisor = self.ctl.get_supervisor()
  875. try:
  876. configinfo = supervisor.getAllConfigInfo()
  877. except xmlrpclib.Fault as e:
  878. if e.faultCode == xmlrpc.Faults.SHUTDOWN_STATE:
  879. self.ctl.output('ERROR: supervisor shutting down')
  880. else:
  881. raise
  882. else:
  883. for pinfo in configinfo:
  884. self.ctl.output(self._formatConfigInfo(pinfo))
  885. def help_avail(self):
  886. self.ctl.output("avail\t\t\tDisplay all configured processes")
  887. def do_reread(self, arg):
  888. supervisor = self.ctl.get_supervisor()
  889. try:
  890. result = supervisor.reloadConfig()
  891. except xmlrpclib.Fault as e:
  892. if e.faultCode == xmlrpc.Faults.SHUTDOWN_STATE:
  893. self.ctl.output('ERROR: supervisor shutting down')
  894. elif e.faultCode == xmlrpc.Faults.CANT_REREAD:
  895. self.ctl.output('ERROR: %s' % e.faultString)
  896. else:
  897. raise
  898. else:
  899. self._formatChanges(result[0])
  900. def help_reread(self):
  901. self.ctl.output("reread \t\t\tReload the daemon's configuration files")
  902. def do_add(self, arg):
  903. names = arg.split()
  904. supervisor = self.ctl.get_supervisor()
  905. for name in names:
  906. try:
  907. supervisor.addProcessGroup(name)
  908. except xmlrpclib.Fault as e:
  909. if e.faultCode == xmlrpc.Faults.SHUTDOWN_STATE:
  910. self.ctl.output('ERROR: shutting down')
  911. elif e.faultCode == xmlrpc.Faults.ALREADY_ADDED:
  912. self.ctl.output('ERROR: process group already active')
  913. elif e.faultCode == xmlrpc.Faults.BAD_NAME:
  914. self.ctl.output(
  915. "ERROR: no such process/group: %s" % name)
  916. else:
  917. raise
  918. else:
  919. self.ctl.output("%s: added process group" % name)
  920. def help_add(self):
  921. self.ctl.output("add <name> [...]\tActivates any updates in config "
  922. "for process/group")
  923. def do_remove(self, arg):
  924. names = arg.split()
  925. supervisor = self.ctl.get_supervisor()
  926. for name in names:
  927. try:
  928. supervisor.removeProcessGroup(name)
  929. except xmlrpclib.Fault as e:
  930. if e.faultCode == xmlrpc.Faults.STILL_RUNNING:
  931. self.ctl.output('ERROR: process/group still running: %s'
  932. % name)
  933. elif e.faultCode == xmlrpc.Faults.BAD_NAME:
  934. self.ctl.output(
  935. "ERROR: no such process/group: %s" % name)
  936. else:
  937. raise
  938. else:
  939. self.ctl.output("%s: removed process group" % name)
  940. def help_remove(self):
  941. self.ctl.output("remove <name> [...]\tRemoves process/group from "
  942. "active config")
  943. def do_update(self, arg):
  944. def log(name, message):
  945. self.ctl.output("%s: %s" % (name, message))
  946. supervisor = self.ctl.get_supervisor()
  947. try:
  948. result = supervisor.reloadConfig()
  949. except xmlrpclib.Fault as e:
  950. if e.faultCode == xmlrpc.Faults.SHUTDOWN_STATE:
  951. self.ctl.output('ERROR: already shutting down')
  952. return
  953. else:
  954. raise
  955. added, changed, removed = result[0]
  956. valid_gnames = set(arg.split())
  957. # If all is specified treat it as if nothing was specified.
  958. if "all" in valid_gnames:
  959. valid_gnames = set()
  960. # If any gnames are specified we need to verify that they are
  961. # valid in order to print a useful error message.
  962. if valid_gnames:
  963. groups = set()
  964. for info in supervisor.getAllProcessInfo():
  965. groups.add(info['group'])
  966. # New gnames would not currently exist in this set so
  967. # add those as well.
  968. groups.update(added)
  969. for gname in valid_gnames:
  970. if gname not in groups:
  971. self.ctl.output('ERROR: no such group: %s' % gname)
  972. for gname in removed:
  973. if valid_gnames and gname not in valid_gnames:
  974. continue
  975. results = supervisor.stopProcessGroup(gname)
  976. log(gname, "stopped")
  977. fails = [res for res in results
  978. if res['status'] == xmlrpc.Faults.FAILED]
  979. if fails:
  980. log(gname, "has problems; not removing")
  981. continue
  982. supervisor.removeProcessGroup(gname)
  983. log(gname, "removed process group")
  984. for gname in changed:
  985. if valid_gnames and gname not in valid_gnames:
  986. continue
  987. supervisor.stopProcessGroup(gname)
  988. log(gname, "stopped")
  989. supervisor.removeProcessGroup(gname)
  990. supervisor.addProcessGroup(gname)
  991. log(gname, "updated process group")
  992. for gname in added:
  993. if valid_gnames and gname not in valid_gnames:
  994. continue
  995. supervisor.addProcessGroup(gname)
  996. log(gname, "added process group")
  997. def help_update(self):
  998. self.ctl.output("update\t\t\tReload config and add/remove as necessary")
  999. self.ctl.output("update all\t\tReload config and add/remove as necessary")
  1000. self.ctl.output("update <gname> [...]\tUpdate specific groups")
  1001. def _clearresult(self, result):
  1002. name = make_namespec(result['group'], result['name'])
  1003. code = result['status']
  1004. template = '%s: ERROR (%s)'
  1005. if code == xmlrpc.Faults.BAD_NAME:
  1006. return template % (name, 'no such process')
  1007. elif code == xmlrpc.Faults.FAILED:
  1008. return template % (name, 'failed')
  1009. elif code == xmlrpc.Faults.SUCCESS:
  1010. return '%s: cleared' % name
  1011. raise ValueError('Unknown result code %s for %s' % (code, name))
  1012. def do_clear(self, arg):
  1013. if not self.ctl.upcheck():
  1014. return
  1015. names = arg.split()
  1016. if not names:
  1017. self.ctl.output('Error: clear requires a process name')
  1018. self.help_clear()
  1019. return
  1020. supervisor = self.ctl.get_supervisor()
  1021. if 'all' in names:
  1022. results = supervisor.clearAllProcessLogs()
  1023. for result in results:
  1024. result = self._clearresult(result)
  1025. self.ctl.output(result)
  1026. else:
  1027. for name in names:
  1028. group_name, process_name = split_namespec(name)
  1029. try:
  1030. supervisor.clearProcessLogs(name)
  1031. except xmlrpclib.Fault as e:
  1032. error = self._clearresult({'status': e.faultCode,
  1033. 'name': process_name,
  1034. 'group': group_name,
  1035. 'description': e.faultString})
  1036. self.ctl.output(error)
  1037. else:
  1038. name = make_namespec(group_name, process_name)
  1039. self.ctl.output('%s: cleared' % name)
  1040. def help_clear(self):
  1041. self.ctl.output("clear <name>\t\tClear a process' log files.")
  1042. self.ctl.output(
  1043. "clear <name> <name>\tClear multiple process' log files")
  1044. self.ctl.output("clear all\t\tClear all process' log files")
  1045. def do_open(self, arg):
  1046. url = arg.strip()
  1047. parts = urlparse.urlparse(url)
  1048. if parts[0] not in ('unix', 'http'):
  1049. self.ctl.output('ERROR: url must be http:// or unix://')
  1050. return
  1051. self.ctl.options.serverurl = url
  1052. self.do_status('')
  1053. def help_open(self):
  1054. self.ctl.output("open <url>\tConnect to a remote supervisord process.")
  1055. self.ctl.output("\t\t(for UNIX domain socket, use unix:///socket/path)")
  1056. def do_version(self, arg):
  1057. if not self.ctl.upcheck():
  1058. return
  1059. supervisor = self.ctl.get_supervisor()
  1060. self.ctl.output(supervisor.getSupervisorVersion())
  1061. def help_version(self):
  1062. self.ctl.output(
  1063. "version\t\t\tShow the version of the remote supervisord "
  1064. "process")
  1065. def do_fg(self,args=None):
  1066. if not self.ctl.upcheck():
  1067. return
  1068. if not args:
  1069. self.ctl.output('Error: no process name supplied')
  1070. self.help_fg()
  1071. return
  1072. args = args.split()
  1073. if len(args) > 1:
  1074. self.ctl.output('Error: too many process names supplied')
  1075. return
  1076. program = args[0]
  1077. supervisor = self.ctl.get_supervisor()
  1078. try:
  1079. info = supervisor.getProcessInfo(program)
  1080. except xmlrpclib.Fault as msg:
  1081. if msg.faultCode == xmlrpc.Faults.BAD_NAME:
  1082. self.ctl.output('Error: bad process name supplied')
  1083. return
  1084. # for any other fault
  1085. self.ctl.output(str(msg))
  1086. return
  1087. if not info['state'] == states.ProcessStates.RUNNING:
  1088. self.ctl.output('Error: process not running')
  1089. return
  1090. # everything good; continue
  1091. a = None
  1092. try:
  1093. a = fgthread(program,self.ctl)
  1094. # this thread takes care of
  1095. # the output/error messages
  1096. a.start()
  1097. while True:
  1098. # this takes care of the user input
  1099. inp = raw_input() + '\n'
  1100. try:
  1101. supervisor.sendProcessStdin(program, inp)
  1102. except xmlrpclib.Fault as msg:
  1103. if msg.faultCode == xmlrpc.Faults.NOT_RUNNING:
  1104. self.ctl.output('Process got killed')
  1105. self.ctl.output('Exiting foreground')
  1106. a.kill()
  1107. return
  1108. info = supervisor.getProcessInfo(program)
  1109. if not info['state'] == states.ProcessStates.RUNNING:
  1110. self.ctl.output('Process got killed')
  1111. self.ctl.output('Exiting foreground')
  1112. a.kill()
  1113. return
  1114. continue
  1115. except (KeyboardInterrupt, EOFError):
  1116. if a:
  1117. a.kill()
  1118. self.ctl.output('Exiting foreground')
  1119. return
  1120. def help_fg(self,args=None):
  1121. self.ctl.output('fg <process>\tConnect to a process in foreground mode')
  1122. self.ctl.output('Press Ctrl+C to exit foreground')
  1123. def main(args=None, options=None):
  1124. if options is None:
  1125. options = ClientOptions()
  1126. options.realize(args, doc=__doc__)
  1127. c = Controller(options)
  1128. if options.args:
  1129. c.onecmd(" ".join(options.args))
  1130. if options.interactive:
  1131. c.exec_cmdloop(args, options)
  1132. if __name__ == "__main__":
  1133. main()