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