1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation, either version 3 of the License, or
6 # (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 # The author may be contacted at <wking@drexel.edu> on the Internet, or
17 # write to Trevor King, Drexel University, Physics Dept., 3141 Chestnut St.,
18 # Philadelphia PA 19104, USA.
20 """Functions for running external commands on other hosts.
24 from multiprocessing import Manager, Process, Queue, cpu_count
26 except ImportError, multiprocessing_error:
28 _SKIP = ' # doctest: +SKIP'
32 from .thread import ThreadManager, CLOSE_MESSAGE
34 class WorkerProcess (Process):
35 def __init__(self, spawn_queue, receive_queue, *args, **kwargs):
37 raise multiprocessing_error
38 super(WorkerProcess, self).__init__(*args, **kwargs)
39 self.spawn_queue = spawn_queue
40 self.receive_queue = receive_queue
44 msg = self.spawn_queue.get()
45 if msg == CLOSE_MESSAGE:
46 log().debug('%s closing' % self.name)
48 assert isinstance(msg, Job), msg
49 log().debug('%s running job %s' % (self.name, msg))
51 self.receive_queue.put(msg)
54 class SubprocessManager (ThreadManager):
55 """Manage asynchronous `Job` execution via :mod:`subprocess`.
57 >>> from time import sleep
58 >>> from math import sqrt
59 >>> m = SubprocessManager()%(skip)s
61 >>> for i in range(10):%(skip)s
63 ... group_A.append(m.async_invoke(Job(target=sleep, args=[t])))
65 >>> for i in range(10):%(skip)s
66 ... group_B.append(m.async_invoke(Job(target=sqrt, args=[i],
67 ... blocks_on=[j.id for j in group_A])))
68 >>> jobs = m.wait(ids=[j.id for j in group_A[5:8]])%(skip)s
69 >>> print sorted(jobs.values(), key=lambda j: j.id)%(skip)s
70 [<Job 5>, <Job 6>, <Job 7>]
71 >>> jobs = m.wait()%(skip)s
72 >>> print sorted(jobs.values(), key=lambda j: j.id)%(skip)s
73 ... # doctest: +NORMALIZE_WHITESPACE
74 [<Job 0>, <Job 1>, <Job 2>, <Job 3>, <Job 4>, <Job 8>, <Job 9>, <Job 10>,
75 <Job 11>, <Job 12>, <Job 13>, <Job 14>, <Job 15>, <Job 16>, <Job 17>,
77 >>> m.teardown()%(skip)s
79 def __init__(self, worker_pool=None):
81 raise multiprocessing_error
82 super(SubprocessManager, self).__init__(worker_pool=worker_pool)
84 def _setup_queues(self):
85 self._spawn_queue = Queue()
86 self._receive_queue = Queue()
88 def _spawn_workers(self, worker_pool=None):
89 if worker_pool == None:
90 worker_pool = cpu_count() + 1
91 self._manager = Manager()
93 for i in range(worker_pool):
94 worker = WorkerProcess(spawn_queue=self._spawn_queue,
95 receive_queue=self._receive_queue,
97 log().debug('start %s' % worker.name)
99 self._workers.append(worker)
101 def _put_job_in_spawn_queue(self, job):
102 """Place a job in the spawn queue."""
103 self._spawn_queue.put(job)