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