forked from bluesky/bluesky
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_engine.py
2621 lines (2193 loc) · 95.4 KB
/
run_engine.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
import asyncio
from datetime import datetime
import sys
from warnings import warn
from inspect import Parameter, Signature
from itertools import count
from collections import deque, defaultdict, ChainMap
from enum import Enum
import functools
import inspect
from contextlib import ExitStack
import threading
import weakref
from dataclasses import dataclass
import typing
from .bundlers import RunBundler
from . import protocols as bs_protocols
import concurrent
from event_model import DocumentNames, schema_validators
from .log import logger, msg_logger, state_logger, ComposableLogAdapter
from super_state_machine.machines import StateMachine
from super_state_machine.extras import PropertyMachine
from super_state_machine.errors import TransitionError
try:
from asyncio import current_task
except ImportError:
# handle py < 3,7
from asyncio.tasks import Task
current_task = Task.current_task
del Task
from .utils import (CallbackRegistry, SigintHandler,
normalize_subs_input, AsyncInput,
NoReplayAllowed, RequestAbort, RequestStop,
RunEngineInterrupted, IllegalMessageSequence,
FailedPause, FailedStatus, InvalidCommand,
PlanHalt, Msg, ensure_generator, single_gen,
DefaultDuringTask)
class _RunEnginePanic(Exception):
...
@dataclass
class RunEngineResult():
"""
Information about the plan that was run
Attributes
----------
run_start_uids : list
A list of the UIDs generated during the plan (if any)
plan_result :
The return value of the top-level plan that was run
exit_status : str
interrupted : bool
True if the plan was halted, stopped or aborted
reason : str
A text description of the reason why the plan was aborted (if aborted)
exception :
The exception generated by the plan, if any
"""
run_start_uids: typing.Tuple[str, ...]
plan_result: typing.Any
exit_status: str
interrupted: bool
reason: str
exception: typing.Optional[Exception]
class RunEngineStateMachine(StateMachine):
"""
Attributes
----------
is_idle
State machine is in its idle state
is_running
State machine is in its running state
is_paused
State machine is paused.
"""
class States(Enum):
"""state.name = state.value"""
IDLE = 'idle'
RUNNING = 'running'
PAUSING = 'pausing'
PAUSED = 'paused'
HALTING = 'halting'
STOPPING = 'stopping'
ABORTING = 'aborting'
SUSPENDING = 'suspending'
PANICKED = 'panicked'
@classmethod
def states(cls):
return [state.value for state in cls]
class Meta:
allow_empty = False
initial_state = 'idle'
transitions = {
# Notice that 'transitions' and 'named_transitions' have
# opposite to <--> from structure.
# from_state : [valid_to_states]
'idle': ['running', 'panicked'],
'running': ['idle', 'pausing', 'halting', 'stopping',
'aborting', 'suspending', 'panicked'],
'pausing': ['paused', 'idle', 'halting', 'aborting', 'panicked'],
'suspending': ['running', 'halting', 'aborting', 'panicked'],
'paused': ['idle', 'running', 'halting', 'stopping', 'aborting',
'panicked'],
'halting': ['idle', 'panicked'],
'stopping': ['idle', 'panicked'],
'aborting': ['idle', 'panicked'],
'panicked': []
}
named_checkers = [
('can_pause', 'pausing'),
]
class LoggingPropertyMachine(PropertyMachine):
"""expects object to have a `log` attribute
and a `state_hook` attribute that is ``None`` or a callable with signature
``f(value, old_value)``"""
def __init__(self, machine_type):
super().__init__(machine_type)
def __set__(self, obj, value):
own = type(obj)
old_value = self.__get__(obj, own)
with obj._state_lock:
super().__set__(obj, value)
value = self.__get__(obj, own)
tags = {'old_state': old_value,
'new_state': value,
'RE': self}
state_logger.info("Change state on %r from %r -> %r",
obj, old_value, value, extra=tags)
if obj.state_hook is not None:
obj.state_hook(value, old_value)
def __get__(self, instance, owner):
if instance is None:
return super().__get__(instance, owner)
with instance._state_lock:
return super().__get__(instance, owner)
# See RunEngine.__call__.
_call_sig = Signature(
[Parameter('self', Parameter.POSITIONAL_ONLY),
Parameter('plan', Parameter.POSITIONAL_ONLY),
Parameter('subs', Parameter.POSITIONAL_ONLY, default=None),
Parameter('metadata_kw', Parameter.VAR_KEYWORD)])
def default_scan_id_source(md):
return md.get('scan_id', 0) + 1
def _state_locked(func):
@functools.wraps(func)
def inner(self, *args, **kwargs):
with self._state_lock:
return func(self, *args, **kwargs)
return inner
class RunEngine:
"""The Run Engine execute messages and emits Documents.
Parameters
----------
md : dict-like, optional
The default is a standard Python dictionary, but fancier
objects can be used to store long-term history and persist
it between sessions. The standard configuration
instantiates a Run Engine with historydict.HistoryDict, a
simple interface to a sqlite file. Any object supporting
`__getitem__`, `__setitem__`, and `clear` will work.
loop : asyncio event loop
e.g., ``asyncio.get_event_loop()`` or ``asyncio.new_event_loop()``
preprocessors : list, optional
Generator functions that take in a plan (generator instance) and
modify its messages on the way out. Suitable examples include
the functions in the module ``bluesky.plans`` with names ending in
'wrapper'. Functions are composed in order: the preprocessors
``[f, g]`` are applied like ``f(g(plan))``.
context_managers : list, optional
Context managers that will be entered when we run a plan. The context
managers will be composed in order, much like the preprocessors. If
this argument is omitted, we will use a user-oriented handler for
SIGINT. The elements of this list will be passed this ``RunEngine``
instance as their only argument. You may pass an empty list if you
would like a ``RunEngine`` with no signal handling and no context
managers.
md_validator : callable, optional
a function that raises and prevents starting a run if it deems
the metadata to be invalid or incomplete
Expected signature: f(md)
Function should raise if md is invalid. What that means is
completely up to the user. The function's return value is
ignored.
scan_id_source : callable, optional
a function that will be used to calculate scan_id. Default is to
increment scan_id by 1 each time. However you could pass in a
customized function to get a scan_id from any source.
Expected signature: f(md)
Expected return: updated scan_id value
during_task : reference to an object of class DuringTask, optional
Class methods: ``block()`` to be run to block
the main thread during `RE.__call__`
The required signatures for the class methods ::
def block(ev: Threading.Event) -> None:
"Returns when ev is set"
The default value handles the cases of:
- Matplotlib is not imported (just wait on the event)
- Matplotlib is imported, but not using a Qt, notebook or ipympl
backend (just wait on the event)
- Matplotlib is imported and using a Qt backend (run the Qt app
on the main thread until the run finishes)
- Matplotlib is imported and using a nbagg or ipympl backend (
wait on the event and poll to push updates to the browser)
call_returns_result : bool, default False
A flag that controls the return value of __call__
If ``True``, the ``RunEngine`` will return a :class:``RunEngineResult``
object that contains information about the plan that was run.
If ``False``, the ``RunEngine`` will return a tuple of uids.
Defaults to ``False`` to preserve the old ``RunEngine`` behavior,
but the default is expected to change to ``True`` in the future.
Attributes
----------
md
Direct access to the dict-like persistent storage described above
record_interruptions
False by default. Set to True to generate an extra event stream
that records any interruptions (pauses, suspensions).
state
{'idle', 'running', 'paused'}
suspenders
Read-only collection of `bluesky.suspenders.SuspenderBase` objects
which can suspend and resume execution; see related methods.
preprocessors : list
Generator functions that take in a plan (generator instance) and
modify its messages on the way out. Suitable examples include
the functions in the module ``bluesky.plans`` with names ending in
'wrapper'. Functions are composed in order: the preprocessors
``[f, g]`` are applied like ``f(g(plan))``.
msg_hook
Callable that receives all messages before they are processed
(useful for logging or other development purposes); expected
signature is ``f(msg)`` where ``msg`` is a ``bluesky.Msg``, a
kind of namedtuple; default is None.
state_hook
Callable with signature ``f(new_state, old_state)`` that will be
called whenever the RunEngine's state attribute is updated; default
is None
waiting_hook
Callable with signature ``f(status_object)`` that will be called
whenever the RunEngine is waiting for long-running commands
(trigger, set, kickoff, complete) to complete. This hook is useful to
incorporate a progress bar.
ignore_callback_exceptions
Boolean, False by default.
call_returns_result
Boolean, False by default. If False, RunEngine will return uuid list
after running a plan. If True, RunEngine will return a RunEngineResult
object that contains the plan result, error status, and uuid list.
loop : asyncio event loop
e.g., ``asyncio.get_event_loop()`` or ``asyncio.new_event_loop()``
max_depth
Maximum stack depth; set this to prevent users from calling the
RunEngine inside a function (which can result in unexpected
behavior and breaks introspection tools). Default is None.
For built-in Python interpreter, set to 2. For IPython, set to 11
(tested on IPython 5.1.0; other versions may vary).
pause_msg : str
The message printed when a run is interrupted. This message
includes instructions of changing the state of the RunEngine.
It is set to ``bluesky.run_engine.PAUSE_MSG`` by default and
can be modified based on needs.
commands:
The list of commands available to Msg.
"""
_state = LoggingPropertyMachine(RunEngineStateMachine)
_UNCACHEABLE_COMMANDS = ['pause', 'subscribe', 'unsubscribe', 'stage',
'unstage', 'monitor', 'unmonitor', 'open_run',
'close_run', 'install_suspender',
'remove_suspender', '_start_suspender']
@property
def state(self):
return self._state
@property
def deferred_pause_requested(self):
"""
The property returns ``True`` if deferred pause was requested, but
not processed. The deferred pause is processed at the next checkpoint.
If the pause is requested past the last checkpoint, the plan runs
to completion and this property returns ``True`` until the next
plan is started. Starting the next plan clears deferred pause request.
Returns
-------
boolean
Indicates if deferred pause was requested, but not processed.
"""
return self._deferred_pause_requested
def __init__(self, md=None, *, loop=None, preprocessors=None,
context_managers=None, md_validator=None,
scan_id_source=default_scan_id_source,
during_task=None, call_returns_result=False):
if loop is None:
loop = get_bluesky_event_loop()
self._th = _ensure_event_loop_running(loop)
self._state_lock = threading.RLock()
self._loop = loop
if sys.version_info < (3, 8):
self._loop_for_kwargs = {'loop': self._loop}
else:
self._loop_for_kwargs = {}
# When set, RunEngine.__call__ should stop blocking.
self._blocking_event = threading.Event()
# When cleared, RunEngine._run will pause until set.
self._run_permit = None
setup_event = threading.Event()
def setup_run_permit():
self._run_permit = asyncio.Event(**self._loop_for_kwargs)
self._run_permit.set()
setup_event.set()
self.loop.call_soon_threadsafe(setup_run_permit)
setup_event.wait()
# Make a logger for this specific RE instance, using the instance's
# Python id, to keep from mixing output from separate instances.
self.log = ComposableLogAdapter(logger, {'RE': self})
if md is None:
md = {}
self.md = md
self.md.setdefault('versions', {})
try:
import ophyd
self.md['versions']['ophyd'] = ophyd.__version__
except ImportError:
self.log.debug("Failed to import ophyd.")
from ._version import get_versions
self.md['versions']['bluesky'] = get_versions()['version']
del get_versions
if preprocessors is None:
preprocessors = []
self.preprocessors = preprocessors
if context_managers is None:
context_managers = [SigintHandler]
self.context_managers = context_managers
if md_validator is None:
md_validator = _default_md_validator
self.md_validator = md_validator
self.scan_id_source = scan_id_source
self.max_depth = None
self.msg_hook = None
self.state_hook = None
self.waiting_hook = None
self.record_interruptions = False
self.pause_msg = PAUSE_MSG
self.NO_PLAN_RETURN = object()
if during_task is None:
during_task = DefaultDuringTask()
self._during_task = during_task
# The RunEngine keeps track of a *lot* of state.
# All flags and caches are defined here with a comment. Good luck.
self._call_returns_result = call_returns_result # should __call__ return UIDs or plan value
self._run_bundlers = {} # a mapping of open run -> bundlers
self._metadata_per_call = {} # for all runs generated by one __call__
self._deferred_pause_requested = False # pause at next 'checkpoint'
self._exception = None # stored and then raised in the _run loop
self._interrupted = False # True if paused, aborted, or failed
self._staged = set() # objects staged, not yet unstaged
self._objs_seen = set() # all objects seen
self._movable_objs_touched = set() # objects we moved at any point
self._run_start_uids = list() # run start uids generated by __call__
self._suspenders = set() # set holding suspenders
self._groups = defaultdict(set) # sets of Events to wait for
self._status_objs = defaultdict(set) # status objects to wait for
self._temp_callback_ids = set() # ids from CallbackRegistry
self._msg_cache = deque() # history of processed msgs for rewinding
self._rewindable_flag = True # if the RE is allowed to replay msgs
self._plan_stack = deque() # stack of generators to work off of
self._response_stack = deque() # resps to send into the plans
self._exit_status = 'success' # optimistic default
self._reason = '' # reason for abort
self._task = None # asyncio.Task associated with call to self._run
self._task_fut = None # future proxy to the task above
self._status_tasks = deque() # from self._status_object_completed
self._pardon_failures = None # will hold an asyncio.Event
self._plan = None # the plan instance from __call__
self._command_registry = {
'create': self._create,
'save': self._save,
'drop': self._drop,
'read': self._read,
'monitor': self._monitor,
'unmonitor': self._unmonitor,
'null': self._null,
'RE_class': self._RE_class,
'stop': self._stop,
'set': self._set,
'trigger': self._trigger,
'sleep': self._sleep,
'wait': self._wait,
'checkpoint': self._checkpoint,
'clear_checkpoint': self._clear_checkpoint,
'rewindable': self._rewindable,
'pause': self._pause,
'_resume_from_suspender': self._resume,
'_start_suspender': self._start_suspender,
'collect': self._collect,
'kickoff': self._kickoff,
'complete': self._complete,
'configure': self._configure,
'stage': self._stage,
'unstage': self._unstage,
'subscribe': self._subscribe,
'unsubscribe': self._unsubscribe,
'open_run': self._open_run,
'close_run': self._close_run,
'wait_for': self._wait_for,
'input': self._input,
'install_suspender': self._install_suspender,
'remove_suspender': self._remove_suspender, }
# public dispatcher for callbacks
# The Dispatcher's public methods are exposed through the
# RunEngine for user convenience.
self.dispatcher = Dispatcher()
self.ignore_callback_exceptions = False
# aliases for back-compatibility
self.subscribe_lossless = self.dispatcher.subscribe
self.unsubscribe_lossless = self.dispatcher.unsubscribe
self._subscribe_lossless = self.dispatcher.subscribe
self._unsubscribe_lossless = self.dispatcher.unsubscribe
@property
def commands(self):
'''
The list of commands available to Msg.
See Also
--------
:meth:`RunEngine.register_command`
:meth:`RunEngine.unregister_command`
:meth:`RunEngine.print_command_registry`
Examples
--------
>>> from bluesky import RunEngine
>>> RE = RunEngine()
>>> # to list commands
>>> RE.commands
'''
# return as a list, not lazy loader, no surprises...
return list(self._command_registry.keys())
def print_command_registry(self, verbose=False):
'''
This conveniently prints the command registry of available
commands.
Parameters
----------
Verbose : bool, optional
verbose print. Default is False
See Also
--------
:meth:`RunEngine.register_command`
:meth:`RunEngine.unregister_command`
:attr:`RunEngine.commands`
Examples
--------
>>> from bluesky import RunEngine
>>> RE = RunEngine()
>>> # Print a very verbose list of currently registered commands
>>> RE.print_command_registry(verbose=True)
'''
commands = "List of available commands\n"
for command, func in self._command_registry.items():
docstring = func.__doc__
if not verbose:
docstring = docstring.split("\n")[0]
commands = commands + "{} : {}\n".format(command, docstring)
return commands
def subscribe(self, func, name='all'):
"""
Register a callback function to consume documents.
.. versionchanged :: 0.10.0
The order of the arguments was swapped and the ``name``
argument has been given a default value, ``'all'``. Because the
meaning of the arguments is unambiguous (they must be a callable
and a string, respectively) the old order will be supported
indefinitely, with a warning.
Parameters
----------
func: callable
expecting signature like ``f(name, document)``
where name is a string and document is a dict
name : {'all', 'start', 'descriptor', 'event', 'stop'}, optional
the type of document this function should receive ('all' by
default)
Returns
-------
token : int
an integer ID that can be used to unsubscribe
See Also
--------
:meth:`RunEngine.unsubscribe`
"""
# pass through to the Dispatcher, spelled out verbosely here to make
# sphinx happy -- tricks with __doc__ aren't enough to fool it
return self.dispatcher.subscribe(func, name)
def unsubscribe(self, token):
"""
Unregister a callback function its integer ID.
Parameters
----------
token : int
the integer ID issued by :meth:`RunEngine.subscribe`
See Also
--------
:meth:`RunEngine.subscribe`
"""
# pass through to the Dispatcher, spelled out verbosely here to make
# sphinx happy -- tricks with __doc__ aren't enough to fool it
return self.dispatcher.unsubscribe(token)
@property
def rewindable(self):
return self._rewindable_flag
@rewindable.setter
def rewindable(self, v):
cur_state = self._rewindable_flag
self._rewindable_flag = bool(v)
if self.resumable and self._rewindable_flag != cur_state:
self._reset_checkpoint_state()
@property
def loop(self):
return self._loop
@property
def suspenders(self):
return tuple(self._suspenders)
@property
def verbose(self):
return not self.log.disabled
@verbose.setter
def verbose(self, value):
self.log.disabled = not value
@property
def call_returns_result(self):
return self._call_returns_result
def _clear_run_cache(self):
"Clean up for a new run."
self._groups.clear()
self._status_objs.clear()
self._interruptions_desc_uid = None
self._interruptions_counter = count(1)
@_state_locked
def _clear_call_cache(self):
"Clean up for a new __call__ (which may encompass multiple runs)."
self._metadata_per_call.clear()
self._staged.clear()
self._objs_seen.clear()
self._movable_objs_touched.clear()
self._deferred_pause_requested = False
self._plan_stack = deque()
self._msg_cache = deque()
self._response_stack = deque()
self._exception = None
self._run_start_uids.clear()
self._exit_status = 'success'
self._reason = ''
self._task = None
self._task_fut = None
self._status_tasks.clear()
self._pardon_failures = asyncio.Event(**self._loop_for_kwargs)
self._plan = None
self._interrupted = False
# Unsubscribe for per-run callbacks.
for cid in self._temp_callback_ids:
self.unsubscribe(cid)
self._temp_callback_ids.clear()
def reset(self):
"""
Clean up caches and unsubscribe subscriptions.
Lossless subscriptions are not unsubscribed.
"""
if self._state != 'idle':
self.halt()
self._clear_run_cache()
self._clear_call_cache()
self.dispatcher.unsubscribe_all()
@property
def resumable(self):
"i.e., can the plan in progress by rewound"
return self._msg_cache is not None
@property
def ignore_callback_exceptions(self):
return self.dispatcher.ignore_exceptions
@ignore_callback_exceptions.setter
def ignore_callback_exceptions(self, val):
self.dispatcher.ignore_exceptions = val
def register_command(self, name, func):
"""
Register a new Message command.
Parameters
----------
name : str
func : callable
This can be a function or a method. The signature is `f(msg)`.
See Also
--------
:meth:`RunEngine.unregister_command`
:meth:`RunEngine.print_command_registry`
:attr:`RunEngine.commands`
"""
self._command_registry[name] = func
def unregister_command(self, name):
"""
Unregister a Message command.
Parameters
----------
name : str
See Also
--------
:meth:`RunEngine.register_command`
:meth:`RunEngine.print_command_registry`
:attr:`RunEngine.commands`
"""
del self._command_registry[name]
def request_pause(self, defer=False):
"""
Command the Run Engine to pause.
This function is called by 'pause' Messages. It can also be called
by other threads. It cannot be called on the main thread during a run,
but it is called by SIGINT (i.e., Ctrl+C).
If there current run has no checkpoint (via the 'clear_checkpoint'
message), this will cause the run to abort.
Parameters
----------
defer : bool, optional
If False, pause immediately before processing any new messages.
If True, pause at the next checkpoint.
False by default.
"""
future = asyncio.run_coroutine_threadsafe(
self._request_pause_coro(defer),
loop=self.loop)
# TODO add a timeout here?
return future.result()
async def _request_pause_coro(self, defer=False):
# We are pausing. Cancel any deferred pause previously requested.
if not self.state.can_pause:
raise TransitionError(
f"Run Engine is in '{self.state}' state and can not be paused."
)
if defer:
self._deferred_pause_requested = True
print("Deferred pause acknowledged. Continuing to checkpoint.")
return
print("Pausing...")
self._deferred_pause_requested = False
self._interrupted = True
self._state = 'pausing'
for current_run in self._run_bundlers.values():
current_run.record_interruption('pause')
self._task.cancel()
def _create_result(self, plan_return):
"""
Create a RunEngineResult to return from __call__, using
plan_return and internal state
"""
rs = RunEngineResult(tuple(self._run_start_uids),
plan_return,
self._exit_status,
self._interrupted,
self._reason,
self._exception)
return rs
def __call__(self, *args, **metadata_kw):
"""Execute a plan.
Any keyword arguments will be interpreted as metadata and recorded with
any run(s) created by executing the plan. Notice that the plan
(required) and extra subscriptions (optional) must be given as
positional arguments.
Parameters
----------
plan : generator (positional only)
a generator or that yields ``Msg`` objects (or an iterable that
returns such a generator)
subs : callable, list, or dict, optional (positional only)
Temporary subscriptions (a.k.a. callbacks) to be used on this run.
For convenience, any of the following are accepted:
* a callable, which will be subscribed to 'all'
* a list of callables, which again will be subscribed to 'all'
* a dictionary, mapping specific subscriptions to callables or
lists of callables; valid keys are {'all', 'start', 'stop',
'event', 'descriptor'}
Returns
-------
uids : tuple
list of uids (i.e. RunStart Document uids) of run(s)
if :attr:`RunEngine._call_returns_result` is ``False``
result : :class:`RunEngineResult`
if :attr:`RunEngine._call_returns_result` is ``True``
"""
if self.state == 'panicked':
raise RuntimeError("The RunEngine is panicked and "
"cannot be recovered. "
"You must restart bluesky.")
# This scheme lets us make 'plan' and 'subs' POSITIONAL ONLY, reserving
# all keyword arguments for user metdata.
arguments = _call_sig.bind(self, *args, **metadata_kw).arguments
plan = arguments['plan']
subs = arguments.get('subs', None)
metadata_kw = arguments.get('metadata_kw', {})
if 'raise_if_interrupted' in metadata_kw:
warn("The 'raise_if_interrupted' flag has been removed. The "
"RunEngine now always raises RunEngineInterrupted if it is "
"interrupted. The 'raise_if_interrupted' keyword argument, "
"like all keyword arguments, will be interpreted as "
"metadata.")
# Check that the RE is not being called from inside a function.
if self.max_depth is not None:
frame = inspect.currentframe()
depth = len(inspect.getouterframes(frame))
if depth > self.max_depth:
text = MAX_DEPTH_EXCEEDED_ERR_MSG.format(self.max_depth, depth)
raise RuntimeError(text)
# If we are in the wrong state, raise.
if not self._state.is_idle:
raise RuntimeError("The RunEngine is in a %s state" % self._state)
futs = []
tripped_justifications = []
for sup in self.suspenders:
f_lst, justification = sup.get_futures()
if f_lst:
futs.extend(f_lst)
tripped_justifications.append(justification)
if tripped_justifications:
print("At least one suspender has tripped. The plan will begin "
"when all suspenders are ready. Justification:")
for i, justification in enumerate(tripped_justifications):
print(' {}. {}'.format(i + 1, justification))
print()
print("Suspending... To get to the prompt, "
"hit Ctrl-C twice to pause.")
self._clear_call_cache()
self._clear_run_cache() # paranoia, in case of previous bad exit
for name, funcs in normalize_subs_input(subs).items():
for func in funcs:
self._temp_callback_ids.add(self.subscribe(func, name))
self._plan = plan # this ref is just used for metadata introspection
self._metadata_per_call.update(metadata_kw)
gen = ensure_generator(plan)
for wrapper_func in self.preprocessors:
gen = wrapper_func(gen)
self._plan_stack.append(gen)
self._response_stack.append(None)
if futs:
self._plan_stack.append(single_gen(Msg('wait_for', None, futs)))
self._response_stack.append(None)
self.log.info("Executing plan %r", self._plan)
def _build_task():
# make sure _run will block at the top
self._run_permit.clear()
self._blocking_event.clear()
self._task_fut = asyncio.run_coroutine_threadsafe(self._run(),
loop=self.loop)
def set_blocking_event(future):
self._blocking_event.set()
self._task_fut.add_done_callback(set_blocking_event)
plan_return = self._resume_task(init_func=_build_task)
if self._interrupted:
raise RunEngineInterrupted(self.pause_msg) from None
if self._call_returns_result:
run_engine_result = self._create_result(plan_return)
return run_engine_result
else:
return tuple(self._run_start_uids)
__call__.__signature__ = _call_sig
def resume(self):
"""Resume a paused plan from the last checkpoint.
Returns
-------
uids : list
list of uids (i.e. RunStart Document uids) of run(s)
if :attr:`RunEngine._call_returns_result` is ``False``
result : :class:`RunEngineResult`
if :attr:`RunEngine._call_returns_result` is ``True``
"""
if self.state == 'panicked':
raise RuntimeError("The RunEngine is panicked and "
"cannot be recovered. "
"You must restart bluesky.")
# The state machine does not capture the whole picture.
if not self._state.is_paused:
raise TransitionError("The RunEngine is the {0} state. "
"You can only resume for the paused state."
"".format(self._state))
self._interrupted = False
for current_run in self._run_bundlers.values():
current_run.record_interruption('resume')
new_plan = self._rewind()
self._plan_stack.append(new_plan)
self._response_stack.append(None)
# Notify Devices of the resume in case they want to clean up.
for obj in self._objs_seen:
if hasattr(obj, 'resume'):
obj.resume()
plan_return = self._resume_task()
if self._interrupted:
raise RunEngineInterrupted(self.pause_msg) from None
if self._call_returns_result:
run_engine_result = self._create_result(plan_return)
return run_engine_result
else:
return tuple(self._run_start_uids)
def _rewind(self):
'''Clean up in preparation for resuming from a pause or suspension.
Returns
-------
new_plan : generator
A new plan made from the messages in the message cache
'''
len_msg_cache = len(self._msg_cache)
new_plan = ensure_generator(list(self._msg_cache))
self._msg_cache = deque()
if len_msg_cache:
for current_run in self._run_bundlers.values():
current_run.rewind()
return new_plan
def _resume_task(self, *, init_func=None):
# Clear the blocking Event so that we can wait on it below.
# The task will set it when it is done, as it was previously
# configured to do it __call__.
self._blocking_event.clear()
# Handle all context managers
with ExitStack() as stack:
for mgr in self.context_managers:
stack.enter_context(mgr(self))
if init_func is not None:
init_func()
if self._task_fut is None or self._task_fut.done():
try:
return self._task_fut.result()
except concurrent.futures.CancelledError:
return self.NO_PLAN_RETURN
# The _run task is waiting on this Event. Let is continue.
self.loop.call_soon_threadsafe(self._run_permit.set)
try:
# Block until plan is complete or exception is raised.
try:
self._during_task.block(self._blocking_event)
except KeyboardInterrupt:
import ctypes
self._interrupted = True
# we can not interrupt a python thread from the outside
# but there is an API to schedule an exception to be raised
# the next time that thread would interpret byte code.
# The documentation of this function includes the sentence
#
# To prevent naive misuse, you must write your
# own C extension to call this.