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