childutils.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import sys
  2. import time
  3. import xmlrpclib
  4. from supervisor.xmlrpc import SupervisorTransport
  5. from supervisor.events import ProcessCommunicationEvent
  6. from supervisor.dispatchers import PEventListenerDispatcher
  7. def getRPCTransport(env):
  8. u = env.get('SUPERVISOR_USERNAME', '')
  9. p = env.get('SUPERVISOR_PASSWORD', '')
  10. return SupervisorTransport(u, p, env['SUPERVISOR_SERVER_URL'])
  11. def getRPCInterface(env):
  12. # dumbass ServerProxy won't allow us to pass in a non-HTTP url,
  13. # so we fake the url we pass into it and always use the transport's
  14. # 'serverurl' to figure out what to attach to
  15. return xmlrpclib.ServerProxy('http://127.0.0.1', getRPCTransport(env))
  16. def get_headers(line):
  17. return dict([ x.split(':') for x in line.split() ])
  18. def eventdata(payload):
  19. headerinfo, data = payload.split('\n', 1)
  20. headers = get_headers(headerinfo)
  21. return headers, data
  22. def get_asctime(now=None):
  23. if now is None: # for testing
  24. now = time.time() # pragma: no cover
  25. msecs = (now - long(now)) * 1000
  26. part1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now))
  27. asctime = '%s,%03d' % (part1, msecs)
  28. return asctime
  29. class ProcessCommunicationsProtocol:
  30. def send(self, msg, fp=sys.stdout):
  31. fp.write(ProcessCommunicationEvent.BEGIN_TOKEN)
  32. fp.write(msg)
  33. fp.write(ProcessCommunicationEvent.END_TOKEN)
  34. def stdout(self, msg):
  35. return self.send(msg, sys.stdout)
  36. def stderr(self, msg):
  37. return self.send(msg, sys.stderr)
  38. pcomm = ProcessCommunicationsProtocol()
  39. class EventListenerProtocol:
  40. def wait(self, stdin=sys.stdin, stdout=sys.stdout):
  41. self.ready(stdout)
  42. line = stdin.readline()
  43. headers = get_headers(line)
  44. payload = stdin.read(int(headers['len']))
  45. return headers, payload
  46. def ready(self, stdout=sys.stdout):
  47. stdout.write(PEventListenerDispatcher.READY_FOR_EVENTS_TOKEN)
  48. stdout.flush()
  49. def ok(self, stdout=sys.stdout):
  50. self.send('OK', stdout)
  51. def fail(self, stdout=sys.stdout):
  52. self.send('FAIL', stdout)
  53. def send(self, data, stdout=sys.stdout):
  54. resultlen = len(data)
  55. result = '%s%s\n%s' % (PEventListenerDispatcher.RESULT_TOKEN_START,
  56. str(resultlen),
  57. data)
  58. stdout.write(result)
  59. stdout.flush()
  60. listener = EventListenerProtocol()