Debian Codegraph @

cylc/flow/task_events_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 """Task events manager.
17
18 This module provides logic to:
19 * Manage task messages (internal, polled or received).
20 * Set up retries on job failures (submission or execution).
21 * Generate task event handlers.
22 * Retrieval of log files for completed remote jobs.
23 * Email notification.
24 * Custom event handlers.
25 * Manage invoking and retrying of task event handlers.
26 """
27
28 from contextlib import suppress
29 from enum import Enum
30 from logging import (
31 DEBUG,
32 INFO,
33 getLevelName,
34 )
35 import os
36 from pathlib import Path
37 import shlex
38 from shlex import quote
39 from time import time
40 from typing import (
41 TYPE_CHECKING,
42 Any,
43 Callable,
44 Dict,
45 List,
46 NamedTuple,
47 Optional,
48 Sequence,
49 Set,
50 Union,
51 cast,
52 )
53
54 from cylc.flow import (
55 LOG,
56 LOG_LEVELS,
57 )
58 from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
59 from cylc.flow.cycling.loader import get_point
60 from cylc.flow.exceptions import (
61 NoHostsError,
62 PlatformLookupError,
63 )
64 from cylc.flow.hostuserutil import (
65 get_host,
66 get_user,
67 is_remote_platform,
68 )
69 from cylc.flow.parsec.config import ItemNotFoundError
70 from cylc.flow.pathutil import (
71 get_remote_workflow_run_job_dir,
72 get_workflow_run_job_dir,
73 )
74 from cylc.flow.platforms import (
75 get_host_from_platform,
76 get_platform,
77 log_platform_event,
78 )
79 from cylc.flow.run_modes import (
80 JOBLESS_MODES,
81 RunMode,
82 disable_task_event_handlers,
83 )
84 from cylc.flow.subprocctx import (
85 SubFuncContext,
86 SubProcContext,
87 )
88 from cylc.flow.task_action_timer import (
89 TaskActionTimer,
90 TimerFlags,
91 )
92 from cylc.flow.task_job_logs import (
93 JOB_LOG_ERR,
94 JOB_LOG_OUT,
95 get_task_job_activity_log,
96 get_task_job_log,
97 )
98 from cylc.flow.task_message import (
99 ABORT_MESSAGE_PREFIX,
100 FAIL_MESSAGE_PREFIX,
101 VACATION_MESSAGE_PREFIX,
102 split_run_signal,
103 )
104 from cylc.flow.task_outputs import (
105 TASK_OUTPUT_EXPIRED,
106 TASK_OUTPUT_FAILED,
107 TASK_OUTPUT_STARTED,
108 TASK_OUTPUT_SUBMIT_FAILED,
109 TASK_OUTPUT_SUBMITTED,
110 TASK_OUTPUT_SUCCEEDED,
111 )
112 from cylc.flow.task_proxy import TaskProxy
113 from cylc.flow.task_state import (
114 TASK_STATUS_EXPIRED,
115 TASK_STATUS_FAILED,
116 TASK_STATUS_PREPARING,
117 TASK_STATUS_RUNNING,
118 TASK_STATUS_SUBMIT_FAILED,
119 TASK_STATUS_SUBMITTED,
120 TASK_STATUS_SUCCEEDED,
121 TASK_STATUS_WAITING,
122 TASK_STATUSES_ACTIVE,
123 )
124 from cylc.flow.wallclock import (
125 get_current_time_string,
126 get_seconds_as_interval_string as intvl_as_str,
127 )
128 from cylc.flow.workflow_events import (
129 EventData as WorkflowEventData,
130 construct_mail_cmd,
131 get_template_variables as get_workflow_template_variables,
132 process_mail_footer,
133 )
134
135
136 if TYPE_CHECKING:
137 from cylc.flow.broadcast_mgr import BroadcastMgr
138 from cylc.flow.cycling import PointBase
139 from cylc.flow.data_store_mgr import DataStoreMgr
140 from cylc.flow.id import Tokens
141 from cylc.flow.scheduler import Scheduler
142 from cylc.flow.taskdef import TaskDef
143 from cylc.flow.workflow_db_mgr import WorkflowDatabaseManager
144 from cylc.flow.xtrigger_mgr import XtriggerManager
145
146
147 class CustomTaskEventHandlerContext(NamedTuple):
148 key: Union[str, Sequence[str]]
149 cmd: str
150
151
152 class TaskEventMailContext(NamedTuple):
153 key: str
154 mail_from: str
155 mail_to: str
156
157
158 class TaskJobLogsRetrieveContext(NamedTuple):
159 key: Union[str, Sequence[str]]
160 platform_name: Optional[str]
161 max_size: Optional[int]
162
163
164 class EventKey(NamedTuple):
165 """Unique identifier for a task event.
166
167 This contains event context information for event handlers.
168 """
169
170 """The event handler name."""
171 handler: str
172
173 """The task event."""
174 event: str
175
176 """The task event message.
177
178 Warning: This information is not currently preserved in the DB so will be
179 lost on restart.
180 """
181 message: str
182
183 """The job tokens."""
184 tokens: 'Tokens'
185
186
187 def get_event_id(event: str, itask: 'TaskProxy') -> str:
188 """Return a unique event identifier.
189
190 Some events are not unique e.g. task "started" is unique in that it can
191 only happen once per-job, "warning", however, is not unique as this is a
192 message severity level which could be associated with any number of
193 custom task messages.
194
195 To handle this tasks track non-unique-events and number them to ensure
196 their EventKey's remain unique for ease of event tracking.
197
198 Examples:
199 >>> from types import SimpleNamespace
200
201 # regular events are passed straight through:
202 >>> get_event_id('whatever', SimpleNamespace())
203 'whatever'
204
205 # non-unique events get an integer added to the end:
206 >>> get_event_id('warning', SimpleNamespace(non_unique_events={
207 ... 'warning': None,
208 ... }))
209 'warning-1'
210 >>> get_event_id('warning', SimpleNamespace(non_unique_events={
211 ... 'warning': 2,
212 ... }))
213 'warning-2'
214
215 """
216 if event in TaskEventsManager.NON_UNIQUE_EVENTS:
217 event = f'{event}-{itask.non_unique_events[event] or 1:d}'
218 return event
219
220
221 def log_task_job_activity(
222 ctx: 'SubProcContext',
223 workflow: str,
224 point: 'str | PointBase',
225 name: str,
226 submit_num: str | int | None = None,
227 ):
228 """Log an activity for a task job."""
229 ctx_str = str(ctx)
230 if not ctx_str:
231 return
232 if isinstance(ctx.cmd_key, tuple): # An event handler
233 submit_num = ctx.cmd_key[-1]
234 job_activity_log = get_task_job_activity_log(
235 workflow, point, name, submit_num)
236 try:
237 with open(os.path.expandvars(job_activity_log), "ab") as handle:
238 handle.write((ctx_str + '\n').encode())
239 except IOError:
240 # This happens when there is no job directory. E.g., if a job host
241 # selection command causes a submission failure, or if a waiting task
242 # expires before a job log directory is otherwise needed.
243 # (Don't log the exception content, it looks like a bug).
244 LOG.info(ctx_str)
245 if ctx.cmd and ctx.ret_code:
246 LOG.error(ctx_str)
247
248
249 class EventData(Enum):
250 """The following variables are available to task event handlers.
251
252 They can be templated into event handlers with Python percent style string
253 formatting e.g:
254
255 .. code-block:: none
256
257 %(workflow)s is running on %(host)s
258
259 The ``%(event)s`` string, for instance, will be replaced by the actual
260 event name when the handler is invoked.
261
262 If no templates or arguments are specified the following default command
263 line will be used:
264
265 .. code-block:: none
266
267 <event-handler> %(event)s %(workflow)s %(id)s %(message)s
268
269 .. note::
270
271 Substitution patterns should not be quoted in the template strings.
272 This is done automatically where required.
273
274 For an explanation of the substitution syntax, see
275 `String Formatting Operations in the Python documentation
276 <https://docs.python.org/3/library/stdtypes.html
277 #printf-style-string-formatting>`_.
278
279 """
280
281 Event = 'event'
282 """Event name."""
283
284 Workflow = 'workflow'
285 """Workflow ID."""
286
287 Suite = 'suite' # deprecated
288 """Workflow ID.
289
290 .. deprecated:: 8.0.0
291
292 Use "workflow".
293 """
294
295 UUID = 'uuid'
296 """The unique identification string for this workflow run.
297
298 This string is preserved for the lifetime of the scheduler and is restored
299 from the database on restart.
300 """
301
302 SuiteUUID = 'suite_uuid' # deprecated
303 """The unique identification string for this workflow run.
304
305 .. deprecated:: 8.0.0
306
307 Use 'uuid'.
308 """
309
310 CyclePoint = 'point'
311 """The task's cycle point."""
312
313 SubmitNum = 'submit_num'
314 """The job's submit number.
315
316 This starts at 1 and increments with each additional job submission.
317 """
318
319 TryNum = 'try_num'
320 """The job's try number.
321
322 The number of execution attempts.
323 It starts at 1 and increments with automatic
324 :cylc:conf:`flow.cylc[runtime][<namespace>]execution retry delays`.
325 """
326
327 ID = 'id'
328 """The task ID (i.e. ``%(point)/%(name)``)."""
329
330 Message = 'message'
331 """Events message, if any."""
332
333 JobRunnerName = 'job_runner_name'
334 """The job runner name."""
335
336 JobRunnerName_old = 'batch_sys_name' # deprecated
337 """The job runner name.
338
339 .. deprecated:: 8.0.0
340
341 Use "job_runner_name".
342 """
343
344 JobID = 'job_id'
345 """The job ID in the job runner.
346
347 I.E. The job submission ID. For background jobs this is the process ID.
348 """
349
350 JobID_old = 'batch_sys_job_id' # deprecated
351 """The job ID in the job runner.
352
353 .. deprecated:: 8.0.0
354
355 Use "job_id".
356 """
357
358 SubmitTime = 'submit_time'
359 """Date-time when the job was submitted, in ISO8601 format."""
360
361 StartTime = 'start_time'
362 """Date-time when the job started, in ISO8601 format."""
363
364 FinishTime = 'finish_time'
365 """Date-time when the job finished, in ISO8601 format."""
366
367 PlatformName = 'platform_name'
368 """The name of the platform where the job is submitted."""
369
370 UserAtHost = 'user@host'
371 """The name of the platform where the job is submitted.
372
373 .. deprecated:: 8.0.0
374
375 Use "platform_name".
376
377 .. versionchanged:: 8.0.0
378
379 This now provides the platform name rather than ``user@host``.
380 """
381
382 TaskName = 'name'
383 """The name of the task."""
384
385 TaskURL = 'task_url' # deprecated
386 """The URL defined in the task's metadata.
387
388 .. deprecated:: 8.0.0
389
390 Use ``URL`` from ``<task metadata>``.
391 """
392
393 WorkflowURL = 'workflow_url' # deprecated
394 """The URL defined in the workflow's metadata.
395
396 .. deprecated:: 8.0.0
397
398 Use ``workflow_URL`` from ``workflow_<workflow metadata>``.
399 """
400
401 # NOTE: placeholder for task metadata (here for documentation reasons)
402 TaskMeta = '<task metadata>'
403 """Any task metadata defined in
404 :cylc:conf:`flow.cylc[runtime][<namespace>][meta]` can be used e.g:
405
406 ``%(title)s``
407 Task title
408 ``%(URL)s``
409 Task URL
410 ``%(importance)s``
411 Example custom task metadata
412 """
413
414 # NOTE: placeholder for workflow metadata (here for documentation reasons)
415 WorkflowMeta = 'workflow_<workflow metadata>'
416 """Any workflow metadata defined in
417 :cylc:conf:`flow.cylc[meta]` can be used with the ``workflow_``
418 e.g. prefix:
419
420 ``%(workflow_title)s``
421 Workflow title
422 ``%(workflow_URL)s``
423 Workflow URL.
424 ``%(workflow_rating)s``
425 Example custom workflow metadata.
426 """
427
428
429 def get_event_handler_data(task_cfg, workflow_cfg):
430 """Extract event handler data from workflow and task metadata."""
431 handler_data = {}
432 # task metadata
433 for key, value in task_cfg['meta'].items():
434 if key == "URL":
435 handler_data[EventData.TaskURL.value] = quote(value)
436 handler_data[key] = quote(value)
437 # workflow metadata
438 for key, value in workflow_cfg['meta'].items():
439 if key == "URL":
440 handler_data[EventData.WorkflowURL.value] = quote(value)
441 handler_data["workflow_" + key] = quote(value)
442 return handler_data
443
444
445 class TaskEventsManager():
446 """Task events manager.
447
448 This class does the following:
449 * Manage task messages (received or otherwise).
450 * Set up task (submission) retries on job (submission) failures.
451 * Generate and manage task event handlers.
452 """
453 EVENT_FAILED = TASK_OUTPUT_FAILED
454 EVENT_LATE = "late"
455 EVENT_RETRY = "retry"
456 EVENT_STARTED = TASK_OUTPUT_STARTED
457 EVENT_SUBMITTED = TASK_OUTPUT_SUBMITTED
458 EVENT_EXPIRED = TASK_OUTPUT_EXPIRED
459 EVENT_SUBMIT_FAILED = "submission failed"
460 EVENT_SUBMIT_RETRY = "submission retry"
461 EVENT_SUBMIT_TIMEOUT = "submission timeout"
462 EVENT_EXEC_TIMEOUT = "execution timeout"
463 EVENT_SUCCEEDED = TASK_OUTPUT_SUCCEEDED
464 NON_UNIQUE_EVENTS = ('warning', 'critical', 'custom')
465 STD_EVENTS = [
466 EVENT_SUBMITTED,
467 EVENT_SUBMIT_TIMEOUT,
468 EVENT_SUBMIT_RETRY,
469 EVENT_SUBMIT_FAILED,
470 EVENT_STARTED,
471 EVENT_EXEC_TIMEOUT,
472 EVENT_RETRY,
473 EVENT_SUCCEEDED,
474 EVENT_FAILED,
475 EVENT_LATE,
476 EVENT_EXPIRED,
477 *NON_UNIQUE_EVENTS,
478 ]
479
480 HANDLER_CUSTOM = "event-handler"
481 HANDLER_MAIL = "event-mail"
482 JOB_FAILED = "job failed"
483 HANDLER_JOB_LOGS_RETRIEVE = "job-logs-retrieve"
484 FLAG_INTERNAL = "(internal)"
485 FLAG_RECEIVED = "(received)"
486 FLAG_RECEIVED_IGNORED = "(received-ignored)"
487 FLAG_POLLED = "(polled)"
488 FLAG_POLLED_IGNORED = "(polled-ignored)"
489 KEY_EXECUTE_TIME_LIMIT = 'execution_time_limit'
490 JOB_SUBMIT_SUCCESS_FLAG = 0
491 JOB_SUBMIT_FAIL_FLAG = 1
492 JOB_LOGS_RETRIEVAL_EVENTS = {
493 EVENT_FAILED,
494 EVENT_RETRY,
495 EVENT_SUCCEEDED
496 }
497
498 workflow_cfg: Dict[str, Any]
499 uuid_str: str
500 # To be set by the task pool:
501 spawn_func: Callable[['TaskProxy', str], Any]
502
503 mail_interval: float = 0
504 mail_smtp: Optional[str] = None
505 mail_footer: Optional[str] = None
506
507 def __init__(
508 self, workflow, proc_pool, workflow_db_mgr, broadcast_mgr,
509 xtrigger_mgr, data_store_mgr, timestamp, bad_hosts,
510 reset_inactivity_timer_func
511 ):
512 self.workflow = workflow
513 self.proc_pool = proc_pool
514 self.workflow_db_mgr: WorkflowDatabaseManager = workflow_db_mgr
515 self.broadcast_mgr: BroadcastMgr = broadcast_mgr
516 self.xtrigger_mgr: XtriggerManager = xtrigger_mgr
517 self.data_store_mgr: DataStoreMgr = data_store_mgr
518 self.next_mail_time = None
519 self.reset_inactivity_timer_func = reset_inactivity_timer_func
520 # NOTE: do not mutate directly
521 # use the {add,remove,unset_waiting}_event_timers methods
522 self._event_timers: Dict[EventKey, Any] = {}
523 # NOTE: flag for DB use
524 self.event_timers_updated = True
525 self.timestamp = timestamp
526 self.bad_hosts = bad_hosts
527
528 @staticmethod
529 def check_poll_time(itask, now=None):
530 """Set the next task execution/submission poll time.
531
532 If now is set, set the timer only if the previous delay is done.
533 Return the next delay.
534 """
535 if not itask.state(*TASK_STATUSES_ACTIVE):
536 # Reset, task not active
537 itask.timeout = None
538 itask.poll_timer = None
539 return None
540 ctx = (itask.submit_num, itask.state.status)
541 if itask.poll_timer is None or itask.poll_timer.ctx != ctx:
542 # Reset, timer no longer relevant
543 itask.timeout = None
544 itask.poll_timer = None
545 return None
546 if now is not None and not itask.poll_timer.is_delay_done(now):
547 return False
548 if itask.poll_timer.num is None:
549 itask.poll_timer.num = 0
550 itask.poll_timer.next(no_exhaust=True)
551 return True
552
553 def check_job_time(self, itask, now):
554 """Check/handle job timeout and poll timer"""
555 can_poll = self.check_poll_time(itask, now)
556 if itask.timeout is None or now <= itask.timeout:
557 return can_poll
558 # Timeout reached for task, emit event and reset itask.timeout
559 if itask.state(TASK_STATUS_RUNNING):
560 time_ref = itask.summary['started_time']
561 event = self.EVENT_EXEC_TIMEOUT
562 elif itask.state(TASK_STATUS_SUBMITTED):
563 time_ref = itask.summary['submitted_time']
564 event = self.EVENT_SUBMIT_TIMEOUT
565 msg = event
566 with suppress(TypeError, ValueError):
567 msg += ' after %s' % intvl_as_str(itask.timeout - time_ref)
568 itask.timeout = None # emit event only once
569 if msg and event:
570 LOG.warning(f"[{itask}] {msg}")
571 self.setup_event_handlers(itask, event, msg)
572 return True
573 else:
574 return can_poll
575
576 def _get_remote_conf(self, itask, key):
577 """Get deprecated "[remote]" items that default to platforms."""
578 overrides = self.broadcast_mgr.get_broadcast(itask.tokens)
579 SKEY = 'remote'
580 if SKEY not in overrides:
581 overrides[SKEY] = {}
582 return (
583 overrides[SKEY].get(key) or
584 itask.tdef.rtconfig[SKEY][key] or
585 itask.platform[key]
586 )
587
588 def _get_workflow_platforms_conf(self, itask: 'TaskProxy', key: str):
589 """Return top level [runtime] items that default to platforms."""
590 overrides = self.broadcast_mgr.get_broadcast(itask.tokens)
591 return (
592 overrides.get(key) or
593 itask.tdef.rtconfig[key] or
594 itask.platform[key]
595 )
596
597 def process_events(self, schd: 'Scheduler') -> None:
598 """Process task events that were created by "setup_event_handlers".
599 """
600 ctx_groups: dict = {}
601 now = time()
602 for id_key, timer in self._event_timers.copy().items():
603 if timer.is_waiting:
604 continue
605 # Set timer if timeout is None.
606 if not timer.is_timeout_set():
607 if timer.next() is None:
608 LOG.warning(
609 f"{id_key.tokens.relative_id}"
610 f" handler:{id_key.handler}"
611 f" for task event:{id_key.event} failed"
612 )
613 self.remove_event_timer(id_key)
614 continue
615 # Report retries and delayed 1st try
616 msg = None
617 if timer.num > 1:
618 msg = (
619 f"handler:{id_key.handler}"
620 f" for task event:{id_key.event} failed,"
621 f" retrying in {timer.delay_timeout_as_str()}"
622 )
623 elif timer.delay:
624 msg = (
625 f"handler:{id_key.handler}"
626 f" for task event:{id_key.event} will"
627 f" run after {timer.delay_timeout_as_str()}"
628 )
629 if msg:
630 LOG.debug("%s %s", id_key.tokens.relative_id, msg)
631 # Ready to run?
632 if not timer.is_delay_done() or (
633 # Avoid flooding user's mail box with mail notification.
634 # Group together as many notifications as possible within a
635 # given interval.
636 isinstance(timer.ctx, TaskEventMailContext) and
637 not schd.stop_mode and
638 self.next_mail_time is not None and
639 self.next_mail_time > now
640 ):
641 continue
642
643 timer.set_waiting()
644 if isinstance(timer.ctx, CustomTaskEventHandlerContext):
645 # Run custom event handlers on their own
646 self.proc_pool.put_command(
647 SubProcContext(
648 (
649 (id_key.handler, id_key.event),
650 id_key.tokens.submit_num,
651 ),
652 timer.ctx.cmd,
653 env=os.environ,
654 shell=True, # nosec
655 ), # designed to run user defined code
656 callback=self._custom_handler_callback,
657 callback_args=[schd, id_key]
658 )
659 else:
660 # Group together built-in event handlers, where possible
661 if timer.ctx not in ctx_groups:
662 ctx_groups[timer.ctx] = []
663 ctx_groups[timer.ctx].append(id_key)
664
665 next_mail_time = now + self.mail_interval
666 for ctx, id_keys in ctx_groups.items():
667 if isinstance(ctx, TaskEventMailContext):
668 # Set next_mail_time if any mail sent
669 self.next_mail_time = next_mail_time
670 self._process_event_email(schd, ctx, id_keys)
671 elif isinstance(ctx, TaskJobLogsRetrieveContext):
672 self._process_job_logs_retrieval(schd, ctx, id_keys)
673
674 def process_message(
675 self,
676 itask: 'TaskProxy',
677 severity: Union[str, int],
678 message: str,
679 event_time: Optional[str] = None,
680 flag: str = FLAG_INTERNAL,
681 submit_num: Optional[int] = None,
682 forced: bool = False
683 ) -> bool:
684 """Parse a task message and update task state.
685
686 Incoming, e.g. "succeeded at <TIME>", may be from task job or polling.
687
688 It is possible for the current state of a task to be inconsistent with
689 a message (whether internal, received or polled) e.g. due to a late
690 poll result, or a network outage, or manual state reset. To handle
691 this, if a message would take the task state backward, issue a poll to
692 confirm instead of changing state - then always believe the next
693 message. Note that the next message might not be the result of this
694 confirmation poll, in the unlikely event that a job emits a succession
695 of messages very quickly, but this is the best we can do without
696 somehow uniquely associating each poll with its result message.
697
698 Arguments:
699 itask:
700 The task proxy object relevant for the message.
701 severity:
702 Message severity, should be a recognised logging level.
703 message:
704 Message content.
705 event_time:
706 Event time stamp. Expect ISO8601 date time string.
707 If not specified, use current time.
708 flag:
709 If specified, can be:
710 FLAG_INTERNAL (default):
711 To indicate an internal message.
712 FLAG_RECEIVED:
713 To indicate a message received from a job or an
714 external source.
715 FLAG_POLLED:
716 To indicate a message resulted from a poll.
717 submit_num:
718 The submit number of the task relevant for the message.
719 If not specified, use latest submit number.
720 forced:
721 If this message is due to manual completion or not (cylc set)
722
723 Return:
724 False: in normal circumstances.
725 True: if polling is required to confirm a reversal of status.
726
727 """
728 # Useful debug but currently borks tests/f/cylc-message/02-multi.t:
729 # (It checks all log messages in debug mode, which is unhelpful).
730 # TODO: https://github.com/cylc/cylc-flow/issues/6857
731 # LOG.debug(f'Message {flag} for {itask}: "{message}"')
732
733 # Log messages
734 if event_time is None:
735 event_time = get_current_time_string()
736 if submit_num is None:
737 submit_num = itask.submit_num
738 if isinstance(severity, int):
739 severity = cast('str', getLevelName(severity))
740 lseverity = str(severity).lower()
741
742 # Any message represents activity.
743 self.reset_inactivity_timer_func()
744
745 if not self._process_message_check(
746 itask, severity, message, event_time, flag, submit_num, forced
747 ):
748 return False
749
750 if not forced:
751 # always update the workflow state summary for latest message
752 self.data_store_mgr.delta_job_msg(
753 itask.tokens.duplicate(job=str(submit_num)),
754 f'{message} {flag}' if flag == self.FLAG_POLLED
755 else message
756 )
757
758 # Satisfy my output, if possible, and spawn children.
759 # (first remove signal: failed/EXIT -> failed)
760
761 # Complete the corresponding task output, if there is one.
762 task_output, run_signal = split_run_signal(message)
763 job_aborted = (
764 run_signal is not None and task_output == ABORT_MESSAGE_PREFIX
765 )
766 if job_aborted:
767 task_output = TASK_OUTPUT_FAILED
768
769 output_completed: bool | None = False
770 if task_output not in {TASK_OUTPUT_SUBMIT_FAILED, TASK_OUTPUT_FAILED}:
771 output_completed = (
772 itask.state.outputs.set_message_complete(task_output, forced)
773 )
774 if output_completed:
775 self.data_store_mgr.delta_task_output(itask, task_output)
776
777 for implied in (
778 itask.state.outputs.get_incomplete_implied(task_output)
779 ):
780 # Set submitted and/or started first, if skipped.
781 # (whether by forced set, or missed message).
782 LOG.info(f"[{itask}] setting implied output: {implied}")
783 self.process_message(
784 itask, INFO, implied, event_time,
785 self.FLAG_INTERNAL, submit_num, forced
786 )
787
788 if message == self.EVENT_STARTED:
789 if flag == self.FLAG_RECEIVED and itask.state.is_gt(
790 TASK_STATUS_RUNNING
791 ):
792 # Already running.
793 return True
794 self._process_message_started(itask, event_time, forced)
795 self.spawn_children(itask, TASK_OUTPUT_STARTED, forced)
796
797 elif message == self.EVENT_SUCCEEDED:
798 self._process_message_succeeded(itask, event_time, forced)
799 self.spawn_children(itask, TASK_OUTPUT_SUCCEEDED, forced)
800
801 elif message == self.EVENT_EXPIRED:
802 self._process_message_expired(itask, event_time, forced)
803 self.spawn_children(itask, TASK_OUTPUT_EXPIRED, forced)
804
805 elif task_output == self.EVENT_FAILED:
806 if flag == self.FLAG_RECEIVED and itask.state.is_gt(
807 TASK_STATUS_FAILED
808 ):
809 # Already failed.
810 return True
811 msg = self.JOB_FAILED
812 if run_signal is not None:
813 # Task received signal or aborted.
814 self._db_events_insert(
815 itask,
816 'aborted' if job_aborted else 'signaled',
817 run_signal,
818 )
819 if job_aborted:
820 msg = run_signal
821 if self._process_message_failed(
822 itask,
823 event_time,
824 msg,
825 forced,
826 full_message=message,
827 run_signal=run_signal,
828 ):
829 self.spawn_children(itask, TASK_OUTPUT_FAILED, forced)
830
831 elif message == self.EVENT_SUBMIT_FAILED:
832 if flag == self.FLAG_RECEIVED and itask.state.is_gt(
833 TASK_STATUS_SUBMIT_FAILED
834 ):
835 # Already submit-failed
836 return True
837 if forced or self._process_message_submit_failed(
838 itask, event_time
839 ):
840 self.spawn_children(itask, TASK_OUTPUT_SUBMIT_FAILED, forced)
841
842 elif message == self.EVENT_SUBMITTED:
843 if flag == self.FLAG_RECEIVED and itask.state.is_gte(
844 TASK_STATUS_SUBMITTED
845 ):
846 # Already submitted.
847 return True
848 if not forced:
849 # `cylc set --out submitted` only spawns children; it doesn't
850 # affect task state or anything else.
851 self._process_message_submitted(itask, event_time)
852 self.spawn_children(itask, TASK_OUTPUT_SUBMITTED, forced)
853
854 elif run_signal is not None and task_output == VACATION_MESSAGE_PREFIX:
855 # Task job pre-empted into a vacation state
856 self._db_events_insert(itask, "vacated", message)
857 itask.set_summary_time('started') # unset
858 if TimerFlags.SUBMISSION_RETRY in itask.try_timers:
859 itask.try_timers[TimerFlags.SUBMISSION_RETRY].num = 0
860 itask.job_vacated = True
861 # Believe this and change state without polling (could poll?).
862 if itask.state_reset(TASK_STATUS_SUBMITTED, forced=forced):
863 itask.state_reset(is_queued=False, forced=forced)
864 self.data_store_mgr.delta_task_state(itask)
865 self._reset_job_timers(itask)
866 # We should really have a special 'vacated' handler, but given that
867 # this feature can only be used on the deprecated loadleveler
868 # system, we should probably aim to remove support for job vacation
869 # instead. Otherwise, we should have:
870 # self.setup_event_handlers(itask, 'vacated', message)
871
872 elif output_completed:
873 # Must be a message of a custom task output.
874 # No state change.
875 # Log completion of o (not needed for standard outputs)
876 trigger = itask.state.outputs.get_trigger(message)
877 LOG.info(f"[{itask}] completed output {trigger}")
878 self.setup_event_handlers(itask, trigger, message)
879 self.spawn_children(itask, task_output, forced)
880
881 else:
882 # Unhandled messages. These include:
883 # * general non-output/progress messages
884 # * poll messages that repeat previous results
885 # Note that all messages are logged already at the top.
886 # No state change.
887 LOG.debug(f"[{itask}] unhandled: {message}")
888 self._db_events_insert(
889 itask, (f"message {lseverity}"), message)
890
891 if lseverity in self.NON_UNIQUE_EVENTS:
892 itask.non_unique_events.update({lseverity: 1})
893 self.setup_event_handlers(itask, lseverity, message)
894
895 return False
896
897 def _process_message_check(
898 self,
899 itask: 'TaskProxy',
900 severity: str,
901 message: str,
902 event_time: str,
903 flag: str,
904 submit_num: int,
905 forced: bool = False
906 ) -> bool:
907 """Helper for `.process_message`.
908
909 See `.process_message` for argument list
910 Check whether to process/skip message.
911 Return True if `.process_message` should continue, False otherwise.
912 """
913 if itask.transient or forced:
914 return True
915
916 if self.timestamp:
917 timestamp = f" at {event_time}"
918 else:
919 timestamp = ""
920 if flag == self.FLAG_RECEIVED and submit_num != itask.submit_num:
921 # Ignore received messages from old jobs
922 LOG.warning(
923 f"[{itask}] "
924 f"{self.FLAG_RECEIVED_IGNORED}{message}{timestamp} "
925 f"for job({submit_num:02d}) != job({itask.submit_num:02d})"
926 )
927 return False
928
929 # Ignore non-expire messages if task is waiting with a retry lined up.
930 # Waiting tasks normally advance to a new state due to any message, but
931 # the retry implies late arrival after task failure (e.g. a delayed
932 # poll result). Task expire messages are internal, so excluded from
933 # this.
934 if (
935 itask.state(TASK_STATUS_WAITING)
936 and message != TASK_OUTPUT_EXPIRED
937 # Polling in live mode only:
938 and itask.run_mode == RunMode.LIVE
939 and (
940 (
941 # task has a submit-retry lined up
942 TimerFlags.SUBMISSION_RETRY in itask.try_timers
943 and itask.try_timers[
944 TimerFlags.SUBMISSION_RETRY].num > 0
945 )
946 or
947 (
948 # task has an execution-retry lined up
949 TimerFlags.EXECUTION_RETRY in itask.try_timers
950 and itask.try_timers[
951 TimerFlags.EXECUTION_RETRY].num > 0
952 )
953 )
954 ):
955 # Ignore messages if task has a retry lined up
956 # (caused by polling overlapping with task failure)
957 if flag == self.FLAG_RECEIVED:
958 LOG.warning(
959 f"[{itask}] "
960 f"{self.FLAG_RECEIVED_IGNORED}{message}{timestamp}"
961 )
962
963 else:
964 LOG.warning(
965 f"[{itask}] "
966 f"{self.FLAG_POLLED_IGNORED}{message}{timestamp}"
967 )
968 return False
969
970 severity_lvl: int = LOG_LEVELS.get(severity, INFO)
971 # Don't log submit/failure messages here:
972 if flag != self.FLAG_POLLED and message in {
973 self.EVENT_SUBMIT_FAILED, f'{FAIL_MESSAGE_PREFIX}/ERR'
974 }:
975 return True
976 # Demote log level to DEBUG if this is a message that duplicates what
977 # gets logged by itask state change anyway (and not manual poll)
978 if severity_lvl > DEBUG and flag != self.FLAG_POLLED and message in {
979 self.EVENT_SUBMITTED, self.EVENT_STARTED, self.EVENT_SUCCEEDED,
980 }:
981 severity_lvl = DEBUG
982 LOG.log(severity_lvl, f"[{itask}] {flag}{message}{timestamp}")
983 return True
984
985 def process_job_message(
986 self,
987 job_tokens: 'Tokens',
988 tdef: 'TaskDef',
989 message: str,
990 event_time: str,
991 ) -> bool:
992 """Process a job message only, without affecting its task.
993
994 E.g. for a task that is no longer in the pool because it was manually
995 set to completed.
996
997 Returns True if the message was handled, False otherwise.
998 """
999 tmp_itask = TaskProxy(
1000 job_tokens.workflow,
1001 tdef,
1002 get_point(job_tokens['cycle']),
1003 submit_num=job_tokens.submit_num,
1004 data_mode=True,
1005 transient=True,
1006 )
1007 ret = self.data_store_mgr.delta_job_msg(job_tokens, message)
1008 message_prefix, signal = split_run_signal(message)
1009 if message == TASK_OUTPUT_SUBMITTED:
1010 self._process_job_submitted(tmp_itask, event_time)
1011 elif message == TASK_OUTPUT_SUBMIT_FAILED:
1012 self._process_job_submit_failed(tmp_itask, event_time)
1013 elif message == TASK_OUTPUT_STARTED:
1014 self._process_job_started(tmp_itask, event_time)
1015 elif message == TASK_OUTPUT_SUCCEEDED:
1016 self._process_job_succeeded(tmp_itask, event_time)
1017 elif message_prefix in {FAIL_MESSAGE_PREFIX, ABORT_MESSAGE_PREFIX}:
1018 self._process_job_failed(tmp_itask, event_time, signal)
1019 else:
1020 return ret
1021 return True
1022
1023 def setup_event_handlers(self, itask, event, message):
1024 """Set up handlers for a task event."""
1025 if disable_task_event_handlers(itask):
1026 return
1027 msg = ""
1028 if message != f"job {event}":
1029 msg = message
1030 self._db_events_insert(itask, event, msg)
1031 self._setup_job_logs_retrieval(itask, event)
1032 self._setup_event_mail(itask, event, message)
1033 self._setup_custom_event_handlers(itask, event, message)
1034
1035 def _custom_handler_callback(
1036 self,
1037 ctx,
1038 schd: 'Scheduler',
1039 id_key: EventKey,
1040 ) -> None:
1041 """Callback when a custom event handler is done."""
1042 tokens = id_key.tokens
1043 log_task_job_activity(
1044 ctx,
1045 schd.workflow,
1046 tokens['cycle'],
1047 tokens['task'],
1048 tokens['job'],
1049 )
1050 if ctx.ret_code == 0:
1051 self.remove_event_timer(id_key)
1052 else:
1053 self.unset_waiting_event_timer(id_key)
1054
1055 def _db_events_insert(self, itask, event="", message=""):
1056 """Record an event to the DB."""
1057 self.workflow_db_mgr.put_insert_task_events(itask, {
1058 "time": get_current_time_string(),
1059 "event": event,
1060 "message": message})
1061
1062 def _process_event_email(
1063 self,
1064 schd: 'Scheduler',
1065 ctx: TaskEventMailContext,
1066 id_keys: List[EventKey],
1067 ) -> None:
1068 """Process event notification, by email."""
1069 if len(id_keys) == 1:
1070 id_key = id_keys[0]
1071 subject = (
1072 f'[{id_key.tokens.relative_id} {id_key.event}]'
1073 f' {schd.workflow}'
1074 )
1075 else:
1076 event_set = {id_key.event for id_key in id_keys}
1077 if len(event_set) == 1:
1078 # 1 event from n tasks
1079 subject = "[%d tasks %s] %s" % (
1080 len(id_keys), event_set.pop(), schd.workflow)
1081 else:
1082 # n events from n tasks
1083 subject = "[%d task events] %s" % (
1084 len(id_keys), schd.workflow)
1085
1086 # STDIN for mail, tasks
1087 stdin_str = ""
1088 for id_key in sorted(id_keys):
1089 stdin_str += f'job: {id_key.tokens.relative_id}\n'
1090 stdin_str += f'event: {id_key.event}\n'
1091 stdin_str += f'message: {id_key.message}\n\n'
1092
1093 # STDIN for mail, event info + workflow detail
1094 stdin_str += "\n"
1095 for key, value in (
1096 (WorkflowEventData.Workflow.value, schd.workflow),
1097 (WorkflowEventData.Host.value, schd.host),
1098 (WorkflowEventData.Port.value, schd.server.port),
1099 (WorkflowEventData.Owner.value, schd.owner),
1100 ):
1101 stdin_str += '%s: %s\n' % (key, value)
1102
1103 if self.mail_footer:
1104 stdin_str += process_mail_footer(
1105 self.mail_footer,
1106 get_workflow_template_variables(
1107 schd,
1108 id_keys[-1].event,
1109 id_keys[-1].message,
1110 ),
1111 )
1112 self._send_mail(ctx, subject, stdin_str, id_keys, schd)
1113
1114 def _send_mail(
1115 self,
1116 ctx: TaskEventMailContext,
1117 subject: str,
1118 stdin_str: str,
1119 id_keys: List[EventKey],
1120 schd: 'Scheduler',
1121 ) -> None:
1122 cmd = construct_mail_cmd(
1123 subject, from_address=ctx.mail_from, to_address=ctx.mail_to
1124 )
1125 # SMTP server
1126 env = dict(os.environ)
1127 if self.mail_smtp:
1128 env["smtp"] = self.mail_smtp
1129 self.proc_pool.put_command(
1130 SubProcContext(
1131 ctx, cmd, env=env, stdin_str=stdin_str, id_keys=id_keys,
1132 ),
1133 callback=self._event_email_callback, callback_args=[schd])
1134
1135 def _event_email_callback(self, proc_ctx, schd) -> None:
1136 """Call back when email notification command exits."""
1137 id_key: EventKey
1138 for id_key in proc_ctx.cmd_kwargs["id_keys"]:
1139 try:
1140 if proc_ctx.ret_code == 0:
1141 self.remove_event_timer(id_key)
1142 log_ctx = SubProcContext(
1143 (
1144 (id_key.handler, id_key.event),
1145 id_key.tokens['job']
1146 ),
1147 None,
1148 )
1149 log_ctx.ret_code = 0
1150 log_task_job_activity(
1151 log_ctx,
1152 schd.workflow,
1153 id_key.tokens['cycle'],
1154 id_key.tokens['task'],
1155 id_key.tokens['job'],
1156 )
1157 else:
1158 self.unset_waiting_event_timer(id_key)
1159 except KeyError as exc:
1160 LOG.exception(exc)
1161
1162 def _get_events_conf(
1163 self, itask: 'TaskProxy', key: str, default: Any = None
1164 ) -> Any:
1165 """Return an events setting from workflow then global configuration."""
1166 for getter in (
1167 self.broadcast_mgr.get_broadcast(itask.tokens).get("events"),
1168 itask.tdef.rtconfig["mail"],
1169 itask.tdef.rtconfig["events"],
1170 self.workflow_cfg.get("scheduler", {}).get("mail", {}),
1171 glbl_cfg().get(["scheduler", "mail"]),
1172 glbl_cfg().get()["task events"],
1173 ):
1174 try:
1175 value = getter.get(key) # type: ignore[union-attr]
1176 except (AttributeError, ItemNotFoundError, KeyError):
1177 pass
1178 else:
1179 if value is not None:
1180 return value
1181 return default
1182
1183 def _process_job_logs_retrieval(
1184 self,
1185 schd: 'Scheduler',
1186 ctx: TaskJobLogsRetrieveContext,
1187 id_keys: List[EventKey],
1188 ) -> None:
1189 """Process retrieval of task job logs from remote user@host."""
1190 # get a host to run retrieval on
1191 try:
1192 platform = get_platform(ctx.platform_name)
1193 host = get_host_from_platform(platform, bad_hosts=self.bad_hosts)
1194 except NoHostsError:
1195 # All of the platforms hosts have been found to be uncontactable.
1196 # Reset the bad hosts to allow retrieval retry to take place.
1197 self.bad_hosts -= set(platform['hosts'])
1198 try:
1199 # Get a new host and try again.
1200 host = get_host_from_platform(
1201 platform,
1202 bad_hosts=self.bad_hosts
1203 )
1204 except NoHostsError:
1205 # We really can't get a host to try on e.g. no hosts
1206 # configured (shouldn't happen). Nothing more we can do here,
1207 # move onto the next submission retry.
1208 for id_key in id_keys:
1209 self.unset_waiting_event_timer(id_key)
1210 return
1211 except PlatformLookupError:
1212 log_platform_event(
1213 'Unable to retrieve job logs.',
1214 {'name': ctx.platform_name},
1215 level='warning',
1216 )
1217 return
1218
1219 # construct the retrieval command
1220 ssh_str = str(platform["ssh command"])
1221 rsync_str = str(platform["retrieve job logs command"])
1222 cmd = shlex.split(rsync_str) + ["--rsh=" + ssh_str]
1223 if LOG.isEnabledFor(DEBUG):
1224 cmd.append("-v")
1225 if ctx.max_size:
1226 cmd.append("--max-size=%s" % (ctx.max_size,))
1227 # Includes and excludes
1228 includes: Set[str] = set()
1229 for id_key in id_keys:
1230 # Include relevant directories, all levels needed
1231 path = Path(os.sep, id_key.tokens.relative_id, '**')
1232 includes.update(
1233 (str(p) for p in [path, *path.parents][:-1])
1234 )
1235 cmd += ["--include=%s" % (include) for include in sorted(includes)]
1236 cmd.append("--exclude=/**") # exclude everything else
1237 # Remote source
1238 cmd.append("%s:%s/" % (
1239 host,
1240 get_remote_workflow_run_job_dir(
1241 schd.workflow).replace('$HOME/', ''))
1242 )
1243 # Local target
1244 cmd.append(get_workflow_run_job_dir(schd.workflow) + "/")
1245
1246 # schedule command
1247 self.proc_pool.put_command(
1248 SubProcContext(
1249 ctx, cmd, env=dict(os.environ), id_keys=id_keys, host=host
1250 ),
1251 bad_hosts=self.bad_hosts,
1252 callback=self._job_logs_retrieval_callback,
1253 callback_args=[schd],
1254 callback_255=self._job_logs_retrieval_callback_255
1255 )
1256
1257 def _job_logs_retrieval_callback_255(self, proc_ctx, schd) -> None:
1258 """Call back when log job retrieval fails with a 255 error."""
1259 self.bad_hosts.add(proc_ctx.host)
1260 for _ in proc_ctx.cmd_kwargs["id_keys"]:
1261 for key in proc_ctx.cmd_kwargs['id_keys']:
1262 timer = self._event_timers[key]
1263 timer.reset()
1264
1265 def _job_logs_retrieval_callback(self, proc_ctx, schd) -> None:
1266 """Call back when log job retrieval completes."""
1267 if (
1268 (proc_ctx.ret_code and LOG.isEnabledFor(DEBUG))
1269 or (proc_ctx.ret_code and proc_ctx.ret_code != 255)
1270 ):
1271 LOG.error(proc_ctx)
1272 id_key: EventKey
1273 for id_key in proc_ctx.cmd_kwargs["id_keys"]:
1274 try:
1275 # All completed jobs are expected to have a "job.out".
1276 fnames = [JOB_LOG_OUT]
1277 with suppress(TypeError):
1278 if id_key.event not in 'succeeded':
1279 fnames.append(JOB_LOG_ERR)
1280 fname_oks = {}
1281 for fname in fnames:
1282 fname_oks[fname] = os.path.exists(get_task_job_log(
1283 schd.workflow,
1284 id_key.tokens['cycle'],
1285 id_key.tokens['task'],
1286 id_key.tokens['job'],
1287 fname,
1288 ))
1289 # All expected paths must exist to record a good attempt
1290 log_ctx = SubProcContext(
1291 (
1292 (id_key.handler, id_key.event),
1293 id_key.tokens.submit_num
1294 ),
1295 None,
1296 )
1297 if all(fname_oks.values()):
1298 log_ctx.ret_code = 0
1299 self.remove_event_timer(id_key)
1300 else:
1301 log_ctx.ret_code = 1
1302 log_ctx.err = "File(s) not retrieved:"
1303 for fname, exist_ok in sorted(fname_oks.items()):
1304 if not exist_ok:
1305 log_ctx.err += " %s" % fname
1306 self.unset_waiting_event_timer(id_key)
1307 log_task_job_activity(
1308 log_ctx,
1309 schd.workflow,
1310 id_key.tokens['cycle'],
1311 id_key.tokens['task'],
1312 id_key.tokens['job'],
1313 )
1314 except KeyError as exc:
1315 LOG.exception(exc)
1316
1317 def _retry_task(self, itask, wallclock_time, submit_retry=False):
1318 """Retry a task.
1319
1320 Args:
1321 itask (cylc.flow.task_proxy.TaskProxy):
1322 The task to retry.
1323 wallclock_time (float):
1324 Unix time to schedule the retry for.
1325 submit_retry (bool):
1326 False if this is an execution retry.
1327 True if this is a submission retry.
1328
1329 """
1330 # derive an xtrigger label for this retry
1331 label = '_'.join((
1332 '_cylc',
1333 'submit_retry' if submit_retry else 'retry',
1334 itask.identity.replace('/', '_')
1335 ))
1336 kwargs = {
1337 'trigger_time': wallclock_time
1338 }
1339
1340 # if this isn't the first retry the xtrigger will already exist
1341 if label in itask.state.xtriggers:
1342 # retry xtrigger already exists from a previous retry, modify it
1343 self.xtrigger_mgr.mutate_trig(label, kwargs)
1344 itask.state.xtriggers[label] = False
1345 else:
1346 # create a new retry xtrigger
1347 xtrig = SubFuncContext(
1348 label,
1349 'wall_clock',
1350 [],
1351 kwargs
1352 )
1353 self.xtrigger_mgr.xtriggers.add_trig(
1354 label,
1355 xtrig,
1356 os.getenv("CYLC_WORKFLOW_RUN_DIR")
1357 )
1358 itask.state.add_xtrigger(label)
1359
1360 # add the retry xtrigger to the data store
1361 sig = self.xtrigger_mgr.get_xtrig_ctx(itask, label).get_signature()
1362 (
1363 self.data_store_mgr.xtrigger_tasks
1364 .setdefault(sig, set())
1365 .add((itask.tokens.id, label))
1366 )
1367 self.data_store_mgr.delta_xtrigger(sig, False)
1368
1369 if itask.state_reset(TASK_STATUS_WAITING):
1370 self.data_store_mgr.delta_task_state(itask)
1371
1372 def _process_message_failed(
1373 self,
1374 itask: 'TaskProxy',
1375 event_time: str,
1376 message: str,
1377 forced: bool,
1378 full_message: str,
1379 run_signal: str | None = None,
1380 ) -> bool:
1381 """Helper for process_message, handle a failed message.
1382
1383 Return True if no retries (hence go to the failed state).
1384
1385 Args:
1386 full_message:
1387 If we have retries lined up we still tell users what
1388 happened to cause the this attempt to fail.
1389 """
1390 no_retries = False
1391 if not forced:
1392 self._process_job_failed(itask, event_time, run_signal)
1393 LOG.error(f'[{itask}] {full_message or self.EVENT_FAILED}')
1394 if (
1395 forced
1396 or TimerFlags.EXECUTION_RETRY not in itask.try_timers
1397 or itask.try_timers[TimerFlags.EXECUTION_RETRY].next() is None
1398 ):
1399 # No retry lined up: definitive failure.
1400 no_retries = True
1401 if itask.state_reset(TASK_STATUS_FAILED, forced=forced):
1402 if itask.removed:
1403 # Need to update DB as task not include in pool update
1404 self.workflow_db_mgr.put_update_task_state(itask)
1405 else:
1406 self.setup_event_handlers(
1407 itask, self.EVENT_FAILED, message
1408 )
1409 itask.state.outputs.set_message_complete(TASK_OUTPUT_FAILED)
1410 self.data_store_mgr.delta_task_output(
1411 itask, TASK_OUTPUT_FAILED)
1412 self.data_store_mgr.delta_task_state(itask)
1413 else:
1414 # There is an execution retry lined up.
1415 timer = itask.try_timers[TimerFlags.EXECUTION_RETRY]
1416 self._retry_task(itask, timer.timeout)
1417 delay_msg = f"retrying in {timer.delay_timeout_as_str()}"
1418 LOG.warning(f'[{itask}] - {delay_msg}')
1419 msg = f"{self.JOB_FAILED}, {delay_msg}"
1420 self.setup_event_handlers(itask, self.EVENT_RETRY, msg)
1421 self._reset_job_timers(itask)
1422 return no_retries
1423
1424 def _process_job_failed(
1425 self,
1426 itask: 'TaskProxy',
1427 event_time: str,
1428 run_signal: str | None = None,
1429 ):
1430 itask.set_summary_time('finished', event_time)
1431 self.data_store_mgr.delta_job_time(itask, 'finished', event_time)
1432 self.data_store_mgr.delta_job_state(itask, TASK_STATUS_FAILED)
1433 db_update = {
1434 'run_status': 1,
1435 'time_run_exit': event_time,
1436 }
1437 if run_signal:
1438 db_update['run_signal'] = run_signal
1439 self.workflow_db_mgr.put_update_task_jobs(itask, db_update)
1440
1441 def _process_message_started(
1442 self, itask: 'TaskProxy', event_time: str, forced: bool
1443 ):
1444 """Helper for process_message, handle a started message."""
1445 if not forced:
1446 self._process_job_started(itask, event_time)
1447 if itask.job_vacated:
1448 itask.job_vacated = False
1449 LOG.info(f"[{itask}] Vacated job restarted")
1450 if itask.state_reset(TASK_STATUS_RUNNING, forced=forced):
1451 self.setup_event_handlers(
1452 itask, self.EVENT_STARTED, f'job {self.EVENT_STARTED}')
1453 self.data_store_mgr.delta_task_state(itask)
1454 self._reset_job_timers(itask)
1455
1456 # submission was successful so reset submission try number
1457 if TimerFlags.SUBMISSION_RETRY in itask.try_timers:
1458 itask.try_timers[TimerFlags.SUBMISSION_RETRY].num = 0
1459
1460 def _process_job_started(self, itask: 'TaskProxy', event_time: str):
1461 itask.set_summary_time('started', event_time)
1462 self.data_store_mgr.delta_job_time(itask, 'started', event_time)
1463 self.data_store_mgr.delta_job_state(itask, TASK_STATUS_RUNNING)
1464 self.workflow_db_mgr.put_update_task_jobs(itask, {
1465 "time_run": event_time,
1466 })
1467
1468 def _process_message_expired(self, itask, event_time, forced):
1469 """Helper for process_message, handle task expiry."""
1470 if not itask.state_reset(TASK_STATUS_EXPIRED, forced=forced):
1471 return
1472 self.data_store_mgr.delta_task_state(itask)
1473 self.setup_event_handlers(
1474 itask,
1475 self.EVENT_EXPIRED,
1476 "Task expired: will not submit job."
1477 )
1478
1479 def _process_message_succeeded(
1480 self, itask: 'TaskProxy', event_time: str, forced: bool
1481 ):
1482 """Helper for process_message, handle a succeeded message."""
1483 if not forced:
1484 self._process_job_succeeded(itask, event_time)
1485 # Update mean elapsed time only on task succeeded,
1486 # (Don't record skip mode / `cylc set` run times)
1487 if (
1488 itask.summary['started_time'] is not None
1489 and not (forced or itask.run_mode == RunMode.SKIP)
1490 ):
1491 itask.tdef.elapsed_times.append(
1492 itask.summary['finished_time'] - itask.summary['started_time']
1493 )
1494 if itask.state_reset(TASK_STATUS_SUCCEEDED, forced=forced):
1495 self.setup_event_handlers(
1496 itask, self.EVENT_SUCCEEDED, f"job {self.EVENT_SUCCEEDED}")
1497 self.data_store_mgr.delta_task_state(itask)
1498 self._reset_job_timers(itask)
1499
1500 def _process_job_succeeded(self, itask: 'TaskProxy', event_time: str):
1501 itask.set_summary_time('finished', event_time)
1502 self.data_store_mgr.delta_job_time(itask, 'finished', event_time)
1503 self.data_store_mgr.delta_job_state(itask, TASK_STATUS_SUCCEEDED)
1504 self.workflow_db_mgr.put_update_task_jobs(itask, {
1505 "run_status": 0,
1506 "time_run_exit": event_time,
1507 })
1508
1509 def _process_message_submit_failed(
1510 self, itask: 'TaskProxy', event_time: str
1511 ) -> bool:
1512 """Helper for process_message, handle a submit-failed message.
1513
1514 Return True if no retries (hence go to the submit-failed state).
1515 """
1516 no_retries = False
1517 LOG.error(f"[{itask}] {self.EVENT_SUBMIT_FAILED}")
1518 if (
1519 TimerFlags.SUBMISSION_RETRY not in itask.try_timers
1520 or itask.try_timers[TimerFlags.SUBMISSION_RETRY].next() is None
1521 ):
1522 # No submission retry lined up: definitive failure.
1523 # See github #476.
1524 no_retries = True
1525 if itask.state_reset(TASK_STATUS_SUBMIT_FAILED):
1526 if itask.removed:
1527 # Need to update DB as task not include in pool update
1528 self.workflow_db_mgr.put_update_task_state(itask)
1529 else:
1530 self.setup_event_handlers(
1531 itask, self.EVENT_SUBMIT_FAILED,
1532 f'job {self.EVENT_SUBMIT_FAILED}'
1533 )
1534 itask.state.outputs.set_message_complete(
1535 TASK_OUTPUT_SUBMIT_FAILED
1536 )
1537 self.data_store_mgr.delta_task_output(
1538 itask, TASK_OUTPUT_SUBMIT_FAILED)
1539 self.data_store_mgr.delta_task_state(itask)
1540 else:
1541 # There is a submission retry lined up.
1542 timer = itask.try_timers[TimerFlags.SUBMISSION_RETRY]
1543 self._retry_task(itask, timer.timeout, submit_retry=True)
1544 delay_msg = f"retrying in {timer.delay_timeout_as_str()}"
1545 LOG.warning(f"[{itask}] {delay_msg}")
1546 msg = f"job {self.EVENT_SUBMIT_FAILED}, {delay_msg}"
1547 self.setup_event_handlers(itask, self.EVENT_SUBMIT_RETRY, msg)
1548
1549 self._process_job_submit_failed(itask, event_time)
1550 self._reset_job_timers(itask)
1551
1552 return no_retries
1553
1554 def _process_job_submit_failed(self, itask: 'TaskProxy', event_time: str):
1555 # Register newly submit-failed job with the database and datastore.
1556 self._insert_task_job(itask, event_time, self.JOB_SUBMIT_FAIL_FLAG)
1557 self.data_store_mgr.delta_job_state(itask, TASK_STATUS_SUBMIT_FAILED)
1558 self.data_store_mgr.delta_job_time(itask, 'submitted', event_time)
1559
1560 def _process_message_submitted(
1561 self, itask: 'TaskProxy', event_time: str
1562 ) -> None:
1563 """Helper for process_message, handle a submit-succeeded message."""
1564 with suppress(KeyError):
1565 LOG.info(
1566 f"[{itask}] submitted to "
1567 f"{itask.summary['platforms_used'][itask.submit_num]}:"
1568 f"{itask.summary['job_runner_name']}"
1569 f"[{itask.summary['submit_method_id']}]"
1570 )
1571
1572 itask.set_summary_time('submitted', event_time)
1573 # Unset started and finished times in case of resubmission.
1574 itask.set_summary_time('started')
1575 itask.set_summary_time('finished')
1576 if itask.state.status == TASK_STATUS_PREPARING:
1577 # The job started message can (rarely) come in before the
1578 # submit command returns - in which case do not go back to
1579 # 'submitted'.
1580 if itask.state_reset(TASK_STATUS_SUBMITTED):
1581 itask.state_reset(is_queued=False)
1582 self.setup_event_handlers(
1583 itask,
1584 self.EVENT_SUBMITTED,
1585 f'job {self.EVENT_SUBMITTED}',
1586 )
1587 self.data_store_mgr.delta_task_state(itask)
1588 self._reset_job_timers(itask)
1589
1590 # Do after itask has changed state
1591 self._process_job_submitted(itask, event_time)
1592
1593 def _process_job_submitted(self, itask: 'TaskProxy', event_time: str):
1594 # Register the newly submitted job with the database and datastore.
1595 self._insert_task_job(itask, event_time, self.JOB_SUBMIT_SUCCESS_FLAG)
1596 self.data_store_mgr.delta_job_time(itask, 'submitted', event_time)
1597 self.data_store_mgr.delta_job_state(itask, TASK_STATUS_SUBMITTED)
1598 # update the job ID in the job proxy (it only
1599 # comes in via the submission message).
1600 self.data_store_mgr.delta_job_attr(
1601 itask, 'job_id', itask.summary['submit_method_id']
1602 )
1603
1604 def _insert_task_job(
1605 self,
1606 itask: 'TaskProxy',
1607 event_time: str,
1608 submit_status: int,
1609 ):
1610 """Insert a new job proxy into the datastore; update existing entry
1611 in the DB.
1612
1613 Args:
1614 itask: create a job proxy for this task proxy
1615 event_time: time of job submission
1616 submit_status: 0 (success), 1 (fail)
1617
1618 """
1619 # itask.jobs appends for automatic retries (which reuse the same task
1620 # proxy) but a retriggered task that was not already in the pool will
1621 # not see previous submissions (so can't use itask.jobs[submit_num-1]).
1622 if itask.run_mode and itask.run_mode.value in JOBLESS_MODES:
1623 job_conf = {"submit_num": itask.submit_num}
1624 else:
1625 try:
1626 job_conf = itask.jobs[-1]
1627 except IndexError:
1628 # we do not have access to the job config (e.g. Scheduler
1629 # crashed) - https://github.com/cylc/cylc-flow/pull/6326
1630 LOG.warning(
1631 'Could not find the job configuration for '
1632 f'"{itask.job_tokens.relative_id}".'
1633 )
1634 itask.jobs.append({"submit_num": itask.submit_num})
1635 job_conf = itask.jobs[-1]
1636
1637 # Job status should be task status unless task is awaiting a
1638 # retry:
1639 if itask.state.status == TASK_STATUS_WAITING and itask.try_timers:
1640 job_status = (
1641 TASK_STATUS_SUBMITTED if submit_status == 0
1642 else TASK_STATUS_SUBMIT_FAILED
1643 )
1644 else:
1645 job_status = itask.state.status
1646
1647 # insert job into data store
1648 self.data_store_mgr.insert_job(
1649 itask,
1650 job_status,
1651 {
1652 **job_conf,
1653 # NOTE: the platform name may have changed since task
1654 # preparation started due to intelligent host (and or
1655 # platform) selection
1656 'platform': itask.platform,
1657 },
1658 )
1659 # update job in database
1660 # NOTE: the job must be added to the DB earlier so that Cylc can
1661 # reconnect with job submissions if the scheduler is restarted
1662 self.workflow_db_mgr.put_update_task_jobs(
1663 itask,
1664 {
1665 'submit_status': submit_status,
1666 'time_submit_exit': event_time,
1667 'job_id': itask.summary.get('submit_method_id'),
1668 # NOTE: the platform name may have changed since task
1669 # preparation started due to intelligent host (and or
1670 # platform) selection
1671 'platform_name': itask.platform['name'],
1672 },
1673 )
1674
1675 def _setup_job_logs_retrieval(self, itask, event) -> None:
1676 """Set up remote job logs retrieval.
1677
1678 For a task with a job completion event, i.e. succeeded, failed,
1679 (execution) retry.
1680 """
1681 if (
1682 event not in self.JOB_LOGS_RETRIEVAL_EVENTS
1683 or not is_remote_platform(itask.platform)
1684 or not self._get_remote_conf(itask, "retrieve job logs")
1685 ):
1686 # event does not need to be processed
1687 return
1688
1689 id_key = EventKey(
1690 self.HANDLER_JOB_LOGS_RETRIEVE,
1691 event,
1692 event,
1693 itask.job_tokens,
1694 )
1695 if id_key in self._event_timers:
1696 # event already being processed
1697 return
1698
1699 retry_delays = self._get_remote_conf(
1700 itask, "retrieve job logs retry delays")
1701 if not retry_delays:
1702 retry_delays = [0]
1703 self.add_event_timer(
1704 id_key,
1705 TaskActionTimer(
1706 TaskJobLogsRetrieveContext(
1707 key=self.HANDLER_JOB_LOGS_RETRIEVE,
1708 platform_name=itask.platform['name'],
1709 max_size=self._get_remote_conf(
1710 itask, "retrieve job logs max size"
1711 ),
1712 ),
1713 retry_delays
1714 )
1715 )
1716
1717 def _setup_event_mail(
1718 self,
1719 itask: 'TaskProxy',
1720 event: str,
1721 message: str,
1722 ) -> None:
1723 """Set up task event notification, by email."""
1724 if event not in self._get_events_conf(itask, "mail events", []):
1725 # event does not need to be processed
1726 return
1727
1728 id_key = EventKey(
1729 self.HANDLER_MAIL,
1730 get_event_id(event, itask),
1731 message,
1732 itask.job_tokens,
1733 )
1734 if id_key in self._event_timers:
1735 # event already being processed
1736 return
1737
1738 self.add_event_timer(
1739 id_key,
1740 TaskActionTimer(
1741 TaskEventMailContext(
1742 key=self.HANDLER_MAIL,
1743 mail_from=self._get_events_conf(
1744 itask, "from", f"notifications@{get_host()}"
1745 ),
1746 mail_to=self._get_events_conf(itask, "to", get_user())
1747 )
1748 )
1749 )
1750
1751 def _setup_custom_event_handlers(
1752 self,
1753 itask: 'TaskProxy',
1754 event: str,
1755 message: str,
1756 ) -> None:
1757 """Set up custom task event handlers."""
1758 handlers = self._get_events_conf(itask, f'{event} handlers')
1759 if (
1760 handlers is None
1761 and event in self._get_events_conf(itask, 'handler events', [])
1762 ):
1763 handlers = self._get_events_conf(itask, 'handlers')
1764 if handlers is None:
1765 return
1766 retry_delays = self._get_events_conf(
1767 itask,
1768 'handler retry delays'
1769 )
1770 if not retry_delays:
1771 retry_delays = [0]
1772 # There can be multiple custom event handlers
1773 for i, handler in enumerate(handlers):
1774 id_key = EventKey(
1775 f'{self.HANDLER_CUSTOM}-{i:02d}',
1776 get_event_id(event, itask),
1777 message,
1778 itask.job_tokens,
1779 )
1780
1781 if id_key in self._event_timers:
1782 continue
1783 # Note: user@host may not always be set for a submit number, e.g.
1784 # on late event or if host select command fails. Use null string to
1785 # prevent issues in this case.
1786 platform_name = itask.summary['platforms_used'].get(
1787 itask.submit_num, ''
1788 )
1789 # Custom event handler can be a command template string
1790 # or a command that takes 4 arguments (classic interface)
1791 # Note quote() fails on None, need str(None).
1792
1793 template_variables = self._get_handler_template_variables(
1794 itask,
1795 event,
1796 message,
1797 platform_name,
1798 )
1799 key1 = (id_key.handler, id_key.event)
1800 try:
1801 cmd = handler % template_variables
1802 except KeyError as exc:
1803 LOG.error(
1804 f'{id_key.tokens.relative_id}'
1805 f" {key1} bad template: {exc}")
1806 continue
1807
1808 if cmd == handler:
1809 # Nothing substituted, assume classic interface
1810 cmd = (f"{handler} '{event}' '{self.workflow}' "
1811 f"'{itask.identity}' '{message}'")
1812 LOG.debug(f"[{itask}] Queueing {event} handler: {cmd}")
1813 self.add_event_timer(
1814 id_key,
1815 TaskActionTimer(
1816 CustomTaskEventHandlerContext(key=key1, cmd=cmd),
1817 retry_delays
1818 )
1819 )
1820
1821 def _get_handler_template_variables(
1822 self,
1823 itask,
1824 event,
1825 message,
1826 platform_name,
1827 ):
1828 # fmt: off
1829 return {
1830 EventData.JobID.value:
1831 quote(str(itask.summary['submit_method_id'])),
1832 EventData.JobRunnerName.value:
1833 quote(str(itask.summary['job_runner_name'])),
1834 EventData.CyclePoint.value:
1835 quote(str(itask.point)),
1836 EventData.Event.value:
1837 quote(event),
1838 EventData.FinishTime.value:
1839 quote(str(itask.summary['finished_time_string'])),
1840 EventData.ID.value:
1841 quote(itask.identity),
1842 EventData.Message.value:
1843 quote(message),
1844 EventData.TaskName.value:
1845 quote(itask.tdef.name),
1846 EventData.PlatformName.value:
1847 quote(platform_name),
1848 EventData.UserAtHost.value:
1849 quote(platform_name),
1850 EventData.StartTime.value:
1851 quote(str(itask.summary['started_time_string'])),
1852 EventData.SubmitNum.value:
1853 itask.submit_num,
1854 EventData.SubmitTime.value:
1855 quote(str(itask.summary['submitted_time_string'])),
1856 EventData.Workflow.value:
1857 quote(self.workflow),
1858 EventData.UUID.value:
1859 quote(self.uuid_str),
1860 # BACK COMPAT: Suite, SuiteUUID deprecated
1861 # url:
1862 # https://github.com/cylc/cylc-flow/pull/4174
1863 # from:
1864 # Cylc 8
1865 # remove at:
1866 # Cylc 8.x
1867 EventData.Suite.value: # deprecated
1868 quote(self.workflow),
1869 EventData.SuiteUUID.value: # deprecated
1870 quote(self.uuid_str),
1871 EventData.TryNum.value:
1872 itask.get_try_num(),
1873 # BACK COMPAT: JobID_old, JobRunnerName_old
1874 # url:
1875 # https://github.com/cylc/cylc-flow/pull/3992
1876 # from:
1877 # Cylc < 8
1878 # remove at:
1879 # Cylc8.x - pending announcement of deprecation
1880 # next 2 (JobID_old, JobRunnerName_old) are deprecated
1881 EventData.JobID_old.value:
1882 quote(str(itask.summary['submit_method_id'])),
1883 EventData.JobRunnerName_old.value:
1884 quote(str(itask.summary['job_runner_name'])),
1885 # task and workflow metadata
1886 **get_event_handler_data(
1887 itask.tdef.rtconfig, self.workflow_cfg)
1888 }
1889 # fmt: on
1890
1891 def _reset_job_timers(self, itask: 'TaskProxy'):
1892 """Set up poll timer and timeout for task."""
1893
1894 if itask.run_mode == RunMode.SIMULATION or itask.transient:
1895 return
1896
1897 if not itask.state(*TASK_STATUSES_ACTIVE):
1898 # Reset, task not active
1899 itask.timeout = None
1900 itask.poll_timer = None
1901 return
1902
1903 ctx = (itask.submit_num, itask.state.status)
1904 if itask.poll_timer and itask.poll_timer.ctx == ctx:
1905 return
1906 # Set poll timer
1907 # Set timeout
1908 timeref = None # reference time, submitted or started time
1909 timeout = None # timeout in setting
1910 if itask.state(TASK_STATUS_RUNNING):
1911 timeref = itask.summary['started_time']
1912 timeout_key = self.EVENT_EXEC_TIMEOUT
1913 # Actual timeout after all polling.
1914 timeout = self._get_events_conf(itask, timeout_key)
1915 execution_polling_intervals = list(
1916 self._get_workflow_platforms_conf(
1917 itask, 'execution polling intervals'))
1918 if itask.summary[TaskEventsManager.KEY_EXECUTE_TIME_LIMIT]:
1919 time_limit = itask.summary[
1920 TaskEventsManager.KEY_EXECUTE_TIME_LIMIT]
1921 time_limit_polling_intervals = itask.platform.get(
1922 'execution time limit polling intervals')
1923 delays = self.process_execution_polling_intervals(
1924 execution_polling_intervals,
1925 time_limit,
1926 time_limit_polling_intervals
1927 )
1928 else:
1929 delays = execution_polling_intervals
1930 else: # if itask.state.status == TASK_STATUS_SUBMITTED:
1931 timeref = itask.summary['submitted_time']
1932 timeout_key = self.EVENT_SUBMIT_TIMEOUT
1933 timeout = self._get_events_conf(itask, timeout_key)
1934 delays = list(self._get_workflow_platforms_conf(
1935 itask, 'submission polling intervals'))
1936 try:
1937 itask.timeout = timeref + float(timeout)
1938 timeout_str = intvl_as_str(timeout)
1939 except (TypeError, ValueError):
1940 itask.timeout = None
1941 timeout_str = None
1942 itask.poll_timer = TaskActionTimer(ctx=ctx, delays=delays)
1943 # Log timeout and polling schedule
1944 message = f"health: {timeout_key}={timeout_str}"
1945 if itask.poll_timer.delays:
1946 # Group identical consecutive delays as N*DELAY,...
1947 items: List[List[float]] = [] # [[number of item, item], ...]
1948 for delay in itask.poll_timer.delays:
1949 if items and items[-1][1] == delay:
1950 items[-1][0] += 1
1951 else:
1952 items.append([1, delay])
1953 message += ', polling intervals='
1954 for num, item in items:
1955 if num > 1:
1956 message += f'{num}*'
1957 message += '%s,' % intvl_as_str(item)
1958 message += '...'
1959 LOG.debug(f"[{itask}] {message}")
1960 # Set next poll time
1961 self.check_poll_time(itask)
1962
1963 @staticmethod
1964 def process_execution_polling_intervals(
1965 polling_intervals: List[float],
1966 time_limit: float,
1967 time_limit_polling_intervals: Optional[List[float]]
1968 ) -> List[float]:
1969 """Create a list of polling times.
1970
1971 Args:
1972 (execution) polling_intervals
1973 (execution) time_limit
1974 (execution) time_limit_polling_intervals
1975
1976 Examples:
1977
1978 >>> this = TaskEventsManager.process_execution_polling_intervals
1979
1980 # Basic example:
1981 >>> this([40, 35], 100, [10])
1982 [40, 35, 35, 10]
1983
1984 # Second 40 second delay gets lopped off the list because it's after
1985 # the execution time limit:
1986 >>> this([40, 40], 60, [10])
1987 [40, 30, 10]
1988
1989 # Expand last item in exection polling intervals to fill the
1990 # execution time limit:
1991 >>> this([5, 20], 100, [10])
1992 [5, 20, 20, 20, 20, 25, 10]
1993
1994 # There are no execution polling intervals set - polling starts
1995 # at execution time limit:
1996 >>> this([], 10, [5])
1997 [15, 5]
1998
1999 # There are no execution time limit polling intervals set - just
2000 # repeat the execution polling interval until the time limit:
2001 >>> this([10], 25, None)
2002 [10, 10]
2003
2004 # We have a list of execution time limit polling intervals,
2005 >>> this([10], 25, [5, 6, 7, 8])
2006 [10, 10, 10, 6, 7, 8]
2007 """
2008 delays = polling_intervals
2009 if sum(delays) > time_limit:
2010 # Remove execution polling which would overshoot the
2011 # execution time limit:
2012 while sum(delays) > time_limit:
2013 del delays[-1]
2014 elif delays:
2015 # Repeat the last execution polling interval up to the execution
2016 # time limit:
2017 size = int((time_limit - sum(delays)) / delays[-1])
2018 delays.extend([delays[-1]] * size)
2019
2020 if time_limit_polling_intervals:
2021 # After the last delay before the execution time limit add the
2022 # delay to get to the execution_time_limit
2023 if len(time_limit_polling_intervals) == 1:
2024 time_limit_polling_intervals.append(
2025 time_limit_polling_intervals[0]
2026 )
2027 time_limit_polling_intervals[0] += time_limit - sum(delays)
2028
2029 # After the execution time limit, poll at the
2030 # execution time limit polling intervals.
2031 delays += time_limit_polling_intervals
2032
2033 return delays
2034
2035 def add_event_timer(
2036 self, id_key: EventKey, event_timer: TaskActionTimer
2037 ) -> None:
2038 """Add a new event timer."""
2039 self._event_timers[id_key] = event_timer
2040 self.event_timers_updated = True
2041
2042 def remove_event_timer(self, id_key: EventKey) -> None:
2043 """Remove an event timer."""
2044 del self._event_timers[id_key]
2045 self.event_timers_updated = True
2046
2047 def unset_waiting_event_timer(self, id_key: EventKey) -> None:
2048 """Invoke unset_waiting on an event timer."""
2049 self._event_timers[id_key].unset_waiting()
2050 self.event_timers_updated = True
2051
2052 def reset_bad_hosts(self):
2053 """Clear bad_hosts list."""
2054 if self.bad_hosts:
2055 LOG.info(
2056 'Clearing bad hosts: '
2057 f'{self.bad_hosts}'
2058 )
2059 self.bad_hosts.clear()
2060
2061 def spawn_children(
2062 self,
2063 itask: 'TaskProxy',
2064 output: str,
2065 forced=False
2066 ) -> None:
2067 """Spawn children of this output."""
2068 self.workflow_db_mgr.put_update_task_outputs(itask)
2069 if not itask.transient or forced:
2070 # Spawn children if forced or not transient.
2071 # Removed-and-killed running tasks end up here as transient
2072 # after removal from the pool; don't spawn or log completion.
2073 # Forced spawning from transients is used for "cylc set" outputs.
2074 self.spawn_func(itask, output)