sup_process.py 2.5 KB
Newer Older
1 2
# pylint: disable-msg=W0311,C0103

3 4
import os
import signal
5
import time
6
import six.moves.xmlrpc_client as xmlrpclib
7 8 9 10 11

# This mini-library is used to communicate with supervisord process
# It aims to replace the file "process.py"
# For the moment, we keep both for compatibility

12

13
def isRunning(config, process):
14 15 16
  """
  Ask supervisor if given process is currently running
  """
17 18
  server = xmlrpclib.Server(config['supervisord_server'])
  state = server.supervisor.getProcessInfo(process)['state']
19 20 21 22
  return (True if state in (10, 20) else False)


def killRunningProcess(config, process, sig=signal.SIGTERM):
23 24 25 26
  """
  Send signal "sig" to given process.
  Default signal sent is SIGTERM
  """
27 28 29 30
  server = xmlrpclib.Server(config['supervisord_server'])
  pid = server.supervisor.getProcessInfo(process)['pid']
  if pid != 0:
    os.kill(pid, sig)
31 32 33


def returnCode(config, process):
34 35 36
  """
  Get the returned code of the last run of given process
  """
37 38 39 40 41 42
  server = xmlrpclib.Server(config['supervisord_server'])
  code = server.supervisor.getProcessInfo(process)['exitstatus']
  return code


def runProcess(config, process):
43 44 45
  """
  Start a process registered by supervisor
  """
46
  server = xmlrpclib.Server(config['supervisord_server'])
47
  return server.supervisor.startProcess(process)
48 49 50


def runProcesses(config, processes):
51 52 53
  """
  Start by supervisor a list of given processes, one by one
  """
54 55 56
  server = xmlrpclib.Server(config['supervisord_server'])
  for proc in processes:
    server.supervisor.startProcess(proc)
57
    waitForProcessEnd(config, proc)
58 59


60 61 62 63
def stopProcess(config, process):
  """
  Ask supervisor to stop a process
  """
64 65
  if isRunning(config, process):
    server = xmlrpclib.Server(config['supervisord_server'])
66
    return server.supervisor.stopProcess(process)
67 68 69


def stopProcesses(config, processes):
70
  """
71 72 73
  Stop a list of processes.
  Returns True if all the processes have ended correctly.
  Returns False if at least one process didn't stop correctly.
74
  """
75
  server = xmlrpclib.Server(config['supervisord_server'])
76
  return_status_list = []
77
  for proc in processes:
78 79 80
    return_status_list.append(server.supervisor.stopProcess(proc))
  return len(return_status_list) == sum(return_status_list)

81 82


83
def waitForProcessEnd(config, process):
84 85 86
  """
  Block program's execution until given process quits Running state
  """
87 88 89 90
  server = xmlrpclib.Server(config['supervisord_server'])
  while True:
    state = server.supervisor.getProcessInfo(process)['state']
    if state == 20:
91 92 93
      time.sleep(3)
    else:
      return True
94
  return False