/
comms.py
584 lines (464 loc) · 17.1 KB
/
comms.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
"""
libEnsemble communication interface
====================================================
A comm provides a message passing abstraction for communication
between a worker user function and the manager. Basic messages are:
stop() - manager tells persistent gen/sim to stop
worker_avail(nworker) - manager tells gen that workers are available
request(recs) - worker requests simulations
queued(id) - manager assigns simulation IDs to request
kill(id) - gen requests manager kill a simulation
update(id, rec) - manager informs gen of partial sim information
result(id, rec) - manager informs gen a sim completed
killed(id) - manager informs gen a sim was killed
To facilitate information sharing, we also have messages for history
access and monitoring (for persistent gens):
get_history(lo, hi) - gen requests history
subscribe() - gen subscribes to all history updates
"""
from abc import ABC, abstractmethod
from time import time
from threading import Thread
from multiprocessing import Process, Queue, Value, Lock
from traceback import format_exc
import queue
import copy
import numpy as np
class Timeout(Exception):
"Communication timeout exception."
class CommFinishedException(Exception):
"Read from terminated comm exception."
class ManagerStop(Exception):
"Exception raised by default when manager sends a stop message."
class RemoteException(Exception):
"Exception raised when we received a remote exception."
def __init__(self, msg, exc):
super().__init__(msg)
self.exc = exc
class CommResult:
"Container for a result returned on exit."
def __init__(self, value):
self.value = value
class CommResultErr:
"Container for an exception returned on exit."
def __init__(self, msg, exc):
self.msg = msg
self.exc = exc
def _timeout_fun(timeout):
"Return a function that gets timeouts for time remaining."
if timeout is None:
return (lambda: None)
else:
tdeath = time() + timeout
return (lambda: tdeath-time())
class Comm(ABC):
"""Bidirectional communication
"""
@abstractmethod
def send(self, *args):
"Send a message."
@abstractmethod
def recv(self, timeout=None):
"Receive a message or raise TimeoutError."
def mail_flag(self):
"Check whether we know a message is ready for receipt."
return False
def kill_pending(self):
"Cancel any pending sends (don't worry about those in the system)."
class QComm(Comm):
"""Queue-based bidirectional communicator
A QComm provides a message passing abstraction based on a pair of message
queues: an inbox for incoming messages and an outbox for outgoing messages.
These can be used with threads or multiprocessing.
"""
# Integer count - shared amongst Processes in multiprocessing
lock = Lock()
_ncomms = Value('i', 0) # todo - check: Maybe this should be in QCommProcess
def __init__(self, inbox, outbox, copy_msg=False):
"Set the inbox and outbox queues."
self._inbox = inbox
self._outbox = outbox
self._copy = copy_msg
self.recv_buffer = None
with QComm.lock:
QComm._ncomms.value += 1
# Does this fit with terminate?
# def __del__(self):
# #global _ncomms
# with QComm.lock:
# QComm._ncomms.value -= 1
def get_num_workers(self):
"""Return global _ncomms"""
return QComm._ncomms.value
def send(self, *args):
"Place a message on the outbox queue."
if self._copy:
args = copy.deepcopy(args)
self._outbox.put(args)
def recv(self, timeout=None):
"Return a message from the inbox queue or raise TimeoutError."
pb_result = self.recv_buffer
self.recv_buffer = None
if pb_result is not None:
return pb_result
try:
if not self._inbox.empty():
return self._inbox.get()
return self._inbox.get(timeout=timeout)
except queue.Empty:
raise Timeout()
# TODO: This should go away once I have internal comms working
def push_to_buffer(self, *args):
self.recv_buffer = args
def mail_flag(self):
"Check whether we know a message is ready for receipt."
return not self._inbox.empty()
class QCommThread(Comm):
"""Launch a user function in a thread with an attached QComm.
"""
def __init__(self, main, *args, **kwargs):
self.inbox = queue.Queue()
self.outbox = queue.Queue()
self.main = main
self._result = None
self._exception = None
kwargs['comm'] = QComm(self.inbox, self.outbox, True)
self.thread = Thread(target=self._qcomm_main,
args=args, kwargs=kwargs)
def send(self, *args):
"Send a message to the thread (called from creator)"
self.inbox.put(copy.deepcopy(args))
def recv(self, timeout=None):
"Return a message from the thread or raise TimeoutError."
try:
if not self.outbox.empty():
return self.outbox.get()
return self.outbox.get(timeout=timeout)
except queue.Empty:
raise Timeout()
def mail_flag(self):
"Check whether we know a message is ready for receipt."
return not self.outbox.empty()
def run(self):
"Start the thread."
self.thread.start()
def result(self):
"Join and return the thread main result (or re-raise an exception)."
self.thread.join()
if isinstance(self._exception, Exception):
raise self._exception
return self._result
@property
def running(self):
"Check if the thread is running."
return self.thread.is_alive()
def _qcomm_main(self, *args, **kwargs):
"Main routine -- handles return values and exceptions."
try:
self._result = self.main(*args, **kwargs)
except Exception as e:
self._exception = e
def __enter__(self):
self.run()
return self
def __exit__(self, etype, value, traceback):
self.thread.join()
class QCommProcess(Comm):
"""Launch a user function in a process with an attached QComm.
"""
def __init__(self, main, *args, **kwargs):
self.inbox = Queue()
self.outbox = Queue()
self._result = None
self._exception = None
self._done = False
comm = QComm(self.inbox, self.outbox)
self.process = Process(target=QCommProcess._qcomm_main,
args=(comm, main) + args, kwargs=kwargs)
def _is_result_msg(self, msg):
"Return true if message indicates final result (and set result/except)."
if len(msg) and isinstance(msg[0], CommResult):
self._result = msg[0].value
self._done = True
return True
if len(msg) and isinstance(msg[0], CommResultErr):
self._exception = msg[0]
self._done = True
return True
return False
def send(self, *args):
"Send a message to the thread (called from creator)"
self.inbox.put(args)
def recv(self, timeout=None):
"Return a message from the thread or raise TimeoutError."
try:
if self._done:
raise CommFinishedException()
if not self.outbox.empty():
msg = self.outbox.get()
else:
msg = self.outbox.get(timeout=timeout)
if self._is_result_msg(msg):
raise CommFinishedException()
return msg
except queue.Empty:
raise Timeout()
def mail_flag(self):
"Check whether we know a message is ready for receipt."
return not self.outbox.empty()
def run(self):
"Start the process."
self.process.start()
def result(self, timeout=None):
"Join and return the thread main result (or re-raise an exception)."
get_timeout = _timeout_fun(timeout)
while not self._done and (timeout is None or timeout >= 0):
try:
msg = self.outbox.get(timeout=timeout)
except queue.Empty:
raise Timeout()
self._is_result_msg(msg)
timeout = get_timeout()
if not self._done:
raise Timeout()
self.process.join(timeout=timeout)
if self.running:
raise Timeout()
if self._exception is not None:
raise RemoteException(self._exception.msg, self._exception.exc)
return self._result
def terminate(self, timeout=None):
"Terminate the process."
if self.running:
self.process.terminate()
self.process.join(timeout=timeout)
if self.running:
raise Timeout()
@property
def running(self):
"Return true if process is running"
return self.process.is_alive()
@staticmethod
def _qcomm_main(comm, main, *args, **kwargs):
"Main routine -- handles return values and exceptions."
try:
_result = main(comm, *args, **kwargs)
comm.send(CommResult(_result))
except Exception as e:
comm.send(CommResultErr(str(e), format_exc()))
raise e
def __enter__(self):
self.run()
return self
def __exit__(self, etype, value, traceback):
self.process.join()
class CommHandler(ABC):
"""Comm wrapper with message handler dispatching.
The comm wrapper defines a message processor that dispatches to
different handler methods based on message types. An incoming message
with the tag 'foo' gets dispatched to a handler 'on_foo'; if 'on_foo'
is not defined, we pass to the 'on_unhandled_message' routine.
"""
def __init__(self, comm):
"Set the comm to be wrapped."
self.comm = comm
def send(self, *args):
"Send via the comm."
self.comm.send(*args)
def process_message(self, timeout=None):
"Receive and process a message via the comm."
msg = self.comm.recv(timeout)
msg_type = msg[0]
args = msg[1:]
try:
method = 'on_{}'.format(msg_type)
handler = getattr(self, method)
except AttributeError:
return self.on_unhandled_message(msg)
return handler(*args)
def on_unhandled_message(self, msg):
"Handle any messages for which there are no named handlers."
raise ValueError("No handler available for message {0}{1}".
format(msg[0], msg[1:]))
class GenCommHandler(CommHandler):
"Wrapper for handling messages at a persistent gen."
def send_request(self, recs):
"Request new evaluations."
self.send('request', recs)
def send_kill(self, sim_id):
"Kill an evaluation."
self.send('kill', sim_id)
def send_get_history(self, lo, hi):
"Request history from manager."
self.send('get_history', lo, hi)
def send_subscribe(self):
"Request subscription to updates on sims not launched by this gen."
self.send('subscribe')
def on_stop(self):
"Handle stop message."
raise ManagerStop()
@abstractmethod
def on_worker_avail(self, nworker):
"Handle updated number of workers available to perform sims."
@abstractmethod
def on_queued(self, sim_id):
"Handle sim_id assignment in response to a request"
@abstractmethod
def on_result(self, sim_id, recs):
"Handle simulation results"
@abstractmethod
def on_update(self, sim_id, recs):
"Handle simulation updates"
@abstractmethod
def on_killed(self, sim_id):
"Handle a simulation kill"
class SimCommHandler(CommHandler):
"Wrapper for handling messages at sim."
def send_result(self, sim_id, recs):
"Send a simulation result"
self.send('result', sim_id, recs)
def send_update(self, sim_id, recs):
"Send a simulation update"
self.send('update', sim_id, recs)
def send_killed(self, sim_id):
"Send notification that a simulation was killed"
self.send('killed', sim_id)
def on_stop(self):
"Handle stop message."
raise ManagerStop()
@abstractmethod
def on_request(self, sim_id, recs):
"Handle a request for a simulation"
@abstractmethod
def on_kill(self, sim_id):
"Handle a request to kill a simulation"
class CommEval(GenCommHandler):
"""Future-based interface for generator comms
"""
def __init__(self, comm, workers=0, gen_specs=None):
super().__init__(comm)
self.sim_started = 0
self.sim_pending = 0
self.workers = workers
self.gen_specs = gen_specs
self.promises = {}
self.returning_promises = None
self.waiting_for_queued = 0
def request(self, recs):
"Request simulations, return promises"
self.sim_started += len(recs)
self.sim_pending += len(recs)
self.send_request(recs)
self.waiting_for_queued = len(recs)
while self.waiting_for_queued > 0:
self.process_message()
returning_promises = self.returning_promises
self.returning_promises = None
return returning_promises
def __call__(self, *args, **kwargs):
"Request a simulation and return a promise"
assert not (args and kwargs), \
"Must specify simulation args by position or keyword, but not both"
assert args or kwargs, \
"Must specify simulation arguments."
rec = np.zeros(1, dtype=self.gen_specs['out'])
if args:
assert len(args) == len(self.gen_specs['out']), \
"Wrong number of positional arguments in sim call."
for k, spec in enumerate(self.gen_specs['out']):
name = spec[0]
rec[name] = args[k]
else:
for name, value in kwargs.items():
rec[name] = value
return self.request(rec)[0]
def wait_any(self):
"Wait for any pending simulation to be done"
sim_pending = self.sim_pending
while sim_pending == self.sim_pending:
self.process_message()
def wait_all(self):
"Wait for all pending simulations to be done"
while self.sim_pending > 0:
self.process_message()
# --- Message handlers
def on_worker_avail(self, nworker):
"Update worker count"
self.workers = nworker
return -1
def on_queued(self, sim_id):
"Set up futures with indicated simulation IDs"
lo = sim_id
hi = sim_id + self.waiting_for_queued
self.waiting_for_queued = 0
self.returning_promises = []
for s in range(lo, hi):
promise = Future(self, s)
self.promises[s] = promise
self.returning_promises.append(promise)
return -1
def on_result(self, sim_id, recs):
"Handle completed simulation"
for k, rec in enumerate(recs):
self.sim_pending -= 1
self.promises[sim_id+k].on_result(rec)
return sim_id
def on_update(self, sim_id, recs):
"Handle updated simulation"
for k, rec in enumerate(recs):
self.promises[sim_id+k].on_update(rec)
return sim_id
def on_killed(self, sim_id):
"Handle killed simulation"
self.sim_pending -= 1
self.promises[sim_id].on_killed()
return sim_id
class Future:
"""Future objects for monitoring asynchronous simulation calls.
The Future objects are not meant to be instantiated on their own;
they are only produced by a call on a CommEval object.
"""
def __init__(self, ceval, sim_id):
self._ceval = ceval
self._id = sim_id
self._comm = ceval.comm
self._result = None
self._killed = False
self._success = False
@property
def current_result(self):
"Return the current (possibly incomplete) result immediately."
return self._result
def cancelled(self):
"Return True if the simulation was killed."
return self._killed
def done(self):
"Return True if the simulation completed successfully or was killed."
return self._success or self._killed
def cancel(self):
"Cancel the simulation."
self._ceval.send_kill(self._id)
def result(self, timeout=None):
"Get the result of the simulation or throw a timeout."
while not self.done():
if timeout is not None and timeout < 0:
raise Timeout()
tstart = time()
try:
self._ceval.process_message(timeout)
except Timeout:
pass
if timeout is not None:
timeout -= (time() - tstart)
return self._result
# --- Message handlers
def on_result(self, result):
"Handle an incoming result."
self._result = result
self._success = True
def on_update(self, result):
"Handle an incoming update."
self._result = result
def on_killed(self):
"Handle a kill notification."
self._killed = True