Disable pysawsim.manager.subproc is multiprocessing is missing.
[sawsim.git] / pysawsim / manager / subproc.py
1 # Copyright (C) 2010  W. Trevor King <wking@drexel.edu>
2 #
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.
7 #
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.
12 #
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/>.
15 #
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.
19
20 """Functions for running external commands on other hosts.
21 """
22
23 try:
24     from multiprocessing import Manager, Process, Queue, cpu_count
25     _SKIP = ''
26 except ImportError, multiprocessing_error:
27     Process = object
28     _SKIP = '  # doctest: +SKIP'
29
30 from .. import log
31 from . import Job
32 from .thread import ThreadManager, CLOSE_MESSAGE
33
34 class WorkerProcess (Process):
35     def __init__(self, spawn_queue, receive_queue, *args, **kwargs):
36         if Process == object:
37             raise multiprocessing_error
38         super(WorkerProcess, self).__init__(*args, **kwargs)
39         self.spawn_queue = spawn_queue
40         self.receive_queue = receive_queue
41
42     def run(self):
43         while True:
44             msg = self.spawn_queue.get()
45             if msg == CLOSE_MESSAGE:
46                 log().debug('%s closing' % self.name)
47                 break
48             assert isinstance(msg, Job), msg
49             log().debug('%s running job %s' % (self.name, msg))
50             msg.run()
51             self.receive_queue.put(msg)
52
53
54 class SubprocessManager (ThreadManager):
55     """Manage asynchronous `Job` execution via :mod:`subprocess`.
56
57     >>> from time import sleep
58     >>> from math import sqrt
59     >>> m = SubprocessManager()%(skip)s
60     >>> group_A = []
61     >>> for i in range(10):%(skip)s
62     ...     t = max(0, 5-i)
63     ...     group_A.append(m.async_invoke(Job(target=sleep, args=[t])))
64     >>> group_B = []
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>,
76      <Job 18>, <Job 19>]
77     >>> m.teardown()%(skip)s
78     """ % {'skip': _SKIP}
79     def __init__(self, worker_pool=None):
80         if Process == object:
81             raise multiprocessing_error
82         super(SubprocessManager, self).__init__(worker_pool=worker_pool)
83
84     def _setup_queues(self):
85         self._spawn_queue = Queue()
86         self._receive_queue = Queue()
87
88     def _spawn_workers(self, worker_pool=None):
89         if worker_pool == None:
90             worker_pool = cpu_count() + 1
91         self._manager = Manager()
92         self._workers = []
93         for i in range(worker_pool):
94             worker = WorkerProcess(spawn_queue=self._spawn_queue,
95                                    receive_queue=self._receive_queue,
96                                    name='worker-%d' % i)
97             log().debug('start %s' % worker.name)
98             worker.start()
99             self._workers.append(worker)
100
101     def _put_job_in_spawn_queue(self, job):
102         """Place a job in the spawn queue."""
103         self._spawn_queue.put(job)