| 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 |
"""Allow a task to record its messages. |
| 17 |
|
| 18 |
Send messages to: |
| 19 |
- The stdout/stderr. |
| 20 |
- The job status file, if there is one. |
| 21 |
- The scheduler, if communication is possible. |
| 22 |
""" |
| 23 |
|
| 24 |
from logging import ( |
| 25 |
CRITICAL, |
| 26 |
ERROR, |
| 27 |
WARNING, |
| 28 |
getLevelName, |
| 29 |
) |
| 30 |
import os |
| 31 |
import sys |
| 32 |
from typing import List |
| 33 |
|
| 34 |
from cylc.flow.exceptions import WorkflowStopped |
| 35 |
import cylc.flow.flags |
| 36 |
from cylc.flow.network.client_factory import ( |
| 37 |
CommsMeth, |
| 38 |
get_client, |
| 39 |
get_comms_method, |
| 40 |
) |
| 41 |
from cylc.flow.pathutil import get_workflow_run_job_dir |
| 42 |
from cylc.flow.task_outputs import ( |
| 43 |
TASK_OUTPUT_FAILED, |
| 44 |
TASK_OUTPUT_STARTED, |
| 45 |
TASK_OUTPUT_SUCCEEDED, |
| 46 |
) |
| 47 |
from cylc.flow.wallclock import get_current_time_string |
| 48 |
|
| 49 |
|
| 50 |
CYLC_JOB_PID = "CYLC_JOB_PID" |
| 51 |
CYLC_JOB_INIT_TIME = "CYLC_JOB_INIT_TIME" |
| 52 |
CYLC_JOB_EXIT = "CYLC_JOB_EXIT" |
| 53 |
CYLC_JOB_EXIT_TIME = "CYLC_JOB_EXIT_TIME" |
| 54 |
CYLC_MESSAGE = "CYLC_MESSAGE" |
| 55 |
|
| 56 |
ABORT_MESSAGE_PREFIX = "aborted" |
| 57 |
FAIL_MESSAGE_PREFIX = TASK_OUTPUT_FAILED |
| 58 |
VACATION_MESSAGE_PREFIX = "vacated" |
| 59 |
|
| 60 |
STDERR_LEVELS = (getLevelName(level) for level in (WARNING, ERROR, CRITICAL)) |
| 61 |
|
| 62 |
MUTATION = ''' |
| 63 |
mutation ( |
| 64 |
$wFlows: [WorkflowID]!, |
| 65 |
$taskJob: String!, |
| 66 |
$eventTime: String, |
| 67 |
$messages: [[String]] |
| 68 |
) { |
| 69 |
message ( |
| 70 |
workflows: $wFlows, |
| 71 |
taskJob: $taskJob, |
| 72 |
eventTime: $eventTime, |
| 73 |
messages: $messages |
| 74 |
) { |
| 75 |
result |
| 76 |
} |
| 77 |
} |
| 78 |
''' |
| 79 |
|
| 80 |
|
| 81 |
def split_run_signal(message: str) -> tuple[str, str | None]: |
| 82 |
"""Get the run signal from a message. |
| 83 |
|
| 84 |
>>> split_run_signal('failed/ERR') |
| 85 |
('failed', 'ERR') |
| 86 |
>>> split_run_signal('aborted/mission') |
| 87 |
('aborted', 'mission') |
| 88 |
>>> split_run_signal('failed') |
| 89 |
('failed', None) |
| 90 |
""" |
| 91 |
prefix, *signal = message.split('/', 1) |
| 92 |
return prefix, signal[0] if signal else None |
| 93 |
|
| 94 |
|
| 95 |
def record_messages(workflow: str, job_id: str, messages: List[list]) -> None: |
| 96 |
"""Record task job messages. |
| 97 |
|
| 98 |
Print the messages according to their severity. |
| 99 |
Write the messages in the job status file. |
| 100 |
Send the messages to the workflow, if possible. |
| 101 |
|
| 102 |
Arguments: |
| 103 |
workflow: Workflow ID. |
| 104 |
job_id: Job identifier "CYCLE/TASK_NAME/SUBMIT_NUM". |
| 105 |
messages: List of messages "[[severity, message], ...]". |
| 106 |
""" |
| 107 |
# Record the event time, in case the message is delayed in some way. |
| 108 |
event_time = get_current_time_string( |
| 109 |
override_use_utc=(os.getenv('CYLC_UTC') == 'True')) |
| 110 |
write_messages(workflow, job_id, messages, event_time) |
| 111 |
if get_comms_method() != CommsMeth.POLL: |
| 112 |
send_messages(workflow, job_id, messages, event_time) |
| 113 |
|
| 114 |
|
| 115 |
def write_messages(workflow, job_id, messages, event_time): |
| 116 |
# Print to stdout/stderr |
| 117 |
for severity, message in messages: |
| 118 |
if severity in STDERR_LEVELS: |
| 119 |
handle = sys.stderr |
| 120 |
else: |
| 121 |
handle = sys.stdout |
| 122 |
handle.write('%s %s - %s\n' % (event_time, severity, message)) |
| 123 |
handle.flush() |
| 124 |
# Write to job.status |
| 125 |
_append_job_status_file(workflow, job_id, event_time, messages) |
| 126 |
|
| 127 |
|
| 128 |
def send_messages( |
| 129 |
workflow: str, job_id: str, messages: List[list], event_time: str |
| 130 |
) -> None: |
| 131 |
workflow = os.path.normpath(workflow) |
| 132 |
try: |
| 133 |
pclient = get_client(workflow) |
| 134 |
except WorkflowStopped: |
| 135 |
# on a remote host this means the contact file is not present |
| 136 |
# either the workflow is stopped or the contact file is not present |
| 137 |
# on the job host (i.e. comms method is polling) |
| 138 |
# eitherway don't try messaging |
| 139 |
return |
| 140 |
except Exception as exc: |
| 141 |
print(f"{type(exc).__name__}: {exc}", file=sys.stderr) |
| 142 |
if cylc.flow.flags.verbosity > 1: |
| 143 |
import traceback |
| 144 |
traceback.print_exc() |
| 145 |
# cylc message shouldn't fail if the client can't initialize. |
| 146 |
return |
| 147 |
mutation_kwargs = { |
| 148 |
'request_string': MUTATION, |
| 149 |
'variables': { |
| 150 |
'wFlows': [workflow], |
| 151 |
'taskJob': job_id, |
| 152 |
'eventTime': event_time, |
| 153 |
'messages': messages, |
| 154 |
} |
| 155 |
} |
| 156 |
pclient('graphql', mutation_kwargs) |
| 157 |
|
| 158 |
|
| 159 |
def _append_job_status_file(workflow, job_id, event_time, messages): |
| 160 |
"""Write messages to job status file.""" |
| 161 |
job_log_name = os.getenv('CYLC_TASK_LOG_ROOT') |
| 162 |
if not job_log_name: |
| 163 |
job_log_name = get_workflow_run_job_dir(workflow, job_id, 'job') |
| 164 |
try: |
| 165 |
job_status_file = open(job_log_name + '.status', 'a') # noqa: SIM115 |
| 166 |
# TODO: niceify read/write/appending messages to this file |
| 167 |
except IOError as exc: |
| 168 |
print(f"{type(exc).__name__}: {exc}", file=sys.stderr) |
| 169 |
if cylc.flow.flags.verbosity > 1: |
| 170 |
import traceback |
| 171 |
traceback.print_exc() |
| 172 |
return |
| 173 |
for severity, message in messages: |
| 174 |
message_prefix, signal = split_run_signal(message) |
| 175 |
if message == TASK_OUTPUT_STARTED: |
| 176 |
job_id = os.getppid() |
| 177 |
if job_id > 1: |
| 178 |
# If os.getppid() returns 1, the original job process |
| 179 |
# is likely killed already |
| 180 |
job_status_file.write('%s=%s\n' % (CYLC_JOB_PID, job_id)) |
| 181 |
job_status_file.write('%s=%s\n' % (CYLC_JOB_INIT_TIME, event_time)) |
| 182 |
elif message == TASK_OUTPUT_SUCCEEDED: |
| 183 |
job_status_file.write( |
| 184 |
('%s=%s\n' % (CYLC_JOB_EXIT, TASK_OUTPUT_SUCCEEDED.upper())) + |
| 185 |
('%s=%s\n' % (CYLC_JOB_EXIT_TIME, event_time))) |
| 186 |
elif signal is not None and message_prefix in { |
| 187 |
FAIL_MESSAGE_PREFIX, ABORT_MESSAGE_PREFIX |
| 188 |
}: |
| 189 |
job_status_file.write( |
| 190 |
('%s=%s\n' % (CYLC_JOB_EXIT, signal)) + |
| 191 |
('%s=%s\n' % (CYLC_JOB_EXIT_TIME, event_time)) |
| 192 |
) |
| 193 |
elif signal is not None and message_prefix == VACATION_MESSAGE_PREFIX: |
| 194 |
# Job vacated, remove entries related to current job |
| 195 |
job_status_file_name = job_status_file.name |
| 196 |
job_status_file.close() |
| 197 |
lines = [] |
| 198 |
for line in open(job_status_file_name): # noqa: SIM115 |
| 199 |
if not line.startswith('CYLC_JOB_'): |
| 200 |
lines.append(line) |
| 201 |
job_status_file = open(job_status_file_name, 'w') # noqa: SIM115 |
| 202 |
for line in lines: |
| 203 |
job_status_file.write(line) |
| 204 |
job_status_file.write('%s=%s|%s|%s\n' % ( |
| 205 |
CYLC_MESSAGE, event_time, severity, message)) |
| 206 |
else: |
| 207 |
job_status_file.write('%s=%s|%s|%s\n' % ( |
| 208 |
CYLC_MESSAGE, event_time, severity, message)) |
| 209 |
try: |
| 210 |
job_status_file.close() |
| 211 |
except IOError: |
| 212 |
if cylc.flow.flags.verbosity > 1: |
| 213 |
import traceback |
| 214 |
traceback.print_exc() |