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 | class EngineServer(EngineBase):
"""
The server portion of BBOT's RPC Engine.
Methods defined here must match the methods in your EngineClient.
To use the functions, you must create mappings for them in the CMDS attribute, as shown below.
Examples:
>>> from bbot.core.engine import EngineServer
>>>
>>> class MyServer(EngineServer):
>>> CMDS = {
>>> 0: "my_function",
>>> 1: "my_generator",
>>> }
>>>
>>> def my_function(self, arg1=None):
>>> await asyncio.sleep(1)
>>> return str(arg1)
>>>
>>> def my_generator(self):
>>> for i in range(10):
>>> await asyncio.sleep(1)
>>> yield i
"""
CMDS = {}
def __init__(self, socket_path, debug=False):
self.name = f"EngineServer {self.__class__.__name__}"
super().__init__(debug=debug)
self.engine_debug(f"{self.name}: finished setup 1 (_debug={self._engine_debug})")
self.socket_path = socket_path
self.client_id_var = contextvars.ContextVar("client_id", default=None)
# task <--> client id mapping
self.tasks = {}
# child tasks spawned by main tasks
self.child_tasks = {}
self.engine_debug(f"{self.name}: finished setup 2 (_debug={self._engine_debug})")
if self.socket_path is not None:
# create ZeroMQ context
self.context = zmq.asyncio.Context()
# ROUTER socket can handle multiple concurrent requests
self.socket = self.context.socket(zmq.ROUTER)
self.socket.setsockopt(zmq.LINGER, 0) # Discard pending messages immediately disconnect() or close()
self.socket.setsockopt(zmq.SNDHWM, 0) # Unlimited send buffer
self.socket.setsockopt(zmq.RCVHWM, 0) # Unlimited receive buffer
# create socket file
self.socket.bind(f"ipc://{self.socket_path}")
self.engine_debug(f"{self.name}: finished setup 3 (_debug={self._engine_debug})")
@contextlib.contextmanager
def client_id_context(self, value):
token = self.client_id_var.set(value)
try:
yield
finally:
self.client_id_var.reset(token)
async def run_and_return(self, client_id, command_fn, *args, **kwargs):
fn_str = f"{command_fn.__name__}({args}, {kwargs})"
self.engine_debug(fn_str)
with self.client_id_context(client_id):
try:
self.engine_debug(f"{self.name}: starting run-and-return {fn_str}")
try:
result = await command_fn(*args, **kwargs)
except BaseException as e:
if in_exception_chain(e, (KeyboardInterrupt, asyncio.CancelledError)):
log_fn = self.log.debug
else:
log_fn = self.log.error
error = f"{self.name}: error in {fn_str}: {e}"
trace = traceback.format_exc()
log_fn(error)
self.log.trace(trace)
result = {"_e": (error, trace)}
finally:
self.tasks.pop(client_id, None)
self.engine_debug(f"{self.name}: sending response to {fn_str}: {result}")
await self.send_socket_multipart(client_id, result)
except BaseException as e:
self.log.critical(
f"Unhandled exception in {self.name}.run_and_return({client_id}, {command_fn}, {args}, {kwargs}): {e}"
)
self.log.critical(traceback.format_exc())
finally:
self.engine_debug(f"{self.name} finished run-and-return {fn_str}")
async def run_and_yield(self, client_id, command_fn, *args, **kwargs):
fn_str = f"{command_fn.__name__}({args}, {kwargs})"
with self.client_id_context(client_id):
try:
self.engine_debug(f"{self.name}: starting run-and-yield {fn_str}")
try:
async for _ in command_fn(*args, **kwargs):
self.engine_debug(f"{self.name}: sending iteration for {fn_str}: {_}")
await self.send_socket_multipart(client_id, _)
except BaseException as e:
if in_exception_chain(e, (KeyboardInterrupt, asyncio.CancelledError)):
log_fn = self.log.debug
else:
log_fn = self.log.error
error = f"{self.name}: error in {fn_str}: {e}"
trace = traceback.format_exc()
log_fn(error)
self.log.trace(trace)
result = {"_e": (error, trace)}
await self.send_socket_multipart(client_id, result)
finally:
self.engine_debug(f"{self.name}: reached end of run-and-yield iteration for {fn_str}")
# _s == special signal that means StopIteration
await self.send_socket_multipart(client_id, {"_s": None})
self.tasks.pop(client_id, None)
except BaseException as e:
self.log.critical(
f"Unhandled exception in {self.name}.run_and_yield({client_id}, {command_fn}, {args}, {kwargs}): {e}"
)
self.log.critical(traceback.format_exc())
finally:
self.engine_debug(f"{self.name}: finished run-and-yield {fn_str}")
async def send_socket_multipart(self, client_id, message):
try:
message = pickle.dumps(message)
await self._infinite_retry(self.socket.send_multipart, [client_id, message])
except Exception as e:
self.log.verbose(f"{self.name}: error sending ZMQ message: {e}")
self.log.trace(traceback.format_exc())
def check_error(self, message):
if message is error_sentinel:
return True
async def worker(self):
self.engine_debug(f"{self.name}: starting worker")
try:
while 1:
client_id, binary = await self.socket.recv_multipart()
message = self.unpickle(binary)
self.engine_debug(f"{self.name} got message: {message}")
if self.check_error(message):
continue
cmd = message.get("c", None)
if not isinstance(cmd, int):
self.log.warning(f"{self.name}: no command sent in message: {message}")
continue
# -1 == cancel task
if cmd == -1:
self.engine_debug(f"{self.name} got cancel signal")
await self.send_socket_multipart(client_id, {"m": "CANCEL_OK"})
await self.cancel_task(client_id)
continue
# -99 == shutdown task
if cmd == -99:
self.log.verbose(f"{self.name} got shutdown signal")
await self.send_socket_multipart(client_id, {"m": "SHUTDOWN_OK"})
await self._shutdown()
return
args = message.get("a", ())
if not isinstance(args, tuple):
self.log.warning(f"{self.name}: received invalid args of type {type(args)}, should be tuple")
continue
kwargs = message.get("k", {})
if not isinstance(kwargs, dict):
self.log.warning(f"{self.name}: received invalid kwargs of type {type(kwargs)}, should be dict")
continue
command_name = self.CMDS[cmd]
command_fn = getattr(self, command_name, None)
if command_fn is None:
self.log.warning(f'{self.name} has no function named "{command_fn}"')
continue
if inspect.isasyncgenfunction(command_fn):
self.engine_debug(f"{self.name}: creating run-and-yield coroutine for {command_name}()")
coroutine = self.run_and_yield(client_id, command_fn, *args, **kwargs)
else:
self.engine_debug(f"{self.name}: creating run-and-return coroutine for {command_name}()")
coroutine = self.run_and_return(client_id, command_fn, *args, **kwargs)
self.engine_debug(f"{self.name}: creating task for {command_name}() coroutine")
task = asyncio.create_task(coroutine)
self.tasks[client_id] = task, command_fn, args, kwargs
self.engine_debug(f"{self.name}: finished creating task for {command_name}() coroutine")
except BaseException as e:
await self._shutdown()
if not in_exception_chain(e, (KeyboardInterrupt, asyncio.CancelledError)):
self.log.error(f"{self.name}: error in EngineServer worker: {e}")
self.log.trace(traceback.format_exc())
finally:
self.engine_debug(f"{self.name}: finished worker()")
async def _shutdown(self):
if not self._shutdown_status:
self.log.verbose(f"{self.name}: shutting down...")
self._shutdown_status = True
await self.cancel_all_tasks()
context = getattr(self, "context", None)
if context is not None:
try:
context.destroy(linger=0)
except Exception:
self.log.trace(traceback.format_exc())
try:
context.term()
except Exception:
self.log.trace(traceback.format_exc())
self.log.verbose(f"{self.name}: finished shutting down")
async def task_pool(self, fn, args_kwargs, threads=10, timeout=300, global_kwargs=None):
if global_kwargs is None:
global_kwargs = {}
tasks = {}
args_kwargs = list(args_kwargs)
def new_task():
if args_kwargs:
kwargs = {}
tracker = None
args = args_kwargs.pop(0)
if isinstance(args, (list, tuple)):
# you can specify a custom tracker value if you want
# this helps with correlating results
with suppress(ValueError):
args, kwargs, tracker = args
# or you can just specify args/kwargs
with suppress(ValueError):
args, kwargs = args
if not isinstance(kwargs, dict):
raise ValueError(f"kwargs must be dict (got: {kwargs})")
if not isinstance(args, (list, tuple)):
args = [args]
task = self.new_child_task(fn(*args, **kwargs, **global_kwargs))
tasks[task] = (args, kwargs, tracker)
for _ in range(threads): # Start initial batch of tasks
new_task()
while tasks: # While there are tasks pending
# Wait for the first task to complete
finished = await self.finished_tasks(tasks, timeout=timeout)
for task in finished:
result = task.result()
(args, kwargs, tracker) = tasks.pop(task)
yield (args, kwargs, tracker), result
new_task()
def new_child_task(self, coro):
"""
Create a new asyncio task, making sure to track it based on the client id.
This allows the task to be automatically cancelled if its parent is cancelled.
"""
client_id = self.client_id_var.get()
task = asyncio.create_task(coro)
if client_id:
def remove_task(t):
tasks = self.child_tasks.get(client_id, set())
tasks.discard(t)
if not tasks:
self.child_tasks.pop(client_id, None)
task.add_done_callback(remove_task)
try:
self.child_tasks[client_id].add(task)
except KeyError:
self.child_tasks[client_id] = {task}
return task
async def finished_tasks(self, tasks, timeout=None):
"""
Given a list of asyncio tasks, return the ones that are finished with an optional timeout
"""
if tasks:
try:
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED, timeout=timeout)
return done
except BaseException as e:
if isinstance(e, (TimeoutError, asyncio.exceptions.TimeoutError)):
self.log.warning(f"{self.name}: Timeout after {timeout:,} seconds in finished_tasks({tasks})")
for task in list(tasks):
task.cancel()
self._await_cancelled_task(task)
else:
if not in_exception_chain(e, (KeyboardInterrupt, asyncio.CancelledError)):
self.log.error(f"{self.name}: Unhandled exception in finished_tasks({tasks}): {e}")
self.log.trace(traceback.format_exc())
raise
return set()
async def cancel_task(self, client_id):
parent_task = self.tasks.pop(client_id, None)
if parent_task is None:
return
parent_task, _cmd, _args, _kwargs = parent_task
self.engine_debug(f"{self.name}: Cancelling client id {client_id} (task: {parent_task})")
parent_task.cancel()
child_tasks = self.child_tasks.pop(client_id, set())
if child_tasks:
self.engine_debug(f"{self.name}: Cancelling {len(child_tasks):,} child tasks for client id {client_id}")
for child_task in child_tasks:
child_task.cancel()
for task in [parent_task] + list(child_tasks):
await self._await_cancelled_task(task)
async def _await_cancelled_task(self, task):
try:
await asyncio.wait_for(task, timeout=10)
except (TimeoutError, asyncio.exceptions.TimeoutError):
self.log.trace(f"{self.name}: Timeout cancelling task: {task}")
return
except (KeyboardInterrupt, asyncio.CancelledError):
return
except BaseException as e:
self.log.error(f"Unhandled error in {task.get_coro().__name__}(): {e}")
self.log.trace(traceback.format_exc())
async def cancel_all_tasks(self):
for client_id in list(self.tasks):
await self.cancel_task(client_id)
for client_id, tasks in self.child_tasks.items():
for task in list(tasks):
await self._await_cancelled_task(task)
|