Debian Codegraph @

cylc/flow/xtrigger_mgr.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 from contextlib import suppress
18 from enum import Enum
19 from inspect import signature
20 import json
21 import re
22 from copy import deepcopy
23 from time import time
24 from typing import (
25 Any,
26 Dict,
27 Optional,
28 Set,
29 Tuple,
30 List,
31 TYPE_CHECKING
32 )
33
34 from cylc.flow import LOG
35 from cylc.flow.exceptions import WorkflowConfigError, XtriggerConfigError
36 import cylc.flow.flags
37 from cylc.flow.hostuserutil import get_user
38 from cylc.flow.subprocctx import add_kwarg_to_sig
39 from cylc.flow.subprocpool import get_xtrig_func
40 from cylc.flow.xtriggers.wall_clock import _wall_clock
41 from cylc.flow.xtriggers.workflow_state import (
42 workflow_state,
43 _workflow_state_backcompat,
44 _upgrade_workflow_state_sig,
45 )
46
47 if TYPE_CHECKING:
48 from inspect import BoundArguments, Signature
49 from cylc.flow.scheduler import Scheduler
50 from cylc.flow.subprocctx import SubFuncContext
51 from cylc.flow.task_proxy import TaskProxy
52
53
54 class TemplateVariables(Enum):
55 """Templates variables for string replacement in xtrigger functions.
56
57 The following string templates are available for use, if the trigger
58 function needs any of this information, in function arguments in the
59 workflow configuration.
60
61 .. code-block:: cylc
62
63 [scheduling]
64 initial cycle point = now
65 [[xtriggers]]
66 my_xtrigger = my_xtrigger_fcn('%(workflow)s', '%(point)s')
67
68 For an explanation of the substitution syntax, see
69 `String Formatting Operations in the Python documentation
70 <https://docs.python.org/3/library/stdtypes.html
71 #printf-style-string-formatting>`_.
72
73 """
74
75 CyclePoint = 'point'
76 """The cycle point of the dependent task."""
77
78 DebugMode = 'debug'
79 """True if Cylc is being run in debug mode (--debug, -vv)."""
80
81 RunDir = 'workflow_run_dir'
82 """The path to the workflow run directory."""
83
84 ShareDir = 'workflow_share_dir'
85 """The path to the workflow share directory."""
86
87 TaskID = 'id'
88 """The ID of the dependent task."""
89
90 TaskName = 'name'
91 """The name of the dependent task."""
92
93 UserName = 'user_name'
94 """The user account under which the workflow is being run."""
95
96 Workflow = 'workflow'
97 """The workflow ID."""
98
99 # BACK COMPAT: workflow_name deprecated
100 # url:
101 # TODO
102 # from:
103 # Cylc 8
104 # remove at:
105 # Cylc 8.x
106 WorkflowName = 'workflow_name'
107 """The workflow ID.
108
109 .. deprecated:: 8.0.0
110
111 Use ``workflow`` instead.
112 """
113
114 # BACK COMPAT: suite_name deprecated
115 # url:
116 # TODO
117 # from:
118 # Cylc 8
119 # remove at:
120 # Cylc 8.x
121 SuiteName = 'suite_name'
122 """The workflow ID.
123
124 .. deprecated:: 8.0.0
125
126 Use ``workflow`` instead.
127 """
128
129 # BACK COMPAT: suite_run_dir deprecated
130 # url:
131 # TODO
132 # from:
133 # Cylc 8
134 # remove at:
135 # Cylc 8.x
136 SuiteRunDir = 'suite_run_dir'
137 """The path to the workflow run directory.
138
139 .. deprecated:: 8.0.0
140
141 Use ``workflow_run_dir`` instead.
142 """
143
144 # BACK COMPAT: suite_share_dir deprecated
145 # url:
146 # TODO
147 # from:
148 # Cylc 8
149 # remove at:
150 # Cylc 8.x
151 SuiteShareDir = 'suite_share_dir'
152 """The path to the workflow share directory.
153
154 .. deprecated:: 8.0.0
155
156 Use ``workflow_share_dir`` instead.
157 """
158
159
160 # Extract 'foo' from string templates '%(foo)s', avoiding '%%' escaping
161 # ('%%(foo)s` is not a string template).
162 RE_STR_TMPL = re.compile(r'(?<!%)%\(([\w]+)\)s')
163
164
165 class XtriggerCollator:
166 """Collate and validate parsed xtriggers.
167
168 Separate from XtriggerManager to simplify validation and testing.
169
170 """
171
172 def __init__(self):
173 # Map xtrig label to function context.
174 self.functx_map: 'Dict[str, SubFuncContext]' = {}
175 # Clock labels, to avoid repeated string comparisons
176 self.wall_clock_labels: Set[str] = set()
177 # Workflow-wide default, used when not specified in xtrigger kwargs.
178 self.sequential_xtriggers_default = False
179 # Labels whose xtriggers are sequentially checked.
180 self.sequential_xtrigger_labels: Set[str] = set()
181
182 def update(self, xtriggers: 'XtriggerCollator'):
183 self.functx_map.update(xtriggers.functx_map)
184 self.wall_clock_labels.update(xtriggers.wall_clock_labels)
185 self.sequential_xtrigger_labels.update(
186 xtriggers.sequential_xtrigger_labels)
187
188 def purge_user_xtriggers(self):
189 """Purge user-defined triggers before a reload.
190
191 User-defined triggers need to be recreated from the config file.
192 Auto-defined triggers (retries) need to be kept.
193
194 """
195 nuke = []
196 for label in self.functx_map:
197 if (
198 label.startswith("_cylc_wallclock")
199 or not label.startswith("_cylc")
200 ):
201 # _cylc_wallclock xtriggers are user-defined
202 # otherwise all _cylc xtriggers are automatic.
203 nuke.append(label)
204 for label in nuke:
205 del self.functx_map[label]
206 with suppress(KeyError):
207 self.wall_clock_labels.remove(label)
208 with suppress(KeyError):
209 self.sequential_xtrigger_labels.remove(label)
210
211 def add_trig(self, label: str, fctx: 'SubFuncContext', fdir: str) -> None:
212 """Add a new xtrigger function.
213
214 Args:
215 label: xtrigger label
216 fctx: function context
217 fdir: module directory
218
219 """
220 if (
221 not label.startswith('_cylc_retry_') and
222 not label.startswith('_cylc_submit_retry_')
223 ):
224 # (the "_wall_clock" function fails "wall_clock" validation)
225 self._validate(label, fctx, fdir)
226
227 self.functx_map[label] = fctx
228
229 if fctx.func_kwargs.pop(
230 'sequential',
231 self.sequential_xtriggers_default
232 ):
233 self.sequential_xtrigger_labels.add(label)
234
235 if fctx.func_name == "wall_clock":
236 self.wall_clock_labels.add(label)
237
238 @classmethod
239 def _validate(
240 cls,
241 label: str,
242 fctx: 'SubFuncContext',
243 fdir: str,
244 ) -> None:
245 """Check xtrigger existence, string templates and function signature.
246
247 Also call a specific xtrigger argument validation function, "validate",
248 if defined in the xtrigger module.
249
250 Args:
251 label: xtrigger label
252 fctx: function context
253 fdir: function directory
254
255 Raises:
256 XtriggerConfigError:
257 * If the function module was not found.
258 * If the function was not found in the xtrigger module.
259 * If the function is not callable.
260 * If any string template in the function context
261 arguments are not present in the expected template values.
262 * If the arguments do not match the function signature.
263
264 """
265 sig_str = fctx.get_signature()
266
267 try:
268 func = get_xtrig_func(fctx.mod_name, fctx.func_name, fdir)
269 except (ImportError, AttributeError) as exc:
270 raise XtriggerConfigError(label, sig_str, exc) from None
271 try:
272 sig = signature(func)
273 except TypeError as exc:
274 # not callable
275 raise XtriggerConfigError(label, sig_str, exc) from None
276
277 sig = cls._handle_sequential_kwarg(label, fctx, sig)
278
279 # Validate args and kwargs against the function signature
280 try:
281 bound_args = sig.bind(*fctx.func_args, **fctx.func_kwargs)
282 except TypeError as exc:
283 err = XtriggerConfigError(label, sig_str, exc)
284 if func is workflow_state:
285 bound_args = cls._try_workflow_state_backcompat(
286 label, fctx, err
287 )
288 else:
289 raise err from None
290
291 # Specific xtrigger.validate(), if available.
292 # Note arg string templating has not been done at this point.
293 cls._try_xtrig_validate_func(
294 label, fctx, fdir, bound_args, sig_str
295 )
296
297 # Check any string templates in the function arg values (note this
298 # won't catch bad task-specific values - which are added dynamically).
299 template_vars = set()
300 for argv in fctx.func_args + list(fctx.func_kwargs.values()):
301 if not isinstance(argv, str):
302 # Not a string arg.
303 continue
304
305 # check template variables are valid
306 for match in RE_STR_TMPL.findall(argv):
307 try:
308 template_vars.add(TemplateVariables(match))
309 except ValueError:
310 raise XtriggerConfigError(
311 label, sig_str,
312 f"Illegal template in xtrigger: {match}",
313 ) from None
314
315 # check for deprecated template variables
316 deprecated_variables = template_vars & {
317 TemplateVariables.WorkflowName,
318 TemplateVariables.SuiteName,
319 TemplateVariables.SuiteRunDir,
320 TemplateVariables.SuiteShareDir,
321 }
322 if deprecated_variables:
323 LOG.warning(
324 f'Xtrigger "{label}" uses deprecated template variables:'
325 f' {", ".join(t.value for t in deprecated_variables)}'
326 )
327
328 @staticmethod
329 def _handle_sequential_kwarg(
330 label: str, fctx: 'SubFuncContext', sig: 'Signature'
331 ) -> 'Signature':
332 """Handle reserved 'sequential' kwarg in xtrigger functions."""
333 sequential_param = sig.parameters.get('sequential', None)
334 if sequential_param:
335 if not isinstance(sequential_param.default, bool):
336 raise XtriggerConfigError(
337 label, fctx.func_name,
338 (
339 "xtrigger has a reserved argument"
340 " 'sequential' with no boolean default"
341 )
342 )
343 fctx.func_kwargs.setdefault('sequential', sequential_param.default)
344
345 if 'sequential' in fctx.func_kwargs:
346 # xtrig marked as sequential in function call
347 value = fctx.func_kwargs['sequential']
348 if not isinstance(value, bool):
349 raise XtriggerConfigError(
350 label, fctx.func_name,
351 f"invalid argument 'sequential={value}' - must be boolean"
352 )
353 if not sequential_param:
354 sig = add_kwarg_to_sig(sig, 'sequential', value)
355 return sig
356
357 @staticmethod
358 def _try_xtrig_validate_func(
359 label: str,
360 fctx: 'SubFuncContext',
361 fdir: str,
362 bound_args: 'BoundArguments',
363 signature_str: str,
364 ):
365 """Call an xtrigger's `validate()` function if it is implemented.
366
367 Raise XtriggerConfigError if validation fails.
368
369 """
370 vname = "validate"
371 if fctx.func_name == _workflow_state_backcompat.__name__:
372 vname = "_validate_backcompat"
373
374 try:
375 xtrig_validate_func = get_xtrig_func(fctx.mod_name, vname, fdir)
376 except (AttributeError, ImportError):
377 return
378 bound_args.apply_defaults()
379 try:
380 xtrig_validate_func(bound_args.arguments)
381 except Exception as exc: # Note: catch all errors
382 if not isinstance(exc, WorkflowConfigError):
383 LOG.exception(exc)
384 raise XtriggerConfigError(label, signature_str, exc) from None
385
386 # BACK COMPAT: workflow_state_backcompat
387 # from: 8.0.0
388 # to: 8.3.0
389 # remove at: 8.x
390 @classmethod
391 def _try_workflow_state_backcompat(
392 cls,
393 label: str,
394 fctx: 'SubFuncContext',
395 err: XtriggerConfigError,
396 ) -> 'BoundArguments':
397 """Try to validate args against the old workflow_state signature.
398
399 Raise the original signature check error if this signature check fails.
400
401 Returns the bound arguments for the old signature.
402 """
403 sig = cls._handle_sequential_kwarg(
404 label, fctx, signature(_workflow_state_backcompat)
405 )
406 try:
407 bound_args = sig.bind(*fctx.func_args, **fctx.func_kwargs)
408 except TypeError:
409 # failed signature check for backcompat function
410 raise err from None # original signature check error
411
412 old_sig_str = fctx.get_signature()
413 upg_sig_str = "workflow_state({})".format(
414 ", ".join(
415 f'{k}={v}' for k, v in
416 _upgrade_workflow_state_sig(bound_args.arguments).items()
417 if v is not None
418 )
419 )
420 LOG.warning(
421 "(8.3.0) Deprecated function signature used for "
422 "workflow_state xtrigger was automatically upgraded. Please "
423 "alter your workflow to use the new syntax:\n"
424 f" {old_sig_str} --> {upg_sig_str}"
425 )
426 fctx.func_name = _workflow_state_backcompat.__name__
427 return bound_args
428
429
430 class XtriggerManager:
431 """Manage clock triggers and xtrigger functions.
432
433 # Example:
434 [scheduling]
435 [[xtriggers]]
436 clock_0 = wall_clock() # offset PT0H
437 clock_1 = wall_clock(offset=PT1H)
438 # or wall_clock(PT1H)
439 workflow_x = workflow_state(
440 workflow_task_id=other, point=%(task_cycle_point)s):PT30S
441 [[graph]]
442 PT1H = '''
443 @clock_1 & @workflow_x => foo & bar
444 @wall_clock = baz # pre-defined zero-offset clock
445 '''
446
447 Task proxies store xtriggers labels: clock_0, workflow_x, etc. above, and
448 record whether or not their dependence on xtriggers is satisfied.
449
450 Labels are mapped to the defined function call signatures.
451
452 The interval ("name(args):INTVL") determines call frequency.
453
454 This XtriggerManager class handles all xtrigger execution logic centrally,
455 to avoid duplication when multiple tasks depend on the same xtrigger.
456
457 Uniqueness is determined by function signature (name and arguments). So
458 workflow_x above defines a different xtrigger for each cycle point. A new
459 call will not be made before the previous one has returned.
460
461 Xtrigger functions are called asynchronously in the subprocess pool,
462 except for clock triggers, called synchronously because they're quick.
463
464 If parentless tasks have xtriggers that are fundamentally sequential in
465 nature, spawning them out to the runahead limit can result in unnecessary
466 xtrigger activity and UI clutter, so clock-triggered tasks get spawned
467 sequentially (as each xtrigger completes) by default, and other xtriggers
468 can optionally be configured to spawn sequentially.
469
470 # Example:
471 [scheduling]
472 sequential xtriggers = True
473 [[xtriggers]]
474 # "sequential=False" here overrides workflow and function default.
475 clock_0 = wall_clock(sequential=False)
476 workflow_x = workflow_state(
477 workflow_task_id=other, point=%(task_cycle_point)s):PT30S
478 [[graph]]
479 PT1H = '''
480 @workflow_x => foo & bar # spawned on workflow_x satisfaction
481 @clock_0 => baz # baz spawned out to RH
482 '''
483
484 Args:
485 schd: Scheduler
486 workflow_run_dir: workflow run directory
487 workflow_share_dir: workflow share directory
488
489 """
490
491 def __init__(
492 self,
493 schd: 'Scheduler',
494 workflow_run_dir: Optional[str] = None,
495 workflow_share_dir: Optional[str] = None,
496 ):
497 self.schd = schd
498 workflow = schd.workflow
499 user = schd.owner
500 # When next to call a function, by signature.
501 self.t_next_call: dict = {}
502 # Succeeded triggers and their function results, by signature.
503 self.sat_xtrig: dict = {}
504 # Signatures of active functions (waiting on callback).
505 self.active: list = []
506
507 self.workflow_run_dir = workflow_run_dir
508
509 # For function arg templating.
510 if not user:
511 user = get_user()
512 self.farg_templ: Dict[str, Any] = {
513 TemplateVariables.Workflow.value: workflow,
514 TemplateVariables.UserName.value: user,
515 TemplateVariables.RunDir.value: workflow_run_dir,
516 TemplateVariables.ShareDir.value: workflow_share_dir,
517 TemplateVariables.DebugMode.value: cylc.flow.flags.verbosity > 1,
518 # deprecated
519 TemplateVariables.WorkflowName.value: workflow,
520 TemplateVariables.SuiteName.value: workflow,
521 TemplateVariables.SuiteRunDir.value: workflow,
522 TemplateVariables.SuiteShareDir.value: workflow,
523 }
524
525 self.proc_pool = schd.proc_pool
526 self.workflow_db_mgr = schd.workflow_db_mgr
527 self.broadcast_mgr = schd.broadcast_mgr
528 self.data_store_mgr = schd.data_store_mgr
529 self.do_housekeeping = False
530 self.xtriggers = XtriggerCollator()
531
532 def add_xtriggers(self, xtriggers: 'XtriggerCollator', reload=False):
533 """Add validated xtriggers, parsed from the workflow config."""
534 if reload:
535 self.xtriggers.purge_user_xtriggers()
536 self.xtriggers.update(xtriggers)
537 self.xtriggers.sequential_xtriggers_default = (
538 xtriggers.sequential_xtriggers_default
539 )
540
541 def mutate_trig(self, label, kwargs):
542 self.xtriggers.functx_map[label].func_kwargs.update(kwargs)
543
544 def load_xtrigger_for_restart(self, row_idx: int, row: Tuple[str, str]):
545 """Load succeeded xtrigger results from workflow DB.
546
547 Note this is succeeded xtriggers, not task xtrigger prerequisites
548 (which can be manually satisfied independently of the xtrigger).
549
550 Args:
551 row_idx (int): row index (used for logging)
552 row (Tuple[str, str]): tuple with the signature and results (json)
553 Raises:
554 ValueError: if the row cannot be parsed as JSON
555 """
556 if row_idx == 0:
557 LOG.info("LOADING succeeded xtriggers")
558 sig, results = row
559 self.sat_xtrig[sig] = json.loads(results)
560 # Tell the datastore this xtrigger succeeded.
561 self.data_store_mgr.delta_xtrigger(sig, True)
562
563 def _get_xtrigs(
564 self, itask: 'TaskProxy', unsat_only: bool = False,
565 sigs_only: bool = False
566 ) -> 'List[Any]':
567 """(Internal helper method.)
568
569 Args:
570 itask: the task instance
571 unsat_only: retrieve only unsatisfied xtrigger prerequisites
572 sigs_only: append only the xtrigger function signature
573
574 Returns:
575 List[Union[str, Tuple[str, str, SubFuncContext, bool]]]: a list
576 with either signature (if sigs_only True) or with tuples of
577 label, signature, function context, and flag for satisfied.
578 """
579 res: 'List[Any]' = []
580 for label, satisfied in itask.state.xtriggers.items():
581 if unsat_only and satisfied:
582 continue
583 ctx = self.get_xtrig_ctx(itask, label)
584 sig = ctx.get_signature()
585 if sigs_only:
586 res.append(sig)
587 else:
588 res.append((label, sig, ctx, satisfied))
589 return res
590
591 def get_xtrig_ctx(
592 self,
593 itask: 'TaskProxy',
594 label: str,
595 ) -> 'SubFuncContext':
596 """Get a real function context from the template.
597
598 Args:
599 itask: task proxy
600 label: xtrigger label
601 Returns:
602 function context
603 """
604 farg_templ = {
605 TemplateVariables.CyclePoint.value: str(itask.point),
606 TemplateVariables.TaskName.value: str(itask.tdef.name),
607 TemplateVariables.TaskID.value: str(itask.identity)
608 }
609 farg_templ.update(self.farg_templ)
610 ctx = deepcopy(self.xtriggers.functx_map[label])
611
612 args = []
613 kwargs = {}
614 if label in self.xtriggers.wall_clock_labels:
615 if "trigger_time" in ctx.func_kwargs: # noqa: SIM401 (readabilty)
616 # Internal (retry timer): trigger_time already set.
617 kwargs["trigger_time"] = ctx.func_kwargs["trigger_time"]
618 else:
619 # External (clock xtrigger): convert offset to trigger_time.
620 # Datetime cycling only.
621 kwargs["trigger_time"] = itask.get_clock_trigger_time(
622 itask.point,
623 ctx.func_kwargs.get(
624 "offset",
625 ctx.func_args[0] if ctx.func_args else None
626 )
627 )
628 else:
629 # Other xtrig functions: substitute template values.
630 for val in ctx.func_args:
631 with suppress(TypeError):
632 val = val % farg_templ
633 args.append(val)
634 for key, val in ctx.func_kwargs.items():
635 with suppress(TypeError):
636 val = val % farg_templ
637 kwargs[key] = val
638 ctx.func_args = args
639 ctx.func_kwargs = kwargs
640
641 ctx.update_command(self.workflow_run_dir)
642 return ctx
643
644 def call_xtriggers_async(self, itask: 'TaskProxy'):
645 """Call itask's xtrigger functions via the process pool...
646
647 ...if previous call not still in-process and retry period is up.
648
649 Args:
650 itask: task proxy to check.
651 """
652 for label, sig, ctx, _ in self._get_xtrigs(itask, unsat_only=True):
653 if label in self.xtriggers.wall_clock_labels:
654 # Special case: quick synchronous clock check.
655 if sig in self.sat_xtrig:
656 # Already satisfied, just update the task
657 itask.state.xtriggers[label] = True
658 elif _wall_clock(*ctx.func_args, **ctx.func_kwargs):
659 # Newly satisfied
660 itask.state.xtriggers[label] = True
661 self.sat_xtrig[sig] = {}
662 self.data_store_mgr.delta_xtrigger(sig, True)
663 self.workflow_db_mgr.put_xtriggers({sig: {}})
664 LOG.info('xtrigger succeeded: %s = %s', label, sig)
665 self.do_housekeeping = True
666 continue
667 # General case: potentially slow asynchronous function call.
668 if sig in self.sat_xtrig:
669 # Already satisfied, just update the task
670 LOG.info(f"[{itask}] satisfying xtrigger prerequisite: {sig}")
671 if not itask.state.xtriggers[label]:
672 itask.state.xtriggers[label] = True
673 res = {}
674 for key, val in self.sat_xtrig[sig].items():
675 res["%s_%s" % (label, key)] = val
676 if res:
677 xtrigger_env = [{'environment': {key: str(val)}} for
678 key, val in res.items()]
679 self.broadcast_mgr.put_broadcast(
680 [str(itask.point)],
681 [itask.tdef.name],
682 xtrigger_env
683 )
684 continue
685
686 # Call the function to check the xtrigger.
687 if sig in self.active:
688 # Already waiting on this result.
689 continue
690
691 if sig not in self.t_next_call:
692 # Log at first call only.
693 LOG.info(f"Commencing xtrigger, {ctx.get_description(True)}")
694
695 now = time()
696 if sig in self.t_next_call and now < self.t_next_call[sig]:
697 # Too soon to call this one again.
698 continue
699 self.t_next_call[sig] = now + ctx.intvl
700 # Queue to the process pool, and record as active.
701 self.active.append(sig)
702 self.proc_pool.put_command(ctx, callback=self.callback)
703
704 def housekeep(self, itasks):
705 """Forget succeeded xtriggers no longer needed by any task.
706
707 Check self.do_housekeeping before calling this method.
708
709 Args:
710 itasks: list of all task proxies.
711 """
712 all_xtrig = []
713 for itask in itasks:
714 all_xtrig += self._get_xtrigs(
715 itask, sigs_only=True, unsat_only=True)
716 for sig in list(self.sat_xtrig):
717 if sig not in all_xtrig:
718 LOG.debug(f"Housekeeping xtrigger result: {sig}")
719 del self.sat_xtrig[sig]
720 with suppress(KeyError):
721 del self.t_next_call[sig]
722 self.do_housekeeping = False
723
724 def all_task_seq_xtriggers_satisfied(self, itask: 'TaskProxy') -> bool:
725 """Check if all sequential xtriggers are satisfied for a task."""
726 return itask.is_xtrigger_sequential and all(
727 itask.state.xtriggers[label]
728 for label in itask.state.xtriggers
729 if label in self.xtriggers.sequential_xtrigger_labels
730 )
731
732 def callback(self, ctx: 'SubFuncContext'):
733 """Callback for asynchronous xtrigger functions.
734
735 Record completion status (succeeded) and function results dict.
736
737 Log a warning if the xtrigger functions errors, to distinguish
738 errors from not-succeeded.
739
740 Args:
741 ctx (SubFuncContext): function context
742 """
743 sig = ctx.get_signature()
744 self.active.remove(sig)
745
746 if ctx.ret_code != 0:
747 msg = f"ERROR in xtrigger {sig}"
748 if ctx.err:
749 msg += f"\n{ctx.err}"
750 LOG.warning(msg)
751
752 try:
753 succeeded, results = json.loads(ctx.out)
754 except (ValueError, TypeError):
755 return
756
757 LOG.debug('%s: returned %s', sig, results)
758 if not succeeded:
759 return
760
761 self.data_store_mgr.delta_xtrigger(sig, succeeded)
762 self.workflow_db_mgr.put_xtriggers({sig: results})
763 LOG.info(f"xtrigger succeeded: {ctx.get_description()}")
764 self.sat_xtrig[sig] = results
765
766 self.do_housekeeping = True
767
768 def force_satisfy(
769 self,
770 itask: 'TaskProxy',
771 xtriggers: 'Dict[str, bool]',
772 log: bool = True,
773 ) -> None:
774 """Force un/satisfy one or all xtrigger prerequisites of itask.
775
776 Ignores xtriggers not valid for itask.
777 (However, these are now weeded out by the caller).
778
779 Args:
780 itask: task proxy
781 xtriggers: xtrigger prerequisites to un/satisfy
782 log: if True outcome will be logged
783
784 """
785 # [(label, satisfied), ]
786 xtrigs = list(xtriggers.items())
787
788 if len(xtrigs) == 1 and xtrigs[0][0] == 'all':
789 xtrigs = [(x, xtrigs[0][1]) for x in itask.state.xtriggers]
790
791 for label, satisfied in xtrigs:
792 if label not in itask.state.xtriggers:
793 continue
794
795 if label not in self.xtriggers.functx_map:
796 # This xtrigger's definition was removed (e.g. by reload).
797 # Just satisfy it directly without context lookup.
798 itask.state.xtriggers[label] = satisfied
799 continue
800
801 ctx = self.get_xtrig_ctx(itask, label)
802 sig = ctx.get_signature()
803
804 # Un/satisfy the xtrigger prerequisite and log what we did.
805 # (Say "prerequisite": the xtrigger itself is not touched).
806
807 prefix = f"[{itask}] prerequisite"
808 suffix = ctx.get_description()
809 state = "satisfied" if satisfied else "unsatisfied"
810
811 if itask.state.xtriggers[label] == satisfied:
812 if log:
813 LOG.info(f"{prefix} already {state}: {suffix}")
814 continue
815
816 itask.state.xtriggers[label] = satisfied
817
818 self.data_store_mgr.delta_task_xtrigger(
819 itask, label, sig, satisfied)
820 if log:
821 LOG.info(f"{prefix} force-{state}: {suffix}")
822
823 def force_satisfy_all(self, itask: 'TaskProxy', log: bool = True):
824 """Force satisfy all xtriggers for the provided task."""
825 self.force_satisfy(
826 itask,
827 dict.fromkeys(itask.state.xtriggers, True),
828 log=log,
829 )