paulb@40 | 1 | #!/usr/bin/env python |
paulb@40 | 2 | |
paulb@40 | 3 | """ |
paulb@40 | 4 | A simple parallel processing API for Python, inspired somewhat by the thread |
paulb@40 | 5 | module, slightly less by pypar, and slightly less still by pypvm. |
paulb@40 | 6 | |
paulb@135 | 7 | Copyright (C) 2005, 2006, 2007, 2008 Paul Boddie <paul@boddie.org.uk> |
paulb@41 | 8 | |
paulb@79 | 9 | This program is free software; you can redistribute it and/or modify it under |
paulb@79 | 10 | the terms of the GNU Lesser General Public License as published by the Free |
paulb@79 | 11 | Software Foundation; either version 3 of the License, or (at your option) any |
paulb@79 | 12 | later version. |
paulb@41 | 13 | |
paulb@79 | 14 | This program is distributed in the hope that it will be useful, but WITHOUT |
paulb@79 | 15 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
paulb@79 | 16 | FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more |
paulb@79 | 17 | details. |
paulb@41 | 18 | |
paulb@79 | 19 | You should have received a copy of the GNU Lesser General Public License along |
paulb@79 | 20 | with this program. If not, see <http://www.gnu.org/licenses/>. |
paulb@40 | 21 | """ |
paulb@40 | 22 | |
paulb@135 | 23 | __version__ = "0.3.2" |
paulb@40 | 24 | |
paulb@40 | 25 | import os |
paulb@40 | 26 | import sys |
paulb@40 | 27 | import select |
paulb@40 | 28 | import socket |
paulb@40 | 29 | |
paulb@40 | 30 | try: |
paulb@40 | 31 | import cPickle as pickle |
paulb@40 | 32 | except ImportError: |
paulb@40 | 33 | import pickle |
paulb@40 | 34 | |
paulb@135 | 35 | try: |
paulb@135 | 36 | set |
paulb@135 | 37 | except NameError: |
paulb@135 | 38 | from sets import Set as set |
paulb@135 | 39 | |
paulb@84 | 40 | # Communications. |
paulb@84 | 41 | |
paulb@40 | 42 | class AcknowledgementError(Exception): |
paulb@40 | 43 | pass |
paulb@40 | 44 | |
paulb@40 | 45 | class Channel: |
paulb@40 | 46 | |
paulb@40 | 47 | "A communications channel." |
paulb@40 | 48 | |
paulb@40 | 49 | def __init__(self, pid, read_pipe, write_pipe): |
paulb@40 | 50 | |
paulb@40 | 51 | """ |
paulb@40 | 52 | Initialise the channel with a process identifier 'pid', a 'read_pipe' |
paulb@40 | 53 | from which messages will be received, and a 'write_pipe' into which |
paulb@40 | 54 | messages will be sent. |
paulb@40 | 55 | """ |
paulb@40 | 56 | |
paulb@40 | 57 | self.pid = pid |
paulb@40 | 58 | self.read_pipe = read_pipe |
paulb@40 | 59 | self.write_pipe = write_pipe |
paulb@40 | 60 | |
paulb@40 | 61 | def __del__(self): |
paulb@40 | 62 | |
paulb@40 | 63 | # Since signals don't work well with I/O, we close pipes and wait for |
paulb@40 | 64 | # created processes upon finalisation. |
paulb@40 | 65 | |
paulb@40 | 66 | self.close() |
paulb@40 | 67 | |
paulb@40 | 68 | def close(self): |
paulb@40 | 69 | |
paulb@40 | 70 | "Explicitly close the channel." |
paulb@40 | 71 | |
paulb@140 | 72 | if self.read_pipe is not None: |
paulb@40 | 73 | self.read_pipe.close() |
paulb@140 | 74 | self.read_pipe = None |
paulb@140 | 75 | if self.write_pipe is not None: |
paulb@40 | 76 | self.write_pipe.close() |
paulb@140 | 77 | self.write_pipe = None |
paulb@140 | 78 | #self.wait(os.WNOHANG) |
paulb@40 | 79 | |
paulb@40 | 80 | def wait(self, options=0): |
paulb@40 | 81 | |
paulb@40 | 82 | "Wait for the created process, if any, to exit." |
paulb@40 | 83 | |
paulb@40 | 84 | if self.pid != 0: |
paulb@40 | 85 | try: |
paulb@40 | 86 | os.waitpid(self.pid, options) |
paulb@40 | 87 | except OSError: |
paulb@40 | 88 | pass |
paulb@40 | 89 | |
paulb@40 | 90 | def _send(self, obj): |
paulb@40 | 91 | |
paulb@40 | 92 | "Send the given object 'obj' through the channel." |
paulb@40 | 93 | |
paulb@40 | 94 | pickle.dump(obj, self.write_pipe) |
paulb@40 | 95 | self.write_pipe.flush() |
paulb@40 | 96 | |
paulb@40 | 97 | def send(self, obj): |
paulb@40 | 98 | |
paulb@40 | 99 | """ |
paulb@40 | 100 | Send the given object 'obj' through the channel. Then wait for an |
paulb@40 | 101 | acknowledgement. (The acknowledgement makes the caller wait, thus |
paulb@40 | 102 | preventing processes from exiting and disrupting the communications |
paulb@40 | 103 | channel and losing data.) |
paulb@40 | 104 | """ |
paulb@40 | 105 | |
paulb@40 | 106 | self._send(obj) |
paulb@40 | 107 | if self._receive() != "OK": |
paulb@40 | 108 | raise AcknowledgementError, obj |
paulb@40 | 109 | |
paulb@40 | 110 | def _receive(self): |
paulb@40 | 111 | |
paulb@40 | 112 | "Receive an object through the channel, returning the object." |
paulb@40 | 113 | |
paulb@40 | 114 | obj = pickle.load(self.read_pipe) |
paulb@40 | 115 | if isinstance(obj, Exception): |
paulb@40 | 116 | raise obj |
paulb@40 | 117 | else: |
paulb@40 | 118 | return obj |
paulb@40 | 119 | |
paulb@40 | 120 | def receive(self): |
paulb@40 | 121 | |
paulb@40 | 122 | """ |
paulb@40 | 123 | Receive an object through the channel, returning the object. Send an |
paulb@40 | 124 | acknowledgement of receipt. (The acknowledgement makes the sender wait, |
paulb@40 | 125 | thus preventing processes from exiting and disrupting the communications |
paulb@40 | 126 | channel and losing data.) |
paulb@40 | 127 | """ |
paulb@40 | 128 | |
paulb@40 | 129 | try: |
paulb@40 | 130 | obj = self._receive() |
paulb@40 | 131 | return obj |
paulb@40 | 132 | finally: |
paulb@40 | 133 | self._send("OK") |
paulb@40 | 134 | |
paulb@140 | 135 | class PersistentChannel(Channel): |
paulb@140 | 136 | |
paulb@140 | 137 | """ |
paulb@140 | 138 | A persistent communications channel which can handle peer disconnection, |
paulb@140 | 139 | acting as a server, meaning that this channel is associated with a specific |
paulb@140 | 140 | address which can be contacted by other processes. |
paulb@140 | 141 | """ |
paulb@140 | 142 | |
paulb@140 | 143 | def __init__(self, pid, endpoint, address): |
paulb@140 | 144 | Channel.__init__(self, pid, None, None) |
paulb@140 | 145 | self.endpoint = endpoint |
paulb@140 | 146 | self.address = address |
paulb@140 | 147 | self.poller = select.poll() |
paulb@140 | 148 | self._ensure_pipes() |
paulb@140 | 149 | |
paulb@140 | 150 | def close(self): |
paulb@140 | 151 | #print "Closing persistent channel" |
paulb@140 | 152 | Channel.close(self) |
paulb@140 | 153 | try: |
paulb@140 | 154 | os.unlink(self.address) |
paulb@140 | 155 | except OSError: |
paulb@140 | 156 | pass |
paulb@140 | 157 | |
paulb@140 | 158 | def _ensure_pipes(self): |
paulb@140 | 159 | |
paulb@140 | 160 | "Ensure that the channel is capable of communicating." |
paulb@140 | 161 | |
paulb@140 | 162 | if self.read_pipe is None or self.write_pipe is None: |
paulb@140 | 163 | #print "Waiting for connection" |
paulb@140 | 164 | self.endpoint.listen(1) |
paulb@140 | 165 | endpoint, address = self.endpoint.accept() |
paulb@140 | 166 | self.read_pipe = endpoint.makefile("r", 0) |
paulb@140 | 167 | self.write_pipe = endpoint.makefile("w", 0) |
paulb@140 | 168 | |
paulb@140 | 169 | # Monitor the write pipe for error conditions. |
paulb@140 | 170 | |
paulb@140 | 171 | fileno = self.write_pipe.fileno() |
paulb@140 | 172 | self.poller.register(fileno, select.POLLOUT | select.POLLHUP | select.POLLNVAL | select.POLLERR) |
paulb@140 | 173 | |
paulb@140 | 174 | def _reset_pipes(self): |
paulb@140 | 175 | fileno = self.write_pipe.fileno() |
paulb@140 | 176 | self.poller.unregister(fileno) |
paulb@140 | 177 | self.read_pipe = None |
paulb@140 | 178 | self.write_pipe = None |
paulb@140 | 179 | |
paulb@140 | 180 | def _ensure_communication(self, timeout=None): |
paulb@140 | 181 | |
paulb@140 | 182 | "Ensure that sending and receiving are possible." |
paulb@140 | 183 | |
paulb@140 | 184 | while 1: |
paulb@140 | 185 | fileno = self.write_pipe.fileno() |
paulb@140 | 186 | fds = self.poller.poll(timeout) |
paulb@140 | 187 | for fd, status in fds: |
paulb@140 | 188 | if fd != fileno: |
paulb@140 | 189 | continue |
paulb@140 | 190 | if status & (select.POLLHUP | select.POLLNVAL | select.POLLERR): |
paulb@140 | 191 | #print "Broken connection" |
paulb@140 | 192 | self._reset_pipes() |
paulb@140 | 193 | self._ensure_pipes() |
paulb@140 | 194 | break |
paulb@140 | 195 | else: |
paulb@140 | 196 | return |
paulb@140 | 197 | |
paulb@140 | 198 | def _send(self, obj): |
paulb@140 | 199 | |
paulb@140 | 200 | "Send the given object 'obj' through the channel." |
paulb@140 | 201 | |
paulb@140 | 202 | self._ensure_communication() |
paulb@140 | 203 | Channel._send(self, obj) |
paulb@140 | 204 | |
paulb@140 | 205 | def _receive(self): |
paulb@140 | 206 | |
paulb@140 | 207 | "Receive an object through the channel, returning the object." |
paulb@140 | 208 | |
paulb@140 | 209 | self._ensure_communication() |
paulb@140 | 210 | return Channel._receive(self) |
paulb@140 | 211 | |
paulb@84 | 212 | # Management of processes and communications. |
paulb@84 | 213 | |
paulb@40 | 214 | class Exchange: |
paulb@40 | 215 | |
paulb@40 | 216 | """ |
paulb@40 | 217 | A communications exchange that can be used to detect channels which are |
paulb@67 | 218 | ready to communicate. Subclasses of this class can define the 'store_data' |
paulb@67 | 219 | method in order to enable the 'add_wait', 'wait' and 'finish' methods. |
paulb@40 | 220 | """ |
paulb@40 | 221 | |
paulb@116 | 222 | def __init__(self, channels=None, limit=None, reuse=0, autoclose=1): |
paulb@40 | 223 | |
paulb@40 | 224 | """ |
paulb@67 | 225 | Initialise the exchange with an optional list of 'channels'. |
paulb@67 | 226 | |
paulb@67 | 227 | If the optional 'limit' is specified, restrictions on the addition of |
paulb@67 | 228 | new channels can be enforced and observed through the 'add_wait', 'wait' |
paulb@67 | 229 | and 'finish' methods. To make use of these methods, create a subclass of |
paulb@67 | 230 | this class and define a working 'store_data' method. |
paulb@67 | 231 | |
paulb@116 | 232 | If the optional 'reuse' parameter is set to a true value, channels and |
paulb@116 | 233 | processes will be reused for waiting computations. |
paulb@116 | 234 | |
paulb@67 | 235 | If the optional 'autoclose' parameter is set to a false value, channels |
paulb@67 | 236 | will not be closed automatically when they are removed from the exchange |
paulb@67 | 237 | - by default they are closed when removed. |
paulb@40 | 238 | """ |
paulb@40 | 239 | |
paulb@67 | 240 | self.limit = limit |
paulb@116 | 241 | self.reuse = reuse |
paulb@116 | 242 | self.autoclose = autoclose |
paulb@99 | 243 | self.waiting = [] |
paulb@40 | 244 | self.readables = {} |
paulb@58 | 245 | self.removed = [] |
paulb@40 | 246 | self.poller = select.poll() |
paulb@40 | 247 | for channel in channels or []: |
paulb@40 | 248 | self.add(channel) |
paulb@40 | 249 | |
paulb@40 | 250 | def add(self, channel): |
paulb@40 | 251 | |
paulb@40 | 252 | "Add the given 'channel' to the exchange." |
paulb@40 | 253 | |
paulb@140 | 254 | fileno = channel.read_pipe.fileno() |
paulb@140 | 255 | self.readables[fileno] = channel |
paulb@140 | 256 | self.poller.register(fileno, select.POLLIN | select.POLLHUP | select.POLLNVAL | select.POLLERR) |
paulb@40 | 257 | |
paulb@40 | 258 | def active(self): |
paulb@40 | 259 | |
paulb@40 | 260 | "Return a list of active channels." |
paulb@40 | 261 | |
paulb@40 | 262 | return self.readables.values() |
paulb@40 | 263 | |
paulb@40 | 264 | def ready(self, timeout=None): |
paulb@40 | 265 | |
paulb@40 | 266 | """ |
paulb@40 | 267 | Wait for a period of time specified by the optional 'timeout' (or until |
paulb@40 | 268 | communication is possible) and return a list of channels which are ready |
paulb@40 | 269 | to be read from. |
paulb@40 | 270 | """ |
paulb@40 | 271 | |
paulb@40 | 272 | fds = self.poller.poll(timeout) |
paulb@40 | 273 | readables = [] |
paulb@58 | 274 | self.removed = [] |
paulb@58 | 275 | |
paulb@40 | 276 | for fd, status in fds: |
paulb@40 | 277 | channel = self.readables[fd] |
paulb@55 | 278 | removed = 0 |
paulb@40 | 279 | |
paulb@40 | 280 | # Remove ended/error channels. |
paulb@40 | 281 | |
paulb@40 | 282 | if status & (select.POLLHUP | select.POLLNVAL | select.POLLERR): |
paulb@40 | 283 | self.remove(channel) |
paulb@58 | 284 | self.removed.append(channel) |
paulb@55 | 285 | removed = 1 |
paulb@40 | 286 | |
paulb@40 | 287 | # Record readable channels. |
paulb@40 | 288 | |
paulb@55 | 289 | if status & select.POLLIN: |
paulb@55 | 290 | if not (removed and self.autoclose): |
paulb@55 | 291 | readables.append(channel) |
paulb@40 | 292 | |
paulb@40 | 293 | return readables |
paulb@40 | 294 | |
paulb@40 | 295 | def remove(self, channel): |
paulb@40 | 296 | |
paulb@40 | 297 | """ |
paulb@40 | 298 | Remove the given 'channel' from the exchange. |
paulb@40 | 299 | """ |
paulb@40 | 300 | |
paulb@40 | 301 | del self.readables[channel.read_pipe.fileno()] |
paulb@40 | 302 | self.poller.unregister(channel.read_pipe.fileno()) |
paulb@40 | 303 | if self.autoclose: |
paulb@40 | 304 | channel.close() |
paulb@40 | 305 | channel.wait() |
paulb@40 | 306 | |
paulb@67 | 307 | # Enhanced exchange methods involving channel limits. |
paulb@67 | 308 | |
paulb@67 | 309 | def add_wait(self, channel): |
paulb@67 | 310 | |
paulb@67 | 311 | """ |
paulb@67 | 312 | Add the given 'channel' to the exchange, waiting if the limit on active |
paulb@67 | 313 | channels would be exceeded by adding the channel. |
paulb@67 | 314 | """ |
paulb@67 | 315 | |
paulb@67 | 316 | self.wait() |
paulb@67 | 317 | self.add(channel) |
paulb@67 | 318 | |
paulb@67 | 319 | def wait(self): |
paulb@67 | 320 | |
paulb@67 | 321 | """ |
paulb@67 | 322 | Test for the limit on channels, blocking and reading incoming data until |
paulb@67 | 323 | the number of channels is below the limit. |
paulb@67 | 324 | """ |
paulb@67 | 325 | |
paulb@67 | 326 | # If limited, block until channels have been closed. |
paulb@67 | 327 | |
paulb@67 | 328 | while self.limit is not None and len(self.active()) >= self.limit: |
paulb@67 | 329 | self.store() |
paulb@67 | 330 | |
paulb@140 | 331 | def _get_waiting(self, channel): |
paulb@99 | 332 | |
paulb@99 | 333 | """ |
paulb@140 | 334 | Get waiting callable and argument information for new processes, given |
paulb@140 | 335 | the reception of data on the given 'channel'. |
paulb@99 | 336 | """ |
paulb@99 | 337 | |
paulb@99 | 338 | if self.waiting: |
paulb@99 | 339 | callable, args, kw = self.waiting.pop() |
paulb@116 | 340 | |
paulb@116 | 341 | # Try and reuse existing channels if possible. |
paulb@116 | 342 | |
paulb@116 | 343 | if self.reuse: |
paulb@119 | 344 | |
paulb@119 | 345 | # Re-add the channel - this may update information related to |
paulb@119 | 346 | # the channel in subclasses. |
paulb@119 | 347 | |
paulb@119 | 348 | self.add(channel) |
paulb@116 | 349 | channel.send((args, kw)) |
paulb@116 | 350 | else: |
paulb@140 | 351 | return callable, args, kw |
paulb@116 | 352 | |
paulb@116 | 353 | # Where channels are being reused, but where no processes are waiting |
paulb@116 | 354 | # any more, send a special value to tell them to quit. |
paulb@116 | 355 | |
paulb@116 | 356 | elif self.reuse: |
paulb@116 | 357 | channel.send(None) |
paulb@99 | 358 | |
paulb@140 | 359 | return None |
paulb@140 | 360 | |
paulb@67 | 361 | def finish(self): |
paulb@67 | 362 | |
paulb@67 | 363 | """ |
paulb@67 | 364 | Finish the use of the exchange by waiting for all channels to complete. |
paulb@67 | 365 | """ |
paulb@67 | 366 | |
paulb@67 | 367 | while self.active(): |
paulb@67 | 368 | self.store() |
paulb@67 | 369 | |
paulb@67 | 370 | def store(self): |
paulb@67 | 371 | |
paulb@67 | 372 | "For each ready channel, process the incoming data." |
paulb@67 | 373 | |
paulb@67 | 374 | for channel in self.ready(): |
paulb@67 | 375 | self.store_data(channel) |
paulb@116 | 376 | self.start_waiting(channel) |
paulb@67 | 377 | |
paulb@67 | 378 | def store_data(self, channel): |
paulb@67 | 379 | |
paulb@67 | 380 | """ |
paulb@67 | 381 | Store incoming data from the specified 'channel'. In subclasses of this |
paulb@67 | 382 | class, such data could be stored using instance attributes. |
paulb@67 | 383 | """ |
paulb@67 | 384 | |
paulb@67 | 385 | raise NotImplementedError, "store_data" |
paulb@67 | 386 | |
paulb@140 | 387 | # Support for the convenience methods. |
paulb@140 | 388 | |
paulb@140 | 389 | def _set_waiting(self, callable, args, kw): |
paulb@140 | 390 | |
paulb@140 | 391 | """ |
paulb@140 | 392 | Support process creation by returning whether the given 'callable' has |
paulb@140 | 393 | been queued for later invocation. |
paulb@140 | 394 | """ |
paulb@140 | 395 | |
paulb@140 | 396 | if self.limit is not None and len(self.active()) >= self.limit: |
paulb@140 | 397 | self.waiting.insert(0, (callable, args, kw)) |
paulb@140 | 398 | return 1 |
paulb@140 | 399 | else: |
paulb@140 | 400 | return 0 |
paulb@140 | 401 | |
paulb@140 | 402 | def _get_channel_for_process(self, channel): |
paulb@140 | 403 | |
paulb@140 | 404 | """ |
paulb@140 | 405 | Support process creation by returning the given 'channel' to the |
paulb@140 | 406 | creating process, and None to the created process. |
paulb@140 | 407 | """ |
paulb@140 | 408 | |
paulb@140 | 409 | if channel.pid == 0: |
paulb@140 | 410 | return channel |
paulb@140 | 411 | else: |
paulb@140 | 412 | self.add_wait(channel) |
paulb@140 | 413 | return None |
paulb@140 | 414 | |
paulb@140 | 415 | # Methods for overriding, related to the convenience methods. |
paulb@140 | 416 | |
paulb@140 | 417 | def start_waiting(self, channel): |
paulb@140 | 418 | |
paulb@140 | 419 | """ |
paulb@140 | 420 | Start a waiting process given the reception of data on the given |
paulb@140 | 421 | 'channel'. |
paulb@140 | 422 | """ |
paulb@140 | 423 | |
paulb@140 | 424 | details = self._get_waiting(channel) |
paulb@140 | 425 | if details is not None: |
paulb@140 | 426 | callable, args, kw = details |
paulb@140 | 427 | self.add(start(callable, *args, **kw)) |
paulb@140 | 428 | |
paulb@79 | 429 | # Convenience methods. |
paulb@79 | 430 | |
paulb@84 | 431 | def start(self, callable, *args, **kw): |
paulb@79 | 432 | |
paulb@79 | 433 | """ |
paulb@140 | 434 | Create a new process for the given 'callable' using any additional |
paulb@140 | 435 | arguments provided. Then, monitor the channel created between this |
paulb@140 | 436 | process and the created process. |
paulb@79 | 437 | """ |
paulb@79 | 438 | |
paulb@140 | 439 | if self._set_waiting(callable, args, kw): |
paulb@99 | 440 | return |
paulb@99 | 441 | |
paulb@84 | 442 | self.add_wait(start(callable, *args, **kw)) |
paulb@84 | 443 | |
paulb@97 | 444 | def create(self): |
paulb@97 | 445 | |
paulb@97 | 446 | """ |
paulb@140 | 447 | Create a new process and return the created communications channel to |
paulb@140 | 448 | the created process. In the creating process, return None - the channel |
paulb@140 | 449 | receiving data from the created process will be automatically managed by |
paulb@140 | 450 | this exchange. |
paulb@97 | 451 | """ |
paulb@97 | 452 | |
paulb@97 | 453 | channel = create() |
paulb@140 | 454 | return self._get_channel_for_process(channel) |
paulb@97 | 455 | |
paulb@84 | 456 | def manage(self, callable): |
paulb@84 | 457 | |
paulb@84 | 458 | """ |
paulb@84 | 459 | Wrap the given 'callable' in an object which can then be called in the |
paulb@84 | 460 | same way as 'callable', but with new processes and communications |
paulb@84 | 461 | managed automatically. |
paulb@84 | 462 | """ |
paulb@84 | 463 | |
paulb@84 | 464 | return ManagedCallable(callable, self) |
paulb@84 | 465 | |
paulb@140 | 466 | class Persistent: |
paulb@140 | 467 | |
paulb@140 | 468 | """ |
paulb@140 | 469 | A mix-in class providing methods to exchanges for the management of |
paulb@140 | 470 | persistent communications. |
paulb@140 | 471 | """ |
paulb@140 | 472 | |
paulb@140 | 473 | def start_waiting(self, channel): |
paulb@140 | 474 | |
paulb@140 | 475 | """ |
paulb@140 | 476 | Start a waiting process given the reception of data on the given |
paulb@140 | 477 | 'channel'. |
paulb@140 | 478 | """ |
paulb@140 | 479 | |
paulb@140 | 480 | details = self._get_waiting(channel) |
paulb@140 | 481 | if details is not None: |
paulb@140 | 482 | callable, args, kw = details |
paulb@140 | 483 | self.add(start_persistent(channel.address, callable, *args, **kw)) |
paulb@140 | 484 | |
paulb@140 | 485 | def start(self, address, callable, *args, **kw): |
paulb@140 | 486 | |
paulb@140 | 487 | """ |
paulb@140 | 488 | Create a new process, located at the given 'address', for the given |
paulb@140 | 489 | 'callable' using any additional arguments provided. Then, monitor the |
paulb@140 | 490 | channel created between this process and the created process. |
paulb@140 | 491 | """ |
paulb@140 | 492 | |
paulb@140 | 493 | if self._set_waiting(callable, args, kw): |
paulb@140 | 494 | return |
paulb@140 | 495 | |
paulb@140 | 496 | start_persistent(address, callable, *args, **kw) |
paulb@140 | 497 | |
paulb@140 | 498 | def create(self, address): |
paulb@140 | 499 | |
paulb@140 | 500 | """ |
paulb@140 | 501 | Create a new process, located at the given 'address', and return the |
paulb@140 | 502 | created communications channel to the created process. In the creating |
paulb@140 | 503 | process, return None - the channel receiving data from the created |
paulb@140 | 504 | process will be automatically managed by this exchange. |
paulb@140 | 505 | """ |
paulb@140 | 506 | |
paulb@140 | 507 | channel = create_persistent(address) |
paulb@140 | 508 | return self._get_channel_for_process(channel) |
paulb@140 | 509 | |
paulb@140 | 510 | def manage(self, address, callable): |
paulb@140 | 511 | |
paulb@140 | 512 | """ |
paulb@140 | 513 | Using the given 'address', publish the given 'callable' in an object |
paulb@140 | 514 | which can then be called in the same way as 'callable', but with new |
paulb@140 | 515 | processes and communications managed automatically. |
paulb@140 | 516 | """ |
paulb@140 | 517 | |
paulb@140 | 518 | return PersistentCallable(address, callable, self) |
paulb@140 | 519 | |
paulb@140 | 520 | def connect(self, address): |
paulb@140 | 521 | |
paulb@140 | 522 | "Connect to a process which is contactable via the given 'address'." |
paulb@140 | 523 | |
paulb@140 | 524 | channel = connect_persistent(address) |
paulb@140 | 525 | self.add_wait(channel) |
paulb@140 | 526 | |
paulb@84 | 527 | class ManagedCallable: |
paulb@84 | 528 | |
paulb@84 | 529 | "A callable managed by an exchange." |
paulb@84 | 530 | |
paulb@84 | 531 | def __init__(self, callable, exchange): |
paulb@84 | 532 | |
paulb@84 | 533 | """ |
paulb@84 | 534 | Wrap the given 'callable', using the given 'exchange' to monitor the |
paulb@84 | 535 | channels created for communications between this and the created |
paulb@94 | 536 | processes. Note that the 'callable' must be parallel-aware (that is, |
paulb@94 | 537 | have a 'channel' parameter). Use the MakeParallel class to wrap other |
paulb@94 | 538 | kinds of callable objects. |
paulb@84 | 539 | """ |
paulb@84 | 540 | |
paulb@84 | 541 | self.callable = callable |
paulb@84 | 542 | self.exchange = exchange |
paulb@84 | 543 | |
paulb@84 | 544 | def __call__(self, *args, **kw): |
paulb@84 | 545 | |
paulb@84 | 546 | "Invoke the callable with the supplied arguments." |
paulb@84 | 547 | |
paulb@84 | 548 | self.exchange.start(self.callable, *args, **kw) |
paulb@84 | 549 | |
paulb@140 | 550 | class PersistentCallable: |
paulb@140 | 551 | |
paulb@140 | 552 | "A callable which sets up a persistent communications channel." |
paulb@140 | 553 | |
paulb@140 | 554 | def __init__(self, address, callable, exchange): |
paulb@140 | 555 | |
paulb@140 | 556 | """ |
paulb@140 | 557 | Using the given 'address', wrap the given 'callable', using the given |
paulb@140 | 558 | 'exchange' to monitor the channels created for communications between |
paulb@140 | 559 | this and the created processes, so that when it is called, a background |
paulb@140 | 560 | process is started within which the 'callable' will run. Note that the |
paulb@140 | 561 | 'callable' must be parallel-aware (that is, have a 'channel' parameter). |
paulb@140 | 562 | Use the MakeParallel class to wrap other kinds of callable objects. |
paulb@140 | 563 | """ |
paulb@140 | 564 | |
paulb@140 | 565 | self.callable = callable |
paulb@140 | 566 | self.exchange = exchange |
paulb@140 | 567 | self.address = address |
paulb@140 | 568 | |
paulb@140 | 569 | def __call__(self, *args, **kw): |
paulb@140 | 570 | |
paulb@140 | 571 | "Invoke the callable and discard the result." |
paulb@140 | 572 | |
paulb@140 | 573 | self.exchange.start(self.address, self.callable, *args, **kw) |
paulb@140 | 574 | |
paulb@84 | 575 | # Abstractions and utilities. |
paulb@84 | 576 | |
paulb@84 | 577 | class Map(Exchange): |
paulb@84 | 578 | |
paulb@84 | 579 | "An exchange which can be used like the built-in 'map' function." |
paulb@84 | 580 | |
paulb@107 | 581 | def __init__(self, *args, **kw): |
paulb@107 | 582 | Exchange.__init__(self, *args, **kw) |
paulb@107 | 583 | self.init() |
paulb@107 | 584 | |
paulb@107 | 585 | def init(self): |
paulb@107 | 586 | |
paulb@107 | 587 | "Remember the channel addition order to order output." |
paulb@107 | 588 | |
paulb@107 | 589 | self.channel_number = 0 |
paulb@107 | 590 | self.channels = {} |
paulb@107 | 591 | self.results = [] |
paulb@107 | 592 | |
paulb@84 | 593 | def add(self, channel): |
paulb@84 | 594 | |
paulb@84 | 595 | "Add the given 'channel' to the exchange." |
paulb@84 | 596 | |
paulb@84 | 597 | Exchange.add(self, channel) |
paulb@92 | 598 | self.channels[channel] = self.channel_number |
paulb@92 | 599 | self.channel_number += 1 |
paulb@84 | 600 | |
paulb@107 | 601 | def start(self, callable, *args, **kw): |
paulb@107 | 602 | |
paulb@107 | 603 | """ |
paulb@140 | 604 | Create a new process for the given 'callable' using any additional |
paulb@140 | 605 | arguments provided. Then, monitor the channel created between this |
paulb@140 | 606 | process and the created process. |
paulb@107 | 607 | """ |
paulb@107 | 608 | |
paulb@107 | 609 | self.results.append(None) # placeholder |
paulb@107 | 610 | Exchange.start(self, callable, *args, **kw) |
paulb@107 | 611 | |
paulb@110 | 612 | def create(self): |
paulb@110 | 613 | |
paulb@110 | 614 | """ |
paulb@140 | 615 | Create a new process and return the created communications channel to |
paulb@140 | 616 | the created process. In the creating process, return None - the channel |
paulb@140 | 617 | receiving data from the created process will be automatically managed by |
paulb@140 | 618 | this exchange. |
paulb@110 | 619 | """ |
paulb@110 | 620 | |
paulb@110 | 621 | self.results.append(None) # placeholder |
paulb@110 | 622 | return Exchange.create(self) |
paulb@110 | 623 | |
paulb@84 | 624 | def __call__(self, callable, sequence): |
paulb@84 | 625 | |
paulb@89 | 626 | "Wrap and invoke 'callable' for each element in the 'sequence'." |
paulb@89 | 627 | |
paulb@92 | 628 | if not isinstance(callable, MakeParallel): |
paulb@92 | 629 | wrapped = MakeParallel(callable) |
paulb@92 | 630 | else: |
paulb@92 | 631 | wrapped = callable |
paulb@84 | 632 | |
paulb@107 | 633 | self.init() |
paulb@84 | 634 | |
paulb@107 | 635 | # Start processes for each element in the sequence. |
paulb@84 | 636 | |
paulb@84 | 637 | for i in sequence: |
paulb@92 | 638 | self.start(wrapped, i) |
paulb@107 | 639 | |
paulb@107 | 640 | # Access to the results occurs through this object. |
paulb@107 | 641 | |
paulb@107 | 642 | return self |
paulb@84 | 643 | |
paulb@107 | 644 | def __getitem__(self, i): |
paulb@107 | 645 | self.finish() |
paulb@107 | 646 | return self.results[i] |
paulb@84 | 647 | |
paulb@107 | 648 | def __iter__(self): |
paulb@107 | 649 | self.finish() |
paulb@107 | 650 | return iter(self.results) |
paulb@84 | 651 | |
paulb@84 | 652 | def store_data(self, channel): |
paulb@84 | 653 | |
paulb@84 | 654 | "Accumulate the incoming data, associating results with channels." |
paulb@84 | 655 | |
paulb@84 | 656 | data = channel.receive() |
paulb@92 | 657 | self.results[self.channels[channel]] = data |
paulb@92 | 658 | del self.channels[channel] |
paulb@84 | 659 | |
paulb@97 | 660 | class Queue(Exchange): |
paulb@97 | 661 | |
paulb@97 | 662 | """ |
paulb@97 | 663 | An exchange acting as a queue, making data from created processes available |
paulb@97 | 664 | in the order in which it is received. |
paulb@97 | 665 | """ |
paulb@97 | 666 | |
paulb@97 | 667 | def __init__(self, *args, **kw): |
paulb@97 | 668 | Exchange.__init__(self, *args, **kw) |
paulb@97 | 669 | self.queue = [] |
paulb@97 | 670 | |
paulb@97 | 671 | def store_data(self, channel): |
paulb@97 | 672 | |
paulb@97 | 673 | "Accumulate the incoming data, associating results with channels." |
paulb@97 | 674 | |
paulb@97 | 675 | data = channel.receive() |
paulb@97 | 676 | self.queue.insert(0, data) |
paulb@97 | 677 | |
paulb@97 | 678 | def __iter__(self): |
paulb@97 | 679 | return self |
paulb@97 | 680 | |
paulb@97 | 681 | def next(self): |
paulb@97 | 682 | |
paulb@97 | 683 | "Return the next element in the queue." |
paulb@97 | 684 | |
paulb@97 | 685 | if self.queue: |
paulb@97 | 686 | return self.queue.pop() |
paulb@97 | 687 | while self.active(): |
paulb@97 | 688 | self.store() |
paulb@97 | 689 | if self.queue: |
paulb@97 | 690 | return self.queue.pop() |
paulb@97 | 691 | else: |
paulb@97 | 692 | raise StopIteration |
paulb@97 | 693 | |
paulb@84 | 694 | class MakeParallel: |
paulb@84 | 695 | |
paulb@84 | 696 | "A wrapper around functions making them able to communicate results." |
paulb@84 | 697 | |
paulb@84 | 698 | def __init__(self, callable): |
paulb@84 | 699 | |
paulb@94 | 700 | """ |
paulb@94 | 701 | Initialise the wrapper with the given 'callable'. This object will then |
paulb@94 | 702 | be able to accept a 'channel' parameter when invoked, and to forward the |
paulb@94 | 703 | result of the given 'callable' via the channel provided back to the |
paulb@94 | 704 | invoking process. |
paulb@94 | 705 | """ |
paulb@84 | 706 | |
paulb@84 | 707 | self.callable = callable |
paulb@84 | 708 | |
paulb@84 | 709 | def __call__(self, channel, *args, **kw): |
paulb@84 | 710 | |
paulb@84 | 711 | "Invoke the callable and return its result via the given 'channel'." |
paulb@84 | 712 | |
paulb@84 | 713 | channel.send(self.callable(*args, **kw)) |
paulb@84 | 714 | |
paulb@119 | 715 | class MakeReusable(MakeParallel): |
paulb@119 | 716 | |
paulb@119 | 717 | """ |
paulb@119 | 718 | A wrapper around functions making them able to communicate results in a |
paulb@119 | 719 | reusable fashion. |
paulb@119 | 720 | """ |
paulb@119 | 721 | |
paulb@119 | 722 | def __call__(self, channel, *args, **kw): |
paulb@119 | 723 | |
paulb@119 | 724 | "Invoke the callable and return its result via the given 'channel'." |
paulb@119 | 725 | |
paulb@119 | 726 | channel.send(self.callable(*args, **kw)) |
paulb@119 | 727 | t = channel.receive() |
paulb@119 | 728 | while t is not None: |
paulb@119 | 729 | args, kw = t |
paulb@119 | 730 | channel.send(self.callable(*args, **kw)) |
paulb@119 | 731 | t = channel.receive() |
paulb@119 | 732 | |
paulb@140 | 733 | # Persistent variants. |
paulb@140 | 734 | |
paulb@140 | 735 | class PersistentExchange(Persistent, Exchange): |
paulb@140 | 736 | |
paulb@140 | 737 | "An exchange which manages persistent communications." |
paulb@140 | 738 | |
paulb@140 | 739 | pass |
paulb@140 | 740 | |
paulb@140 | 741 | class PersistentQueue(Persistent, Queue): |
paulb@140 | 742 | |
paulb@140 | 743 | "A queue which manages persistent communications." |
paulb@140 | 744 | |
paulb@140 | 745 | pass |
paulb@140 | 746 | |
paulb@84 | 747 | # Utility functions. |
paulb@79 | 748 | |
paulb@135 | 749 | _cpuinfo_fields = "physical id", "core id" |
paulb@135 | 750 | |
paulb@135 | 751 | def get_number_of_cores(): |
paulb@135 | 752 | |
paulb@135 | 753 | """ |
paulb@135 | 754 | Return the number of distinct, genuine processor cores. If the platform is |
paulb@135 | 755 | not supported by this function, None is returned. |
paulb@135 | 756 | """ |
paulb@135 | 757 | |
paulb@135 | 758 | try: |
paulb@135 | 759 | f = open("/proc/cpuinfo") |
paulb@135 | 760 | try: |
paulb@135 | 761 | processors = set() |
paulb@135 | 762 | processor = [None, None] |
paulb@135 | 763 | |
paulb@135 | 764 | for line in f.xreadlines(): |
paulb@135 | 765 | for i, field in enumerate(_cpuinfo_fields): |
paulb@135 | 766 | if line.startswith(field): |
paulb@135 | 767 | t = line.split(":") |
paulb@135 | 768 | processor[i] = int(t[1].strip()) |
paulb@135 | 769 | break |
paulb@135 | 770 | else: |
paulb@135 | 771 | if line.startswith("processor") and processor[0] is not None: |
paulb@135 | 772 | processors.add(tuple(processor)) |
paulb@135 | 773 | processor = [None, None] |
paulb@135 | 774 | |
paulb@135 | 775 | if processor[0] is not None: |
paulb@135 | 776 | processors.add(tuple(processor)) |
paulb@135 | 777 | |
paulb@135 | 778 | return len(processors) |
paulb@135 | 779 | |
paulb@135 | 780 | finally: |
paulb@135 | 781 | f.close() |
paulb@135 | 782 | |
paulb@135 | 783 | except OSError: |
paulb@135 | 784 | return None |
paulb@135 | 785 | |
paulb@40 | 786 | def create(): |
paulb@40 | 787 | |
paulb@40 | 788 | """ |
paulb@40 | 789 | Create a new process, returning a communications channel to both the |
paulb@40 | 790 | creating process and the created process. |
paulb@40 | 791 | """ |
paulb@40 | 792 | |
paulb@40 | 793 | parent, child = socket.socketpair() |
paulb@40 | 794 | for s in [parent, child]: |
paulb@40 | 795 | s.setblocking(1) |
paulb@40 | 796 | |
paulb@40 | 797 | pid = os.fork() |
paulb@40 | 798 | if pid == 0: |
paulb@40 | 799 | parent.close() |
paulb@73 | 800 | return Channel(pid, child.makefile("r", 0), child.makefile("w", 0)) |
paulb@40 | 801 | else: |
paulb@40 | 802 | child.close() |
paulb@73 | 803 | return Channel(pid, parent.makefile("r", 0), parent.makefile("w", 0)) |
paulb@40 | 804 | |
paulb@140 | 805 | def create_persistent(address): |
paulb@140 | 806 | |
paulb@140 | 807 | """ |
paulb@140 | 808 | Create a new process, returning a persistent communications channel between |
paulb@140 | 809 | the creating process and the created process. This channel can be |
paulb@140 | 810 | disconnected from the creating process and connected to another process, and |
paulb@140 | 811 | thus can be used to collect results from daemon processes. |
paulb@140 | 812 | |
paulb@140 | 813 | In order to be able to reconnect to created processes, the 'address' of the |
paulb@140 | 814 | communications endpoint for the created process needs to be provided. This |
paulb@140 | 815 | should be a filename. |
paulb@140 | 816 | """ |
paulb@140 | 817 | |
paulb@140 | 818 | parent = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
paulb@140 | 819 | child = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
paulb@140 | 820 | child.bind(address) |
paulb@140 | 821 | |
paulb@140 | 822 | for s in [parent, child]: |
paulb@140 | 823 | s.setblocking(1) |
paulb@140 | 824 | |
paulb@140 | 825 | pid = os.fork() |
paulb@140 | 826 | if pid == 0: |
paulb@140 | 827 | parent.close() |
paulb@140 | 828 | return PersistentChannel(pid, child, address) |
paulb@140 | 829 | else: |
paulb@140 | 830 | child.close() |
paulb@140 | 831 | #parent.connect(address) |
paulb@140 | 832 | return Channel(pid, parent.makefile("r", 0), parent.makefile("w", 0)) |
paulb@140 | 833 | |
paulb@140 | 834 | def connect_persistent(address): |
paulb@140 | 835 | |
paulb@140 | 836 | """ |
paulb@140 | 837 | Connect via a persistent channel to an existing created process, reachable |
paulb@140 | 838 | at the given 'address'. |
paulb@140 | 839 | """ |
paulb@140 | 840 | |
paulb@140 | 841 | parent = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
paulb@140 | 842 | parent.setblocking(1) |
paulb@140 | 843 | parent.connect(address) |
paulb@140 | 844 | return Channel(0, parent.makefile("r", 0), parent.makefile("w", 0)) |
paulb@140 | 845 | |
paulb@97 | 846 | def exit(channel): |
paulb@97 | 847 | |
paulb@97 | 848 | """ |
paulb@97 | 849 | Terminate a created process, closing the given 'channel'. |
paulb@97 | 850 | """ |
paulb@97 | 851 | |
paulb@97 | 852 | channel.close() |
paulb@97 | 853 | os._exit(0) |
paulb@97 | 854 | |
paulb@84 | 855 | def start(callable, *args, **kw): |
paulb@40 | 856 | |
paulb@40 | 857 | """ |
paulb@40 | 858 | Create a new process which shall start running in the given 'callable'. |
paulb@94 | 859 | Additional arguments to the 'callable' can be given as additional arguments |
paulb@94 | 860 | to this function. |
paulb@94 | 861 | |
paulb@94 | 862 | Return a communications channel to the creating process. For the created |
paulb@94 | 863 | process, supply a channel as the 'channel' parameter in the given 'callable' |
paulb@94 | 864 | so that it may send data back to the creating process. |
paulb@40 | 865 | """ |
paulb@40 | 866 | |
paulb@40 | 867 | channel = create() |
paulb@40 | 868 | if channel.pid == 0: |
paulb@40 | 869 | try: |
paulb@40 | 870 | try: |
paulb@84 | 871 | callable(channel, *args, **kw) |
paulb@40 | 872 | except: |
paulb@40 | 873 | exc_type, exc_value, exc_traceback = sys.exc_info() |
paulb@40 | 874 | channel.send(exc_value) |
paulb@40 | 875 | finally: |
paulb@99 | 876 | exit(channel) |
paulb@40 | 877 | else: |
paulb@40 | 878 | return channel |
paulb@40 | 879 | |
paulb@140 | 880 | def start_persistent(address, callable, *args, **kw): |
paulb@140 | 881 | |
paulb@140 | 882 | """ |
paulb@140 | 883 | Create a new process which shall be reachable using the given 'address' and |
paulb@140 | 884 | which will start running in the given 'callable'. Additional arguments to |
paulb@140 | 885 | the 'callable' can be given as additional arguments to this function. |
paulb@140 | 886 | |
paulb@140 | 887 | Return a communications channel to the creating process. For the created |
paulb@140 | 888 | process, supply a channel as the 'channel' parameter in the given 'callable' |
paulb@140 | 889 | so that it may send data back to the creating process. |
paulb@140 | 890 | |
paulb@140 | 891 | Note that the created process employs a channel which is persistent: it can |
paulb@140 | 892 | withstand disconnection from the creating process and subsequent connections |
paulb@140 | 893 | from other processes. |
paulb@140 | 894 | """ |
paulb@140 | 895 | |
paulb@140 | 896 | channel = create_persistent(address) |
paulb@140 | 897 | if channel.pid == 0: |
paulb@140 | 898 | close_streams() |
paulb@140 | 899 | try: |
paulb@140 | 900 | try: |
paulb@140 | 901 | callable(channel, *args, **kw) |
paulb@140 | 902 | except: |
paulb@140 | 903 | exc_type, exc_value, exc_traceback = sys.exc_info() |
paulb@140 | 904 | channel.send(exc_value) |
paulb@140 | 905 | finally: |
paulb@140 | 906 | exit(channel) |
paulb@140 | 907 | else: |
paulb@140 | 908 | return channel |
paulb@140 | 909 | |
paulb@140 | 910 | def close_streams(): |
paulb@140 | 911 | |
paulb@140 | 912 | """ |
paulb@140 | 913 | Close streams which keep the current process attached to any creating |
paulb@140 | 914 | processes. |
paulb@140 | 915 | """ |
paulb@140 | 916 | |
paulb@140 | 917 | os.close(sys.stdin.fileno()) |
paulb@140 | 918 | os.close(sys.stdout.fileno()) |
paulb@140 | 919 | os.close(sys.stderr.fileno()) |
paulb@140 | 920 | |
paulb@40 | 921 | def waitall(): |
paulb@40 | 922 | |
paulb@40 | 923 | "Wait for all created processes to terminate." |
paulb@40 | 924 | |
paulb@40 | 925 | try: |
paulb@40 | 926 | while 1: |
paulb@40 | 927 | os.wait() |
paulb@40 | 928 | except OSError: |
paulb@40 | 929 | pass |
paulb@40 | 930 | |
paulb@89 | 931 | def pmap(callable, sequence, limit=None): |
paulb@84 | 932 | |
paulb@89 | 933 | """ |
paulb@89 | 934 | A parallel version of the built-in map function with an optional process |
paulb@94 | 935 | 'limit'. The given 'callable' should not be parallel-aware (that is, have a |
paulb@94 | 936 | 'channel' parameter) since it will be wrapped for parallel communications |
paulb@94 | 937 | before being invoked. |
paulb@94 | 938 | |
paulb@94 | 939 | Return the processed 'sequence' where each element in the sequence is |
paulb@94 | 940 | processed by a different process. |
paulb@89 | 941 | """ |
paulb@84 | 942 | |
paulb@89 | 943 | mymap = Map(limit=limit) |
paulb@84 | 944 | return mymap(callable, sequence) |
paulb@84 | 945 | |
paulb@40 | 946 | # vim: tabstop=4 expandtab shiftwidth=4 |