2014-09-17 02:43:19 +00:00
|
|
|
from multiprocessing import Process, Queue
|
|
|
|
import logging
|
|
|
|
import multiprocessing
|
|
|
|
import os
|
|
|
|
import time
|
2014-10-08 18:18:41 +00:00
|
|
|
import sys
|
|
|
|
import traceback
|
2014-09-17 02:43:19 +00:00
|
|
|
|
|
|
|
logger = multiprocessing.log_to_stderr()
|
|
|
|
logger.setLevel(logging.INFO)
|
|
|
|
|
|
|
|
class QueueProcess(object):
|
|
|
|
""" Helper class which invokes a worker in a process to produce
|
|
|
|
data for one (or more) queues.
|
|
|
|
"""
|
2014-10-21 21:40:57 +00:00
|
|
|
def __init__(self, get_producer, chunk_size, max_size, args, finished=None):
|
2014-09-17 02:43:19 +00:00
|
|
|
self._get_producer = get_producer
|
|
|
|
self._queues = []
|
|
|
|
self._chunk_size = chunk_size
|
|
|
|
self._max_size = max_size
|
|
|
|
self._args = args or []
|
2014-10-21 21:40:57 +00:00
|
|
|
self._finished = finished
|
2014-09-17 02:43:19 +00:00
|
|
|
|
|
|
|
def create_queue(self):
|
|
|
|
""" Adds a multiprocessing queue to the list of queues. Any queues added
|
|
|
|
will have the data produced appended.
|
|
|
|
"""
|
|
|
|
queue = Queue(self._max_size / self._chunk_size)
|
|
|
|
self._queues.append(queue)
|
|
|
|
return queue
|
|
|
|
|
|
|
|
@staticmethod
|
2014-10-21 21:40:57 +00:00
|
|
|
def run_process(target, args, finished=None):
|
|
|
|
def _target(tar, arg, fin):
|
|
|
|
try:
|
|
|
|
tar(*args)
|
|
|
|
finally:
|
|
|
|
if fin:
|
|
|
|
fin()
|
|
|
|
|
|
|
|
Process(target=_target, args=(target, args, finished)).start()
|
2014-09-17 02:43:19 +00:00
|
|
|
|
|
|
|
def run(self):
|
|
|
|
# Important! gipc is used here because normal multiprocessing does not work
|
|
|
|
# correctly with gevent when we sleep.
|
|
|
|
args = (self._get_producer, self._queues, self._chunk_size, self._args)
|
2014-10-21 21:40:57 +00:00
|
|
|
QueueProcess.run_process(_run, args, finished=self._finished)
|
2014-09-17 02:43:19 +00:00
|
|
|
|
|
|
|
def _run(get_producer, queues, chunk_size, args):
|
|
|
|
producer = get_producer(*args)
|
|
|
|
while True:
|
2014-09-29 16:54:22 +00:00
|
|
|
try:
|
|
|
|
data = producer(chunk_size) or None
|
2014-10-08 18:20:57 +00:00
|
|
|
except Exception as ex:
|
|
|
|
message = '%s\n%s' % (ex.message, "".join(traceback.format_exception(*sys.exc_info())))
|
|
|
|
data = Exception(message)
|
2014-09-29 16:54:22 +00:00
|
|
|
|
2014-09-17 02:43:19 +00:00
|
|
|
for queue in queues:
|
|
|
|
try:
|
2014-10-14 17:58:08 +00:00
|
|
|
queue.put(data, block=True)
|
2014-09-17 02:43:19 +00:00
|
|
|
except Exception as ex:
|
2014-10-14 17:58:08 +00:00
|
|
|
logger.exception('Exception writing to queue.')
|
2014-09-17 02:43:19 +00:00
|
|
|
return
|
|
|
|
|
2014-09-29 16:54:22 +00:00
|
|
|
if data is None or isinstance(data, Exception):
|
2014-09-17 02:43:19 +00:00
|
|
|
break
|
|
|
|
|
|
|
|
# Important! This allows the thread that writes the queue data to the pipe
|
|
|
|
# to do so. Otherwise, this hangs.
|
|
|
|
time.sleep(0)
|
|
|
|
|