Debian Codegraph @

cylc/flow/commands.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 """Cylc scheduler commands.
18
19 These are the scripts which are actioned on the Scheduler instance when you
20 call a mutation.
21
22 Each is an async generator providing functionalities for:
23
24 * Validation:
25 * The generator is executed up to the first "yield" before the command is
26 queued.
27 * Validation and argument parsing can be performed at this stage.
28 * If the generator raises an Exception then the error message will be
29 communicated back to the user and the command will not be queued.
30 * If the execution string is not obvious to a user, catch the exception and
31 re-raise it as an InputError with a more obvious string.
32 * Any other exceptions will be treated as genuine errors.
33 * Execution:
34 * The generator is executed up to the second "yield" when the command is run
35 by the Scheduler's main-loop:
36 * The execution may also stop at a return or the end of the generator code.
37 * If the generator raises a CommandFailedError at this stage, the error will
38 be caught and logged.
39 * Any other exceptions will be treated as genuine errors.
40
41 In the future we may change this interface to allow generators to "yield" any
42 arbitrary number of strings to serve the function of communicating command
43 progress back to the user. For example, the generator might yield the messages:
44
45 * Command queued.
46 * Done 1/3 things
47 * Done 2/3 things
48 * Done 3/3 things
49 * Done
50
51 For more info see: https://github.com/cylc/cylc-flow/issues/3329
52
53 """
54
55 from contextlib import suppress
56 import itertools
57 from time import (
58 sleep,
59 time,
60 )
61 from typing import (
62 TYPE_CHECKING,
63 AsyncGenerator,
64 Callable,
65 Dict,
66 Iterable,
67 List,
68 Optional,
69 Set,
70 TypeVar,
71 )
72
73 from metomi.isodatetime.parsers import TimePointParser
74
75 from cylc.flow import LOG
76 from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
77 import cylc.flow.command_validation as validate
78 from cylc.flow.cycling.loader import get_point
79 from cylc.flow.exceptions import (
80 CommandFailedError,
81 CyclingError,
82 CylcConfigError,
83 )
84 import cylc.flow.flags
85 from cylc.flow.flow_mgr import FLOW_NONE, repr_flow_nums
86 from cylc.flow.id import TaskTokens
87 from cylc.flow.log_level import log_level_to_verbosity
88 from cylc.flow.parsec.exceptions import ParsecError
89 from cylc.flow.prerequisite import PrereqTuple
90 from cylc.flow.run_modes import RunMode
91 from cylc.flow.task_id import TaskID
92 from cylc.flow.task_state import (
93 TASK_STATUS_PREPARING,
94 TASK_STATUSES_ACTIVE,
95 )
96 from cylc.flow.taskdef import generate_graph_children
97 from cylc.flow.util import get_connected_groups
98 from cylc.flow.workflow_status import StopMode
99
100
101 if TYPE_CHECKING:
102 from enum import Enum
103
104 from cylc.flow.flow_mgr import FlowNums
105 from cylc.flow.scheduler import Scheduler
106 from cylc.flow.task_proxy import TaskProxy
107
108 # define a type for command implementations
109 Command = Callable[..., AsyncGenerator]
110 # define a generic type needed for the @_command decorator
111 _TCommand = TypeVar('_TCommand', bound=Command)
112
113 # a directory of registered commands (populated on module import)
114 COMMANDS: 'Dict[str, Command]' = {}
115
116
117 # BACK COMPAT: handle --flow=all from pre-8.5 clients.
118 def back_compat_flow_all(flow: List[str]) -> List[str]:
119 """From 8.5 the old --flow=all is just the default.
120
121 Examples:
122 >>> back_compat_flow_all(['1', '2', '3'])
123 ['1', '2', '3']
124
125 >>> back_compat_flow_all(["all"])
126 []
127
128 """
129 if flow == ["all"]:
130 return []
131 else:
132 return flow
133
134
135 def _command(name: str):
136 """Decorator to register a command."""
137 def _command(fcn: '_TCommand') -> '_TCommand':
138 COMMANDS[name] = fcn
139 fcn.command_name = name # type: ignore[attr-defined]
140 return fcn
141 return _command
142
143
144 def _report_unmatched(unmatched: Set[TaskTokens]):
145 """Log unmatched IDs."""
146 if len(unmatched) == 1:
147 LOG.warning(
148 'No tasks match'
149 f' "{next(iter(unmatched)).relative_id_with_selectors}"'
150 )
151 elif len(unmatched) > 1:
152 LOG.warning(
153 'No tasks match the IDs:\n* '
154 + '\n* '.join(
155 sorted([id_.relative_id_with_selectors for id_ in unmatched])
156 )
157 )
158
159
160 def _remove_matched_tasks(
161 schd: 'Scheduler',
162 ids: Set[TaskTokens],
163 flow_nums: 'FlowNums',
164 warn_unremovable: bool = True,
165 ):
166 """Remove matched tasks."""
167 # Mapping of *relative* task IDs to removed flow numbers:
168 removed: Dict[TaskTokens, FlowNums] = {}
169 not_removed: Set[TaskTokens] = set()
170 to_kill: List[TaskProxy] = []
171
172 for id_ in ids:
173 itask = schd.pool._get_task_by_id(id_.relative_id)
174
175 if itask:
176 # remove active task from the pool
177 fnums_to_remove = itask.match_flows(flow_nums)
178 if not fnums_to_remove:
179 not_removed.add(itask.tokens.task)
180 continue
181 removed[itask.tokens.task] = fnums_to_remove
182 if fnums_to_remove == itask.flow_nums:
183 schd.pool.remove(itask, 'request')
184 to_kill.append(itask)
185 itask.removed = True
186 itask.flow_nums.difference_update(fnums_to_remove)
187
188 # remove task from the DB
189 tdef = schd.config.taskdefs[id_['task']]
190 icycle = get_point(id_['cycle'])
191
192 # Go through any tasks downstream of this matched task to see if
193 # any need to stand down as a result of this task being removed:
194 for child in set(itertools.chain.from_iterable(
195 generate_graph_children(tdef, icycle).values()
196 )):
197 child_itask = schd.pool.get_task(child.point, child.name)
198 if not child_itask:
199 continue
200 fnums_to_remove = child_itask.match_flows(flow_nums)
201 if not fnums_to_remove:
202 continue
203 prereqs_changed = False
204 for prereq in (
205 *child_itask.state.prerequisites,
206 *child_itask.state.suicide_prerequisites,
207 ):
208 # Unset any prereqs naturally satisfied by these tasks
209 # (do not unset those satisfied by `cylc set --pre`):
210 if prereq.unset_naturally_satisfied(id_.relative_id):
211 prereqs_changed = True
212 removed.setdefault(id_, set()).update(
213 fnums_to_remove
214 )
215 if not prereqs_changed:
216 continue
217 schd.data_store_mgr.delta_task_prerequisite(child_itask)
218 # Check if downstream task is still ready to run:
219 if (
220 child_itask.state.is_gte(TASK_STATUS_PREPARING)
221 # Still ready if the task exists in other flows:
222 or child_itask.flow_nums != fnums_to_remove
223 or child_itask.state.prerequisites_all_satisfied()
224 ):
225 continue
226 # No longer ready to run
227 schd.pool.unqueue_task(child_itask)
228 # Check if downstream task should remain spawned:
229 if (
230 # Ignoring tasks we are already dealing with:
231 child_itask.tokens.task in ids
232 or child_itask.state.any_satisfied_prerequisite_outputs()
233 ):
234 continue
235 # No longer has reason to be in pool:
236 schd.pool.remove(child_itask, schd.pool.REMOVED_BY_PREREQ)
237 # Remove this downstream task from flows in DB tables to ensure
238 # it is not skipped if it respawns in future:
239 schd.workflow_db_mgr.remove_task_from_flows(
240 str(child.point), child.name, fnums_to_remove
241 )
242
243 # Remove the matched tasks from the flows in the DB tables:
244 db_removed_fnums = schd.workflow_db_mgr.remove_task_from_flows(
245 id_['cycle'], id_['task'], flow_nums,
246 )
247 if db_removed_fnums:
248 removed.setdefault(id_, set()).update(db_removed_fnums)
249
250 if id_ not in removed:
251 not_removed.add(id_)
252
253 if to_kill:
254 schd.kill_tasks(to_kill, warn=False)
255
256 if removed:
257 tasks_str_list = []
258 for task, fnums in removed.items():
259 schd.data_store_mgr.delta_remove_task_flow_nums(
260 task.relative_id, fnums
261 )
262 tasks_str_list.append(
263 f"{task.relative_id} {repr_flow_nums(fnums, full=True)}"
264 )
265 LOG.info(f"Removed tasks: {', '.join(sorted(tasks_str_list))}")
266
267 if warn_unremovable and not_removed:
268 fnums_str = (
269 repr_flow_nums(flow_nums, full=True) if flow_nums else ''
270 )
271 tasks_str = ', '.join(
272 sorted(tokens.relative_id for tokens in not_removed)
273 )
274 LOG.warning(f"Task(s) not removable: {tasks_str} {fnums_str}")
275
276 if removed and schd.pool.compute_runahead():
277 schd.pool.release_runahead_tasks()
278
279
280 async def run_cmd(bound_fcn: AsyncGenerator):
281 """Run a command outside of the scheduler's main loop.
282
283 Normally commands are run via the Scheduler's command_queue (which is
284 correct), however, there are some use cases for running commands outside of
285 the loop:
286
287 * Running synchronous commands within the scheduler itself (e.g. on
288 shutdown).
289 * Integration tests (where you may want to cut out the main loop and
290 command queueing mechanism for simplicity).
291
292 For these purposes use "run_cmd", otherwise, queue commands via the
293 scheduler as normal.
294 """
295 await bound_fcn.__anext__() # validate
296 with suppress(StopAsyncIteration):
297 return await bound_fcn.__anext__() # run
298
299
300 @_command('set')
301 async def set_prereqs_and_outputs(
302 schd: 'Scheduler',
303 tasks: List[str],
304 flow: List[str],
305 outputs: Optional[List[str]] = None,
306 prerequisites: Optional[List[str]] = None,
307 flow_wait: bool = False,
308 flow_descr: Optional[str] = None,
309 ) -> AsyncGenerator:
310 """Force spawn task successors.
311
312 Note, the "outputs" and "prerequisites" arguments might not be
313 populated in the mutation arguments so must provide defaults here.
314 """
315 flow = back_compat_flow_all(flow) # BACK COMPAT (see func def)
316 validate.consistency(outputs, prerequisites)
317 outputs = validate.outputs(outputs)
318 prerequisites = validate.prereqs(prerequisites)
319 validate.flow_opts(flow, flow_wait)
320 ids = validate.is_tasks(tasks)
321
322 yield
323
324 if outputs is None:
325 outputs = []
326 if prerequisites is None:
327 prerequisites = []
328 yield schd.pool.set_prereqs_and_outputs(
329 ids,
330 outputs,
331 prerequisites,
332 flow,
333 flow_wait,
334 flow_descr,
335 )
336
337
338 @_command('stop')
339 async def stop(
340 schd: 'Scheduler',
341 mode: 'Optional[Enum]',
342 cycle_point: Optional[str] = None,
343 # NOTE clock_time YYYY/MM/DD-HH:mm back-compat removed
344 clock_time: Optional[str] = None,
345 task: Optional[str] = None,
346 flow_num: Optional[int] = None,
347 ):
348 if task:
349 validate.is_tasks([task])
350 yield
351 if flow_num:
352 schd.pool.stop_flow(flow_num)
353 return
354
355 if cycle_point is not None:
356 # schedule shutdown after tasks pass provided cycle point
357 point = TaskID.get_standardised_point(cycle_point)
358 if point is not None and schd.pool.set_stop_point(point):
359 schd.options.stopcp = str(point)
360 schd.config.stop_point = point
361 schd.workflow_db_mgr.put_workflow_stop_cycle_point(
362 schd.options.stopcp
363 )
364 schd._update_workflow_state()
365 elif clock_time is not None:
366 # schedule shutdown after wallclock time passes provided time
367 parser = TimePointParser()
368 schd.set_stop_clock(
369 int(parser.parse(clock_time).seconds_since_unix_epoch)
370 )
371 schd._update_workflow_state()
372 elif task is not None:
373 # schedule shutdown after task succeeds
374 task_id = TaskID.get_standardised_taskid(task)
375 schd.pool.set_stop_task(task_id)
376 schd._update_workflow_state()
377 else:
378 # immediate shutdown
379 try:
380 # BACK COMPAT: mode=None
381 # the mode can be `None` for commands issued from older Cylc
382 # versions
383 # From: 8.4
384 # To: 8.5
385 # Remove at: 8.x
386 mode = StopMode(mode.value) if mode else StopMode.REQUEST_CLEAN
387 except ValueError:
388 raise CommandFailedError(f"Invalid stop mode: '{mode}'") from None
389 schd._set_stop(mode)
390 if mode is StopMode.REQUEST_KILL:
391 schd.time_next_kill = time()
392
393
394 @_command('release')
395 async def release(schd: 'Scheduler', tasks: Iterable[str]):
396 """Release held tasks."""
397 ids = validate.is_tasks(tasks)
398 yield
399 yield schd.pool.release_held_tasks(ids)
400
401
402 @_command('release_hold_point')
403 async def release_hold_point(schd: 'Scheduler'):
404 """Release all held tasks and unset workflow hold after cycle point,
405 if set."""
406 yield
407 LOG.info("Releasing all tasks and removing hold cycle point.")
408 schd.pool.release_hold_point()
409 schd._update_workflow_state()
410
411
412 @_command('resume')
413 async def resume(schd: 'Scheduler'):
414 """Resume paused workflow."""
415 yield
416 schd.resume_workflow()
417
418
419 @_command('poll_tasks')
420 async def poll_tasks(schd: 'Scheduler', tasks: Iterable[str]):
421 """Poll pollable tasks or a task or family if options are provided."""
422 ids = validate.is_tasks(tasks)
423 yield
424 if schd.get_run_mode() == RunMode.SIMULATION:
425 yield 0
426 matched, unmatched = schd.pool.id_match(ids, only_match_pool=True)
427 _report_unmatched(unmatched)
428 itasks = schd.pool.get_itasks(matched)
429 schd.task_job_mgr.poll_task_jobs(itasks)
430 yield len(unmatched)
431
432
433 @_command('kill_tasks')
434 async def kill_tasks(schd: 'Scheduler', tasks: Iterable[str]):
435 """Kill tasks.
436
437 Args:
438 tasks: Tasks/families/globs to kill.
439 """
440 ids = validate.is_tasks(tasks)
441 yield
442 matched, unmatched = schd.pool.id_match(ids, only_match_pool=True)
443 _report_unmatched(unmatched)
444 itasks = schd.pool.get_itasks(matched)
445 num_unkillable = schd.kill_tasks(itasks)
446 yield len(unmatched) + num_unkillable
447
448
449 @_command('hold')
450 async def hold(schd: 'Scheduler', tasks: Iterable[str]):
451 """Hold specified tasks."""
452 ids = validate.is_tasks(tasks)
453 yield
454 yield schd.pool.hold_tasks(ids)
455
456
457 @_command('set_hold_point')
458 async def set_hold_point(schd: 'Scheduler', point: str):
459 """Hold all tasks after the specified cycle point."""
460 cycle_point = TaskID.get_standardised_point(point)
461 if cycle_point is None:
462 raise CyclingError("Cannot set hold point to None")
463 yield
464 LOG.info(
465 f"Setting hold cycle point: {cycle_point}\n"
466 "All tasks after this point will be held."
467 )
468 schd.pool.set_hold_point(cycle_point)
469 schd._update_workflow_state()
470
471
472 @_command('pause')
473 async def pause(schd: 'Scheduler'):
474 """Pause the workflow."""
475 yield
476 schd.pause_workflow()
477
478
479 @_command('set_verbosity')
480 async def set_verbosity(schd: 'Scheduler', level: 'Enum'):
481 """Set workflow verbosity."""
482 try:
483 LOG.setLevel(level.value)
484 except (TypeError, ValueError) as exc:
485 raise CommandFailedError(exc) from None
486 cylc.flow.flags.verbosity = log_level_to_verbosity(level.value)
487 yield
488
489
490 @_command('remove_tasks')
491 async def remove_tasks(
492 schd: 'Scheduler', tasks: Iterable[str], flow: List[str]
493 ):
494 """Match and remove tasks (`cylc remove` command).
495
496 Args:
497 tasks: Relative IDs or globs to match.
498 flow: flows to remove the tasks from.
499 """
500 flow = back_compat_flow_all(flow) # BACK COMPAT (see func def)
501 ids = validate.is_tasks(tasks)
502 validate.flow_opts(flow, flow_wait=False, allow_new_or_none=False)
503 yield
504
505 matched, unmatched = schd.pool.id_match(ids)
506 _report_unmatched(unmatched)
507 if matched:
508 _remove_matched_tasks(
509 schd,
510 matched,
511 schd.pool.flow_mgr.cli_to_flow_nums(flow)
512 )
513
514
515 @_command('reload_workflow')
516 async def reload_workflow(schd: 'Scheduler', reload_global: bool = False):
517 """Reload workflow configuration."""
518 yield
519 # pause the workflow if not already
520 was_paused_before_reload = schd.is_paused
521 if not was_paused_before_reload:
522 schd.pause_workflow('Reloading workflow')
523 schd.process_workflow_db_queue() # see #5593
524
525 # flush out preparing tasks before attempting reload
526 schd.reload_pending = 'waiting for pending tasks to submit'
527 while schd.release_tasks_to_run() or any(
528 itask.waiting_on_job_prep or itask.state(TASK_STATUS_PREPARING)
529 for itask in schd.pool.get_tasks()
530 ):
531 # Run the subset of main-loop functionality required to push
532 # preparing through the submission pipeline and keep the workflow
533 # responsive (e.g. to the `cylc stop` command).
534
535 # NOTE: this reload method was called by process_command_queue
536 # which is called synchronously in the main loop so this call is
537 # blocking to other main loop functions
538
539 # subproc pool - for issueing/tracking remote-init commands
540 schd.proc_pool.process()
541 # task messages - for tracking task status changes
542 schd.process_queued_task_messages()
543 # command queue - keeps the scheduler responsive
544 await schd.process_command_queue()
545 # allows the scheduler to shutdown --now
546 await schd.workflow_shutdown()
547 # keep the data store up to date with what's going on
548 await schd.update_data_structure()
549 schd.update_data_store()
550 # give commands time to complete
551 sleep(1) # give any remove-init's time to complete
552
553 try:
554 # Back up the current config in case workflow reload errors
555 global_cfg_old = glbl_cfg()
556
557 if reload_global:
558 # Reload global config if requested
559 schd.reload_pending = 'reloading the global configuration'
560 schd.update_data_store() # update workflow status msg
561 await schd.update_data_structure()
562 LOG.info("Reloading the global configuration.")
563
564 glbl_cfg(reload=True)
565
566 # reload the workflow definition
567 schd.reload_pending = 'loading the workflow definition'
568 schd.update_data_store() # update workflow status msg
569 schd._update_workflow_state()
570 # Things that can't change on workflow reload:
571 schd._set_workflow_params(
572 schd.workflow_db_mgr.pri_dao.select_workflow_params()
573 )
574 LOG.info("Reloading the workflow definition.")
575 config = schd.load_flow_file(is_reload=True)
576 except (ParsecError, CylcConfigError) as exc:
577 if cylc.flow.flags.verbosity > 1:
578 # log full traceback in debug mode
579 LOG.exception(exc)
580 LOG.critical(
581 f'Reload failed - {exc.__class__.__name__}: {exc}'
582 '\nThis is probably due to an issue with the new'
583 ' configuration.'
584 '\nTo continue with the pre-reload config, un-pause the'
585 ' workflow.'
586 '\nOtherwise, fix the configuration and attempt to reload'
587 ' again.'
588 )
589
590 # Rollback global config
591 glbl_cfg().set_cache(global_cfg_old)
592 else:
593 schd.reload_pending = 'applying the new config'
594 old_tasks = set(schd.config.get_task_name_list())
595
596 schd.apply_new_config(config, is_reload=True)
597 schd.broadcast_mgr.linearized_ancestors = (
598 schd.config.get_linearized_ancestors()
599 )
600
601 schd.task_events_mgr.mail_interval = schd.cylc_config['mail'][
602 'task event batch interval'
603 ]
604 schd.task_events_mgr.mail_smtp = schd._get_events_conf("smtp")
605 schd.task_events_mgr.mail_footer = schd._get_events_conf("footer")
606
607 # Log tasks that have been added by the reload, removed tasks are
608 # logged by the TaskPool.
609 add = set(schd.config.get_task_name_list()) - old_tasks
610 for task in add:
611 LOG.info(f"Added task: '{task}'")
612 schd.workflow_db_mgr.put_workflow_template_vars(schd.template_vars)
613 schd.workflow_db_mgr.put_runtime_inheritance(schd.config)
614 schd.workflow_db_mgr.put_workflow_params(schd)
615 schd.process_workflow_db_queue() # see #5593
616 schd.is_updated = True
617 schd.is_reloaded = True
618 schd._update_workflow_state()
619
620 # Re-initialise data model on reload
621 schd.data_store_mgr.initiate_data_model(schd.is_reloaded)
622
623 # Reset the remote init map to trigger fresh file installation
624 schd.task_job_mgr.task_remote_mgr.remote_init_map.clear()
625 schd.task_job_mgr.task_remote_mgr.is_reload = True
626 schd.pool.reload(config)
627 schd.data_store_mgr.apply_task_proxy_db_history()
628 # Load jobs from DB
629 schd.workflow_db_mgr.pri_dao.select_jobs_for_restart(
630 schd.data_store_mgr.insert_db_job
631 )
632 if schd.pool.compute_runahead(force=True):
633 schd.pool.release_runahead_tasks()
634 schd.is_reloaded = True
635 schd.is_updated = True
636
637 LOG.info("Reload completed.")
638
639 # resume the workflow if previously paused
640 schd.reload_pending = False
641 schd.update_data_store() # update workflow status msg
642 schd._update_workflow_state()
643 if not was_paused_before_reload:
644 schd.resume_workflow()
645 schd.process_workflow_db_queue() # see #5593
646
647
648 @_command('force_trigger_tasks')
649 async def force_trigger_tasks(
650 schd: 'Scheduler',
651 tasks: Iterable[str],
652 flow: List[str],
653 flow_wait: bool = False,
654 flow_descr: Optional[str] = None,
655 # BACK COMPAT: on_resume
656 # Arg no longer used but retained for older clients.
657 # From: 8.6
658 # Remove at: 8.7
659 on_resume: bool = False
660 ):
661 """Match and trigger a group of tasks (`cylc trigger` command).
662
663 Satisfy any off-group prerequisites. Group start tasks (parentless,
664 or only off-group prerequisites) will run immediately. In-group
665 prerequisites will be respected.
666
667 Implements the Group Trigger Proposal:
668 cylc-admin/docs/proposal-group-trigger.md
669
670 """
671 flow = back_compat_flow_all(flow) # BACK COMPAT (see func def)
672 ids = validate.is_tasks(tasks)
673 validate.flow_opts(flow, flow_wait)
674 yield
675
676 matched, unmatched = schd.pool.id_match(ids)
677 _report_unmatched(unmatched)
678
679 # split IDs into connected groups of tasks
680 adjacency: Dict[TaskTokens, Set[TaskTokens]] = {}
681 for id_ in matched:
682 id_ = id_.duplicate(task_sel=None) # strip the task selector
683 icycle = get_point(id_['cycle'])
684 prereqs = {
685 prereq_id
686 for prereq_id in (
687 TaskTokens(str(trg.get_point(icycle)), trg.task_name)
688 for trg in schd.config.taskdefs[id_['task']].get_triggers(
689 icycle
690 )
691 )
692 if prereq_id in matched
693 }
694 adjacency.setdefault((id_), set()).update(prereqs)
695 for prereq in prereqs:
696 adjacency.setdefault(prereq, set()).add(id_)
697
698 # trigger each group of tasks individually
699 for group in get_connected_groups(adjacency):
700 _force_trigger_tasks(
701 schd,
702 group,
703 flow,
704 flow_wait,
705 flow_descr,
706 )
707
708
709 def _force_trigger_tasks(
710 schd: 'Scheduler',
711 group_ids: Set[TaskTokens],
712 flow: List[str],
713 flow_wait: bool = False,
714 flow_descr: Optional[str] = None,
715 ):
716 active = schd.pool.get_itasks(group_ids)
717 if flow or not active:
718 flow_nums = schd.pool.flow_mgr.cli_to_flow_nums(flow, flow_descr)
719 if flow != [FLOW_NONE] and not flow_nums:
720 # Here, empty flow_nums means either no-flow or all active flows.
721 flow_nums = schd.pool._get_active_flow_nums()
722
723 else:
724 flow_nums = set()
725 for itask in active:
726 flow_nums.update(itask.flow_nums)
727
728 # Record off-group prerequisites, and active tasks to be removed.
729 active_to_remove: List[TaskTokens] = []
730 active_to_resume: Set[TaskTokens] = set()
731
732 warnings_flow_none = []
733 warnings_has_job = []
734 active_completed_outputs = {}
735 inactive: Set[TaskTokens] = set(group_ids)
736 for itask in active:
737 # Find active group start tasks (parentless, or with only off-group
738 # prerequisites) and set all prerequisites (to trigger them now).
739
740 # Preparing, submitted, or running group start tasks are already
741 # active, so leave them be (and merge the flows).
742
743 # Compute prerequisites from the TaskDef in case active tasks were
744 # spawned before a reload (which could alter prerequisites).
745
746 # Remove non group start and final-status group start tasks, and
747 # trigger them from scratch (so only the TaskDef matters).
748
749 # Group start tasks are not removed, but a reload would
750 # replace them, so using the TaskDef is fine.
751 inactive.remove(itask.tokens.task)
752
753 if not any(
754 TaskTokens(str(trg.get_point(itask.point)), trg.task_name)
755 in group_ids
756 for trg in itask.tdef.get_triggers(itask.point)
757 ):
758 # This is a group start task (it has no in-group prerequisites).
759 if flow == [FLOW_NONE] and itask.flow_nums:
760 # Exclude --flow=none for flow-assigned active tasks.
761 warnings_flow_none.append(
762 f"{itask.identity}: "
763 f"{repr_flow_nums(itask.flow_nums, full=True)}"
764 )
765 continue
766
767 if itask.state(*TASK_STATUSES_ACTIVE):
768 for (label, msg, completed) in itask.state.outputs:
769 if completed:
770 active_completed_outputs[
771 (str(itask.point), itask.tdef.name)] = (label, msg)
772
773 if itask.state(TASK_STATUS_PREPARING, *TASK_STATUSES_ACTIVE):
774 # This is a live active group start task
775 warnings_has_job.append(str(itask))
776 # Just merge the flows.
777 schd.pool.merge_flows(itask, flow_nums)
778
779 else:
780 # This is a non-live active group start task...
781 # ... satisfy off-group (i.e. all) prerequisites
782 itask.state.set_all_task_prerequisites_satisfied()
783 # ... and satisfy all xtrigger prerequisites.
784 schd.pool.xtrigger_mgr.force_satisfy(itask, {"all": True})
785 # ... and satisfy all push external triggers.
786 itask.force_satisfy_external_triggers()
787
788 schd.pool.merge_flows(itask, flow_nums)
789
790 # Trigger group start task.
791 schd.pool.queue_or_trigger(itask)
792
793 else:
794 active_to_remove.append(itask.tokens.task)
795 active_to_resume.add(itask.tokens.task)
796
797 if warnings_flow_none:
798 msg = '\n * '.join(warnings_flow_none)
799 LOG.warning(f"Already active - ignoring no-flow trigger: \n * {msg}")
800
801 if warnings_has_job:
802 msg = '\n * '.join(warnings_has_job)
803 LOG.warning(f"Job already in process - ignoring trigger:\n * {msg}")
804
805 # Remove all inactive and selected active group members.
806 if flow != [FLOW_NONE]:
807 # (No need to remove tasks if triggering with no-flow).
808 _remove_matched_tasks(
809 schd,
810 ids := {*active_to_remove, *inactive},
811 flow_nums,
812 warn_unremovable=False,
813 )
814 # Record pre-startcp tasks, as these would not normally be spawned -
815 # see https://github.com/cylc/cylc-flow/pull/7148
816 schd.pool.pre_start_tasks_to_trigger.update(
817 (tokens['task'], point)
818 for tokens in ids
819 if (point := get_point(tokens['cycle'])) < schd.config.start_point
820 )
821
822 # trigger should override the held state, however, in-group tasks may
823 # have previously been held and active in-group tasks will become
824 # held as the result of removal
825 schd.pool.release_held_tasks({*active_to_resume, *inactive})
826
827 # Store removal results before moving on.
828 schd.workflow_db_mgr.process_queued_ops()
829
830 # Satisfy any off-group prerequisites in removed tasks.
831 tasks_removed = inactive
832 if active_to_remove:
833 tasks_removed.update(active_to_remove)
834
835 # for tdef, point in tasks_removed:
836 for id_ in tasks_removed:
837 tdef = schd.config.taskdefs[id_['task']]
838 icycle = get_point(id_['cycle'])
839 in_flow_prereqs = False
840 jtask: Optional[TaskProxy] = None
841 if tdef.is_parentless(icycle, cutoff=schd.config.initial_point):
842 # Parentless: set all prereqs to spawn the task.
843 jtask = schd.pool._set_prereqs_tdef(
844 icycle, tdef,
845 [], # prerequisites
846 {"all": True}, # xtriggers
847 flow_nums,
848 flow_wait,
849 set_all=True # prerequisites
850 )
851 else:
852 _prereqs = tdef.get_prereqs(icycle)
853 # Off-flow prereqs to satisfy, for the triggered flow:
854 prereqs_to_set = {
855 PrereqTuple(str(key.point), str(key.task), key.output)
856 for pre in _prereqs
857 for key in pre.keys()
858 if TaskTokens(cycle=key.point, task=key.task) not in group_ids
859 }
860 in_flow_prereqs = any(
861 key
862 for pre in _prereqs
863 for key in pre.keys()
864 if TaskTokens(cycle=key.point, task=key.task) in group_ids
865 )
866 # Prereqs to satisfy, from already-completed outputs of active
867 # group start tasks, for the triggered flow.
868 prereqs_to_set.update({
869 PrereqTuple(str(key.point), str(key.task), key.output)
870 for pre in _prereqs
871 for key in pre.keys()
872 if (str(key.point), key.task) in active_completed_outputs
873 })
874
875 if (
876 prereqs_to_set
877 or tdef.get_xtrigs(icycle)
878 or tdef.external_triggers
879 ):
880 # Satisfy any off-group prereqs or ext/xtriggers to spawn task.
881 jtask = schd.pool._set_prereqs_tdef(
882 icycle, tdef,
883 prereqs_to_set,
884 {"all": True}, # xtriggers
885 flow_nums,
886 flow_wait,
887 set_all=False
888 )
889 if jtask is not None and tdef.external_triggers:
890 jtask.force_satisfy_external_triggers()
891
892 if jtask is not None and not in_flow_prereqs:
893 # Trigger group start task.
894 schd.pool.queue_or_trigger(jtask)
895
896 schd.pool.release_runahead_tasks()