/
processes.py
1307 lines (1040 loc) · 47.4 KB
/
processes.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
# -*- coding: utf-8 -*-
"""The main Process module"""
import abc
import contextlib
import enum
import functools
import copy
import logging
import time
import sys
import uuid
import asyncio
from types import TracebackType
from typing import (
Any, Awaitable, Callable, cast, Dict, Generator, Hashable, List, Optional, Sequence, Tuple, Type, Union
)
try:
from aiocontextvars import ContextVar
except ModuleNotFoundError:
from contextvars import ContextVar
from aio_pika.exceptions import ConnectionClosed
import yaml
import kiwipy
from .process_listener import ProcessListener
from .process_spec import ProcessSpec
from .utils import protected, PID_TYPE, SAVED_STATE_TYPE
from . import exceptions
from . import futures
from .base import state_machine
from .base.utils import super_check, call_with_super_check
from .base.state_machine import event, StateEntryFailed, StateMachine, TransitionFailed
from . import events
from . import persistence
from . import ports
from . import process_comms
from . import process_states
from . import utils
# pylint: disable=too-many-lines
__all__ = ['Process', 'ProcessSpec', 'BundleKeys', 'TransitionFailed']
_LOGGER = logging.getLogger(__name__)
PROCESS_STACK = ContextVar('process stack', default=[])
class BundleKeys:
"""
String keys used by the process to save its state in the state bundle.
See :meth:`plumpy.processes.Process.save_instance_state` and :meth:`plumpy.processes.Process.load_instance_state`.
"""
# pylint: disable=too-few-public-methods
INPUTS_RAW = 'INPUTS_RAW'
INPUTS_PARSED = 'INPUTS_PARSED'
OUTPUTS = 'OUTPUTS'
class ProcessStateMachineMeta(abc.ABCMeta, state_machine.StateMachineMeta):
pass
# Make ProcessStateMachineMeta instances (classes) YAML - able
yaml.representer.Representer.add_representer(ProcessStateMachineMeta, yaml.representer.Representer.represent_name)
def ensure_not_closed(func: Callable[..., Any]) -> Callable[..., Any]:
"""Decorator to check that the process is not closed before running the method."""
@functools.wraps(func)
def func_wrapper(self: Any, *args: Any, **kwargs: Any) -> Any:
# pylint: disable=protected-access
if self._closed:
raise exceptions.ClosedError('Process is closed')
return func(self, *args, **kwargs)
return func_wrapper
@persistence.auto_persist('_pid', '_creation_time', '_future', '_paused', '_status', '_pre_paused_status')
class Process(StateMachine, persistence.Savable, metaclass=ProcessStateMachineMeta):
"""
The Process class is the base for any unit of work in plumpy.
A process can be in one of the following states:
* CREATED
* RUNNING
* WAITING
* FINISHED
* EXCEPTED
* KILLED
as defined in the :class:`~plumpy.process_states.ProcessState` enum.
::
___
| v
CREATED (x) --- RUNNING (x) --- FINISHED (o)
| ^ /
v | /
WAITING (x) --
| ^
---
* -- EXCEPTED (o)
* -- KILLED (o)
* (o): terminal state
* (x): non terminal state
When a Process enters a state is always gets a corresponding message, e.g.
on entering RUNNING it will receive the on_run message. These are
always called immediately after that state is entered but before being
executed.
"""
# pylint: disable=too-many-instance-attributes,too-many-public-methods
# Static class stuff ######################
_spec_class = ProcessSpec
# Default placeholders, will be populated in init()
_stepping = False
_pausing: Optional[futures.CancellableAction] = None
_paused: Optional[persistence.SavableFuture] = None
_killing: Optional[futures.CancellableAction] = None
_interrupt_action: Optional[futures.CancellableAction] = None
_closed = False
_cleanups: Optional[List[Callable[[], None]]] = None
__called: bool = False
@classmethod
def current(cls) -> Optional['Process']:
"""
Get the currently running process i.e. the one at the top of the stack
:return: the currently running process
"""
if PROCESS_STACK.get():
return PROCESS_STACK.get()[-1]
return None
@classmethod
def get_states(cls) -> Sequence[Type[process_states.State]]:
"""Return all allowed states of the process."""
state_classes = cls.get_state_classes()
return (
state_classes[process_states.ProcessState.CREATED],
*[state for state in state_classes.values() if state.LABEL != process_states.ProcessState.CREATED]
)
@classmethod
def get_state_classes(cls) -> Dict[Hashable, Type[process_states.State]]:
# A mapping of the State constants to the corresponding state class
return {
process_states.ProcessState.CREATED: process_states.Created,
process_states.ProcessState.RUNNING: process_states.Running,
process_states.ProcessState.WAITING: process_states.Waiting,
process_states.ProcessState.FINISHED: process_states.Finished,
process_states.ProcessState.EXCEPTED: process_states.Excepted,
process_states.ProcessState.KILLED: process_states.Killed
}
@classmethod
def spec(cls) -> ProcessSpec:
try:
return cls.__getattribute__(cls, '_spec')
except AttributeError:
try:
cls._spec: ProcessSpec = cls._spec_class() # type: ignore
cls.__called: bool = False # type: ignore
cls.define(cls._spec) # type: ignore
assert cls.__called, \
'Process.define() was not called by {}\n' \
'Hint: Did you forget to call the superclass method in your define? ' \
'Try: super().define(spec)'.format(cls)
return cls._spec # type: ignore
except Exception:
del cls._spec # type: ignore
cls.__called = False
raise
@classmethod
def get_name(cls) -> str:
"""Return the process class name."""
return cls.__name__
@classmethod
def define(cls, _spec: ProcessSpec) -> None:
"""Define the specification of the process.
Normally should be overridden by subclasses.
"""
cls.__called = True
@classmethod
def get_description(cls) -> Dict[str, Any]:
"""
Get a human readable description of what this :class:`Process` does.
:return: The description.
"""
description: Dict[str, Any] = {}
if cls.__doc__:
description['description'] = cls.__doc__.strip()
spec_description = cls.spec().get_description()
if spec_description:
description['spec'] = spec_description
return description
@classmethod
def recreate_from(
cls, saved_state: SAVED_STATE_TYPE, load_context: Optional[persistence.LoadSaveContext] = None
) -> 'Process':
"""
Recreate a process from a saved state, passing any positional and
keyword arguments on to load_instance_state
:param saved_state: The saved state to load from
:param load_context: The load context to use
:return: An instance of the object with its state loaded from the save state.
"""
process = cast(Process, super().recreate_from(saved_state, load_context))
call_with_super_check(process.init)
return process
def __init__(
self,
inputs: Optional[dict] = None,
pid: Optional[PID_TYPE] = None,
logger: Optional[logging.Logger] = None,
loop: Optional[asyncio.AbstractEventLoop] = None,
communicator: Optional[kiwipy.Communicator] = None
) -> None:
"""
The signature of the constructor should not be changed by subclassing processes.
:param inputs: A dictionary of the process inputs
:param pid: The process ID, can be manually set, if not a unique pid will be chosen
:param logger: An optional logger for the process to use
:param loop: The event loop
:param communicator: The (optional) communicator
"""
super().__init__()
# Don't allow the spec to be changed anymore
self.spec().seal()
self._loop = loop if loop is not None else asyncio.get_event_loop()
self._setup_event_hooks()
self._status: Optional[str] = None # May hold a current status message
self._pre_paused_status: Optional[
str] = None # Save status when a pause message replaces it, such that it can be restored
self._paused = None
# Input/output
self._raw_inputs = None if inputs is None else utils.AttributesFrozendict(inputs)
self._pid = pid
self._parsed_inputs: Optional[utils.AttributesFrozendict] = None
self._outputs: Dict[str, Any] = {}
self._uuid: Optional[uuid.UUID] = None
self._creation_time: Optional[float] = None
# Runtime variables
self._future = persistence.SavableFuture(loop=self._loop)
self.__event_helper = utils.EventHelper(ProcessListener)
self._logger = logger
self._communicator = communicator
@super_check
def init(self) -> None:
"""Common initialisation logic, after create or load, goes here.
This method is called in :class:`plumpy.base.state_machine.StateMachineMeta`
"""
self._cleanups = [] # a list of functions to be ran on terminated
if self._communicator is not None:
try:
identifier = self._communicator.add_rpc_subscriber(self.message_receive, identifier=str(self.pid))
self.add_cleanup(functools.partial(self._communicator.remove_rpc_subscriber, identifier))
except kiwipy.TimeoutError:
self.logger.exception('Process<%s> failed to register as an RPC subscriber', self.pid)
try:
identifier = self._communicator.add_broadcast_subscriber(
self.broadcast_receive, identifier=str(self.pid)
)
self.add_cleanup(functools.partial(self._communicator.remove_broadcast_subscriber, identifier))
except kiwipy.TimeoutError:
self.logger.exception('Process<%s> failed to register as a broadcast subscriber', self.pid)
if not self._future.done():
def try_killing(future: futures.Future) -> None:
if future.cancelled():
if not self.kill('Killed by future being cancelled'):
self.logger.warning('Failed to kill process on future cancel')
self._future.add_done_callback(try_killing)
def _setup_event_hooks(self) -> None:
"""Set the event hooks to process, when it is created or loaded(recreated)."""
event_hooks = {
state_machine.StateEventHook.ENTERING_STATE:
lambda _s, _h, state: self.on_entering(cast(process_states.State, state)),
state_machine.StateEventHook.ENTERED_STATE:
lambda _s, _h, from_state: self.on_entered(cast(Optional[process_states.State], from_state)),
state_machine.StateEventHook.EXITING_STATE:
lambda _s, _h, _state: self.on_exiting()
}
for hook, callback in event_hooks.items():
self.add_state_event_callback(hook, callback)
@property
def creation_time(self) -> Optional[float]:
"""
The creation time of this Process as returned by time.time() when instantiated
:return: The creation time
"""
return self._creation_time
@property
def pid(self) -> Optional[PID_TYPE]:
"""Return the pid of the process."""
return self._pid
@property
def uuid(self) -> Optional[uuid.UUID]:
"""Return the UUID of the process """
return self._uuid
@property
def raw_inputs(self) -> Optional[utils.AttributesFrozendict]:
"""The `AttributesFrozendict` of inputs (if not None)."""
return self._raw_inputs
@property
def inputs(self) -> Optional[utils.AttributesFrozendict]:
"""Return the parsed inputs."""
return self._parsed_inputs
@property
def outputs(self) -> Dict[str, Any]:
"""
Get the current outputs emitted by the Process. These may grow over
time as the process runs.
:return: A mapping of {output_port: value} outputs
"""
return self._outputs
@property
def logger(self) -> logging.Logger:
"""Return the logger for this class.
If not set, return the default logger.
:return: The logger.
"""
if self._logger is not None:
return self._logger
return _LOGGER
@property
def status(self) -> Optional[str]:
"""Return the status massage of the process."""
return self._status
def set_status(self, status: Optional[str]) -> None:
"""Set the status message of the process."""
self._status = status
@property
def paused(self) -> bool:
"""Return whether the process was being paused."""
return self._paused is not None
def future(self) -> persistence.SavableFuture:
"""Return a savable future representing an eventual result of an asynchronous operation.
The result is set at the terminal state.
"""
return self._future
@ensure_not_closed
def launch(
self,
process_class: Type['Process'],
inputs: Optional[dict] = None,
pid: Optional[PID_TYPE] = None,
logger: Optional[logging.Logger] = None
) -> 'Process':
"""Start running the nested process.
The process is started asynchronously, without blocking other task in the event loop.
"""
process = process_class(inputs=inputs, pid=pid, logger=logger, loop=self.loop, communicator=self._communicator)
self.loop.create_task(process.step_until_terminated())
return process
# region State introspection methods
def has_terminated(self) -> bool:
"""Return whether the process was terminated."""
return self._state.is_terminal()
def result(self) -> Any:
"""
Get the result from the process if it is finished.
If the process was killed then a KilledError will be raise.
If the process has excepted then the failing exception will be raised.
If in any other state this will raise an InvalidStateError.
:return: The result of the process
"""
if isinstance(self._state, process_states.Finished):
return self._state.result
if isinstance(self._state, process_states.Killed):
raise exceptions.KilledError(self._state.msg)
if isinstance(self._state, process_states.Excepted):
raise (self._state.exception or Exception('process excepted'))
raise exceptions.InvalidStateError
def successful(self) -> bool:
"""
Returns whether the result of the process is considered successful
Will raise if the process is not in the FINISHED state
"""
try:
return self._state.successful # type: ignore
except AttributeError as exception:
raise exceptions.InvalidStateError('process is not in the finished state') from exception
@property
def is_successful(self) -> bool:
"""Return whether the result of the process is considered successful.
:return: boolean, True if the process is in `Finished` state with `successful` attribute set to `True`
"""
try:
return self._state.successful # type: ignore
except AttributeError:
return False
def killed(self) -> bool:
"""Return whether the process is killed."""
return self.state == process_states.ProcessState.KILLED
def killed_msg(self) -> Optional[str]:
"""Return the killed message."""
if isinstance(self._state, process_states.Killed):
return self._state.msg
raise exceptions.InvalidStateError('Has not been killed')
def exception(self) -> Optional[BaseException]:
"""Return exception, if the process is terminated in excepted state."""
if isinstance(self._state, process_states.Excepted):
return self._state.exception
return None
def done(self) -> bool:
"""
Return True if the call was successfully killed or finished running.
"""
return self._state.is_terminal()
# endregion
# region loop methods
@property
def loop(self) -> asyncio.AbstractEventLoop:
"""Return the event loop of the process."""
return self._loop
def call_soon(self, callback: Callable[..., Any], *args: Any, **kwargs: Any) -> events.ProcessCallback:
"""
Schedule a callback to what is considered an internal process function
(this needn't be a method).
If it raises an exception it will cause the process to fail.
"""
args = (callback,) + args
handle = events.ProcessCallback(self, self._run_task, args, kwargs)
self.loop.create_task(handle.run())
return handle
def callback_excepted(
self, _callback: Callable[..., Any], exception: Optional[BaseException], trace: Optional[TracebackType]
) -> None:
if self.state != process_states.ProcessState.EXCEPTED:
self.fail(exception, trace)
@contextlib.contextmanager
def _process_scope(self) -> Generator[None, None, None]:
"""
This context manager function is used to make sure the process stack is correct
meaning that globally someone can ask for Process.current() to get the last process
that is on the call stack.
"""
stack_copy = PROCESS_STACK.get().copy()
stack_copy.append(self)
PROCESS_STACK.set(stack_copy)
try:
yield None
finally:
assert Process.current() is self, \
'Somehow, the process at the top of the stack is not me, ' \
'but another process! ({} != {})'.format(self, Process.current())
stack_copy = PROCESS_STACK.get().copy()
stack_copy.pop()
PROCESS_STACK.set(stack_copy)
async def _run_task(self, callback: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
"""
This method should be used to run all Process related functions and coroutines.
If there is an exception the process will enter the EXCEPTED state.
:param callback: A function or coroutine
:param args: Optional positional arguments passed to fn
:param kwargs: Optional keyword arguments passed to fn
:return: The value as returned by fn
"""
# Make sure execute is a coroutine
coro = utils.ensure_coroutine(callback)
with self._process_scope():
result = await coro(*args, **kwargs)
return result
# endregion
# region Persistence
def save_instance_state(
self, out_state: SAVED_STATE_TYPE, save_context: Optional[persistence.LoadSaveContext]
) -> None:
"""
Ask the process to save its current instance state.
:param out_state: A bundle to save the state to
:param save_context: The save context
"""
super().save_instance_state(out_state, save_context)
out_state['_state'] = self._state.save()
# Inputs/outputs
if self.raw_inputs is not None:
out_state[BundleKeys.INPUTS_RAW] = self.encode_input_args(self.raw_inputs)
if self.inputs is not None:
out_state[BundleKeys.INPUTS_PARSED] = self.encode_input_args(self.inputs)
if self.outputs:
out_state[BundleKeys.OUTPUTS] = self.encode_input_args(self.outputs)
@protected
def load_instance_state(self, saved_state: SAVED_STATE_TYPE, load_context: persistence.LoadSaveContext) -> None:
"""Load the process from its saved instance state.
:param saved_state: A bundle to load the state from
:param load_context: The load context
"""
# First make sure the state machine constructor is called
super().__init__()
self._setup_event_hooks()
# Runtime variables, set initial states
self._future = persistence.SavableFuture()
self.__event_helper = utils.EventHelper(ProcessListener)
self._logger = None
self._communicator = None
if 'loop' in load_context:
self._loop = load_context.loop
else:
self._loop = asyncio.get_event_loop()
self._state: process_states.State = self.recreate_state(saved_state['_state'])
if 'communicator' in load_context:
self._communicator = load_context.communicator
if 'logger' in load_context:
self._logger = load_context.logger
# Need to call this here as things downstream may rely on us having the runtime variable above
super().load_instance_state(saved_state, load_context)
# Inputs/outputs
try:
decoded = self.decode_input_args(saved_state[BundleKeys.INPUTS_RAW])
self._raw_inputs = utils.AttributesFrozendict(decoded)
except KeyError:
self._raw_inputs = None
try:
decoded = self.decode_input_args(saved_state[BundleKeys.INPUTS_PARSED])
self._parsed_inputs = utils.AttributesFrozendict(decoded)
except KeyError:
self._parsed_inputs = None
try:
decoded = self.decode_input_args(saved_state[BundleKeys.OUTPUTS])
self._outputs = decoded
except KeyError:
self._outputs = {}
# endregion
def add_process_listener(self, listener: ProcessListener) -> None:
"""Add a process listener to the process.
The listener defines the actions to take when the process is triggering
the specific state condition.
"""
assert (listener != self), 'Cannot listen to yourself!'
self.__event_helper.add_listener(listener)
def remove_process_listener(self, listener: ProcessListener) -> None:
"""Remove a process listener from the process."""
self.__event_helper.remove_listener(listener)
@protected
def set_logger(self, logger: logging.Logger) -> None:
"""Set the logger of the process."""
self._logger = logger
@protected
def log_with_pid(self, level: int, msg: str) -> None:
"""Log the message with the process pid."""
self.logger.log(level, '%s: %s', self.pid, msg)
# region Events
def on_entering(self, state: process_states.State) -> None:
# Map these onto direct functions that the subclass can implement
state_label = state.LABEL
if state_label == process_states.ProcessState.CREATED:
call_with_super_check(self.on_create)
elif state_label == process_states.ProcessState.RUNNING:
call_with_super_check(self.on_run)
elif state_label == process_states.ProcessState.WAITING:
call_with_super_check(self.on_wait, state.data) # type: ignore
elif state_label == process_states.ProcessState.FINISHED:
call_with_super_check(self.on_finish, state.result, state.successful) # type: ignore
elif state_label == process_states.ProcessState.KILLED:
call_with_super_check(self.on_kill, state.msg) # type: ignore
elif state_label == process_states.ProcessState.EXCEPTED:
call_with_super_check(self.on_except, state.get_exc_info()) # type: ignore
def on_entered(self, from_state: Optional[process_states.State]) -> None:
# Map these onto direct functions that the subclass can implement
state_label = self._state.LABEL
if state_label == process_states.ProcessState.RUNNING:
call_with_super_check(self.on_running)
elif state_label == process_states.ProcessState.WAITING:
call_with_super_check(self.on_waiting)
elif state_label == process_states.ProcessState.FINISHED:
call_with_super_check(self.on_finished)
elif state_label == process_states.ProcessState.EXCEPTED:
call_with_super_check(self.on_excepted)
elif state_label == process_states.ProcessState.KILLED:
call_with_super_check(self.on_killed)
if self._communicator and isinstance(self.state, enum.Enum):
from_label = cast(enum.Enum, from_state.LABEL).value if from_state is not None else None
subject = 'state_changed.{}.{}'.format(from_label, self.state.value)
self.logger.info('Broadcasting state change of %d: %s', self.pid, subject)
try:
self._communicator.broadcast_send(body=None, sender=self.pid, subject=subject)
except ConnectionClosed:
message = 'no connection available to broadcast state change from %s to %s'
self.logger.info(message, from_label, self.state.value)
def on_exiting(self) -> None:
state = self.state
if state == process_states.ProcessState.WAITING:
call_with_super_check(self.on_exit_waiting)
elif state == process_states.ProcessState.RUNNING:
call_with_super_check(self.on_exit_running)
@super_check
def on_create(self) -> None:
"""Entering the CREATED state."""
self._creation_time = time.time()
# This will parse the inputs with respect to the input portnamespace of the spec and validate them
raw_inputs = dict(self._raw_inputs) if self._raw_inputs else {}
self._parsed_inputs = self.spec().inputs.pre_process(raw_inputs)
result = self.spec().inputs.validate(self._parsed_inputs)
if result is not None:
raise ValueError(result)
# Set up a process ID
self._uuid = uuid.uuid4()
if self._pid is None:
self._pid = self._uuid
@super_check
def on_exit_running(self) -> None:
"""Exiting the RUNNING state."""
@super_check
def on_exit_waiting(self) -> None:
"""Exiting the WAITING state."""
@super_check
def on_run(self) -> None:
"""Entering the RUNNING state."""
@super_check
def on_running(self) -> None:
"""Entered the RUNNING state."""
self._fire_event(ProcessListener.on_process_running)
def on_output_emitting(self, output_port: str, value: Any) -> None:
"""Output is about to be emitted."""
def on_output_emitted(self, output_port: str, value: Any, dynamic: bool) -> None:
self.__event_helper.fire_event(ProcessListener.on_output_emitted, self, output_port, value, dynamic)
@super_check
def on_wait(self, awaitables: Sequence[Awaitable]) -> None:
"""Entering the WAITING state."""
@super_check
def on_waiting(self) -> None:
"""Entered the WAITING state."""
self._fire_event(ProcessListener.on_process_waiting)
@super_check
def on_pausing(self, msg: Optional[str] = None) -> None:
"""The process is being paused."""
@super_check
def on_paused(self, msg: Optional[str] = None) -> None:
"""The process was paused."""
self._pausing = None
# Create a future to represent the duration of the paused state
self._paused = persistence.SavableFuture()
# Save the current status and potentially overwrite it with the passed message
self._pre_paused_status = self.status
if msg is not None:
self.set_status(msg)
self._fire_event(ProcessListener.on_process_paused)
@super_check
def on_playing(self) -> None:
"""The process was played."""
# Done being paused
if self._paused is not None:
self._paused.set_result(True)
self._paused = None
self.set_status(self._pre_paused_status)
self._pre_paused_status = None
self._fire_event(ProcessListener.on_process_played)
@super_check
def on_finish(self, result: Any, successful: bool) -> None:
"""Entering the FINISHED state."""
if successful:
validation_error = self.spec().outputs.validate(self.outputs)
if validation_error:
raise StateEntryFailed(process_states.ProcessState.FINISHED, result, False)
self.future().set_result(self.outputs)
@super_check
def on_finished(self) -> None:
"""Entered the FINISHED state."""
self._fire_event(ProcessListener.on_process_finished, self.future().result())
@super_check
def on_except(self, exc_info: Tuple[Any, Exception, TracebackType]) -> None:
"""Entering the EXCEPTED state."""
exception = exc_info[1]
exception.__traceback__ = exc_info[2]
self.future().set_exception(exception)
@super_check
def on_excepted(self) -> None:
"""Entered the EXCEPTED state."""
self._fire_event(ProcessListener.on_process_excepted, str(self.future().exception()))
@super_check
def on_kill(self, msg: Optional[str]) -> None:
"""Entering the KILLED state."""
self.set_status(msg)
self.future().set_exception(exceptions.KilledError(msg))
@super_check
def on_killed(self) -> None:
"""Entered the KILLED state."""
self._killing = None
self.future().exception() # exception must be retrieved
self._fire_event(ProcessListener.on_process_killed, self.killed_msg())
def on_terminated(self) -> None:
"""Call when a terminal state is reached."""
super().on_terminated()
self.close()
@super_check
def on_close(self) -> None:
"""
Called when the Process is being closed an will not be ran anymore. This is an opportunity
to free any runtime resources
"""
try:
for cleanup in self._cleanups or []:
try:
cleanup()
except Exception: # pylint: disable=broad-except
self.logger.exception('Exception calling cleanup method %s', cleanup)
self._cleanups = None
finally:
self._event_callbacks = {}
self._closed = True
def _fire_event(self, evt: Callable[..., Any], *args: Any, **kwargs: Any) -> None:
self.__event_helper.fire_event(evt, self, *args, **kwargs)
# endregion
# region Communication
def message_receive(self, _comm: kiwipy.Communicator, msg: Dict[str, Any]) -> Any:
"""
Coroutine called when the process receives a message from the communicator
:param _comm: the communicator that sent the message
:param msg: the message
:return: the outcome of processing the message, the return value will be sent back as a response to the sender
"""
self.logger.debug("RPC message '%s' received with communicator '%s'", msg, _comm)
intent = msg[process_comms.INTENT_KEY]
if intent == process_comms.Intent.PLAY:
return self._schedule_rpc(self.play)
if intent == process_comms.Intent.PAUSE:
return self._schedule_rpc(self.pause, msg=msg.get(process_comms.MESSAGE_KEY, None))
if intent == process_comms.Intent.KILL:
return self._schedule_rpc(self.kill, msg=msg.get(process_comms.MESSAGE_KEY, None))
if intent == process_comms.Intent.STATUS:
status_info: Dict[str, Any] = {}
self.get_status_info(status_info)
return status_info
# Didn't match any known intents
raise RuntimeError('Unknown intent')
def broadcast_receive(self, _comm: kiwipy.Communicator, body: Any, sender: Any, subject: Any,
correlation_id: Any) -> Optional[kiwipy.Future]:
"""
Coroutine called when the process receives a message from the communicator
:param _comm: the communicator that sent the message
:param msg: the message
"""
# pylint: disable=unused-argument
self.logger.debug("Broadcast message '%s' received with communicator '%s'", body, _comm)
# If we get a message we recognise then action it, otherwise ignore
if subject == process_comms.Intent.PLAY:
return self._schedule_rpc(self.play)
if subject == process_comms.Intent.PAUSE:
return self._schedule_rpc(self.pause, msg=body)
if subject == process_comms.Intent.KILL:
return self._schedule_rpc(self.kill, msg=body)
return None
def _schedule_rpc(self, callback: Callable[..., Any], *args: Any, **kwargs: Any) -> kiwipy.Future:
"""
Schedule a call to a callback as a result of an RPC communication call, this will return
a future that resolves to the final result (even after one or more layer of futures being
returned) of the callback.
The callback will be scheduled at the working
thread where the process event loop runs.
:param callback: the callback function or coroutine
:param args: the positional arguments to the callback
:param kwargs: the keyword arguments to the callback
:return: a kiwi future that resolves to the outcome of the callback
"""
kiwi_future = kiwipy.Future()
async def run_callback() -> None:
with kiwipy.capture_exceptions(kiwi_future):
result = callback(*args, **kwargs)
while asyncio.isfuture(result):
result = await result
kiwi_future.set_result(result)
# Schedule the task and give back a kiwi future
asyncio.run_coroutine_threadsafe(run_callback(), self.loop)
return kiwi_future
# endregion
@ensure_not_closed
def add_cleanup(self, cleanup: Callable[[], None]) -> None:
"""Add callback, which will be run when the process is being closed."""
assert self._cleanups is not None
self._cleanups.append(cleanup)
def close(self) -> None:
"""
Calling this method indicates that this process should not ran anymore and will trigger
any runtime resources (such as the communicator connection) to be cleaned up. The state
of the process will still be accessible.
It is safe to call this method multiple times.
"""
if self._closed:
return
call_with_super_check(self.on_close)
# region State related methods
def transition_excepted(
self, _initial_state: Any, final_state: process_states.ProcessState, exception: Exception, trace: TracebackType
) -> None:
# If we are creating, then reraise instead of failing.
if final_state == process_states.ProcessState.CREATED:
raise exception.with_traceback(trace)
self.transition_to(process_states.ProcessState.EXCEPTED, exception, trace)
def pause(self, msg: Union[str, None] = None) -> Union[bool, futures.CancellableAction]:
"""Pause the process.
:param msg: an optional message to set as the status. The current status will be saved in the private
`_pre_paused_status attribute`, such that it can be restored when the process is played again.
:return: False if process is already terminated,
True if already paused or pausing,
a `CancellableAction` to pause if the process was running steps
"""
if self.has_terminated():
return False
if self.paused:
# Already paused
return True
if self._pausing is not None:
# Already pausing
return self._pausing
if self._stepping:
# Ask the step function to pause by setting this flag and giving the
# caller back a future
interrupt_exception = process_states.PauseInterruption(msg)
self._set_interrupt_action_from_exception(interrupt_exception)
self._pausing = self._interrupt_action
# Try to interrupt the state
self._state.interrupt(interrupt_exception)
return cast(futures.CancellableAction, self._interrupt_action)
return self._do_pause(msg)
def _do_pause(self, state_msg: Optional[str], next_state: Optional[process_states.State] = None) -> bool:
""" Carry out the pause procedure, optionally transitioning to the next state first"""