| 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 |
"""Utilities supporting simulation mode |
| 17 |
""" |
| 18 |
|
| 19 |
from dataclasses import dataclass |
| 20 |
from logging import INFO |
| 21 |
from time import time |
| 22 |
from typing import ( |
| 23 |
TYPE_CHECKING, |
| 24 |
Any, |
| 25 |
Dict, |
| 26 |
List, |
| 27 |
Literal, |
| 28 |
Tuple, |
| 29 |
Union, |
| 30 |
) |
| 31 |
|
| 32 |
from metomi.isodatetime.parsers import DurationParser |
| 33 |
|
| 34 |
from cylc.flow import LOG |
| 35 |
from cylc.flow.cycling import PointBase |
| 36 |
from cylc.flow.cycling.loader import get_point |
| 37 |
from cylc.flow.exceptions import PointParsingError |
| 38 |
from cylc.flow.platforms import FORBIDDEN_WITH_PLATFORM |
| 39 |
from cylc.flow.run_modes import RunMode |
| 40 |
from cylc.flow.task_outputs import ( |
| 41 |
TASK_OUTPUT_STARTED, |
| 42 |
TASK_OUTPUT_SUBMITTED, |
| 43 |
) |
| 44 |
from cylc.flow.task_state import ( |
| 45 |
TASK_STATUS_FAILED, |
| 46 |
TASK_STATUS_RUNNING, |
| 47 |
TASK_STATUS_SUCCEEDED, |
| 48 |
) |
| 49 |
from cylc.flow.util import serialise_set |
| 50 |
from cylc.flow.wallclock import get_unix_time_from_time_string |
| 51 |
|
| 52 |
|
| 53 |
if TYPE_CHECKING: |
| 54 |
from cylc.flow.task_events_mgr import TaskEventsManager |
| 55 |
from cylc.flow.task_job_mgr import TaskJobManager |
| 56 |
from cylc.flow.task_proxy import TaskProxy |
| 57 |
from cylc.flow.workflow_db_mgr import WorkflowDatabaseManager |
| 58 |
|
| 59 |
|
| 60 |
def submit_task_job( |
| 61 |
task_job_mgr: 'TaskJobManager', |
| 62 |
itask: 'TaskProxy', |
| 63 |
rtconfig: Dict[str, Any], |
| 64 |
now: Tuple[float, str] |
| 65 |
) -> 'Literal[True]': |
| 66 |
"""Submit a task in simulation mode. |
| 67 |
|
| 68 |
Returns: |
| 69 |
True - indicating that TaskJobManager need take no further action. |
| 70 |
""" |
| 71 |
configure_sim_mode( |
| 72 |
rtconfig, |
| 73 |
itask.tdef.rtconfig['simulation']['fail cycle points']) |
| 74 |
itask.summary['started_time'] = now[0] |
| 75 |
task_job_mgr._set_retry_timers(itask, rtconfig) |
| 76 |
itask.mode_settings = ModeSettings( |
| 77 |
itask, |
| 78 |
task_job_mgr.workflow_db_mgr, |
| 79 |
rtconfig |
| 80 |
) |
| 81 |
itask.waiting_on_job_prep = False |
| 82 |
itask.submit_num += 1 |
| 83 |
|
| 84 |
itask.platform = { |
| 85 |
'name': RunMode.SIMULATION.value, |
| 86 |
'install target': 'localhost', |
| 87 |
'hosts': ['localhost'], |
| 88 |
'submission retry delays': [], |
| 89 |
'execution retry delays': [] |
| 90 |
} |
| 91 |
itask.summary['job_runner_name'] = RunMode.SIMULATION.value |
| 92 |
itask.summary[task_job_mgr.KEY_EXECUTE_TIME_LIMIT] = ( |
| 93 |
itask.mode_settings.simulated_run_length |
| 94 |
) |
| 95 |
itask.jobs.append( |
| 96 |
task_job_mgr.get_simulation_job_conf(itask) |
| 97 |
) |
| 98 |
for output in (TASK_OUTPUT_SUBMITTED, TASK_OUTPUT_STARTED): |
| 99 |
task_job_mgr.task_events_mgr.process_message(itask, INFO, output) |
| 100 |
task_job_mgr.workflow_db_mgr.put_insert_task_jobs( |
| 101 |
itask, { |
| 102 |
'time_submit': now[1], |
| 103 |
'time_run': now[1], |
| 104 |
'try_num': itask.get_try_num(), |
| 105 |
'flow_nums': serialise_set(itask.flow_nums), |
| 106 |
'is_manual_submit': itask.is_manual_submit, |
| 107 |
'job_runner_name': RunMode.SIMULATION.value, |
| 108 |
'platform_name': RunMode.SIMULATION.value, |
| 109 |
'submit_status': 0 # Submission has succeeded |
| 110 |
} |
| 111 |
) |
| 112 |
return True |
| 113 |
|
| 114 |
|
| 115 |
@dataclass |
| 116 |
class ModeSettings: |
| 117 |
"""A store of state for simulation modes. |
| 118 |
|
| 119 |
Used instead of modifying the runtime config. We want to leave the |
| 120 |
config unchanged so that clearing a broadcast change of run mode |
| 121 |
clears the run mode settings. |
| 122 |
|
| 123 |
Args: |
| 124 |
itask: |
| 125 |
The task proxy this submission relates to. |
| 126 |
broadcast_mgr: |
| 127 |
The broadcast manager is used to apply any runtime alterations |
| 128 |
pre simulated submission. |
| 129 |
db_mgr: |
| 130 |
The database manager must be provided for simulated jobs |
| 131 |
that are being resumed after workflow restart. It is used to |
| 132 |
extract the original scheduled finish time for the job. |
| 133 |
|
| 134 |
Attrs: |
| 135 |
simulated_run_length: |
| 136 |
The length of time this simulated job will take to run in seconds. |
| 137 |
timeout: |
| 138 |
The wall-clock time at which this simulated job will finish as |
| 139 |
a Unix epoch time. |
| 140 |
sim_task_fails: |
| 141 |
True, if this job is intended to fail when it finishes, else False. |
| 142 |
|
| 143 |
""" |
| 144 |
simulated_run_length: float = 0.0 |
| 145 |
sim_task_fails: bool = False |
| 146 |
timeout: float = 0.0 |
| 147 |
|
| 148 |
def __init__( |
| 149 |
self, |
| 150 |
itask: 'TaskProxy', |
| 151 |
db_mgr: 'WorkflowDatabaseManager', |
| 152 |
rtconfig: Dict[str, Any] |
| 153 |
): |
| 154 |
# itask.summary['started_time'] and mode_settings.timeout need |
| 155 |
# repopulating from the DB on workflow restart: |
| 156 |
started_time = itask.summary['started_time'] |
| 157 |
try_num = None |
| 158 |
if started_time is None: |
| 159 |
# This is a restart - Get DB info |
| 160 |
db_info = db_mgr.pri_dao.select_task_job( |
| 161 |
itask.tokens['cycle'], |
| 162 |
itask.tokens['task'], |
| 163 |
itask.submit_num, |
| 164 |
) |
| 165 |
|
| 166 |
if db_info['time_submit']: |
| 167 |
started_time = get_unix_time_from_time_string( |
| 168 |
db_info["time_submit"]) |
| 169 |
itask.summary['started_time'] = started_time |
| 170 |
else: |
| 171 |
started_time = time() |
| 172 |
|
| 173 |
try_num = db_info["try_num"] |
| 174 |
|
| 175 |
# Parse fail cycle points: |
| 176 |
if not rtconfig: |
| 177 |
rtconfig = itask.tdef.rtconfig |
| 178 |
if rtconfig and rtconfig != itask.tdef.rtconfig: |
| 179 |
rtconfig["simulation"][ |
| 180 |
"fail cycle points" |
| 181 |
] = parse_fail_cycle_points( |
| 182 |
rtconfig["simulation"]["fail cycle points"], |
| 183 |
itask.tdef.rtconfig['simulation']['fail cycle points'] |
| 184 |
) |
| 185 |
|
| 186 |
# Calculate simulation outcome and run-time: |
| 187 |
self.simulated_run_length = ( |
| 188 |
get_simulated_run_len(rtconfig)) |
| 189 |
self.sim_task_fails = sim_task_failed( |
| 190 |
rtconfig['simulation'], |
| 191 |
itask.point, |
| 192 |
try_num or itask.get_try_num() |
| 193 |
) |
| 194 |
self.timeout = started_time + self.simulated_run_length |
| 195 |
|
| 196 |
|
| 197 |
def configure_sim_mode(rtc, fallback, warnonly: bool = True): |
| 198 |
"""Adjust task defs for simulation mode. |
| 199 |
|
| 200 |
Example: |
| 201 |
>>> this = configure_sim_mode |
| 202 |
>>> rtc = { |
| 203 |
... 'submission retry delays': [42, 24, 23], |
| 204 |
... 'environment': {'DoNot': '"WantThis"'}, |
| 205 |
... 'simulation': {'fail cycle points': ['all']} |
| 206 |
... } |
| 207 |
>>> this(rtc, [53]) |
| 208 |
>>> rtc['submission retry delays'] |
| 209 |
[1] |
| 210 |
>>> rtc['environment'] |
| 211 |
{} |
| 212 |
>>> rtc['simulation'] |
| 213 |
{'fail cycle points': None} |
| 214 |
>>> rtc['platform'] |
| 215 |
'localhost' |
| 216 |
""" |
| 217 |
if not warnonly: |
| 218 |
parse_fail_cycle_points( |
| 219 |
rtc["simulation"]["fail cycle points"], |
| 220 |
fallback, |
| 221 |
warnonly |
| 222 |
) |
| 223 |
return |
| 224 |
rtc['submission retry delays'] = [1] |
| 225 |
|
| 226 |
disable_platforms(rtc) |
| 227 |
|
| 228 |
# Disable environment, in case it depends on env-script. |
| 229 |
rtc['environment'] = {} |
| 230 |
|
| 231 |
rtc["simulation"][ |
| 232 |
"fail cycle points" |
| 233 |
] = parse_fail_cycle_points( |
| 234 |
rtc["simulation"]["fail cycle points"], |
| 235 |
fallback, |
| 236 |
warnonly |
| 237 |
) |
| 238 |
|
| 239 |
|
| 240 |
def get_simulated_run_len(rtc: Dict[str, Any]) -> int: |
| 241 |
"""Calculate simulation run time from a task's config. |
| 242 |
|
| 243 |
rtc = run time config |
| 244 |
""" |
| 245 |
limit = rtc['execution time limit'] |
| 246 |
speedup = rtc['simulation']['speedup factor'] |
| 247 |
|
| 248 |
if limit and speedup: |
| 249 |
sleep_sec = (DurationParser().parse( |
| 250 |
str(limit)).get_seconds() / speedup) |
| 251 |
else: |
| 252 |
sleep_sec = DurationParser().parse( |
| 253 |
str(rtc['simulation']['default run length']) |
| 254 |
).get_seconds() |
| 255 |
|
| 256 |
return sleep_sec |
| 257 |
|
| 258 |
|
| 259 |
def disable_platforms( |
| 260 |
rtc: Dict[str, Any] |
| 261 |
) -> None: |
| 262 |
"""Force platform = localhost |
| 263 |
|
| 264 |
Remove legacy sections [job] and [remote], which would conflict |
| 265 |
with setting platforms. |
| 266 |
|
| 267 |
This can be simplified when support for the FORBIDDEN_WITH_PLATFORM |
| 268 |
configurations is dropped. |
| 269 |
""" |
| 270 |
for section, keys in FORBIDDEN_WITH_PLATFORM.items(): |
| 271 |
if section in rtc: |
| 272 |
for key in keys: |
| 273 |
if key in rtc[section]: |
| 274 |
rtc[section][key] = None |
| 275 |
rtc['platform'] = 'localhost' |
| 276 |
|
| 277 |
|
| 278 |
def parse_fail_cycle_points( |
| 279 |
fail_at_points_updated: List[str], |
| 280 |
fail_at_points_config, |
| 281 |
warnonly: bool = True |
| 282 |
) -> 'Union[None, List[PointBase]]': |
| 283 |
"""Parse `[simulation][fail cycle points]`. |
| 284 |
|
| 285 |
- None for "fail all points". |
| 286 |
- Else a list of cycle point objects. |
| 287 |
|
| 288 |
Args: |
| 289 |
fail_at_points_updated: Fail cycle points from a broadcast. |
| 290 |
fail_at_points_config: |
| 291 |
Fail cycle points from original workflow config, which would |
| 292 |
have caused the scheduler to fail on config parsing. This check is |
| 293 |
designed to prevent broadcasts from taking the scheduler down. |
| 294 |
|
| 295 |
Examples: |
| 296 |
>>> this = parse_fail_cycle_points |
| 297 |
>>> this(['all'], ['42']) is None |
| 298 |
True |
| 299 |
>>> this([], ['42']) |
| 300 |
[] |
| 301 |
>>> this(None, ['42']) is None |
| 302 |
True |
| 303 |
""" |
| 304 |
fail_at_points: 'List[PointBase]' = [] |
| 305 |
if ( |
| 306 |
fail_at_points_updated is None |
| 307 |
or fail_at_points_updated |
| 308 |
and 'all' in fail_at_points_updated |
| 309 |
): |
| 310 |
return None |
| 311 |
elif fail_at_points_updated: |
| 312 |
for point_str in fail_at_points_updated: |
| 313 |
if isinstance(point_str, PointBase): |
| 314 |
fail_at_points.append(point_str) |
| 315 |
else: |
| 316 |
try: |
| 317 |
fail_at_points.append(get_point(point_str).standardise()) |
| 318 |
except PointParsingError as exc: |
| 319 |
if warnonly: |
| 320 |
LOG.warning(exc.args[0]) |
| 321 |
return fail_at_points_config |
| 322 |
else: |
| 323 |
raise exc |
| 324 |
return fail_at_points |
| 325 |
|
| 326 |
|
| 327 |
def sim_time_check( |
| 328 |
task_events_manager: 'TaskEventsManager', |
| 329 |
itasks: 'List[TaskProxy]', |
| 330 |
db_mgr: 'WorkflowDatabaseManager', |
| 331 |
) -> bool: |
| 332 |
"""Check if sim tasks have been "running" for as long as required. |
| 333 |
|
| 334 |
If they have change the task state. |
| 335 |
|
| 336 |
Returns: |
| 337 |
True if _any_ simulated task state has changed. |
| 338 |
""" |
| 339 |
now = time() |
| 340 |
sim_task_state_changed: bool = False |
| 341 |
|
| 342 |
for itask in itasks: |
| 343 |
if ( |
| 344 |
itask.state.status != TASK_STATUS_RUNNING |
| 345 |
or ( |
| 346 |
itask.run_mode |
| 347 |
and itask.run_mode != RunMode.SIMULATION |
| 348 |
) |
| 349 |
): |
| 350 |
continue |
| 351 |
|
| 352 |
# This occurs if the workflow has been restarted. |
| 353 |
if itask.mode_settings is None: |
| 354 |
rtconfig = task_events_manager.broadcast_mgr.get_updated_rtconfig( |
| 355 |
itask) |
| 356 |
rtconfig = configure_sim_mode( |
| 357 |
rtconfig, |
| 358 |
itask.tdef.rtconfig['simulation']['fail cycle points']) |
| 359 |
itask.mode_settings = ModeSettings( |
| 360 |
itask, |
| 361 |
db_mgr, |
| 362 |
rtconfig |
| 363 |
) |
| 364 |
|
| 365 |
if now > itask.mode_settings.timeout: |
| 366 |
# simulate custom outputs |
| 367 |
for msg in itask.tdef.rtconfig['outputs'].values(): |
| 368 |
task_events_manager.process_message( |
| 369 |
itask, 'DEBUG', msg, |
| 370 |
flag=task_events_manager.FLAG_RECEIVED |
| 371 |
) |
| 372 |
|
| 373 |
# simulate job outcome |
| 374 |
if itask.mode_settings.sim_task_fails: |
| 375 |
task_events_manager.process_message( |
| 376 |
itask, 'CRITICAL', TASK_STATUS_FAILED, |
| 377 |
flag=task_events_manager.FLAG_RECEIVED |
| 378 |
) |
| 379 |
else: |
| 380 |
task_events_manager.process_message( |
| 381 |
itask, 'DEBUG', TASK_STATUS_SUCCEEDED, |
| 382 |
flag=task_events_manager.FLAG_RECEIVED |
| 383 |
) |
| 384 |
|
| 385 |
# We've finished this pseudo job, so delete all the mode settings. |
| 386 |
itask.mode_settings = None |
| 387 |
sim_task_state_changed = True |
| 388 |
return sim_task_state_changed |
| 389 |
|
| 390 |
|
| 391 |
def sim_task_failed( |
| 392 |
sim_conf: Dict[str, Any], |
| 393 |
point: 'PointBase', |
| 394 |
try_num: int, |
| 395 |
) -> bool: |
| 396 |
"""Encapsulate logic for deciding whether a sim task has failed. |
| 397 |
|
| 398 |
Allows Unit testing. |
| 399 |
""" |
| 400 |
return ( |
| 401 |
sim_conf['fail cycle points'] is None # i.e. "all" |
| 402 |
or point in sim_conf['fail cycle points'] |
| 403 |
) and ( |
| 404 |
try_num == 1 or not sim_conf['fail try 1 only'] |
| 405 |
) |