supervisorctl.py 47 KB

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