# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
"""Task events manager.
This module provides logic to:
* Manage task messages (internal, polled or received).
* Set up retries on job failures (submission or execution).
* Generate task event handlers.
* Retrieval of log files for completed remote jobs.
* Email notification.
* Custom event handlers.
* Manage invoking and retrying of task event handlers.
"""
from contextlib import suppress
from enum import Enum
from logging import (
DEBUG,
INFO,
getLevelName,
)
import os
from pathlib import Path
import shlex
from shlex import quote
from time import time
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
NamedTuple,
Optional,
Sequence,
Set,
Union,
cast,
)
from cylc.flow import (
LOG,
LOG_LEVELS,
)
from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
from cylc.flow.cycling.loader import get_point
from cylc.flow.exceptions import (
NoHostsError,
PlatformLookupError,
)
from cylc.flow.hostuserutil import (
get_host,
get_user,
is_remote_platform,
)
from cylc.flow.parsec.config import ItemNotFoundError
from cylc.flow.pathutil import (
get_remote_workflow_run_job_dir,
get_workflow_run_job_dir,
)
from cylc.flow.platforms import (
get_host_from_platform,
get_platform,
log_platform_event,
)
from cylc.flow.run_modes import (
JOBLESS_MODES,
RunMode,
disable_task_event_handlers,
)
from cylc.flow.subprocctx import (
SubFuncContext,
SubProcContext,
)
from cylc.flow.task_action_timer import (
TaskActionTimer,
TimerFlags,
)
from cylc.flow.task_job_logs import (
JOB_LOG_ERR,
JOB_LOG_OUT,
get_task_job_activity_log,
get_task_job_log,
)
from cylc.flow.task_message import (
ABORT_MESSAGE_PREFIX,
FAIL_MESSAGE_PREFIX,
VACATION_MESSAGE_PREFIX,
split_run_signal,
)
from cylc.flow.task_outputs import (
TASK_OUTPUT_EXPIRED,
TASK_OUTPUT_FAILED,
TASK_OUTPUT_STARTED,
TASK_OUTPUT_SUBMIT_FAILED,
TASK_OUTPUT_SUBMITTED,
TASK_OUTPUT_SUCCEEDED,
)
from cylc.flow.task_proxy import TaskProxy
from cylc.flow.task_state import (
TASK_STATUS_EXPIRED,
TASK_STATUS_FAILED,
TASK_STATUS_PREPARING,
TASK_STATUS_RUNNING,
TASK_STATUS_SUBMIT_FAILED,
TASK_STATUS_SUBMITTED,
TASK_STATUS_SUCCEEDED,
TASK_STATUS_WAITING,
TASK_STATUSES_ACTIVE,
)
from cylc.flow.wallclock import (
get_current_time_string,
get_seconds_as_interval_string as intvl_as_str,
)
from cylc.flow.workflow_events import (
EventData as WorkflowEventData,
construct_mail_cmd,
get_template_variables as get_workflow_template_variables,
process_mail_footer,
)
if TYPE_CHECKING:
from cylc.flow.broadcast_mgr import BroadcastMgr
from cylc.flow.cycling import PointBase
from cylc.flow.data_store_mgr import DataStoreMgr
from cylc.flow.id import Tokens
from cylc.flow.scheduler import Scheduler
from cylc.flow.taskdef import TaskDef
from cylc.flow.workflow_db_mgr import WorkflowDatabaseManager
from cylc.flow.xtrigger_mgr import XtriggerManager
class CustomTaskEventHandlerContext(NamedTuple):
key: Union[str, Sequence[str]]
cmd: str
class TaskEventMailContext(NamedTuple):
key: str
mail_from: str
mail_to: str
class TaskJobLogsRetrieveContext(NamedTuple):
key: Union[str, Sequence[str]]
platform_name: Optional[str]
max_size: Optional[int]
class EventKey(NamedTuple):
"""Unique identifier for a task event.
This contains event context information for event handlers.
"""
"""The event handler name."""
handler: str
"""The task event."""
event: str
"""The task event message.
Warning: This information is not currently preserved in the DB so will be
lost on restart.
"""
message: str
"""The job tokens."""
tokens: 'Tokens'
def get_event_id(event: str, itask: 'TaskProxy') -> str:
"""Return a unique event identifier.
Some events are not unique e.g. task "started" is unique in that it can
only happen once per-job, "warning", however, is not unique as this is a
message severity level which could be associated with any number of
custom task messages.
To handle this tasks track non-unique-events and number them to ensure
their EventKey's remain unique for ease of event tracking.
Examples:
>>> from types import SimpleNamespace
# regular events are passed straight through:
>>> get_event_id('whatever', SimpleNamespace())
'whatever'
# non-unique events get an integer added to the end:
>>> get_event_id('warning', SimpleNamespace(non_unique_events={
... 'warning': None,
... }))
'warning-1'
>>> get_event_id('warning', SimpleNamespace(non_unique_events={
... 'warning': 2,
... }))
'warning-2'
"""
if event in TaskEventsManager.NON_UNIQUE_EVENTS:
event = f'{event}-{itask.non_unique_events[event] or 1:d}'
return event
def log_task_job_activity(
ctx: 'SubProcContext',
workflow: str,
point: 'str | PointBase',
name: str,
submit_num: str | int | None = None,
):
"""Log an activity for a task job."""
ctx_str = str(ctx)
if not ctx_str:
return
if isinstance(ctx.cmd_key, tuple): # An event handler
submit_num = ctx.cmd_key[-1]
job_activity_log = get_task_job_activity_log(
workflow, point, name, submit_num)
try:
with open(os.path.expandvars(job_activity_log), "ab") as handle:
handle.write((ctx_str + '\n').encode())
except IOError:
# This happens when there is no job directory. E.g., if a job host
# selection command causes a submission failure, or if a waiting task
# expires before a job log directory is otherwise needed.
# (Don't log the exception content, it looks like a bug).
LOG.info(ctx_str)
if ctx.cmd and ctx.ret_code:
LOG.error(ctx_str)
class EventData(Enum):
"""The following variables are available to task event handlers.
They can be templated into event handlers with Python percent style string
formatting e.g:
.. code-block:: none
%(workflow)s is running on %(host)s
The ``%(event)s`` string, for instance, will be replaced by the actual
event name when the handler is invoked.
If no templates or arguments are specified the following default command
line will be used:
.. code-block:: none
%(event)s %(workflow)s %(id)s %(message)s
.. note::
Substitution patterns should not be quoted in the template strings.
This is done automatically where required.
For an explanation of the substitution syntax, see
`String Formatting Operations in the Python documentation
`_.
"""
Event = 'event'
"""Event name."""
Workflow = 'workflow'
"""Workflow ID."""
Suite = 'suite' # deprecated
"""Workflow ID.
.. deprecated:: 8.0.0
Use "workflow".
"""
UUID = 'uuid'
"""The unique identification string for this workflow run.
This string is preserved for the lifetime of the scheduler and is restored
from the database on restart.
"""
SuiteUUID = 'suite_uuid' # deprecated
"""The unique identification string for this workflow run.
.. deprecated:: 8.0.0
Use 'uuid'.
"""
CyclePoint = 'point'
"""The task's cycle point."""
SubmitNum = 'submit_num'
"""The job's submit number.
This starts at 1 and increments with each additional job submission.
"""
TryNum = 'try_num'
"""The job's try number.
The number of execution attempts.
It starts at 1 and increments with automatic
:cylc:conf:`flow.cylc[runtime][]execution retry delays`.
"""
ID = 'id'
"""The task ID (i.e. ``%(point)/%(name)``)."""
Message = 'message'
"""Events message, if any."""
JobRunnerName = 'job_runner_name'
"""The job runner name."""
JobRunnerName_old = 'batch_sys_name' # deprecated
"""The job runner name.
.. deprecated:: 8.0.0
Use "job_runner_name".
"""
JobID = 'job_id'
"""The job ID in the job runner.
I.E. The job submission ID. For background jobs this is the process ID.
"""
JobID_old = 'batch_sys_job_id' # deprecated
"""The job ID in the job runner.
.. deprecated:: 8.0.0
Use "job_id".
"""
SubmitTime = 'submit_time'
"""Date-time when the job was submitted, in ISO8601 format."""
StartTime = 'start_time'
"""Date-time when the job started, in ISO8601 format."""
FinishTime = 'finish_time'
"""Date-time when the job finished, in ISO8601 format."""
PlatformName = 'platform_name'
"""The name of the platform where the job is submitted."""
UserAtHost = 'user@host'
"""The name of the platform where the job is submitted.
.. deprecated:: 8.0.0
Use "platform_name".
.. versionchanged:: 8.0.0
This now provides the platform name rather than ``user@host``.
"""
TaskName = 'name'
"""The name of the task."""
TaskURL = 'task_url' # deprecated
"""The URL defined in the task's metadata.
.. deprecated:: 8.0.0
Use ``URL`` from ````.
"""
WorkflowURL = 'workflow_url' # deprecated
"""The URL defined in the workflow's metadata.
.. deprecated:: 8.0.0
Use ``workflow_URL`` from ``workflow_``.
"""
# NOTE: placeholder for task metadata (here for documentation reasons)
TaskMeta = ''
"""Any task metadata defined in
:cylc:conf:`flow.cylc[runtime][][meta]` can be used e.g:
``%(title)s``
Task title
``%(URL)s``
Task URL
``%(importance)s``
Example custom task metadata
"""
# NOTE: placeholder for workflow metadata (here for documentation reasons)
WorkflowMeta = 'workflow_'
"""Any workflow metadata defined in
:cylc:conf:`flow.cylc[meta]` can be used with the ``workflow_``
e.g. prefix:
``%(workflow_title)s``
Workflow title
``%(workflow_URL)s``
Workflow URL.
``%(workflow_rating)s``
Example custom workflow metadata.
"""
def get_event_handler_data(task_cfg, workflow_cfg):
"""Extract event handler data from workflow and task metadata."""
handler_data = {}
# task metadata
for key, value in task_cfg['meta'].items():
if key == "URL":
handler_data[EventData.TaskURL.value] = quote(value)
handler_data[key] = quote(value)
# workflow metadata
for key, value in workflow_cfg['meta'].items():
if key == "URL":
handler_data[EventData.WorkflowURL.value] = quote(value)
handler_data["workflow_" + key] = quote(value)
return handler_data
class TaskEventsManager():
"""Task events manager.
This class does the following:
* Manage task messages (received or otherwise).
* Set up task (submission) retries on job (submission) failures.
* Generate and manage task event handlers.
"""
EVENT_FAILED = TASK_OUTPUT_FAILED
EVENT_LATE = "late"
EVENT_RETRY = "retry"
EVENT_STARTED = TASK_OUTPUT_STARTED
EVENT_SUBMITTED = TASK_OUTPUT_SUBMITTED
EVENT_EXPIRED = TASK_OUTPUT_EXPIRED
EVENT_SUBMIT_FAILED = "submission failed"
EVENT_SUBMIT_RETRY = "submission retry"
EVENT_SUBMIT_TIMEOUT = "submission timeout"
EVENT_EXEC_TIMEOUT = "execution timeout"
EVENT_SUCCEEDED = TASK_OUTPUT_SUCCEEDED
NON_UNIQUE_EVENTS = ('warning', 'critical', 'custom')
STD_EVENTS = [
EVENT_SUBMITTED,
EVENT_SUBMIT_TIMEOUT,
EVENT_SUBMIT_RETRY,
EVENT_SUBMIT_FAILED,
EVENT_STARTED,
EVENT_EXEC_TIMEOUT,
EVENT_RETRY,
EVENT_SUCCEEDED,
EVENT_FAILED,
EVENT_LATE,
EVENT_EXPIRED,
*NON_UNIQUE_EVENTS,
]
HANDLER_CUSTOM = "event-handler"
HANDLER_MAIL = "event-mail"
JOB_FAILED = "job failed"
HANDLER_JOB_LOGS_RETRIEVE = "job-logs-retrieve"
FLAG_INTERNAL = "(internal)"
FLAG_RECEIVED = "(received)"
FLAG_RECEIVED_IGNORED = "(received-ignored)"
FLAG_POLLED = "(polled)"
FLAG_POLLED_IGNORED = "(polled-ignored)"
KEY_EXECUTE_TIME_LIMIT = 'execution_time_limit'
JOB_SUBMIT_SUCCESS_FLAG = 0
JOB_SUBMIT_FAIL_FLAG = 1
JOB_LOGS_RETRIEVAL_EVENTS = {
EVENT_FAILED,
EVENT_RETRY,
EVENT_SUCCEEDED
}
workflow_cfg: Dict[str, Any]
uuid_str: str
# To be set by the task pool:
spawn_func: Callable[['TaskProxy', str], Any]
mail_interval: float = 0
mail_smtp: Optional[str] = None
mail_footer: Optional[str] = None
def __init__(
self, workflow, proc_pool, workflow_db_mgr, broadcast_mgr,
xtrigger_mgr, data_store_mgr, timestamp, bad_hosts,
reset_inactivity_timer_func
):
self.workflow = workflow
self.proc_pool = proc_pool
self.workflow_db_mgr: WorkflowDatabaseManager = workflow_db_mgr
self.broadcast_mgr: BroadcastMgr = broadcast_mgr
self.xtrigger_mgr: XtriggerManager = xtrigger_mgr
self.data_store_mgr: DataStoreMgr = data_store_mgr
self.next_mail_time = None
self.reset_inactivity_timer_func = reset_inactivity_timer_func
# NOTE: do not mutate directly
# use the {add,remove,unset_waiting}_event_timers methods
self._event_timers: Dict[EventKey, Any] = {}
# NOTE: flag for DB use
self.event_timers_updated = True
self.timestamp = timestamp
self.bad_hosts = bad_hosts
@staticmethod
def check_poll_time(itask, now=None):
"""Set the next task execution/submission poll time.
If now is set, set the timer only if the previous delay is done.
Return the next delay.
"""
if not itask.state(*TASK_STATUSES_ACTIVE):
# Reset, task not active
itask.timeout = None
itask.poll_timer = None
return None
ctx = (itask.submit_num, itask.state.status)
if itask.poll_timer is None or itask.poll_timer.ctx != ctx:
# Reset, timer no longer relevant
itask.timeout = None
itask.poll_timer = None
return None
if now is not None and not itask.poll_timer.is_delay_done(now):
return False
if itask.poll_timer.num is None:
itask.poll_timer.num = 0
itask.poll_timer.next(no_exhaust=True)
return True
def check_job_time(self, itask, now):
"""Check/handle job timeout and poll timer"""
can_poll = self.check_poll_time(itask, now)
if itask.timeout is None or now <= itask.timeout:
return can_poll
# Timeout reached for task, emit event and reset itask.timeout
if itask.state(TASK_STATUS_RUNNING):
time_ref = itask.summary['started_time']
event = self.EVENT_EXEC_TIMEOUT
elif itask.state(TASK_STATUS_SUBMITTED):
time_ref = itask.summary['submitted_time']
event = self.EVENT_SUBMIT_TIMEOUT
msg = event
with suppress(TypeError, ValueError):
msg += ' after %s' % intvl_as_str(itask.timeout - time_ref)
itask.timeout = None # emit event only once
if msg and event:
LOG.warning(f"[{itask}] {msg}")
self.setup_event_handlers(itask, event, msg)
return True
else:
return can_poll
def _get_remote_conf(self, itask, key):
"""Get deprecated "[remote]" items that default to platforms."""
overrides = self.broadcast_mgr.get_broadcast(itask.tokens)
SKEY = 'remote'
if SKEY not in overrides:
overrides[SKEY] = {}
return (
overrides[SKEY].get(key) or
itask.tdef.rtconfig[SKEY][key] or
itask.platform[key]
)
def _get_workflow_platforms_conf(self, itask: 'TaskProxy', key: str):
"""Return top level [runtime] items that default to platforms."""
overrides = self.broadcast_mgr.get_broadcast(itask.tokens)
return (
overrides.get(key) or
itask.tdef.rtconfig[key] or
itask.platform[key]
)
def process_events(self, schd: 'Scheduler') -> None:
"""Process task events that were created by "setup_event_handlers".
"""
ctx_groups: dict = {}
now = time()
for id_key, timer in self._event_timers.copy().items():
if timer.is_waiting:
continue
# Set timer if timeout is None.
if not timer.is_timeout_set():
if timer.next() is None:
LOG.warning(
f"{id_key.tokens.relative_id}"
f" handler:{id_key.handler}"
f" for task event:{id_key.event} failed"
)
self.remove_event_timer(id_key)
continue
# Report retries and delayed 1st try
msg = None
if timer.num > 1:
msg = (
f"handler:{id_key.handler}"
f" for task event:{id_key.event} failed,"
f" retrying in {timer.delay_timeout_as_str()}"
)
elif timer.delay:
msg = (
f"handler:{id_key.handler}"
f" for task event:{id_key.event} will"
f" run after {timer.delay_timeout_as_str()}"
)
if msg:
LOG.debug("%s %s", id_key.tokens.relative_id, msg)
# Ready to run?
if not timer.is_delay_done() or (
# Avoid flooding user's mail box with mail notification.
# Group together as many notifications as possible within a
# given interval.
isinstance(timer.ctx, TaskEventMailContext) and
not schd.stop_mode and
self.next_mail_time is not None and
self.next_mail_time > now
):
continue
timer.set_waiting()
if isinstance(timer.ctx, CustomTaskEventHandlerContext):
# Run custom event handlers on their own
self.proc_pool.put_command(
SubProcContext(
(
(id_key.handler, id_key.event),
id_key.tokens.submit_num,
),
timer.ctx.cmd,
env=os.environ,
shell=True, # nosec
), # designed to run user defined code
callback=self._custom_handler_callback,
callback_args=[schd, id_key]
)
else:
# Group together built-in event handlers, where possible
if timer.ctx not in ctx_groups:
ctx_groups[timer.ctx] = []
ctx_groups[timer.ctx].append(id_key)
next_mail_time = now + self.mail_interval
for ctx, id_keys in ctx_groups.items():
if isinstance(ctx, TaskEventMailContext):
# Set next_mail_time if any mail sent
self.next_mail_time = next_mail_time
self._process_event_email(schd, ctx, id_keys)
elif isinstance(ctx, TaskJobLogsRetrieveContext):
self._process_job_logs_retrieval(schd, ctx, id_keys)
def process_message(
self,
itask: 'TaskProxy',
severity: Union[str, int],
message: str,
event_time: Optional[str] = None,
flag: str = FLAG_INTERNAL,
submit_num: Optional[int] = None,
forced: bool = False
) -> bool:
"""Parse a task message and update task state.
Incoming, e.g. "succeeded at