Source

mycloud / src / mycloud / worker.py

Full commit
#!/usr/bin/env python

from cloud.serialization import cloudpickle
from mycloud.util import XMLServer
import argparse
import cPickle
import logging
import mycloud.thread
import mycloud.util
import os
import select
import socket
import sys
import time
import xmlrpclib

mycloud.thread.init()

__doc__ = '''Worker for executing cluster tasks.'''

def watchdog(worker):
  while 1:
    r, w, x = select.select([sys.stdin], [], [sys.stdin], 1)
    if r or x:
      logging.info('Lost controller.  Exiting.')
      os._exit(1)

class Worker(XMLServer):
  def __init__(self, *args, **kw):
    XMLServer.__init__(self, *args, **kw)

    self.host = socket.gethostname()
    self.port = self.server_address[1]
    self.last_keepalive = time.time()

    logging.info('Worker starting on %s:%s', self.host, self.port)

  def execute_task(self, pickled):
    try:
      f, args, kw = cPickle.loads(pickled.data)
      logging.info('Executing task %s %s %s', f, args, kw)
      result = f(*args, **kw)
      dump = cloudpickle.dumps(result)
      logging.info('Got result!')
      return xmlrpclib.Binary(dump)
    except:
      logging.info('Failed to execute task.', exc_info=1)
      raise

  def healthcheck(self):
    self.last_keepalive = time.time()
    return 'alive'

if __name__ == '__main__':
  p = argparse.ArgumentParser()
  p.add_argument('--index', type=int)
  p.add_argument('--logger_host', type=str)
  p.add_argument('--logger_port', type=int)
  p.add_argument('--worker_name', type=str, default='worker')

  opts = p.parse_args()

  index = opts.index
  myport = mycloud.util.find_open_port()

  log_prefix = '/tmp/%s-worker-%03d' % (socket.gethostname(), index)

  logging.basicConfig(stream=open(log_prefix + '.log', 'w'),
                      format='%(asctime)s %(funcName)s %(message)s',
                      level=logging.INFO)

  if opts.logger_host:
    logging.info('Additionally logging to %s:%s',
                 opts.logger_host, opts.logger_port)

    logging.getLogger().addHandler(
      logging.handlers.DatagramHandler(opts.logger_host, opts.logger_port))

  worker = Worker(('0.0.0.0', myport))
  worker.timeout = 1

  print myport
  sys.stdout.flush()

  # redirect stdout and stderr to local files to avoid pipe/buffering issues
  # with controller 
  sys.stdout = open(log_prefix + '.out', 'w')
  sys.stderr = open(log_prefix + '.err', 'w')

  mycloud.thread.spawn(watchdog, worker)

  # handle requests until we lose our stdin connection the controller
  try:
    while 1:
      worker.handle_request()
  except:
    logging.info('Error while serving.', exc_info=1)


  logging.info('Shutting down.')