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