| 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 |
"""Parse and validate the workflow definition file |
| 17 |
|
| 18 |
Set local values of variables to give workflow context before parsing |
| 19 |
config, i.e for template filters (Jinja2, python ...etc) and possibly |
| 20 |
needed locally by event handlers. This is needed for both running and |
| 21 |
non-running workflow parsing (obtaining config/graph info). Potentially |
| 22 |
task-specific due to different directory paths on different task hosts, |
| 23 |
however, they are overridden by tasks prior to job submission. |
| 24 |
|
| 25 |
Do some consistency checking, then construct task proxy objects and graph |
| 26 |
structures. |
| 27 |
""" |
| 28 |
|
| 29 |
from contextlib import suppress |
| 30 |
from copy import copy |
| 31 |
from fnmatch import fnmatchcase |
| 32 |
import os |
| 33 |
from pathlib import Path |
| 34 |
import re |
| 35 |
from textwrap import wrap |
| 36 |
import traceback |
| 37 |
from types import SimpleNamespace |
| 38 |
from typing import ( |
| 39 |
TYPE_CHECKING, |
| 40 |
Any, |
| 41 |
Callable, |
| 42 |
Dict, |
| 43 |
Iterable, |
| 44 |
List, |
| 45 |
Literal, |
| 46 |
Mapping, |
| 47 |
Optional, |
| 48 |
Set, |
| 49 |
Tuple, |
| 50 |
Union, |
| 51 |
) |
| 52 |
|
| 53 |
from metomi.isodatetime.data import Calendar |
| 54 |
from metomi.isodatetime.dumpers import TimePointDumper |
| 55 |
from metomi.isodatetime.exceptions import IsodatetimeError |
| 56 |
from metomi.isodatetime.parsers import DurationParser |
| 57 |
from metomi.isodatetime.timezone import get_local_time_zone_format |
| 58 |
|
| 59 |
from cylc.flow import LOG |
| 60 |
from cylc.flow.c3mro import C3 |
| 61 |
from cylc.flow.cfgspec.glbl_cfg import glbl_cfg |
| 62 |
from cylc.flow.cfgspec.workflow import RawWorkflowConfig |
| 63 |
from cylc.flow.cycling.integer import IntegerInterval |
| 64 |
from cylc.flow.cycling.iso8601 import ( |
| 65 |
ISO8601Interval, |
| 66 |
ingest_time, |
| 67 |
) |
| 68 |
from cylc.flow.cycling.loader import ( |
| 69 |
INTEGER_CYCLING_TYPE, |
| 70 |
ISO8601_CYCLING_TYPE, |
| 71 |
get_dump_format, |
| 72 |
get_interval, |
| 73 |
get_interval_cls, |
| 74 |
get_point, |
| 75 |
get_point_relative, |
| 76 |
get_sequence, |
| 77 |
get_sequence_cls, |
| 78 |
init_cyclers, |
| 79 |
) |
| 80 |
from cylc.flow.exceptions import ( |
| 81 |
CylcError, |
| 82 |
InputError, |
| 83 |
IntervalParsingError, |
| 84 |
ParamExpandError, |
| 85 |
TaskDefError, |
| 86 |
WorkflowConfigError, |
| 87 |
) |
| 88 |
import cylc.flow.flags |
| 89 |
from cylc.flow.graph_parser import GraphParser |
| 90 |
from cylc.flow.graphnode import GraphNodeParser |
| 91 |
from cylc.flow.id import Tokens |
| 92 |
from cylc.flow.listify import listify |
| 93 |
from cylc.flow.log_level import verbosity_to_env |
| 94 |
from cylc.flow.param_expand import NameExpander |
| 95 |
from cylc.flow.parsec.OrderedDict import OrderedDictWithDefaults |
| 96 |
from cylc.flow.parsec.exceptions import ItemNotFoundError |
| 97 |
from cylc.flow.parsec.upgrade import upgrader |
| 98 |
from cylc.flow.parsec.util import ( |
| 99 |
dequote, |
| 100 |
replicate, |
| 101 |
) |
| 102 |
from cylc.flow.pathutil import ( |
| 103 |
get_cylc_run_dir, |
| 104 |
get_workflow_name_from_id, |
| 105 |
is_relative_to, |
| 106 |
) |
| 107 |
from cylc.flow.run_modes import ( |
| 108 |
WORKFLOW_ONLY_MODES, |
| 109 |
RunMode, |
| 110 |
) |
| 111 |
from cylc.flow.run_modes.simulation import configure_sim_mode |
| 112 |
from cylc.flow.run_modes.skip import skip_mode_validate |
| 113 |
from cylc.flow.subprocctx import SubFuncContext |
| 114 |
from cylc.flow.task_events_mgr import ( |
| 115 |
EventData, |
| 116 |
TaskEventsManager, |
| 117 |
get_event_handler_data, |
| 118 |
) |
| 119 |
from cylc.flow.task_id import TaskID |
| 120 |
from cylc.flow.task_outputs import ( |
| 121 |
TASK_OUTPUT_FAILED, |
| 122 |
TASK_OUTPUT_FINISHED, |
| 123 |
TASK_OUTPUT_SUCCEEDED, |
| 124 |
TaskOutputs, |
| 125 |
get_completion_expression, |
| 126 |
get_optional_outputs, |
| 127 |
get_trigger_completion_variable_maps, |
| 128 |
trigger_to_completion_variable, |
| 129 |
) |
| 130 |
from cylc.flow.task_qualifiers import ( |
| 131 |
ALT_QUALIFIERS, |
| 132 |
TASK_QUALIFIERS, |
| 133 |
) |
| 134 |
from cylc.flow.task_trigger import ( |
| 135 |
Dependency, |
| 136 |
TaskTrigger, |
| 137 |
) |
| 138 |
from cylc.flow.taskdef import TaskDef |
| 139 |
from cylc.flow.unicode_rules import ( |
| 140 |
TaskMessageValidator, |
| 141 |
TaskNameValidator, |
| 142 |
TaskOutputValidator, |
| 143 |
XtriggerNameValidator, |
| 144 |
) |
| 145 |
from cylc.flow.wallclock import ( |
| 146 |
get_current_time_string, |
| 147 |
get_utc_mode, |
| 148 |
set_utc_mode, |
| 149 |
) |
| 150 |
from cylc.flow.workflow_events import WorkflowEventHandler |
| 151 |
from cylc.flow.workflow_files import ( |
| 152 |
NO_TITLE, |
| 153 |
WorkflowFiles, |
| 154 |
check_deprecation, |
| 155 |
) |
| 156 |
from cylc.flow.xtrigger_mgr import XtriggerCollator |
| 157 |
|
| 158 |
|
| 159 |
if TYPE_CHECKING: |
| 160 |
from optparse import Values |
| 161 |
|
| 162 |
from cylc.flow.cycling import ( |
| 163 |
IntervalBase, |
| 164 |
PointBase, |
| 165 |
SequenceBase, |
| 166 |
) |
| 167 |
|
| 168 |
RE_CLOCK_OFFSET = re.compile( |
| 169 |
rf''' |
| 170 |
^ |
| 171 |
\s* |
| 172 |
({TaskID.NAME_RE}) # task name |
| 173 |
(?:\(\s*(.+)\s*\))? # optional (arguments, ...) |
| 174 |
\s* |
| 175 |
$ |
| 176 |
''', |
| 177 |
re.X, |
| 178 |
) |
| 179 |
|
| 180 |
RE_EXT_TRIGGER = re.compile( |
| 181 |
r''' |
| 182 |
^ |
| 183 |
\s* |
| 184 |
(.*) # task name |
| 185 |
\s* |
| 186 |
\(\s*(.+)\s*\) # required (arguments, ...) |
| 187 |
\s* |
| 188 |
$ |
| 189 |
''', |
| 190 |
re.X, |
| 191 |
) |
| 192 |
RE_SEC_MULTI_SEQ = re.compile(r'(?![^(]+\)),') |
| 193 |
RE_WORKFLOW_ID_VAR = re.compile(r'\${?CYLC_WORKFLOW_(REG_)?ID}?') |
| 194 |
RE_TASK_NAME_VAR = re.compile(r'\${?CYLC_TASK_NAME}?') |
| 195 |
RE_VARNAME = re.compile(r'^[a-zA-Z_][\w]*$') |
| 196 |
|
| 197 |
|
| 198 |
def check_varnames(env: Iterable[str]) -> List[str]: |
| 199 |
"""Check a list of env var names for legality. |
| 200 |
|
| 201 |
Return a list of bad names (empty implies success). |
| 202 |
|
| 203 |
Examples: |
| 204 |
>>> check_varnames(['foo', 'BAR', '+baz']) |
| 205 |
['+baz'] |
| 206 |
|
| 207 |
""" |
| 208 |
bad = [] |
| 209 |
for varname in env: |
| 210 |
if not RE_VARNAME.match(varname): |
| 211 |
bad.append(varname) |
| 212 |
return bad |
| 213 |
|
| 214 |
|
| 215 |
def interpolate_template(tmpl, params_dict): |
| 216 |
"""Try the string interpolation/formatting operator `%` on a template |
| 217 |
string with a dictionary of parameters. |
| 218 |
|
| 219 |
E.g. 'a_%(foo)d' % {'foo': 12} |
| 220 |
|
| 221 |
If it fails, raises ParamExpandError, but if the string does not contain |
| 222 |
`%(`, it just returns the string. |
| 223 |
|
| 224 |
Examples: |
| 225 |
>>> interpolate_template('_%(a)s_', {'a': 'A'}) |
| 226 |
'_A_' |
| 227 |
|
| 228 |
>>> interpolate_template('%(a)s', {'b': 'B'}) |
| 229 |
Traceback (most recent call last): |
| 230 |
cylc.flow.exceptions.ParamExpandError: bad parameter |
| 231 |
|
| 232 |
>>> interpolate_template('%(a)d', {'a': 'A'}) |
| 233 |
Traceback (most recent call last): |
| 234 |
cylc.flow.exceptions.ParamExpandError: wrong data type for parameter |
| 235 |
|
| 236 |
>>> interpolate_template('%(as', {}) |
| 237 |
Traceback (most recent call last): |
| 238 |
cylc.flow.exceptions.ParamExpandError: bad template syntax |
| 239 |
|
| 240 |
""" |
| 241 |
if '%(' not in tmpl: |
| 242 |
return tmpl # User probably not trying to use param template |
| 243 |
try: |
| 244 |
return tmpl % params_dict |
| 245 |
except KeyError: |
| 246 |
raise ParamExpandError('bad parameter') from None |
| 247 |
except TypeError: |
| 248 |
raise ParamExpandError('wrong data type for parameter') from None |
| 249 |
except ValueError: |
| 250 |
raise ParamExpandError('bad template syntax') from None |
| 251 |
|
| 252 |
|
| 253 |
def _parse_iso_cycle_point(value: str) -> str: |
| 254 |
"""Helper for parsing initial/start cycle point option in |
| 255 |
datetime cycling mode.""" |
| 256 |
if value == 'now': |
| 257 |
return get_current_time_string() |
| 258 |
try: |
| 259 |
return ingest_time(value, get_current_time_string()) |
| 260 |
except IsodatetimeError as exc: |
| 261 |
raise WorkflowConfigError(str(exc)) from None |
| 262 |
|
| 263 |
|
| 264 |
class WorkflowConfig: |
| 265 |
"""Class for workflow configuration items and derived quantities.""" |
| 266 |
|
| 267 |
CHECK_CIRCULAR_LIMIT = 100 # If no. tasks > this, don't check circular |
| 268 |
VIS_N_POINTS = 3 |
| 269 |
MAX_WARNING_LINES = 5 |
| 270 |
|
| 271 |
def __init__( |
| 272 |
self, |
| 273 |
workflow: str, |
| 274 |
fpath: Union[Path, str], |
| 275 |
options: 'Values', |
| 276 |
template_vars: Optional[Mapping[str, Any]] = None, |
| 277 |
output_fname: Optional[str] = None, |
| 278 |
mem_log_func: Optional[Callable[[str], None]] = None, |
| 279 |
run_dir: Optional[str] = None, |
| 280 |
log_dir: Optional[str] = None, |
| 281 |
work_dir: Optional[str] = None, |
| 282 |
share_dir: Optional[str] = None, |
| 283 |
force_compat_mode: bool = False, |
| 284 |
) -> None: |
| 285 |
""" |
| 286 |
Initialize the workflow config object. |
| 287 |
|
| 288 |
Args: |
| 289 |
workflow: workflow ID |
| 290 |
fpath: workflow config file path |
| 291 |
options: CLI options |
| 292 |
force_compat_mode: |
| 293 |
If True, forces Cylc to use compatibility mode |
| 294 |
overriding compatibility mode checks. |
| 295 |
See https://github.com/cylc/cylc-rose/issues/319 |
| 296 |
|
| 297 |
""" |
| 298 |
check_deprecation(Path(fpath), force_compat_mode=force_compat_mode) |
| 299 |
self.mem_log = mem_log_func |
| 300 |
if self.mem_log is None: |
| 301 |
self.mem_log = lambda x: None |
| 302 |
self.mem_log("config.py:config.py: start init config") |
| 303 |
self.workflow = workflow |
| 304 |
self.workflow_name = get_workflow_name_from_id(self.workflow) |
| 305 |
self.fpath: Path = Path(fpath) |
| 306 |
self.fdir = str(self.fpath.parent) |
| 307 |
self.run_dir = run_dir |
| 308 |
self.log_dir = log_dir |
| 309 |
self.share_dir = share_dir |
| 310 |
self.work_dir = work_dir |
| 311 |
self.options = options |
| 312 |
self.implicit_tasks: Set[str] = set() |
| 313 |
self.edges: Dict[ |
| 314 |
'SequenceBase', Set[Tuple[str, str, bool, bool]] |
| 315 |
] = {} |
| 316 |
self.taskdefs: Dict[str, TaskDef] = {} |
| 317 |
self.expiration_offsets = {} |
| 318 |
self.ext_triggers = {} # Old external triggers (client/server) |
| 319 |
self.xtrigger_collator = XtriggerCollator() |
| 320 |
self.workflow_polling_tasks = {} # type: ignore # TODO figure out type |
| 321 |
|
| 322 |
self.initial_point: 'PointBase' |
| 323 |
self.start_point: 'PointBase' |
| 324 |
self.stop_point: Optional['PointBase'] = None |
| 325 |
self.final_point: Optional['PointBase'] = None |
| 326 |
self.sequences: List['SequenceBase'] = [] |
| 327 |
self.actual_first_point: Optional['PointBase'] = None |
| 328 |
self._start_point_for_actual_first_point: Optional['PointBase'] = None |
| 329 |
|
| 330 |
self.task_param_vars = {} # type: ignore # TODO figure out type |
| 331 |
self.runahead_limit: Optional['IntervalBase'] = None |
| 332 |
|
| 333 |
# runtime hierarchy dicts keyed by namespace name: |
| 334 |
self.runtime: Dict[str, dict] = { # TODO figure out type |
| 335 |
# lists of parent namespaces |
| 336 |
'parents': {}, |
| 337 |
# lists of C3-linearized ancestor namespaces |
| 338 |
'linearized ancestors': {}, |
| 339 |
# lists of first-parent ancestor namespaces |
| 340 |
'first-parent ancestors': {}, |
| 341 |
# sets of all descendant namespaces |
| 342 |
# (not including the final tasks) |
| 343 |
'descendants': {}, |
| 344 |
# sets of all descendant namespaces from the first-parent |
| 345 |
# hierarchy (first parents are collapsible in visualization) |
| 346 |
'first-parent descendants': {}, |
| 347 |
} |
| 348 |
# tasks |
| 349 |
self.leaves = [] # TODO figure out type |
| 350 |
# one up from root |
| 351 |
self.feet = [] # type: ignore # TODO figure out type |
| 352 |
|
| 353 |
# Export local environmental workflow context before config parsing. |
| 354 |
self.process_workflow_env() |
| 355 |
|
| 356 |
# parse, upgrade, validate the workflow, but don't expand with default |
| 357 |
# items |
| 358 |
self.mem_log("config.py: before RawWorkflowConfig init") |
| 359 |
if output_fname: |
| 360 |
output_fname = os.path.expandvars(output_fname) |
| 361 |
self.pcfg = RawWorkflowConfig( |
| 362 |
fpath, |
| 363 |
output_fname, |
| 364 |
template_vars, |
| 365 |
self.options |
| 366 |
) |
| 367 |
self.mem_log("config.py: after RawWorkflowConfig init") |
| 368 |
self.mem_log("config.py: before get(sparse=True") |
| 369 |
self.cfg = self.pcfg.get(sparse=True) |
| 370 |
self.mem_log("config.py: after get(sparse=True)") |
| 371 |
|
| 372 |
if 'scheduler' in self.cfg and 'install' in self.cfg['scheduler']: |
| 373 |
self.get_validated_rsync_includes() |
| 374 |
|
| 375 |
# First check for the essential scheduling section. |
| 376 |
if 'scheduling' not in self.cfg: |
| 377 |
raise WorkflowConfigError("missing [scheduling] section.") |
| 378 |
if 'graph' not in self.cfg['scheduling']: |
| 379 |
raise WorkflowConfigError("missing [scheduling][[graph]] section.") |
| 380 |
# (The check that 'graph' is defined is below). |
| 381 |
|
| 382 |
# Override the workflow defn with an initial point from the CLI |
| 383 |
# or from reload/restart: |
| 384 |
icp_str = getattr(self.options, 'icp', None) |
| 385 |
if icp_str is not None: |
| 386 |
self.cfg['scheduling']['initial cycle point'] = icp_str |
| 387 |
|
| 388 |
self.prelim_process_graph() |
| 389 |
|
| 390 |
# allow test workflows with no [runtime]: |
| 391 |
if 'runtime' not in self.cfg: |
| 392 |
self.cfg['runtime'] = OrderedDictWithDefaults() |
| 393 |
|
| 394 |
if 'root' not in self.cfg['runtime']: |
| 395 |
self.cfg['runtime']['root'] = OrderedDictWithDefaults() |
| 396 |
|
| 397 |
try: |
| 398 |
# Ugly hack to avoid templates getting included in parameters |
| 399 |
parameter_values = { |
| 400 |
key: value for key, value in |
| 401 |
self.cfg['task parameters'].items() |
| 402 |
if key != 'templates' |
| 403 |
} |
| 404 |
except KeyError: |
| 405 |
# (Workflow config defaults not put in yet.) |
| 406 |
parameter_values = {} |
| 407 |
try: |
| 408 |
parameter_templates = self.cfg['task parameters']['templates'] |
| 409 |
|
| 410 |
except KeyError: |
| 411 |
parameter_templates = {} |
| 412 |
|
| 413 |
# parameter values and templates are normally needed together. |
| 414 |
self.parameters = (parameter_values, parameter_templates) |
| 415 |
LOG.debug("Expanding [runtime] namespace lists and parameters") |
| 416 |
|
| 417 |
# Set default parameter expansion templates if necessary. |
| 418 |
for pname, pvalues in parameter_values.items(): |
| 419 |
if pvalues and pname not in parameter_templates: |
| 420 |
if any(not isinstance(pvalue, int) for pvalue in pvalues): |
| 421 |
# Strings, bare parameter values |
| 422 |
parameter_templates[pname] = r'_%%(%s)s' % pname |
| 423 |
elif any(pvalue < 0 for pvalue in pvalues): |
| 424 |
# Integers, with negative value(s) |
| 425 |
# Prefix values with signs and parameter names |
| 426 |
parameter_templates[pname] = r'_%s%%(%s)+0%dd' % ( |
| 427 |
pname, pname, |
| 428 |
max(len(str(pvalue)) for pvalue in pvalues)) |
| 429 |
else: |
| 430 |
# Integers, positive only |
| 431 |
# Prefix values with parameter names |
| 432 |
parameter_templates[pname] = r'_%s%%(%s)0%dd' % ( |
| 433 |
pname, pname, len(str(max(pvalues)))) |
| 434 |
|
| 435 |
# Expand parameters in 'special task' lists. |
| 436 |
if 'special tasks' in self.cfg['scheduling']: |
| 437 |
for spec, names in self.cfg['scheduling']['special tasks'].items(): |
| 438 |
self.cfg['scheduling']['special tasks'][spec] = ( |
| 439 |
self._expand_name_list(names)) |
| 440 |
|
| 441 |
# Expand parameters in internal queue member lists. |
| 442 |
if 'queues' in self.cfg['scheduling']: |
| 443 |
for queue, cfg in self.cfg['scheduling']['queues'].items(): |
| 444 |
if 'members' not in cfg: |
| 445 |
continue |
| 446 |
self.cfg['scheduling']['queues'][queue]['members'] = ( |
| 447 |
self._expand_name_list(cfg['members'])) |
| 448 |
|
| 449 |
# Check environment variable names and parameter environment templates |
| 450 |
# Done before inheritance to avoid repetition |
| 451 |
self.check_env_names() |
| 452 |
self.check_param_env_tmpls() |
| 453 |
self.check_for_owner(self.cfg['runtime']) |
| 454 |
self.mem_log("config.py: before _expand_runtime") |
| 455 |
self._expand_runtime() |
| 456 |
self.mem_log("config.py: after _expand_runtime") |
| 457 |
|
| 458 |
self.ns_defn_order = list(self.cfg['runtime']) |
| 459 |
|
| 460 |
self.mem_log("config.py: before compute_family_tree") |
| 461 |
# do sparse inheritance |
| 462 |
self.compute_family_tree() |
| 463 |
self.mem_log("config.py: after compute_family_tree") |
| 464 |
self.mem_log("config.py: before inheritance") |
| 465 |
self.compute_inheritance() |
| 466 |
self.mem_log("config.py: after inheritance") |
| 467 |
|
| 468 |
# filter task environment variables after inheritance |
| 469 |
self.filter_env() |
| 470 |
|
| 471 |
# Now add config defaults. Items added prior to this end up in the |
| 472 |
# sparse dict (e.g. parameter-expanded namespaces). |
| 473 |
self.mem_log("config.py: before get(sparse=False)") |
| 474 |
self.cfg = self.pcfg.get(sparse=False) |
| 475 |
self.mem_log("config.py: after get(sparse=False)") |
| 476 |
|
| 477 |
# These 2 must be called before call to init_cyclers(self.cfg): |
| 478 |
self.set_experimental_features() |
| 479 |
self.process_utc_mode() |
| 480 |
self.process_cycle_point_tz() |
| 481 |
|
| 482 |
# after the call to init_cyclers, we can start getting proper points. |
| 483 |
init_cyclers(self.cfg) |
| 484 |
self.cycling_type: Literal['integer', 'iso8601'] = ( |
| 485 |
get_interval_cls().get_null().TYPE |
| 486 |
) |
| 487 |
self.cycle_point_dump_format = get_dump_format(self.cycling_type) |
| 488 |
|
| 489 |
# Initial point from workflow definition (or CLI override above). |
| 490 |
self.process_initial_cycle_point() |
| 491 |
self.process_start_cycle_point() |
| 492 |
self.process_final_cycle_point() |
| 493 |
self.process_stop_cycle_point() |
| 494 |
|
| 495 |
# Parse special task cycle point offsets, and replace family names. |
| 496 |
LOG.debug("Parsing [special tasks]") |
| 497 |
for s_type in self.cfg['scheduling']['special tasks']: |
| 498 |
result = copy(self.cfg['scheduling']['special tasks'][s_type]) |
| 499 |
extn = '' |
| 500 |
for item in self.cfg['scheduling']['special tasks'][s_type]: |
| 501 |
name = item |
| 502 |
if s_type == 'external-trigger': |
| 503 |
match = RE_EXT_TRIGGER.match(item) |
| 504 |
if match is None: |
| 505 |
raise WorkflowConfigError( |
| 506 |
"Illegal %s spec: %s" % (s_type, item) |
| 507 |
) |
| 508 |
name, ext_trigger_msg = match.groups() |
| 509 |
extn = "(" + ext_trigger_msg + ")" |
| 510 |
|
| 511 |
elif s_type in ['clock-trigger', 'clock-expire']: |
| 512 |
match = RE_CLOCK_OFFSET.match(item) |
| 513 |
if match is None: |
| 514 |
raise WorkflowConfigError( |
| 515 |
"Illegal %s spec: %s" % (s_type, item) |
| 516 |
) |
| 517 |
if ( |
| 518 |
self.cfg['scheduling']['cycling mode'] != |
| 519 |
Calendar.MODE_GREGORIAN |
| 520 |
): |
| 521 |
raise WorkflowConfigError( |
| 522 |
"%s tasks require " |
| 523 |
"[scheduling]cycling mode=%s" % ( |
| 524 |
s_type, Calendar.MODE_GREGORIAN) |
| 525 |
) |
| 526 |
name, offset_string = match.groups() |
| 527 |
if not offset_string: |
| 528 |
offset_string = "PT0M" |
| 529 |
if ( |
| 530 |
cylc.flow.flags.verbosity > 0 |
| 531 |
and offset_string.startswith("-") |
| 532 |
): |
| 533 |
LOG.warning( |
| 534 |
"%s offsets are normally positive: %s" % ( |
| 535 |
s_type, item)) |
| 536 |
try: |
| 537 |
offset_interval = ( |
| 538 |
get_interval(offset_string).standardise()) |
| 539 |
except IntervalParsingError: |
| 540 |
raise WorkflowConfigError( |
| 541 |
"Illegal %s spec: %s" % (s_type, offset_string) |
| 542 |
) from None |
| 543 |
extn = "(" + offset_string + ")" |
| 544 |
|
| 545 |
# Replace family names with members. |
| 546 |
if name in self.runtime['descendants']: |
| 547 |
result.remove(item) |
| 548 |
for member in self.runtime['descendants'][name]: |
| 549 |
if member in self.runtime['descendants']: |
| 550 |
# (sub-family) |
| 551 |
continue |
| 552 |
result.append(member + extn) |
| 553 |
if s_type == 'clock-expire': |
| 554 |
self.expiration_offsets[member] = offset_interval |
| 555 |
if s_type == 'external-trigger': |
| 556 |
self.ext_triggers[member] = ext_trigger_msg |
| 557 |
elif s_type == 'clock-expire': |
| 558 |
self.expiration_offsets[name] = offset_interval |
| 559 |
elif s_type == 'external-trigger': |
| 560 |
self.ext_triggers[name] = dequote(ext_trigger_msg) |
| 561 |
|
| 562 |
self.cfg['scheduling']['special tasks'][s_type] = result |
| 563 |
|
| 564 |
self.process_config_env() |
| 565 |
self._upg_wflow_event_names() |
| 566 |
|
| 567 |
self.mem_log("config.py: before load_graph()") |
| 568 |
self._load_graph() |
| 569 |
self.mem_log("config.py: after load_graph()") |
| 570 |
|
| 571 |
self._set_completion_expressions() |
| 572 |
|
| 573 |
self.process_runahead_limit() |
| 574 |
|
| 575 |
run_mode = RunMode.get(self.options) |
| 576 |
if run_mode in {RunMode.SIMULATION, RunMode.DUMMY}: |
| 577 |
for taskdef in self.taskdefs.values(): |
| 578 |
configure_sim_mode(taskdef.rtconfig, None, False) |
| 579 |
|
| 580 |
self.configure_workflow_state_polling_tasks() |
| 581 |
|
| 582 |
for taskdef in self.taskdefs.values(): |
| 583 |
self._check_task_event_names(taskdef) |
| 584 |
self._check_task_event_handlers(taskdef) |
| 585 |
self._check_special_tasks() # adds to self.implicit_tasks |
| 586 |
self._check_explicit_cycling() |
| 587 |
|
| 588 |
self._warn_if_queues_have_implicit_tasks( |
| 589 |
self.cfg, self.taskdefs, self.MAX_WARNING_LINES) |
| 590 |
|
| 591 |
self._check_implicit_tasks() |
| 592 |
self._check_sequence_bounds() |
| 593 |
self.validate_namespace_names() |
| 594 |
|
| 595 |
# Check that external trigger messages are only used once (they have to |
| 596 |
# be discarded immediately to avoid triggering the next instance of the |
| 597 |
# just-triggered task). |
| 598 |
seen = {} |
| 599 |
for name, tdef in self.taskdefs.items(): |
| 600 |
for msg in tdef.external_triggers: |
| 601 |
if msg not in seen: |
| 602 |
seen[msg] = name |
| 603 |
else: |
| 604 |
LOG.error( |
| 605 |
"External trigger '%s'\n used in tasks %s and %s." % ( |
| 606 |
msg, name, seen[msg])) |
| 607 |
raise WorkflowConfigError( |
| 608 |
"external triggers must be used only once.") |
| 609 |
|
| 610 |
self.upgrade_clock_triggers() |
| 611 |
|
| 612 |
self.leaves = self.get_task_name_list() |
| 613 |
for ancestors in self.runtime['first-parent ancestors'].values(): |
| 614 |
try: |
| 615 |
foot = ancestors[-2] # one back from 'root' |
| 616 |
except IndexError: |
| 617 |
pass |
| 618 |
else: |
| 619 |
if foot not in self.feet: |
| 620 |
self.feet.append(foot) |
| 621 |
self.feet.sort() # sort effects get_graph_raw output |
| 622 |
|
| 623 |
self.process_metadata_urls() |
| 624 |
|
| 625 |
if getattr(self.options, 'is_validate', False): |
| 626 |
self.mem_log("config.py: before _check_circular()") |
| 627 |
self._check_circular() |
| 628 |
self.mem_log("config.py: after _check_circular()") |
| 629 |
|
| 630 |
self.mem_log("config.py: end init config") |
| 631 |
|
| 632 |
skip_mode_validate(self.taskdefs) |
| 633 |
|
| 634 |
def set_experimental_features(self): |
| 635 |
all_ = self.cfg['scheduler']['experimental']['all'] |
| 636 |
self.experimental = SimpleNamespace(**{ |
| 637 |
key.replace(' ', '_'): value or all_ |
| 638 |
for key, value in self.cfg['scheduler']['experimental'].items() |
| 639 |
if key != 'all' |
| 640 |
}) |
| 641 |
|
| 642 |
@staticmethod |
| 643 |
def _warn_if_queues_have_implicit_tasks( |
| 644 |
config, taskdefs, max_warning_lines |
| 645 |
): |
| 646 |
"""Warn if queues contain implict tasks. |
| 647 |
""" |
| 648 |
implicit_q_msg = '' |
| 649 |
|
| 650 |
# Get the names of the first N implicit queue tasks: |
| 651 |
for queue in config["scheduling"]["queues"]: |
| 652 |
for name in config["scheduling"]["queues"][queue][ |
| 653 |
"members" |
| 654 |
]: |
| 655 |
if ( |
| 656 |
name not in taskdefs |
| 657 |
and name not in config['runtime'] |
| 658 |
and len(implicit_q_msg.split('\n')) <= max_warning_lines |
| 659 |
): |
| 660 |
implicit_q_msg += f'\n * task {name!r} in queue {queue!r}' |
| 661 |
|
| 662 |
# Warn users if tasks are implied by queues. |
| 663 |
if implicit_q_msg: |
| 664 |
truncation_msg = ( |
| 665 |
f"\n...showing first {max_warning_lines} tasks..." |
| 666 |
if len(implicit_q_msg.split('\n')) > max_warning_lines |
| 667 |
else "" |
| 668 |
) |
| 669 |
LOG.warning( |
| 670 |
'Queues contain tasks not defined in' |
| 671 |
f' runtime: {implicit_q_msg}{truncation_msg}' |
| 672 |
) |
| 673 |
|
| 674 |
def prelim_process_graph(self) -> None: |
| 675 |
"""Ensure graph is not empty; set integer cycling mode and icp/fcp = 1 |
| 676 |
for simplest "R1 = foo" type graphs. |
| 677 |
""" |
| 678 |
graphdict = self.cfg['scheduling']['graph'] |
| 679 |
if not any(graphdict.values()): |
| 680 |
raise WorkflowConfigError('No workflow dependency graph defined.') |
| 681 |
|
| 682 |
if ( |
| 683 |
'cycling mode' not in self.cfg['scheduling'] and |
| 684 |
self.cfg['scheduling'].get('initial cycle point', '1') == '1' and |
| 685 |
all(item in ['graph', '1', 'R1'] for item in graphdict) |
| 686 |
): |
| 687 |
# Pure acyclic graph, assume integer cycling mode with '1' cycle |
| 688 |
for key in ('initial cycle point', 'final cycle point'): |
| 689 |
if key not in self.cfg['scheduling']: |
| 690 |
self.cfg['scheduling'][key] = '1' |
| 691 |
self.cfg['scheduling']['cycling mode'] = INTEGER_CYCLING_TYPE |
| 692 |
|
| 693 |
def process_utc_mode(self): |
| 694 |
"""Set UTC mode from config or from stored value on restart. |
| 695 |
|
| 696 |
Sets: |
| 697 |
self.cfg['scheduler']['UTC mode'] |
| 698 |
The UTC mode flag |
| 699 |
""" |
| 700 |
cfg_utc_mode = self.cfg['scheduler']['UTC mode'] |
| 701 |
# Get the original UTC mode if restart: |
| 702 |
orig_utc_mode = getattr(self.options, 'utc_mode', None) |
| 703 |
if orig_utc_mode is None: |
| 704 |
# Not a restart - will save config value |
| 705 |
if cfg_utc_mode is not None: |
| 706 |
orig_utc_mode = cfg_utc_mode |
| 707 |
else: |
| 708 |
orig_utc_mode = glbl_cfg().get(['scheduler', 'UTC mode']) |
| 709 |
elif cfg_utc_mode is not None and cfg_utc_mode != orig_utc_mode: |
| 710 |
LOG.warning( |
| 711 |
"UTC mode = {0} specified in configuration, but is stored as " |
| 712 |
"{1} from the initial run. The workflow will continue to use " |
| 713 |
"UTC mode = {1}" |
| 714 |
.format(cfg_utc_mode, orig_utc_mode) |
| 715 |
) |
| 716 |
self.cfg['scheduler']['UTC mode'] = orig_utc_mode |
| 717 |
set_utc_mode(orig_utc_mode) |
| 718 |
|
| 719 |
def process_cycle_point_tz(self): |
| 720 |
"""Set the cycle point time zone from config or from stored value |
| 721 |
on restart. |
| 722 |
|
| 723 |
Ensure workflows restart with the same cycle point time zone even after |
| 724 |
system time zone changes e.g. DST (the value is put in db by |
| 725 |
Scheduler). |
| 726 |
|
| 727 |
Sets: |
| 728 |
self.cfg['scheduler']['cycle point time zone'] |
| 729 |
""" |
| 730 |
|
| 731 |
cfg_cp_tz = self.cfg['scheduler'].get('cycle point time zone') |
| 732 |
if ( |
| 733 |
not cylc.flow.flags.cylc7_back_compat |
| 734 |
and not cfg_cp_tz |
| 735 |
): |
| 736 |
cfg_cp_tz = 'Z' |
| 737 |
# Get the original workflow run time zone if restart: |
| 738 |
orig_cp_tz = getattr(self.options, 'cycle_point_tz', None) |
| 739 |
if orig_cp_tz is None: |
| 740 |
# Not a restart |
| 741 |
if cfg_cp_tz is None: |
| 742 |
if get_utc_mode() is True: |
| 743 |
orig_cp_tz = 'Z' |
| 744 |
else: |
| 745 |
orig_cp_tz = get_local_time_zone_format() |
| 746 |
else: |
| 747 |
orig_cp_tz = cfg_cp_tz |
| 748 |
elif cfg_cp_tz is not None: |
| 749 |
dmp = TimePointDumper() |
| 750 |
if dmp.get_time_zone(cfg_cp_tz) != dmp.get_time_zone(orig_cp_tz): |
| 751 |
LOG.warning( |
| 752 |
"cycle point time zone = {0} specified in configuration, " |
| 753 |
"but there is a stored value of {1} from the initial run. " |
| 754 |
"The workflow will continue to run in {1}" |
| 755 |
.format(cfg_cp_tz, orig_cp_tz) |
| 756 |
) |
| 757 |
self.cfg['scheduler']['cycle point time zone'] = orig_cp_tz |
| 758 |
|
| 759 |
def process_initial_cycle_point(self) -> None: |
| 760 |
"""Validate and set initial cycle point from flow.cylc or options. |
| 761 |
|
| 762 |
Sets: |
| 763 |
self.initial_point |
| 764 |
self.cfg['scheduling']['initial cycle point'] |
| 765 |
Raises: |
| 766 |
WorkflowConfigError - if it fails to validate |
| 767 |
""" |
| 768 |
orig_icp = self.cfg['scheduling']['initial cycle point'] |
| 769 |
if self.cycling_type == INTEGER_CYCLING_TYPE: |
| 770 |
if orig_icp is None: |
| 771 |
orig_icp = '1' |
| 772 |
icp = orig_icp |
| 773 |
else: |
| 774 |
if orig_icp is None: |
| 775 |
raise WorkflowConfigError( |
| 776 |
"This workflow requires an initial cycle point.") |
| 777 |
icp = _parse_iso_cycle_point(orig_icp) |
| 778 |
self.initial_point = get_point(icp).standardise() |
| 779 |
self.cfg['scheduling']['initial cycle point'] = str(self.initial_point) |
| 780 |
|
| 781 |
# Validate initial cycle point against any constraints |
| 782 |
constraints = self.cfg['scheduling']['initial cycle point constraints'] |
| 783 |
if constraints: |
| 784 |
valid_icp = False |
| 785 |
for entry in constraints: |
| 786 |
possible_pt = get_point_relative( |
| 787 |
entry, self.initial_point |
| 788 |
).standardise() |
| 789 |
if self.initial_point == possible_pt: |
| 790 |
valid_icp = True |
| 791 |
break |
| 792 |
if not valid_icp: |
| 793 |
raise WorkflowConfigError( |
| 794 |
f"Initial cycle point {self.initial_point} does not meet " |
| 795 |
f"the constraints {constraints}") |
| 796 |
|
| 797 |
def process_start_cycle_point(self) -> None: |
| 798 |
"""Set the start cycle point from options. |
| 799 |
|
| 800 |
Sets: |
| 801 |
self.options.startcp |
| 802 |
self.start_point |
| 803 |
""" |
| 804 |
startcp = getattr(self.options, 'startcp', None) |
| 805 |
starttask = getattr(self.options, 'starttask', None) |
| 806 |
|
| 807 |
if startcp is not None and starttask is not None: |
| 808 |
raise InputError( |
| 809 |
"--start-cycle-point and --start-task are mutually exclusive" |
| 810 |
) |
| 811 |
if startcp: |
| 812 |
# Start from a point later than initial point. |
| 813 |
if self.cycling_type == ISO8601_CYCLING_TYPE: |
| 814 |
self.options.startcp = _parse_iso_cycle_point(startcp) |
| 815 |
self.start_point = get_point(self.options.startcp).standardise() |
| 816 |
elif starttask: |
| 817 |
# Start from designated task(s). |
| 818 |
# Select the earliest start point for use in pre-initial ignore. |
| 819 |
try: |
| 820 |
cycle_points = [ |
| 821 |
Tokens(taskid, relative=True)['cycle'] |
| 822 |
for taskid in self.options.starttask |
| 823 |
] |
| 824 |
except ValueError as exc: |
| 825 |
raise InputError(str(exc)) from None |
| 826 |
self.start_point = min( |
| 827 |
get_point(cycle).standardise() |
| 828 |
for cycle in cycle_points if cycle |
| 829 |
) |
| 830 |
else: |
| 831 |
# Start from the initial point. |
| 832 |
self.start_point = self.initial_point |
| 833 |
|
| 834 |
def process_final_cycle_point(self) -> None: |
| 835 |
"""Validate and set the final cycle point from flow.cylc or options. |
| 836 |
|
| 837 |
Sets: |
| 838 |
self.final_point |
| 839 |
self.cfg['scheduling']['final cycle point'] |
| 840 |
Raises: |
| 841 |
WorkflowConfigError - if it fails to validate |
| 842 |
""" |
| 843 |
if self.cfg['scheduling']['final cycle point'] == '': |
| 844 |
# (Unlike other cycle point settings in config, fcp is treated as |
| 845 |
# a string by parsec to allow for expressions like '+P1Y') |
| 846 |
self.cfg['scheduling']['final cycle point'] = None |
| 847 |
fcp_str = getattr(self.options, 'fcp', None) |
| 848 |
if fcp_str == 'reload': |
| 849 |
fcp_str = self.options.fcp = None |
| 850 |
if fcp_str is None: |
| 851 |
fcp_str = self.cfg['scheduling']['final cycle point'] |
| 852 |
if fcp_str is not None: |
| 853 |
# Is the final "point"(/interval) relative to initial? |
| 854 |
if self.cycling_type == INTEGER_CYCLING_TYPE: |
| 855 |
if "P" in fcp_str: |
| 856 |
# Relative, integer cycling. |
| 857 |
self.final_point = get_point_relative( |
| 858 |
self.cfg['scheduling']['final cycle point'], |
| 859 |
self.initial_point |
| 860 |
).standardise() |
| 861 |
else: |
| 862 |
with suppress(IsodatetimeError): |
| 863 |
# Relative, ISO8601 cycling. |
| 864 |
self.final_point = get_point_relative( |
| 865 |
fcp_str, self.initial_point).standardise() |
| 866 |
if self.final_point is None: |
| 867 |
# Must be absolute. |
| 868 |
self.final_point = get_point(fcp_str).standardise() |
| 869 |
self.cfg['scheduling']['final cycle point'] = str(self.final_point) |
| 870 |
|
| 871 |
if (self.final_point is not None and |
| 872 |
self.initial_point > self.final_point): |
| 873 |
raise WorkflowConfigError( |
| 874 |
f"The initial cycle point:{self.initial_point} is after the " |
| 875 |
f"final cycle point:{self.final_point}.") |
| 876 |
|
| 877 |
# Validate final cycle point against any constraints |
| 878 |
constraints = self.cfg['scheduling']['final cycle point constraints'] |
| 879 |
if constraints and self.final_point is not None: |
| 880 |
valid_fcp = False |
| 881 |
for entry in constraints: |
| 882 |
possible_pt = get_point_relative( |
| 883 |
entry, self.final_point).standardise() |
| 884 |
if self.final_point == possible_pt: |
| 885 |
valid_fcp = True |
| 886 |
break |
| 887 |
if not valid_fcp: |
| 888 |
raise WorkflowConfigError( |
| 889 |
f"Final cycle point {self.final_point} does not " |
| 890 |
f"meet the constraints {constraints}") |
| 891 |
|
| 892 |
def process_stop_cycle_point(self) -> None: |
| 893 |
"""Set the stop after cycle point. |
| 894 |
|
| 895 |
In decreasing priority, it is set: |
| 896 |
* From the command line option (``--stopcp=XYZ``) or database. |
| 897 |
* From the flow.cylc file (``[scheduling]stop after cycle point``). |
| 898 |
|
| 899 |
However, if ``--stopcp=reload`` on the command line during restart, |
| 900 |
the ``[scheduling]stop after cycle point`` value is used. |
| 901 |
""" |
| 902 |
stopcp_str: Optional[str] = getattr(self.options, 'stopcp', None) |
| 903 |
if stopcp_str == 'reload': |
| 904 |
stopcp_str = self.options.stopcp = None |
| 905 |
if stopcp_str is None: |
| 906 |
stopcp_str = self.cfg['scheduling']['stop after cycle point'] |
| 907 |
|
| 908 |
if stopcp_str: |
| 909 |
self.stop_point = get_point_relative( |
| 910 |
stopcp_str, |
| 911 |
self.initial_point, |
| 912 |
).standardise() |
| 913 |
if ( |
| 914 |
self.final_point is not None |
| 915 |
and self.stop_point is not None |
| 916 |
and self.stop_point > self.final_point |
| 917 |
): |
| 918 |
LOG.warning( |
| 919 |
f"Stop cycle point '{self.stop_point}' will have no " |
| 920 |
"effect as it is after the final cycle " |
| 921 |
f"point '{self.final_point}'." |
| 922 |
) |
| 923 |
self.stop_point = None |
| 924 |
stopcp_str = str(self.stop_point) if self.stop_point else None |
| 925 |
self.cfg['scheduling']['stop after cycle point'] = stopcp_str |
| 926 |
|
| 927 |
def _check_implicit_tasks(self) -> None: |
| 928 |
"""Raise WorkflowConfigError if implicit tasks are found in graph or |
| 929 |
queue config, unless allowed by config.""" |
| 930 |
if not self.implicit_tasks: |
| 931 |
return |
| 932 |
print_limit = 10 |
| 933 |
tasks_str = '\n * '.join(list(self.implicit_tasks)[:print_limit]) |
| 934 |
num = len(self.implicit_tasks) |
| 935 |
if num > print_limit: |
| 936 |
tasks_str += f"\n and {num} more" |
| 937 |
msg = ( |
| 938 |
"implicit tasks detected (no entry under [runtime]):\n" |
| 939 |
f" * {tasks_str}" |
| 940 |
) |
| 941 |
if self.cfg['scheduler']['allow implicit tasks']: |
| 942 |
LOG.debug(msg) |
| 943 |
return |
| 944 |
|
| 945 |
# Check if implicit tasks explicitly disallowed |
| 946 |
try: |
| 947 |
is_disallowed = self.pcfg.get( |
| 948 |
['scheduler', 'allow implicit tasks'], sparse=True |
| 949 |
) is False |
| 950 |
except ItemNotFoundError: |
| 951 |
is_disallowed = False |
| 952 |
if is_disallowed: |
| 953 |
raise WorkflowConfigError(msg) |
| 954 |
# Otherwise "[scheduler]allow implicit tasks" is not set |
| 955 |
|
| 956 |
if not cylc.flow.flags.cylc7_back_compat: |
| 957 |
msg += ( |
| 958 |
"\nTo allow implicit tasks, use " |
| 959 |
f"'{WorkflowFiles.FLOW_FILE}[scheduler]allow implicit tasks'" |
| 960 |
) |
| 961 |
# Allow implicit tasks in back-compat mode unless rose-suite.conf |
| 962 |
# present (to maintain compat with Rose 2019) |
| 963 |
elif not (self.fpath.parent / "rose-suite.conf").is_file(): |
| 964 |
LOG.debug(msg) |
| 965 |
return |
| 966 |
|
| 967 |
raise WorkflowConfigError(msg) |
| 968 |
|
| 969 |
def _check_circular(self): |
| 970 |
"""Check for circular dependence in graph.""" |
| 971 |
if (len(self.taskdefs) > self.CHECK_CIRCULAR_LIMIT and |
| 972 |
not getattr(self.options, 'check_circular', False)): |
| 973 |
LOG.info( |
| 974 |
f"Number of tasks is > {self.CHECK_CIRCULAR_LIMIT}; will not " |
| 975 |
"check graph for circular dependencies. To run this check" |
| 976 |
" anyway use the option --check-circular.") |
| 977 |
return |
| 978 |
start_point_str = self.cfg['scheduling']['initial cycle point'] |
| 979 |
raw_graph = self.get_graph_raw( |
| 980 |
start_point_str, |
| 981 |
stop_point_str=None, |
| 982 |
sort=False, |
| 983 |
) |
| 984 |
lhs2rhss = {} # left hand side to right hand sides |
| 985 |
rhs2lhss = {} # right hand side to left hand sides |
| 986 |
for lhs, rhs in raw_graph: |
| 987 |
lhs2rhss.setdefault(lhs, set()) |
| 988 |
lhs2rhss[lhs].add(rhs) |
| 989 |
rhs2lhss.setdefault(rhs, set()) |
| 990 |
rhs2lhss[rhs].add(lhs) |
| 991 |
self._check_circular_helper(lhs2rhss, rhs2lhss) |
| 992 |
if rhs2lhss: |
| 993 |
# Before reporting circular dependence, pick out all the edges with |
| 994 |
# no outgoings. |
| 995 |
self._check_circular_helper(rhs2lhss, lhs2rhss) |
| 996 |
err_msg = '' |
| 997 |
for rhs, lhss in sorted(rhs2lhss.items()): |
| 998 |
for lhs in sorted(lhss): |
| 999 |
err_msg += ' %s => %s' % ( |
| 1000 |
Tokens( |
| 1001 |
cycle=str(lhs[1]), |
| 1002 |
task=lhs[0] |
| 1003 |
).relative_id, |
| 1004 |
Tokens( |
| 1005 |
cycle=str(rhs[1]), |
| 1006 |
task=rhs[0] |
| 1007 |
).relative_id, |
| 1008 |
) |
| 1009 |
if err_msg: |
| 1010 |
raise WorkflowConfigError( |
| 1011 |
'circular edges detected:' + err_msg) |
| 1012 |
|
| 1013 |
@staticmethod |
| 1014 |
def _check_circular_helper(x2ys, y2xs): |
| 1015 |
"""Topological elimination. |
| 1016 |
|
| 1017 |
An implementation of Kahn's algorithm for topological sorting, but |
| 1018 |
only use the part for pulling out starter nodes with no incoming |
| 1019 |
edges. See https://en.wikipedia.org/wiki/Topological_sorting |
| 1020 |
|
| 1021 |
x2ys is a map of {x1: [y1, y2, ...], ...} |
| 1022 |
to map edges using x's as keys, such as x1 => y1, x1 => y2, etc |
| 1023 |
|
| 1024 |
y2xs is a map of {y3: [x4, x5, ...], ...} |
| 1025 |
to map edges using y's as keys, such as x4 => y3, x5 => y3, etc |
| 1026 |
""" |
| 1027 |
# Starter x nodes are those with no incoming, i.e. |
| 1028 |
# x nodes that never appear as a y. |
| 1029 |
sxs = set(x2ys).difference(y2xs) |
| 1030 |
while sxs: |
| 1031 |
sx01 = sxs.pop() |
| 1032 |
for y01 in x2ys[sx01]: |
| 1033 |
y2xs[y01].remove(sx01) |
| 1034 |
if not y2xs[y01]: |
| 1035 |
if y01 in x2ys: |
| 1036 |
# No need to look at this again if it does not have any |
| 1037 |
# outgoing. |
| 1038 |
sxs.add(y01) |
| 1039 |
del y2xs[y01] |
| 1040 |
del x2ys[sx01] |
| 1041 |
|
| 1042 |
def _check_sequence_bounds(self) -> None: |
| 1043 |
"""Check bounds of sequences against the initial cycle point.""" |
| 1044 |
out_of_bounds = [ |
| 1045 |
str(seq) |
| 1046 |
for seq in self.sequences |
| 1047 |
if seq.get_first_point(self.initial_point) is None |
| 1048 |
] |
| 1049 |
if out_of_bounds: |
| 1050 |
if len(out_of_bounds) > 1: |
| 1051 |
# avoid spamming users with multiple warnings |
| 1052 |
out_of_bounds_str = '\n'.join( |
| 1053 |
wrap(', '.join(out_of_bounds), 70) |
| 1054 |
) |
| 1055 |
msg = ( |
| 1056 |
"multiple sequences out of bounds for initial cycle point " |
| 1057 |
f"{self.initial_point}:\n{out_of_bounds_str}" |
| 1058 |
) |
| 1059 |
else: |
| 1060 |
msg = ( |
| 1061 |
f"{out_of_bounds[0]}: sequence out of bounds for " |
| 1062 |
f"initial cycle point {self.initial_point}" |
| 1063 |
) |
| 1064 |
LOG.warning(msg) |
| 1065 |
|
| 1066 |
def _set_completion_expressions(self): |
| 1067 |
"""Sets and checks completion expressions for each task. |
| 1068 |
|
| 1069 |
If a task does not have a user-defined completion expression, then set |
| 1070 |
one according to the default rules. |
| 1071 |
|
| 1072 |
If a task does have a used-defined completion expression, then ensure |
| 1073 |
it is consistent with the use of outputs in the graph. |
| 1074 |
""" |
| 1075 |
for name, taskdef in self.taskdefs.items(): |
| 1076 |
expr = taskdef.rtconfig['completion'] |
| 1077 |
if expr: |
| 1078 |
any_suicide = any( |
| 1079 |
dep.suicide |
| 1080 |
for d in taskdef.dependencies.values() |
| 1081 |
for dep in d |
| 1082 |
) |
| 1083 |
# check the user-defined expression |
| 1084 |
self._check_completion_expression(name, expr, any_suicide) |
| 1085 |
else: |
| 1086 |
# derive a completion expression for this taskdef |
| 1087 |
expr = get_completion_expression(taskdef) |
| 1088 |
|
| 1089 |
# update both the sparse and dense configs to make these values |
| 1090 |
# visible to "cylc config" to make the completion expression more |
| 1091 |
# transparent to users. |
| 1092 |
# NOTE: we have to update both because we are setting this value |
| 1093 |
# late on in the process after the dense copy has been made |
| 1094 |
self.pcfg.sparse.setdefault( |
| 1095 |
'runtime', {} |
| 1096 |
).setdefault( |
| 1097 |
name, {} |
| 1098 |
)['completion'] = expr |
| 1099 |
self.pcfg.dense['runtime'][name]['completion'] = expr |
| 1100 |
|
| 1101 |
# update the task's runtime config to make this value visible to |
| 1102 |
# the data store |
| 1103 |
# NOTE: we have to do this because we are setting this value late |
| 1104 |
# on after the TaskDef has been created |
| 1105 |
taskdef.rtconfig['completion'] = expr |
| 1106 |
|
| 1107 |
def _check_completion_expression( |
| 1108 |
self, task_name: str, expr: str, any_suicide: bool |
| 1109 |
) -> None: |
| 1110 |
"""Checks a user-defined completion expression. |
| 1111 |
|
| 1112 |
Args: |
| 1113 |
task_name: |
| 1114 |
The name of the task we are checking. |
| 1115 |
expr: |
| 1116 |
The completion expression as defined in the config. |
| 1117 |
any_suicide: |
| 1118 |
Does this task have any suicide triggers |
| 1119 |
|
| 1120 |
""" |
| 1121 |
# check completion expressions are not being used in compat mode |
| 1122 |
if cylc.flow.flags.cylc7_back_compat: |
| 1123 |
raise WorkflowConfigError( |
| 1124 |
'[runtime][<namespace>]completion cannot be used' |
| 1125 |
' in Cylc 7 compatibility mode.' |
| 1126 |
) |
| 1127 |
|
| 1128 |
# check for invalid triggers in the expression |
| 1129 |
if 'submit-failed' in expr: |
| 1130 |
raise WorkflowConfigError( |
| 1131 |
f'Error in [runtime][{task_name}]completion:' |
| 1132 |
f'\nUse "submit_failed" rather than "submit-failed"' |
| 1133 |
' in completion expressions.' |
| 1134 |
) |
| 1135 |
elif '-' in expr: |
| 1136 |
raise WorkflowConfigError( |
| 1137 |
f'Error in [runtime][{task_name}]completion:' |
| 1138 |
f'\n {expr}' |
| 1139 |
'\nReplace hyphens with underscores in task outputs when' |
| 1140 |
' used in completion expressions.' |
| 1141 |
) |
| 1142 |
|
| 1143 |
# get the outputs and completion expression for this task |
| 1144 |
try: |
| 1145 |
outputs = self.taskdefs[task_name].outputs |
| 1146 |
except KeyError: |
| 1147 |
# this is a family -> we'll check integrity for each task that |
| 1148 |
# inherits from it |
| 1149 |
return |
| 1150 |
|
| 1151 |
( |
| 1152 |
_trigger_to_completion_variable, |
| 1153 |
_completion_variable_to_trigger, |
| 1154 |
) = get_trigger_completion_variable_maps(outputs.keys()) |
| 1155 |
|
| 1156 |
# get the optional/required outputs defined in the graph |
| 1157 |
graph_optionals = { |
| 1158 |
# completion_variable: is_optional |
| 1159 |
_trigger_to_completion_variable[trigger]: ( |
| 1160 |
None if is_required is None else not is_required |
| 1161 |
) |
| 1162 |
for trigger, (_, is_required) |
| 1163 |
in outputs.items() |
| 1164 |
} |
| 1165 |
if ( |
| 1166 |
graph_optionals[TASK_OUTPUT_SUCCEEDED] is True |
| 1167 |
and graph_optionals[TASK_OUTPUT_FAILED] is None |
| 1168 |
): |
| 1169 |
# failed is implicitly optional if succeeded is optional |
| 1170 |
# https://github.com/cylc/cylc-flow/pull/6046#issuecomment-2059266086 |
| 1171 |
graph_optionals[TASK_OUTPUT_FAILED] = True |
| 1172 |
|
| 1173 |
# get the optional/required outputs defined in the expression |
| 1174 |
try: |
| 1175 |
# this involves running the expression which also validates it |
| 1176 |
expression_optionals = get_optional_outputs(expr, outputs) |
| 1177 |
except NameError as exc: |
| 1178 |
# expression references an output which has not been registered |
| 1179 |
error = exc.args[0][5:] |
| 1180 |
|
| 1181 |
if f"'{TASK_OUTPUT_FINISHED}'" in error: |
| 1182 |
# the finished output cannot be used in completion expressions |
| 1183 |
# see proposal point 5:: |
| 1184 |
# https://cylc.github.io/cylc-admin/proposal-optional-output-extension.html#proposal |
| 1185 |
raise WorkflowConfigError( |
| 1186 |
f'Error in [runtime][{task_name}]completion:' |
| 1187 |
f'\n {expr}' |
| 1188 |
'\nThe "finished" output cannot be used in completion' |
| 1189 |
' expressions, use "succeeded or failed".' |
| 1190 |
) from None |
| 1191 |
|
| 1192 |
for alt_qualifier, qualifier in ALT_QUALIFIERS.items(): |
| 1193 |
_alt_compvar = trigger_to_completion_variable(alt_qualifier) |
| 1194 |
_compvar = trigger_to_completion_variable(qualifier) |
| 1195 |
if re.search(rf'\b{_alt_compvar}\b', error): |
| 1196 |
raise WorkflowConfigError( |
| 1197 |
f'Error in [runtime][{task_name}]completion:' |
| 1198 |
f'\n {expr}' |
| 1199 |
f'\nUse "{_compvar}" not "{_alt_compvar}" ' |
| 1200 |
'in completion expressions.' |
| 1201 |
) from None |
| 1202 |
|
| 1203 |
raise WorkflowConfigError( |
| 1204 |
# NOTE: str(exc) == "name 'x' is not defined" tested in |
| 1205 |
# tests/integration/test_optional_outputs.py |
| 1206 |
f'Error in [runtime][{task_name}]completion:' |
| 1207 |
f'\n{error}' |
| 1208 |
) from None |
| 1209 |
except Exception as exc: # includes InvalidCompletionExpression |
| 1210 |
# expression contains non-whitelisted syntax or any other error in |
| 1211 |
# the expression e.g. SyntaxError |
| 1212 |
raise WorkflowConfigError( |
| 1213 |
f'Error in [runtime][{task_name}]completion:' |
| 1214 |
f'\n{str(exc)}' |
| 1215 |
) from None |
| 1216 |
|
| 1217 |
# ensure consistency between the graph and the completion expression |
| 1218 |
for compvar in ( |
| 1219 |
{ |
| 1220 |
*graph_optionals, |
| 1221 |
*expression_optionals |
| 1222 |
} |
| 1223 |
): |
| 1224 |
# is the output optional in the graph? |
| 1225 |
graph_opt = graph_optionals.get(compvar) |
| 1226 |
# is the output optional in the completion expression? |
| 1227 |
expr_opt = expression_optionals.get(compvar) |
| 1228 |
|
| 1229 |
# True = is optional |
| 1230 |
# False = is required |
| 1231 |
# None = is not referenced |
| 1232 |
|
| 1233 |
# graph_opt expr_opt |
| 1234 |
# True True ok |
| 1235 |
# True False not ok |
| 1236 |
# True None not ok [1] |
| 1237 |
# False True not ok [1] |
| 1238 |
# False False ok |
| 1239 |
# False None not ok |
| 1240 |
# None True ok |
| 1241 |
# None False ok |
| 1242 |
# None None ok |
| 1243 |
|
| 1244 |
# [1] applies only to "submit-failed" and "expired" |
| 1245 |
|
| 1246 |
trigger = _completion_variable_to_trigger[compvar] |
| 1247 |
|
| 1248 |
if graph_opt is True and expr_opt is False: |
| 1249 |
raise WorkflowConfigError( |
| 1250 |
f'{task_name}:{trigger} is optional in the graph' |
| 1251 |
' (? symbol), but required in the completion' |
| 1252 |
f' expression:\n{expr}' |
| 1253 |
) |
| 1254 |
|
| 1255 |
if graph_opt is False and expr_opt is None: |
| 1256 |
raise WorkflowConfigError( |
| 1257 |
f'{task_name}:{trigger} is required in the graph,' |
| 1258 |
' but not referenced in the completion' |
| 1259 |
f' expression\n{expr}' |
| 1260 |
) |
| 1261 |
|
| 1262 |
if ( |
| 1263 |
graph_opt is True |
| 1264 |
and expr_opt is None |
| 1265 |
and compvar in {'submit_failed', 'expired'} |
| 1266 |
): |
| 1267 |
msg = ( |
| 1268 |
f'{task_name}:{trigger} is permitted in the graph' |
| 1269 |
' but is not referenced in the completion.' |
| 1270 |
) |
| 1271 |
if ( |
| 1272 |
any_suicide |
| 1273 |
and trigger == "expired" |
| 1274 |
and self.experimental.expire_triggers |
| 1275 |
): |
| 1276 |
msg += ( |
| 1277 |
"\nThis may be due to use of an expire " |
| 1278 |
"(formerly suicide) trigger." |
| 1279 |
) |
| 1280 |
msg += f'\nTry: completion = "{expr} or {compvar}"' |
| 1281 |
raise WorkflowConfigError(msg) |
| 1282 |
|
| 1283 |
if ( |
| 1284 |
graph_opt is False |
| 1285 |
and expr_opt is True |
| 1286 |
and compvar not in {'submit_failed', 'expired'} |
| 1287 |
): |
| 1288 |
raise WorkflowConfigError( |
| 1289 |
f'{task_name}:{trigger} is required in the graph,' |
| 1290 |
' but optional in the completion expression' |
| 1291 |
f'\n{expr}' |
| 1292 |
) |
| 1293 |
|
| 1294 |
def _expand_name_list(self, orig_names): |
| 1295 |
"""Expand any parameters in lists of names.""" |
| 1296 |
name_expander = NameExpander(self.parameters) |
| 1297 |
exp_names = [] |
| 1298 |
for orig_name in orig_names: |
| 1299 |
exp_names += [name for name, _ in name_expander.expand(orig_name)] |
| 1300 |
return exp_names |
| 1301 |
|
| 1302 |
def _update_task_params(self, task_name, params): |
| 1303 |
"""Update the dict of parameters used in a task definition. |
| 1304 |
|
| 1305 |
# Used to expand parameter values in task environments. |
| 1306 |
""" |
| 1307 |
self.task_param_vars.setdefault( |
| 1308 |
task_name, {} |
| 1309 |
).update( |
| 1310 |
params |
| 1311 |
) |
| 1312 |
|
| 1313 |
def _expand_runtime(self): |
| 1314 |
"""Expand [runtime] name lists or parameterized names. |
| 1315 |
|
| 1316 |
This makes individual runtime namespaces out of any headings that |
| 1317 |
represent multiple namespaces, like [[foo, bar]] or [[foo<m,n>]]. |
| 1318 |
It requires replicating the sparse runtime OrderedDict into a new |
| 1319 |
OrderedDict - we can't just stick expanded names on the end because the |
| 1320 |
order matters (for add-or-override by repeated namespaces). |
| 1321 |
|
| 1322 |
TODO - this will have an impact on memory footprint for large workflows |
| 1323 |
with a lot of runtime config. We should consider ditching OrderedDict |
| 1324 |
and instead using an ordinary dict |
| 1325 |
|
| 1326 |
""" |
| 1327 |
if (not self.parameters[0] and |
| 1328 |
not any(',' in ns for ns in self.cfg['runtime'])): |
| 1329 |
# No parameters, no namespace lists: no expansion needed. |
| 1330 |
return |
| 1331 |
|
| 1332 |
newruntime = OrderedDictWithDefaults() |
| 1333 |
name_expander = NameExpander(self.parameters) |
| 1334 |
for namespace_heading, namespace_dict in self.cfg['runtime'].items(): |
| 1335 |
for name, indices in name_expander.expand(namespace_heading): |
| 1336 |
if name not in newruntime: |
| 1337 |
newruntime[name] = OrderedDictWithDefaults() |
| 1338 |
replicate(newruntime[name], namespace_dict) |
| 1339 |
if indices: |
| 1340 |
self._update_task_params(name, indices) |
| 1341 |
new_environ = OrderedDictWithDefaults() |
| 1342 |
if 'environment' in newruntime[name]: |
| 1343 |
new_environ = newruntime[name]['environment'].copy() |
| 1344 |
newruntime[name]['environment'] = new_environ |
| 1345 |
if 'inherit' in newruntime[name]: |
| 1346 |
# Allow inheritance from parameterized namespaces. |
| 1347 |
parents = newruntime[name]['inherit'] |
| 1348 |
origin = 'inherit = %s' % ', '.join(parents) |
| 1349 |
repl_parents = [] |
| 1350 |
for parent in parents: |
| 1351 |
used_indices, expanded = ( |
| 1352 |
name_expander.expand_parent_params( |
| 1353 |
parent, indices, origin) |
| 1354 |
) |
| 1355 |
repl_parents.append(expanded) |
| 1356 |
if used_indices: |
| 1357 |
self._update_task_params(name, used_indices) |
| 1358 |
newruntime[name]['inherit'] = repl_parents |
| 1359 |
self.cfg['runtime'] = newruntime |
| 1360 |
|
| 1361 |
def validate_namespace_names(self): |
| 1362 |
"""Validate task and family names.""" |
| 1363 |
for name in self.implicit_tasks: |
| 1364 |
success, message = TaskNameValidator.validate(name) |
| 1365 |
if not success: |
| 1366 |
raise WorkflowConfigError( |
| 1367 |
f'invalid task name "{name}"\n{message}' |
| 1368 |
) |
| 1369 |
for name in self.cfg['runtime']: |
| 1370 |
if name == 'root': |
| 1371 |
# root is allowed to be defined in the runtime section |
| 1372 |
continue |
| 1373 |
success, message = TaskNameValidator.validate(name) |
| 1374 |
if not success: |
| 1375 |
raise WorkflowConfigError( |
| 1376 |
f'task/family name {message}\n[runtime][[{name}]]' |
| 1377 |
) |
| 1378 |
|
| 1379 |
def check_env_names(self): |
| 1380 |
"""Check for illegal environment variable names""" |
| 1381 |
bad = {} |
| 1382 |
for label, item in self.cfg['runtime'].items(): |
| 1383 |
for key in ('environment', 'parameter environment templates'): |
| 1384 |
if key in item: |
| 1385 |
res = check_varnames(item[key]) |
| 1386 |
if res: |
| 1387 |
bad[(label, key)] = res |
| 1388 |
if bad: |
| 1389 |
raise WorkflowConfigError( |
| 1390 |
"Illegal environment variable name(s) detected:\n* " |
| 1391 |
# f"\n{err_msg}" |
| 1392 |
+ '\n* '.join( |
| 1393 |
f'[runtime][{label}][{key}]{name}' |
| 1394 |
for (label, key), names in bad.items() |
| 1395 |
for name in names |
| 1396 |
) |
| 1397 |
) |
| 1398 |
|
| 1399 |
def check_param_env_tmpls(self): |
| 1400 |
"""Check for illegal parameter environment templates""" |
| 1401 |
parameter_values = { |
| 1402 |
key: values[0] |
| 1403 |
for key, values in self.parameters[0].items() if values |
| 1404 |
} |
| 1405 |
bads = set() |
| 1406 |
for task_name, task_items in self.cfg['runtime'].items(): |
| 1407 |
if 'environment' not in task_items: |
| 1408 |
continue |
| 1409 |
for name, tmpl in task_items['environment'].items(): |
| 1410 |
try: |
| 1411 |
interpolate_template(tmpl, parameter_values) |
| 1412 |
except ParamExpandError as descr: |
| 1413 |
bads.add((task_name, name, tmpl, descr)) |
| 1414 |
if bads: |
| 1415 |
LOG.warning( |
| 1416 |
'bad parameter environment template:\n ' |
| 1417 |
+ '\n '.join( |
| 1418 |
'[runtime][%s][environment]%s = %s # %s' % |
| 1419 |
bad for bad in sorted(bads) |
| 1420 |
) |
| 1421 |
) |
| 1422 |
|
| 1423 |
def filter_env(self): |
| 1424 |
"""Filter environment variables after sparse inheritance""" |
| 1425 |
for ns in self.cfg['runtime'].values(): |
| 1426 |
try: |
| 1427 |
oenv = ns['environment'] |
| 1428 |
except KeyError: |
| 1429 |
# no environment to filter |
| 1430 |
continue |
| 1431 |
|
| 1432 |
try: |
| 1433 |
fincl = ns['environment filter']['include'] |
| 1434 |
except KeyError: |
| 1435 |
# empty include-filter means include all |
| 1436 |
fincl = [] |
| 1437 |
|
| 1438 |
try: |
| 1439 |
fexcl = ns['environment filter']['exclude'] |
| 1440 |
except KeyError: |
| 1441 |
# empty exclude-filter means exclude none |
| 1442 |
fexcl = [] |
| 1443 |
|
| 1444 |
if not fincl and not fexcl: |
| 1445 |
# no filtering to do |
| 1446 |
continue |
| 1447 |
|
| 1448 |
nenv = OrderedDictWithDefaults() |
| 1449 |
for key, val in oenv.items(): |
| 1450 |
if (not fincl or key in fincl) and key not in fexcl: |
| 1451 |
nenv[key] = val |
| 1452 |
ns['environment'] = nenv |
| 1453 |
|
| 1454 |
def compute_family_tree(self): |
| 1455 |
first_parents = {} |
| 1456 |
demoted = {} |
| 1457 |
for name in self.cfg['runtime']: |
| 1458 |
if name == 'root': |
| 1459 |
self.runtime['parents'][name] = [] |
| 1460 |
first_parents[name] = [] |
| 1461 |
continue |
| 1462 |
# get declared parents, with implicit inheritance from root. |
| 1463 |
pts = self.cfg['runtime'][name].get('inherit', ['root']) |
| 1464 |
if not pts: |
| 1465 |
pts = ['root'] |
| 1466 |
for p in pts: |
| 1467 |
if p == "None": |
| 1468 |
# see just below |
| 1469 |
continue |
| 1470 |
if p not in self.cfg['runtime']: |
| 1471 |
raise WorkflowConfigError( |
| 1472 |
"undefined parent for " + name + ": " + p) |
| 1473 |
if pts[0] == "None": |
| 1474 |
if len(pts) < 2: |
| 1475 |
raise WorkflowConfigError( |
| 1476 |
"null parentage for " + name) |
| 1477 |
demoted[name] = pts[1] |
| 1478 |
pts = pts[1:] |
| 1479 |
first_parents[name] = ['root'] |
| 1480 |
else: |
| 1481 |
first_parents[name] = [pts[0]] |
| 1482 |
self.runtime['parents'][name] = pts |
| 1483 |
|
| 1484 |
if cylc.flow.flags.verbosity > 0 and demoted: |
| 1485 |
log_msg = "First parent(s) demoted to secondary:" |
| 1486 |
for n, p in demoted.items(): |
| 1487 |
log_msg += "\n + %s as parent of '%s'" % (p, n) |
| 1488 |
LOG.debug(log_msg) |
| 1489 |
|
| 1490 |
c3 = C3(self.runtime['parents']) |
| 1491 |
c3_single = C3(first_parents) |
| 1492 |
|
| 1493 |
for name in self.cfg['runtime']: |
| 1494 |
try: |
| 1495 |
self.runtime['linearized ancestors'][name] = c3.mro(name) |
| 1496 |
self.runtime['first-parent ancestors'][name] = ( |
| 1497 |
c3_single.mro(name)) |
| 1498 |
except RecursionError: |
| 1499 |
raise WorkflowConfigError( |
| 1500 |
"circular [runtime] inheritance?" |
| 1501 |
) from None |
| 1502 |
except Exception as exc: |
| 1503 |
# catch inheritance errors |
| 1504 |
# TODO - specialise MRO exceptions |
| 1505 |
raise WorkflowConfigError(str(exc)) from None |
| 1506 |
|
| 1507 |
for name in self.cfg['runtime']: |
| 1508 |
ancestors = self.runtime['linearized ancestors'][name] |
| 1509 |
for p in ancestors[1:]: |
| 1510 |
self.runtime['descendants'].setdefault(p, set()).add(name) |
| 1511 |
first_ancestors = self.runtime['first-parent ancestors'][name] |
| 1512 |
for p in first_ancestors[1:]: |
| 1513 |
self.runtime['first-parent descendants'].setdefault( |
| 1514 |
p, set() |
| 1515 |
).add(name) |
| 1516 |
|
| 1517 |
def compute_inheritance(self): |
| 1518 |
LOG.debug("Parsing the runtime namespace hierarchy") |
| 1519 |
|
| 1520 |
# TODO: Note an unused alternative mechanism was removed here |
| 1521 |
# (March 2020). It stored the result of each completed MRO and |
| 1522 |
# re-used these wherever possible. This could be more efficient |
| 1523 |
# for full namespaces in deep hierarchies. We should go back and |
| 1524 |
# look if inheritance computation becomes a problem. |
| 1525 |
|
| 1526 |
results = OrderedDictWithDefaults() |
| 1527 |
|
| 1528 |
# Loop through runtime members, 'root' first. |
| 1529 |
nses = list(self.cfg['runtime']) |
| 1530 |
nses.sort(key=lambda ns: ns != 'root') |
| 1531 |
for ns in nses: |
| 1532 |
# for each namespace ... |
| 1533 |
|
| 1534 |
hierarchy = copy(self.runtime['linearized ancestors'][ns]) |
| 1535 |
hierarchy.reverse() |
| 1536 |
|
| 1537 |
result = OrderedDictWithDefaults() |
| 1538 |
|
| 1539 |
# Go up the linearized MRO from root, replicating or |
| 1540 |
# overriding each namespace element as we go. |
| 1541 |
for name in hierarchy: |
| 1542 |
replicate(result, self.cfg['runtime'][name]) |
| 1543 |
# n_reps += 1 |
| 1544 |
|
| 1545 |
results[ns] = result |
| 1546 |
|
| 1547 |
# replace pre-inheritance namespaces with the post-inheritance result |
| 1548 |
self.cfg['runtime'] = results |
| 1549 |
|
| 1550 |
# uncomment this to compare the simple and efficient methods |
| 1551 |
# print ' Number of namespace replications:', n_reps |
| 1552 |
|
| 1553 |
# def print_inheritance(self): |
| 1554 |
# # (use for debugging) |
| 1555 |
# for foo in self.runtime: |
| 1556 |
# log_msg = '\t' + foo |
| 1557 |
# for item, val in self.runtime[foo].items(): |
| 1558 |
# log_msg += '\t\t' + item + '\t' + val |
| 1559 |
# LOG.info(log_msg) |
| 1560 |
|
| 1561 |
def process_runahead_limit(self): |
| 1562 |
"""Extract runahead limit information.""" |
| 1563 |
limit = self.cfg['scheduling']['runahead limit'] |
| 1564 |
if limit.isdigit(): |
| 1565 |
limit = f'PT{limit}H' |
| 1566 |
LOG.warning( |
| 1567 |
'Use of a raw number of hours for the runahead limit is ' |
| 1568 |
f'deprecated. Use "{limit}" instead') |
| 1569 |
|
| 1570 |
number_limit_regex = re.compile(r'^P\d+$') |
| 1571 |
time_limit_regexes = DurationParser.DURATION_REGEXES |
| 1572 |
|
| 1573 |
if number_limit_regex.fullmatch(limit): |
| 1574 |
self.runahead_limit = IntegerInterval(limit) |
| 1575 |
elif ( # noqa: SIM106 |
| 1576 |
self.cycling_type == ISO8601_CYCLING_TYPE |
| 1577 |
and any(tlr.fullmatch(limit) for tlr in time_limit_regexes) |
| 1578 |
): |
| 1579 |
self.runahead_limit = ISO8601Interval(limit) |
| 1580 |
else: |
| 1581 |
raise WorkflowConfigError( |
| 1582 |
f'bad runahead limit "{limit}" for {self.cycling_type} ' |
| 1583 |
'cycling type') |
| 1584 |
|
| 1585 |
def get_config(self, args, sparse=False): |
| 1586 |
return self.pcfg.get(args, sparse) |
| 1587 |
|
| 1588 |
def adopt_orphans(self, orphans): |
| 1589 |
# Called by the scheduler after reloading the workflow definition |
| 1590 |
# at run time and finding any live task proxies whose |
| 1591 |
# definitions have been removed from the workflow. Keep them |
| 1592 |
# in the default queue and under the root family, until they |
| 1593 |
# run their course and disappear. |
| 1594 |
for orphan in orphans: |
| 1595 |
self.runtime['linearized ancestors'][orphan] = [orphan, 'root'] |
| 1596 |
|
| 1597 |
def configure_workflow_state_polling_tasks(self): |
| 1598 |
|
| 1599 |
# Deprecation warning - automatic workflow state polling tasks don't |
| 1600 |
# necessarily have deprecated config items outside the graph string. |
| 1601 |
if ( |
| 1602 |
self.workflow_polling_tasks and |
| 1603 |
getattr(self.options, 'is_validate', False) |
| 1604 |
): |
| 1605 |
LOG.warning( |
| 1606 |
"Workflow state polling tasks are deprecated." |
| 1607 |
" Please convert to workflow_state xtriggers:\n * " |
| 1608 |
+ "\n * ".join(self.workflow_polling_tasks) |
| 1609 |
) |
| 1610 |
|
| 1611 |
# Check custom script not defined for automatic workflow polling tasks. |
| 1612 |
for l_task in self.workflow_polling_tasks: |
| 1613 |
try: |
| 1614 |
cs = self.pcfg.get(sparse=True)['runtime'][l_task]['script'] |
| 1615 |
except KeyError: |
| 1616 |
pass |
| 1617 |
else: |
| 1618 |
if cs: |
| 1619 |
# (allow explicit blanking of inherited script) |
| 1620 |
raise WorkflowConfigError( |
| 1621 |
"script cannot be defined for automatic" + |
| 1622 |
" workflow polling task '%s':\n%s" % (l_task, cs)) |
| 1623 |
# Generate the automatic scripting. |
| 1624 |
for name, tdef in self.taskdefs.items(): |
| 1625 |
if name not in self.workflow_polling_tasks: |
| 1626 |
continue |
| 1627 |
rtc = tdef.rtconfig |
| 1628 |
comstr = ( |
| 1629 |
"cylc workflow-state " |
| 1630 |
f"{tdef.workflow_polling_cfg['workflow']}//" |
| 1631 |
"$CYLC_TASK_CYCLE_POINT/" |
| 1632 |
f"{tdef.workflow_polling_cfg['task']}" |
| 1633 |
) |
| 1634 |
graph_selector = tdef.workflow_polling_cfg['status'] |
| 1635 |
config_message = rtc['workflow state polling']['message'] |
| 1636 |
if ( |
| 1637 |
graph_selector is not None and |
| 1638 |
( |
| 1639 |
config_message is not None |
| 1640 |
) and ( |
| 1641 |
graph_selector != config_message |
| 1642 |
) |
| 1643 |
): |
| 1644 |
raise WorkflowConfigError( |
| 1645 |
f'Polling task "{name}" must configure a target status or' |
| 1646 |
f' output message in the graph (:{graph_selector}) or task' |
| 1647 |
f' definition (message = "{config_message}") but not both.' |
| 1648 |
) |
| 1649 |
if graph_selector is not None: |
| 1650 |
comstr += f":{graph_selector}" |
| 1651 |
elif config_message is not None: |
| 1652 |
# quote: may contain spaces |
| 1653 |
comstr += f':"{config_message}" --messages' |
| 1654 |
else: |
| 1655 |
# default to :succeeded |
| 1656 |
comstr += f":{TASK_OUTPUT_SUCCEEDED}" |
| 1657 |
|
| 1658 |
for key, fmt in [ |
| 1659 |
('interval', ' --%s=%d'), |
| 1660 |
('max-polls', ' --%s=%s'), |
| 1661 |
('alt-cylc-run-dir', ' --%s=%s')]: |
| 1662 |
if rtc['workflow state polling'][key]: |
| 1663 |
comstr += fmt % (key, rtc['workflow state polling'][key]) |
| 1664 |
script = f"echo {comstr}\n{comstr}" |
| 1665 |
rtc['script'] = script |
| 1666 |
|
| 1667 |
def get_parent_lists(self): |
| 1668 |
return self.runtime['parents'] |
| 1669 |
|
| 1670 |
def get_first_parent_ancestors(self, pruned=False): |
| 1671 |
if pruned: |
| 1672 |
# prune non-task namespaces from ancestors dict |
| 1673 |
pruned_ancestors = {} |
| 1674 |
for key, val in self.runtime['first-parent ancestors'].items(): |
| 1675 |
if key not in self.taskdefs: |
| 1676 |
continue |
| 1677 |
pruned_ancestors[key] = val |
| 1678 |
return pruned_ancestors |
| 1679 |
else: |
| 1680 |
return self.runtime['first-parent ancestors'] |
| 1681 |
|
| 1682 |
def get_linearized_ancestors(self): |
| 1683 |
return self.runtime['linearized ancestors'] |
| 1684 |
|
| 1685 |
def get_first_parent_descendants(self): |
| 1686 |
return self.runtime['first-parent descendants'] |
| 1687 |
|
| 1688 |
def add_tree_titles(self, tree): |
| 1689 |
for key, val in tree.items(): |
| 1690 |
if val == {}: |
| 1691 |
tree[key] = self.cfg['runtime'][key]['meta'].get( |
| 1692 |
'title', NO_TITLE) |
| 1693 |
elif isinstance(val, dict): |
| 1694 |
self.add_tree_titles(val) |
| 1695 |
|
| 1696 |
def get_namespace_list(self, which): |
| 1697 |
names = [] |
| 1698 |
if which == 'graphed tasks': |
| 1699 |
# tasks used only in the graph |
| 1700 |
names = list(self.taskdefs) |
| 1701 |
elif which == 'all namespaces': |
| 1702 |
# all namespaces |
| 1703 |
names = list(self.cfg['runtime']) |
| 1704 |
elif which == 'all tasks': |
| 1705 |
for ns in self.cfg['runtime']: |
| 1706 |
if ns not in self.runtime['descendants']: |
| 1707 |
# tasks have no descendants |
| 1708 |
names.append(ns) |
| 1709 |
result = {} |
| 1710 |
for ns in names: |
| 1711 |
result[ns] = self.cfg['runtime'][ns]['meta'].get( |
| 1712 |
'title', NO_TITLE) |
| 1713 |
|
| 1714 |
return result |
| 1715 |
|
| 1716 |
def get_mro(self, ns): |
| 1717 |
try: |
| 1718 |
mro = self.runtime['linearized ancestors'][ns] |
| 1719 |
except KeyError: |
| 1720 |
mro = ["no such namespace: " + ns] |
| 1721 |
return mro |
| 1722 |
|
| 1723 |
def process_workflow_env(self): |
| 1724 |
"""Export Workflow context to the local environment. |
| 1725 |
|
| 1726 |
A source workflow has only a name. |
| 1727 |
Once installed it also has an ID and a run directory. |
| 1728 |
And at scheduler start-up it has work, share, and log sub-dirs too. |
| 1729 |
""" |
| 1730 |
for key, value in { |
| 1731 |
**verbosity_to_env(cylc.flow.flags.verbosity), |
| 1732 |
'CYLC_WORKFLOW_NAME': self.workflow_name, |
| 1733 |
'CYLC_WORKFLOW_NAME_BASE': str(Path(self.workflow_name).name), |
| 1734 |
}.items(): |
| 1735 |
os.environ[key] = value |
| 1736 |
|
| 1737 |
if is_relative_to(self.fdir, get_cylc_run_dir()): |
| 1738 |
# This is an installed workflow. |
| 1739 |
# - self.run_dir is only defined by the scheduler |
| 1740 |
# - but the run dir exists, created at installation |
| 1741 |
# - run sub-dirs may exist, if this installation was run already |
| 1742 |
# but if the scheduler is not running they shouldn't be used. |
| 1743 |
for key, value in { |
| 1744 |
'CYLC_WORKFLOW_ID': self.workflow, |
| 1745 |
'CYLC_WORKFLOW_RUN_DIR': str(self.fdir), |
| 1746 |
}.items(): |
| 1747 |
os.environ[key] = value |
| 1748 |
|
| 1749 |
if self.run_dir is not None: |
| 1750 |
# Run directory is only defined if the scheduler is running; in |
| 1751 |
# which case the following run sub-directories must exist. |
| 1752 |
for key, value in { |
| 1753 |
'CYLC_WORKFLOW_LOG_DIR': str(self.log_dir), |
| 1754 |
'CYLC_WORKFLOW_WORK_DIR': str(self.work_dir), |
| 1755 |
'CYLC_WORKFLOW_SHARE_DIR': str(self.share_dir), |
| 1756 |
}.items(): |
| 1757 |
os.environ[key] = value |
| 1758 |
|
| 1759 |
def process_config_env(self): |
| 1760 |
"""Set local config derived environment.""" |
| 1761 |
os.environ['CYLC_UTC'] = str(get_utc_mode()) |
| 1762 |
os.environ['CYLC_WORKFLOW_INITIAL_CYCLE_POINT'] = str( |
| 1763 |
self.initial_point |
| 1764 |
) |
| 1765 |
os.environ['CYLC_WORKFLOW_FINAL_CYCLE_POINT'] = str(self.final_point) |
| 1766 |
os.environ['CYLC_CYCLING_MODE'] = self.cfg['scheduling'][ |
| 1767 |
'cycling mode'] |
| 1768 |
# Add workflow bin directory to PATH for workflow and event handlers |
| 1769 |
if self.share_dir is not None: |
| 1770 |
os.environ['PATH'] = os.pathsep.join( |
| 1771 |
[ |
| 1772 |
os.path.join(self.share_dir, 'bin'), |
| 1773 |
os.path.join(self.fdir, 'bin'), |
| 1774 |
os.environ['PATH'] |
| 1775 |
] |
| 1776 |
) |
| 1777 |
else: |
| 1778 |
os.environ['PATH'] = os.pathsep.join( |
| 1779 |
[ |
| 1780 |
os.path.join(self.fdir, 'bin'), |
| 1781 |
os.environ['PATH'] |
| 1782 |
] |
| 1783 |
) |
| 1784 |
|
| 1785 |
def _check_task_event_names(self, taskdef: 'TaskDef') -> None: |
| 1786 |
"""Validate task handler/mail event names.""" |
| 1787 |
for setting in ('handler events', 'mail events'): |
| 1788 |
event_names: Optional[List[str]] = taskdef.rtconfig['events'][ |
| 1789 |
setting |
| 1790 |
] |
| 1791 |
if not event_names: |
| 1792 |
continue |
| 1793 |
invalid = set(event_names).difference( |
| 1794 |
TaskEventsManager.STD_EVENTS, |
| 1795 |
taskdef.rtconfig['outputs'], |
| 1796 |
) |
| 1797 |
if invalid: |
| 1798 |
LOG.warning( |
| 1799 |
"Invalid event name(s) for " |
| 1800 |
f"[runtime][{taskdef.name}][events]{setting}: " |
| 1801 |
+ ', '.join(sorted(invalid)) |
| 1802 |
) |
| 1803 |
|
| 1804 |
def _check_task_event_handlers(self, taskdef: 'TaskDef') -> None: |
| 1805 |
"""Check custom event handler templates can be expanded. |
| 1806 |
|
| 1807 |
Ensures that any %(template_variables)s in task event handlers |
| 1808 |
are present in the data that will be passed to them when called |
| 1809 |
(otherwise they will fail). |
| 1810 |
""" |
| 1811 |
if not taskdef.rtconfig['events']: |
| 1812 |
return |
| 1813 |
handler_data = {item.value: '' for item in EventData} |
| 1814 |
handler_data.update( |
| 1815 |
get_event_handler_data(taskdef.rtconfig, self.cfg) |
| 1816 |
) |
| 1817 |
for key, values in taskdef.rtconfig['events'].items(): |
| 1818 |
if values and (key == 'handlers' or key.endswith(' handlers')): |
| 1819 |
for handler_template in values: |
| 1820 |
try: |
| 1821 |
handler_template % handler_data |
| 1822 |
except (KeyError, ValueError) as exc: |
| 1823 |
raise WorkflowConfigError( |
| 1824 |
f'bad task event handler template' |
| 1825 |
f' {taskdef.name}: {handler_template}: {repr(exc)}' |
| 1826 |
) from None |
| 1827 |
|
| 1828 |
def _check_special_tasks(self): |
| 1829 |
"""Check declared special tasks are valid, and detect special |
| 1830 |
implicit tasks""" |
| 1831 |
for task_type in self.cfg['scheduling']['special tasks']: |
| 1832 |
for name in self.cfg['scheduling']['special tasks'][task_type]: |
| 1833 |
if task_type in ['clock-trigger', 'clock-expire', |
| 1834 |
'external-trigger']: |
| 1835 |
name = name.split('(', 1)[0] |
| 1836 |
if not TaskID.is_valid_name(name): |
| 1837 |
raise WorkflowConfigError( |
| 1838 |
f'Illegal {task_type} task name: {name}') |
| 1839 |
if (name not in self.taskdefs and |
| 1840 |
name not in self.cfg['runtime']): |
| 1841 |
self.implicit_tasks.add(name) |
| 1842 |
|
| 1843 |
def _check_explicit_cycling(self): |
| 1844 |
"""Check that inter-cycle offsets refer to cycling tasks. |
| 1845 |
|
| 1846 |
E.G. foo[-P1] => bar requires foo to be defined in the |
| 1847 |
graph somewhere. |
| 1848 |
""" |
| 1849 |
for taskdef in self.taskdefs.values(): |
| 1850 |
taskdef.check_for_explicit_cycling() |
| 1851 |
|
| 1852 |
def get_task_name_list(self): |
| 1853 |
"""Return a sorted list of all tasks used in the dependency graph. |
| 1854 |
|
| 1855 |
Note: the sort order may effect get_graph_raw ouput. |
| 1856 |
|
| 1857 |
""" |
| 1858 |
return sorted(self.taskdefs) |
| 1859 |
|
| 1860 |
def generate_edges(self, lexpr, orig_lexpr, left_nodes, right, seq, |
| 1861 |
suicide=False): |
| 1862 |
"""Generate edges. |
| 1863 |
|
| 1864 |
Add nodes from this graph section to the abstract graph edges |
| 1865 |
structure. |
| 1866 |
""" |
| 1867 |
conditional = False |
| 1868 |
if '|' in lexpr: |
| 1869 |
# plot conditional triggers differently |
| 1870 |
conditional = True |
| 1871 |
|
| 1872 |
if seq not in self.edges: |
| 1873 |
self.edges[seq] = set() |
| 1874 |
if not left_nodes: |
| 1875 |
# Right is a lone node. |
| 1876 |
self.edges[seq].add((right, None, suicide, conditional)) |
| 1877 |
|
| 1878 |
conditional_xtriggers = [] |
| 1879 |
for left in left_nodes: |
| 1880 |
# if left is None: |
| 1881 |
# continue |
| 1882 |
# TODO - RIGHT CANNOT BE NONE NOW? |
| 1883 |
# if right is not None: |
| 1884 |
# Check for self-edges. |
| 1885 |
if left == right or left.startswith(right + ':'): |
| 1886 |
# (This passes inter-cycle offsets: left[-P1D] => left) |
| 1887 |
# (TODO - but not explicit null offsets like [-P0D]!) |
| 1888 |
if suicide: |
| 1889 |
continue |
| 1890 |
if orig_lexpr != lexpr: |
| 1891 |
LOG.error(f"{orig_lexpr} => {right}") |
| 1892 |
raise WorkflowConfigError( |
| 1893 |
f"self-edge detected: {left} => {right}") |
| 1894 |
if left.startswith('@') and conditional: |
| 1895 |
conditional_xtriggers.append(f'{lexpr} => {right}') |
| 1896 |
else: |
| 1897 |
self.edges[seq].add((left, right, suicide, conditional)) |
| 1898 |
if conditional_xtriggers: |
| 1899 |
raise WorkflowConfigError( |
| 1900 |
'Xtriggers cannot be used in conditional graph' |
| 1901 |
' expressions:\n' + |
| 1902 |
'\n * '.join(conditional_xtriggers) |
| 1903 |
) |
| 1904 |
|
| 1905 |
def generate_taskdef(self, orig_expr, node): |
| 1906 |
"""Generate task definition for node.""" |
| 1907 |
name = GraphNodeParser.get_inst().parse(node)[0] |
| 1908 |
taskdef = self.get_taskdef(name, orig_expr) |
| 1909 |
if name in self.workflow_polling_tasks: |
| 1910 |
taskdef.workflow_polling_cfg = { |
| 1911 |
'workflow': self.workflow_polling_tasks[name][0], |
| 1912 |
'task': self.workflow_polling_tasks[name][1], |
| 1913 |
'status': self.workflow_polling_tasks[name][2] |
| 1914 |
} |
| 1915 |
|
| 1916 |
def add_sequence(self, nodes, seq, suicide): |
| 1917 |
"""Add valid sequences to taskdefs.""" |
| 1918 |
graph_node_parser = GraphNodeParser.get_inst() |
| 1919 |
for node in nodes: |
| 1920 |
name, offset = graph_node_parser.parse(node)[:2] |
| 1921 |
taskdef = self.get_taskdef(name) |
| 1922 |
# Only add sequence to taskdef if explicit (not an offset). |
| 1923 |
if offset: |
| 1924 |
taskdef.used_in_offset_trigger = True |
| 1925 |
elif not suicide: |
| 1926 |
# "foo => !bar" does not define a sequence for bar |
| 1927 |
taskdef.add_sequence(seq) |
| 1928 |
|
| 1929 |
def generate_triggers(self, lexpression, left_nodes, right, seq, |
| 1930 |
suicide, task_triggers): |
| 1931 |
"""Create Dependency and TaskTrigger objects. |
| 1932 |
|
| 1933 |
Register dependency with the relevant TaskDef object. |
| 1934 |
|
| 1935 |
""" |
| 1936 |
if not right or not left_nodes: |
| 1937 |
# Lone nodes have no triggers. |
| 1938 |
return |
| 1939 |
|
| 1940 |
# Convert expression to a (nested) list. |
| 1941 |
try: |
| 1942 |
expr_list = listify(lexpression) |
| 1943 |
except SyntaxError: |
| 1944 |
raise WorkflowConfigError( |
| 1945 |
'Error in expression "%s"' % lexpression |
| 1946 |
) from None |
| 1947 |
|
| 1948 |
triggers = {} |
| 1949 |
xtrig_labels = set() |
| 1950 |
|
| 1951 |
graph_node_parser = GraphNodeParser.get_inst() |
| 1952 |
for left in left_nodes: |
| 1953 |
if left.startswith('@'): |
| 1954 |
xtrig_labels.add(left[1:]) |
| 1955 |
continue |
| 1956 |
# (GraphParseError checked above) |
| 1957 |
(name, offset, output, offset_is_from_icp, |
| 1958 |
offset_is_irregular, offset_is_absolute) = ( |
| 1959 |
graph_node_parser.parse(left) |
| 1960 |
) |
| 1961 |
|
| 1962 |
# Qualifier. |
| 1963 |
outputs = self.cfg['runtime'][name]['outputs'] |
| 1964 |
if outputs and (output in outputs): |
| 1965 |
# Qualifier is a custom task message. |
| 1966 |
qualifier = outputs[output] |
| 1967 |
elif output: |
| 1968 |
if not TaskOutputs.is_valid_std_name(output): |
| 1969 |
raise WorkflowConfigError( |
| 1970 |
f"Undefined custom output: {name}:{output}" |
| 1971 |
) |
| 1972 |
qualifier = output |
| 1973 |
else: |
| 1974 |
# No qualifier specified => use "succeeded". |
| 1975 |
qualifier = TASK_OUTPUT_SUCCEEDED |
| 1976 |
|
| 1977 |
# Generate TaskTrigger if not already done. |
| 1978 |
key = (name, offset, qualifier, |
| 1979 |
offset_is_irregular, offset_is_absolute, |
| 1980 |
offset_is_from_icp, self.initial_point) |
| 1981 |
try: |
| 1982 |
task_trigger = task_triggers[key] |
| 1983 |
except KeyError: |
| 1984 |
task_trigger = TaskTrigger(*key) |
| 1985 |
task_triggers[key] = task_trigger |
| 1986 |
|
| 1987 |
triggers[left] = task_trigger |
| 1988 |
|
| 1989 |
# (name is left name) |
| 1990 |
self.taskdefs[name].add_graph_child(task_trigger, right, seq) |
| 1991 |
# graph_parents not currently used but might be needed soon: |
| 1992 |
self.taskdefs[right].add_graph_parent(task_trigger, name, seq) |
| 1993 |
|
| 1994 |
# Walk down "expr_list" depth first, and replace any items matching a |
| 1995 |
# key in "triggers" ("left" values) with the trigger. |
| 1996 |
stack = [expr_list] |
| 1997 |
while stack: |
| 1998 |
item_list = stack.pop() |
| 1999 |
for i, item in enumerate(item_list): |
| 2000 |
if isinstance(item, list): |
| 2001 |
stack.append(item) |
| 2002 |
elif item in triggers: |
| 2003 |
item_list[i] = triggers[item] |
| 2004 |
|
| 2005 |
if triggers: |
| 2006 |
dependency = Dependency(expr_list, set(triggers.values()), suicide) |
| 2007 |
self.taskdefs[right].add_dependency(dependency, seq) |
| 2008 |
|
| 2009 |
validator = XtriggerNameValidator.validate |
| 2010 |
xtrigs = self.cfg['scheduling']['xtriggers'] |
| 2011 |
for label in xtrigs: |
| 2012 |
valid, msg = validator(label) |
| 2013 |
if not valid: |
| 2014 |
raise WorkflowConfigError( |
| 2015 |
f'Invalid xtrigger name "{label}" - {msg}' |
| 2016 |
) |
| 2017 |
|
| 2018 |
self.xtrigger_collator.sequential_xtriggers_default = ( |
| 2019 |
self.cfg['scheduling']['sequential xtriggers'] |
| 2020 |
) |
| 2021 |
for label in xtrig_labels: |
| 2022 |
try: |
| 2023 |
xtrig = xtrigs[label] |
| 2024 |
except KeyError: |
| 2025 |
if label != 'wall_clock': |
| 2026 |
raise WorkflowConfigError( |
| 2027 |
f"xtrigger not defined: {label}" |
| 2028 |
) from None |
| 2029 |
else: |
| 2030 |
# Allow "@wall_clock" in graph as implicit zero-offset. |
| 2031 |
xtrig = SubFuncContext('wall_clock', 'wall_clock', [], {}) |
| 2032 |
|
| 2033 |
if ( |
| 2034 |
xtrig.func_name == 'wall_clock' |
| 2035 |
and self.cycling_type == INTEGER_CYCLING_TYPE |
| 2036 |
): |
| 2037 |
raise WorkflowConfigError( |
| 2038 |
"Clock xtriggers require datetime cycling:" |
| 2039 |
f" {label} = {xtrig.get_signature()}" |
| 2040 |
) |
| 2041 |
|
| 2042 |
self.xtrigger_collator.add_trig(label, xtrig, self.fdir) |
| 2043 |
self.taskdefs[right].add_xtrig_label(label, seq) |
| 2044 |
|
| 2045 |
def get_actual_first_point(self, start_point): |
| 2046 |
"""Get actual first cycle point for the workflow |
| 2047 |
|
| 2048 |
Get all sequences to adjust the putative start time upward. |
| 2049 |
""" |
| 2050 |
if (self._start_point_for_actual_first_point is not None and |
| 2051 |
self._start_point_for_actual_first_point == start_point and |
| 2052 |
self.actual_first_point is not None): |
| 2053 |
return self.actual_first_point |
| 2054 |
self._start_point_for_actual_first_point = start_point |
| 2055 |
adjusted = [] |
| 2056 |
for seq in self.sequences: |
| 2057 |
point = seq.get_first_point(start_point) |
| 2058 |
if point: |
| 2059 |
adjusted.append(point) |
| 2060 |
if len(adjusted) > 0: |
| 2061 |
adjusted.sort() |
| 2062 |
self.actual_first_point = adjusted[0] |
| 2063 |
else: |
| 2064 |
self.actual_first_point = start_point |
| 2065 |
return self.actual_first_point |
| 2066 |
|
| 2067 |
def _get_stop_point(self, start_point, stop_point_str=None): |
| 2068 |
"""Get stop point from string value or interval, or return None.""" |
| 2069 |
if stop_point_str is None: |
| 2070 |
stop_point = None |
| 2071 |
elif "P" in stop_point_str: |
| 2072 |
# Is the final point(/interval) relative to initial? |
| 2073 |
if self.cfg['scheduling']['cycling mode'] == 'integer': |
| 2074 |
# Relative, integer cycling. |
| 2075 |
stop_point = get_point_relative( |
| 2076 |
stop_point_str, start_point |
| 2077 |
).standardise() |
| 2078 |
else: |
| 2079 |
# Relative, ISO8601 cycling. |
| 2080 |
stop_point = get_point_relative( |
| 2081 |
stop_point_str, start_point |
| 2082 |
).standardise() |
| 2083 |
else: |
| 2084 |
stop_point = get_point(stop_point_str).standardise() |
| 2085 |
return stop_point |
| 2086 |
|
| 2087 |
def get_graph_raw( |
| 2088 |
self, |
| 2089 |
start_point_str=None, |
| 2090 |
stop_point_str=None, |
| 2091 |
grouping=None, |
| 2092 |
sort=True, |
| 2093 |
): |
| 2094 |
"""Return concrete graph edges between specified cycle points. |
| 2095 |
|
| 2096 |
Return a family-collapsed graph if the grouping arg is not None: |
| 2097 |
* ['FAM1', 'FAM2']: group (collapse) specified families |
| 2098 |
* ['<all>']: group (collapse) all families above root |
| 2099 |
|
| 2100 |
For validation, return non-suicide edges with left and right nodes. |
| 2101 |
""" |
| 2102 |
start_point = get_point( |
| 2103 |
start_point_str or |
| 2104 |
self.cfg['scheduling']['initial cycle point'] |
| 2105 |
) |
| 2106 |
stop_point = self._get_stop_point(start_point, stop_point_str) |
| 2107 |
|
| 2108 |
actual_first_point = self.get_actual_first_point(start_point) |
| 2109 |
|
| 2110 |
if grouping is None: |
| 2111 |
grouping = [] |
| 2112 |
elif grouping == ['<all>']: |
| 2113 |
grouping = [ |
| 2114 |
fam for |
| 2115 |
fam in self.runtime["first-parent descendants"].keys() |
| 2116 |
if fam != "root" |
| 2117 |
] |
| 2118 |
else: |
| 2119 |
for bad in ( |
| 2120 |
set(grouping).difference( |
| 2121 |
self.runtime["first-parent descendants"].keys() |
| 2122 |
) |
| 2123 |
): |
| 2124 |
LOG.warning(f"Ignoring undefined family {bad}") |
| 2125 |
grouping.remove(bad) |
| 2126 |
|
| 2127 |
is_validate = getattr( |
| 2128 |
self.options, 'is_validate', False) # this is for _check_circular |
| 2129 |
if is_validate: |
| 2130 |
grouping = [] |
| 2131 |
|
| 2132 |
# Now define the concrete graph edges (pairs of nodes) for plotting. |
| 2133 |
|
| 2134 |
workflow_final_point = get_point( |
| 2135 |
self.cfg['scheduling']['final cycle point']) |
| 2136 |
|
| 2137 |
# For the computed stop point, store VIS_N_POINTS of each sequence, |
| 2138 |
# and then cull later to the first VIS_N_POINTS over all sequences. |
| 2139 |
|
| 2140 |
# For nested closed families, only consider the outermost one |
| 2141 |
fpd = self.runtime['first-parent descendants'] |
| 2142 |
clf_map = {} |
| 2143 |
for name in grouping: |
| 2144 |
if all( |
| 2145 |
name not in fpd[i] |
| 2146 |
for i in grouping |
| 2147 |
): |
| 2148 |
clf_map[name] = fpd[name] |
| 2149 |
|
| 2150 |
gr_edges = {} |
| 2151 |
start_point_offset_cache = {} |
| 2152 |
point_offset_cache = None |
| 2153 |
graph_node_parser = GraphNodeParser.get_inst() |
| 2154 |
for sequence, edges in self.edges.items(): |
| 2155 |
# Get initial cycle point for this sequence |
| 2156 |
point = sequence.get_first_point(start_point) |
| 2157 |
new_points = set() |
| 2158 |
while point is not None: |
| 2159 |
new_points.add(point) |
| 2160 |
if stop_point is None: |
| 2161 |
if len(new_points) > self.VIS_N_POINTS: |
| 2162 |
# Take VIS_N_POINTS cycles from each sequence. |
| 2163 |
break |
| 2164 |
elif point > stop_point: |
| 2165 |
# Beyond requested final cycle point. |
| 2166 |
break |
| 2167 |
if (workflow_final_point is not None |
| 2168 |
and point > workflow_final_point): |
| 2169 |
# Beyond workflow final cycle point. |
| 2170 |
break |
| 2171 |
|
| 2172 |
point_offset_cache = {} |
| 2173 |
for left, right, suicide, cond in edges: |
| 2174 |
if is_validate and (not right or suicide): |
| 2175 |
continue |
| 2176 |
if right: |
| 2177 |
r_id = (right, point) |
| 2178 |
else: |
| 2179 |
r_id = None |
| 2180 |
if left[0] == '@': |
| 2181 |
# @xtrigger node. |
| 2182 |
name = left |
| 2183 |
offset_is_from_icp = False |
| 2184 |
offset = None |
| 2185 |
else: |
| 2186 |
name, offset, _, offset_is_from_icp, _, _ = ( |
| 2187 |
graph_node_parser.parse(left) |
| 2188 |
) |
| 2189 |
if offset: |
| 2190 |
if offset_is_from_icp: |
| 2191 |
cache = start_point_offset_cache |
| 2192 |
rel_point = start_point |
| 2193 |
else: |
| 2194 |
cache = point_offset_cache |
| 2195 |
rel_point = point |
| 2196 |
try: |
| 2197 |
l_point = cache[offset] |
| 2198 |
except KeyError: |
| 2199 |
l_point = get_point_relative(offset, rel_point) |
| 2200 |
cache[offset] = l_point |
| 2201 |
else: |
| 2202 |
l_point = point |
| 2203 |
l_id = (name, l_point) |
| 2204 |
|
| 2205 |
if actual_first_point > l_point: |
| 2206 |
# Check that l_id is not earlier than start time. |
| 2207 |
if ( |
| 2208 |
is_validate |
| 2209 |
or r_id is None |
| 2210 |
or r_id[1] < actual_first_point |
| 2211 |
): |
| 2212 |
continue |
| 2213 |
# Pre-initial dependency; |
| 2214 |
# keep right hand node. |
| 2215 |
l_id = r_id |
| 2216 |
r_id = None |
| 2217 |
gr_edges.setdefault(point, []) |
| 2218 |
if is_validate: |
| 2219 |
gr_edges[point].append((l_id, r_id)) |
| 2220 |
else: |
| 2221 |
lstr, rstr = self._close_families(l_id, r_id, clf_map) |
| 2222 |
gr_edges[point].append( |
| 2223 |
(lstr, rstr, None, suicide, cond)) |
| 2224 |
# Increment the cycle point. |
| 2225 |
point = sequence.get_next_point_on_sequence(point) |
| 2226 |
|
| 2227 |
del clf_map |
| 2228 |
del start_point_offset_cache |
| 2229 |
del point_offset_cache |
| 2230 |
GraphNodeParser.get_inst().clear() |
| 2231 |
if stop_point is None: |
| 2232 |
# Prune to VIS_N_POINTS points in total. |
| 2233 |
graph_raw_edges = [] |
| 2234 |
for point in sorted(gr_edges)[:self.VIS_N_POINTS]: |
| 2235 |
graph_raw_edges.extend(gr_edges[point]) |
| 2236 |
else: |
| 2237 |
# Flatten nested list. |
| 2238 |
graph_raw_edges = ( |
| 2239 |
[i for sublist in gr_edges.values() for i in sublist]) |
| 2240 |
if sort: |
| 2241 |
graph_raw_edges.sort( |
| 2242 |
key=lambda x: [y if y else '' for y in x[:2]] |
| 2243 |
) |
| 2244 |
return graph_raw_edges |
| 2245 |
|
| 2246 |
def get_node_labels(self, start_point_str=None, stop_point_str=None): |
| 2247 |
"""Return dependency graph node labels.""" |
| 2248 |
ret = set() |
| 2249 |
for edge in self.get_graph_raw( |
| 2250 |
start_point_str, |
| 2251 |
stop_point_str, |
| 2252 |
): |
| 2253 |
left, right = edge[0:2] |
| 2254 |
if left: |
| 2255 |
ret.add(left) |
| 2256 |
if right: |
| 2257 |
ret.add(right) |
| 2258 |
return ret |
| 2259 |
|
| 2260 |
@staticmethod |
| 2261 |
def _close_families(l_id, r_id, clf_map): |
| 2262 |
"""Turn (name, point) to 'name.point' for edge. |
| 2263 |
|
| 2264 |
Replace close family members with family nodes if relevant. |
| 2265 |
""" |
| 2266 |
lret = None |
| 2267 |
lname, lpoint = None, None |
| 2268 |
if l_id: |
| 2269 |
lname, lpoint = l_id |
| 2270 |
lret = Tokens( |
| 2271 |
cycle=str(lpoint), |
| 2272 |
task=lname, |
| 2273 |
).relative_id |
| 2274 |
rret = None |
| 2275 |
rname, rpoint = None, None |
| 2276 |
if r_id: |
| 2277 |
rname, rpoint = r_id |
| 2278 |
rret = Tokens( |
| 2279 |
cycle=str(rpoint), |
| 2280 |
task=rname, |
| 2281 |
).relative_id |
| 2282 |
|
| 2283 |
for fam_name, fam_members in clf_map.items(): |
| 2284 |
if lname in fam_members and rname in fam_members: |
| 2285 |
# l and r are both members |
| 2286 |
lret = Tokens( |
| 2287 |
cycle=str(lpoint), |
| 2288 |
task=fam_name, |
| 2289 |
).relative_id |
| 2290 |
rret = Tokens( |
| 2291 |
cycle=str(rpoint), |
| 2292 |
task=fam_name, |
| 2293 |
).relative_id |
| 2294 |
break |
| 2295 |
elif lname in fam_members: |
| 2296 |
# l is a member |
| 2297 |
lret = Tokens( |
| 2298 |
cycle=str(lpoint), |
| 2299 |
task=fam_name, |
| 2300 |
).relative_id |
| 2301 |
elif rname in fam_members: |
| 2302 |
# r is a member |
| 2303 |
rret = Tokens( |
| 2304 |
cycle=str(rpoint), |
| 2305 |
task=fam_name, |
| 2306 |
).relative_id |
| 2307 |
|
| 2308 |
return lret, rret |
| 2309 |
|
| 2310 |
def _load_graph(self): |
| 2311 |
"""Parse and load dependency graph.""" |
| 2312 |
LOG.debug("Parsing the dependency graph") |
| 2313 |
|
| 2314 |
# Generate a map of *task* members of each family. |
| 2315 |
# Note we could exclude 'root' from this and disallow use of 'root' in |
| 2316 |
# the graph (which would probably be quite reasonable). |
| 2317 |
family_map = { |
| 2318 |
family: [ |
| 2319 |
task for task in sorted(tasks) |
| 2320 |
if ( |
| 2321 |
task in self.runtime['parents'] and |
| 2322 |
task not in self.runtime['descendants'] |
| 2323 |
) |
| 2324 |
] |
| 2325 |
for family, tasks in self.runtime['descendants'].items() |
| 2326 |
if family != 'root' |
| 2327 |
} |
| 2328 |
|
| 2329 |
graphdict = self.cfg['scheduling']['graph'] |
| 2330 |
if 'graph' in graphdict: |
| 2331 |
section = get_sequence_cls().get_async_expr() |
| 2332 |
graphdict[section] = graphdict.pop('graph') |
| 2333 |
|
| 2334 |
icp = str(self.initial_point) |
| 2335 |
fcp = self.cfg['scheduling']['final cycle point'] |
| 2336 |
|
| 2337 |
# Make a stack of sections and graphs [(sec1, graph1), ...] |
| 2338 |
sections = [] |
| 2339 |
for section, value in self.cfg['scheduling']['graph'].items(): |
| 2340 |
# Substitute initial and final cycle points. |
| 2341 |
section = section.replace("^", icp) |
| 2342 |
if fcp: |
| 2343 |
section = section.replace("$", fcp) |
| 2344 |
elif "$" in section: |
| 2345 |
raise WorkflowConfigError("Final cycle point referenced" |
| 2346 |
" ($) but not defined.") |
| 2347 |
# If the section consists of more than one sequence, split it up. |
| 2348 |
new_sections = RE_SEC_MULTI_SEQ.split(section) |
| 2349 |
if len(new_sections) > 1: |
| 2350 |
for new_section in new_sections: |
| 2351 |
sections.append((new_section.strip(), value)) |
| 2352 |
else: |
| 2353 |
sections.append((section, value)) |
| 2354 |
|
| 2355 |
# Parse and process each graph section. |
| 2356 |
task_triggers = {} |
| 2357 |
task_output_opt = {} |
| 2358 |
for section, graph in sections: |
| 2359 |
try: |
| 2360 |
seq = get_sequence(section, icp, fcp) |
| 2361 |
except (AttributeError, TypeError, ValueError, CylcError) as exc: |
| 2362 |
if cylc.flow.flags.verbosity > 1: |
| 2363 |
traceback.print_exc() |
| 2364 |
msg = 'Cannot process recurrence %s' % section |
| 2365 |
msg += ' (initial cycle point=%s)' % icp |
| 2366 |
msg += ' (final cycle point=%s)' % fcp |
| 2367 |
if isinstance(exc, CylcError): |
| 2368 |
msg += ' %s' % exc.args[0] |
| 2369 |
raise WorkflowConfigError(msg) from None |
| 2370 |
self.sequences.append(seq) |
| 2371 |
parser = GraphParser( |
| 2372 |
family_map, |
| 2373 |
self.parameters, |
| 2374 |
task_output_opt=task_output_opt, |
| 2375 |
expire_triggers=self.experimental.expire_triggers, |
| 2376 |
) |
| 2377 |
parser.parse_graph(graph) |
| 2378 |
task_output_opt.update(parser.task_output_opt) |
| 2379 |
self.workflow_polling_tasks.update( |
| 2380 |
parser.workflow_state_polling_tasks) |
| 2381 |
self._proc_triggers(parser, seq, task_triggers) |
| 2382 |
|
| 2383 |
# Checking for undefined outputs for terminal tasks. Tasks with |
| 2384 |
# dependencies are checked in generate_triggers: |
| 2385 |
self.check_terminal_outputs(parser.terminals) |
| 2386 |
|
| 2387 |
# set of all cycling intervals containined within the workflow |
| 2388 |
cycling_intervals = { |
| 2389 |
sequence.get_interval() |
| 2390 |
for sequence in self.sequences |
| 2391 |
} | { |
| 2392 |
# add a null interval to handle async workflows |
| 2393 |
get_interval_cls().get_null() |
| 2394 |
} |
| 2395 |
|
| 2396 |
# determine the longest cycling interval in the workflow |
| 2397 |
self.interval_of_longest_sequence: 'IntervalBase' = max({ |
| 2398 |
interval for interval in cycling_intervals |
| 2399 |
# NOTE: None type sorts above a null interval for strange |
| 2400 |
# historical reasons so must be filtered out |
| 2401 |
if interval is not None |
| 2402 |
}) |
| 2403 |
|
| 2404 |
self.set_required_outputs(task_output_opt) |
| 2405 |
|
| 2406 |
if cylc.flow.flags.verbosity > 1: |
| 2407 |
# Print inferred output optionality for debugging the graph parser. |
| 2408 |
# (This does not includes tasks that default to success-required.) |
| 2409 |
optionals = [ |
| 2410 |
f" \u2022 {name}:{output}" |
| 2411 |
for (name, output), (optional, _, _) in task_output_opt.items() |
| 2412 |
if optional |
| 2413 |
] |
| 2414 |
requireds = [ |
| 2415 |
f" \u2022 {name}:{output}" |
| 2416 |
for (name, output), (optional, _, _) in task_output_opt.items() |
| 2417 |
if not optional |
| 2418 |
] |
| 2419 |
if optionals: |
| 2420 |
LOG.debug( |
| 2421 |
"Optional outputs inferred from the graph:\n" |
| 2422 |
f"{'\n'.join(optionals)}" |
| 2423 |
) |
| 2424 |
if requireds: |
| 2425 |
LOG.debug( |
| 2426 |
"Required outputs inferred from the graph:\n" |
| 2427 |
f"{'\n'.join(requireds)}" |
| 2428 |
) |
| 2429 |
|
| 2430 |
# Detect use of xtrigger names with '@' prefix (creates a task). |
| 2431 |
overlap = set(self.taskdefs.keys()).intersection( |
| 2432 |
list(self.cfg['scheduling']['xtriggers'])) |
| 2433 |
if overlap: |
| 2434 |
LOG.error(', '.join(overlap)) |
| 2435 |
raise WorkflowConfigError('task and @xtrigger names clash') |
| 2436 |
|
| 2437 |
for tdef in self.taskdefs.values(): |
| 2438 |
tdef.tweak_outputs() |
| 2439 |
|
| 2440 |
def check_terminal_outputs(self, terminals: Iterable[str]) -> None: |
| 2441 |
"""Check that task outputs have been registered with tasks. |
| 2442 |
|
| 2443 |
Where a "terminal output" is an output for a task at the end of a |
| 2444 |
graph string, such as "end" in `start => middle => end`. |
| 2445 |
|
| 2446 |
Raises: WorkflowConfigError if a custom output is not defined. |
| 2447 |
""" |
| 2448 |
for t in terminals: |
| 2449 |
if ':' not in t: |
| 2450 |
continue |
| 2451 |
task, output = t.split(':') |
| 2452 |
if (output := output.strip('?')) in TASK_QUALIFIERS: |
| 2453 |
continue |
| 2454 |
task = task.strip('!') |
| 2455 |
if output not in self.cfg['runtime'][task]['outputs']: |
| 2456 |
raise WorkflowConfigError( |
| 2457 |
f"Undefined custom output: {task}:{output}" |
| 2458 |
) |
| 2459 |
|
| 2460 |
def _proc_triggers(self, parser, seq, task_triggers): |
| 2461 |
"""Define graph edges, taskdefs, and triggers, from graph sections.""" |
| 2462 |
suicides = 0 |
| 2463 |
for right, val in parser.triggers.items(): |
| 2464 |
for expr, trigs in val.items(): |
| 2465 |
orig = parser.original[right][expr] |
| 2466 |
lefts, suicide = trigs |
| 2467 |
|
| 2468 |
# (lefts, right) e.g.: |
| 2469 |
# for """ |
| 2470 |
# foo|bar => baz |
| 2471 |
# @x => baz |
| 2472 |
# """ |
| 2473 |
# - ([], foo) |
| 2474 |
# - ([], bar) |
| 2475 |
# - (['foo:succeeded', 'bar:succeeded'], baz) |
| 2476 |
# - (['@x'], baz) |
| 2477 |
self.generate_edges(expr, orig, lefts, right, seq, suicide) |
| 2478 |
|
| 2479 |
# Lefts can be null; all appear on RHS once so can generate |
| 2480 |
# taskdefs with right only. Right is never None or @xtrigger. |
| 2481 |
self.generate_taskdef(orig, right) |
| 2482 |
|
| 2483 |
self.add_sequence( |
| 2484 |
[ |
| 2485 |
node |
| 2486 |
for node in lefts + [right] |
| 2487 |
if node and not node.startswith('@') |
| 2488 |
], |
| 2489 |
seq, |
| 2490 |
suicide |
| 2491 |
) |
| 2492 |
|
| 2493 |
# RHS quals not needed now (used already for taskdef outputs) |
| 2494 |
right = parser.REC_QUAL.sub('', right) |
| 2495 |
self.generate_triggers( |
| 2496 |
expr, lefts, right, seq, suicide, task_triggers) |
| 2497 |
if suicide: |
| 2498 |
suicides += 1 |
| 2499 |
|
| 2500 |
if suicides and not cylc.flow.flags.cylc7_back_compat: |
| 2501 |
LOG.info( |
| 2502 |
f"{suicides} suicide trigger(s) detected. These are rarely " |
| 2503 |
"needed in Cylc 8 - see https://cylc.github.io/cylc-doc/" |
| 2504 |
"stable/html/7-to-8/major-changes/suicide-triggers.html" |
| 2505 |
) |
| 2506 |
|
| 2507 |
def set_required_outputs( |
| 2508 |
self, task_output_opt: Dict[Tuple[str, str], Tuple[bool, bool, bool]] |
| 2509 |
) -> None: |
| 2510 |
"""set optional/required status of parsed task outputs. |
| 2511 |
|
| 2512 |
Args: |
| 2513 |
task_output_opt: {(task, output): (is-optional, default, is_set)} |
| 2514 |
""" |
| 2515 |
for name, taskdef in self.taskdefs.items(): |
| 2516 |
for output in taskdef.outputs: |
| 2517 |
try: |
| 2518 |
optional, _, _ = task_output_opt[(name, output)] |
| 2519 |
except KeyError: |
| 2520 |
# Output not used in graph. |
| 2521 |
continue |
| 2522 |
taskdef.set_required_output(output, not optional) |
| 2523 |
|
| 2524 |
def find_taskdefs(self, name: str) -> Set[TaskDef]: |
| 2525 |
"""Find TaskDef objects in family "name" or matching "name". |
| 2526 |
|
| 2527 |
Return a list of TaskDef objects which: |
| 2528 |
* have names that glob matches "name". |
| 2529 |
* are in a family that glob matches "name". |
| 2530 |
""" |
| 2531 |
if name in self.taskdefs: |
| 2532 |
# Match a task name |
| 2533 |
return {self.taskdefs[name]} |
| 2534 |
|
| 2535 |
fams = self.runtime['first-parent descendants'] |
| 2536 |
if name in fams: |
| 2537 |
# Match a family name |
| 2538 |
return { |
| 2539 |
self.taskdefs[member] for member in fams[name] |
| 2540 |
if member in self.taskdefs |
| 2541 |
} |
| 2542 |
|
| 2543 |
# Glob match |
| 2544 |
from_task_names = { |
| 2545 |
taskdef for key, taskdef in self.taskdefs.items() |
| 2546 |
if fnmatchcase(key, name) |
| 2547 |
} |
| 2548 |
from_family_names = { |
| 2549 |
self.taskdefs[member] |
| 2550 |
for key, members in fams.items() |
| 2551 |
if fnmatchcase(key, name) |
| 2552 |
for member in members |
| 2553 |
if member in self.taskdefs |
| 2554 |
} |
| 2555 |
return from_task_names.union(from_family_names) |
| 2556 |
|
| 2557 |
def get_taskdef( |
| 2558 |
self, name: str, orig_expr: Optional[str] = None |
| 2559 |
) -> TaskDef: |
| 2560 |
"""Return an instance of TaskDef for task name.""" |
| 2561 |
if name not in self.taskdefs: |
| 2562 |
if name == 'root': |
| 2563 |
self.implicit_tasks.add(name) |
| 2564 |
elif name not in self.cfg['runtime']: |
| 2565 |
# implicit inheritance from root |
| 2566 |
self.implicit_tasks.add(name) |
| 2567 |
# These can't just be a reference to root runtime as we have to |
| 2568 |
# make some items task-specific: e.g. subst task name in URLs. |
| 2569 |
self.cfg['runtime'][name] = OrderedDictWithDefaults() |
| 2570 |
replicate(self.cfg['runtime'][name], |
| 2571 |
self.cfg['runtime']['root']) |
| 2572 |
if 'root' not in self.runtime['descendants']: |
| 2573 |
# (happens when no runtimes are defined in flow.cylc) |
| 2574 |
self.runtime['descendants']['root'] = set() |
| 2575 |
if 'root' not in self.runtime['first-parent descendants']: |
| 2576 |
# (happens when no runtimes are defined in flow.cylc) |
| 2577 |
self.runtime['first-parent descendants']['root'] = set() |
| 2578 |
self.runtime['parents'][name] = ['root'] |
| 2579 |
self.runtime['linearized ancestors'][name] = [name, 'root'] |
| 2580 |
self.runtime['first-parent ancestors'][name] = [name, 'root'] |
| 2581 |
self.runtime['descendants']['root'].add(name) |
| 2582 |
self.runtime['first-parent descendants']['root'].add(name) |
| 2583 |
self.ns_defn_order.append(name) |
| 2584 |
|
| 2585 |
try: |
| 2586 |
self.taskdefs[name] = self._get_taskdef(name) |
| 2587 |
except TaskDefError as exc: |
| 2588 |
if orig_expr: |
| 2589 |
LOG.error(orig_expr) |
| 2590 |
raise WorkflowConfigError(str(exc)) from None |
| 2591 |
else: |
| 2592 |
# Record custom message outputs from [runtime]. |
| 2593 |
messages = set(self.cfg['runtime'][name]['outputs'].values()) |
| 2594 |
for output, message in ( |
| 2595 |
self.cfg['runtime'][name]['outputs'].items() |
| 2596 |
): |
| 2597 |
try: |
| 2598 |
messages.remove(message) |
| 2599 |
except KeyError: |
| 2600 |
raise WorkflowConfigError( |
| 2601 |
'Duplicate task message in' |
| 2602 |
f' "[runtime][{name}][outputs]' |
| 2603 |
f'{output} = {message}" - messages must be unique' |
| 2604 |
) from None |
| 2605 |
valid, msg = TaskOutputValidator.validate(output) |
| 2606 |
if not valid: |
| 2607 |
raise WorkflowConfigError( |
| 2608 |
f'Invalid task output "' |
| 2609 |
f'[runtime][{name}][outputs]' |
| 2610 |
f'{output} = {message}" - {msg}' |
| 2611 |
) |
| 2612 |
valid, msg = TaskMessageValidator.validate(message) |
| 2613 |
if not valid: |
| 2614 |
raise WorkflowConfigError( |
| 2615 |
f'Invalid task message "' |
| 2616 |
f'[runtime][{name}][outputs]' |
| 2617 |
f'{output} = {message}" - {msg}' |
| 2618 |
) |
| 2619 |
self.taskdefs[name].add_output(output, message) |
| 2620 |
|
| 2621 |
return self.taskdefs[name] |
| 2622 |
|
| 2623 |
def _get_taskdef(self, name: str) -> TaskDef: |
| 2624 |
"""Get the dense task runtime.""" |
| 2625 |
# (TaskDefError caught above) |
| 2626 |
|
| 2627 |
try: |
| 2628 |
rtcfg = self.cfg['runtime'][name] |
| 2629 |
|
| 2630 |
# If the workflow mode is simulation or dummy always |
| 2631 |
# override the task config: |
| 2632 |
workflow_run_mode = RunMode.get(self.options) |
| 2633 |
if workflow_run_mode.value in WORKFLOW_ONLY_MODES: |
| 2634 |
rtcfg['run mode'] = workflow_run_mode.value |
| 2635 |
|
| 2636 |
except KeyError: |
| 2637 |
raise WorkflowConfigError("Task not defined: %s" % name) from None |
| 2638 |
# We may want to put in some handling for cases of changing the |
| 2639 |
# initial cycle via restart (accidentally or otherwise). |
| 2640 |
|
| 2641 |
# Get the taskdef object for generating the task proxy class |
| 2642 |
taskd = TaskDef( |
| 2643 |
name, |
| 2644 |
rtcfg, |
| 2645 |
self.start_point, |
| 2646 |
self.initial_point) |
| 2647 |
|
| 2648 |
# TODO - put all taskd.foo items in a single config dict |
| 2649 |
|
| 2650 |
if name in self.expiration_offsets: |
| 2651 |
taskd.expiration_offset = self.expiration_offsets[name] |
| 2652 |
if name in self.ext_triggers: |
| 2653 |
taskd.external_triggers.append(self.ext_triggers[name]) |
| 2654 |
|
| 2655 |
taskd.sequential = ( |
| 2656 |
name in self.cfg['scheduling']['special tasks']['sequential']) |
| 2657 |
|
| 2658 |
taskd.namespace_hierarchy = list( |
| 2659 |
reversed(self.runtime['linearized ancestors'][name])) |
| 2660 |
|
| 2661 |
if name in self.task_param_vars: |
| 2662 |
taskd.param_var.update(self.task_param_vars[name]) |
| 2663 |
|
| 2664 |
return taskd |
| 2665 |
|
| 2666 |
def describe(self, name): |
| 2667 |
"""Return title and description of the named task.""" |
| 2668 |
return self.taskdefs[name].describe() |
| 2669 |
|
| 2670 |
def get_ref_log_name(self): |
| 2671 |
"""Return path to reference log (for reference test).""" |
| 2672 |
return os.path.join(self.fdir, 'reference.log') |
| 2673 |
|
| 2674 |
def get_expected_failed_tasks(self): |
| 2675 |
"""Return list of expected failed tasks. |
| 2676 |
|
| 2677 |
Return: |
| 2678 |
- An empty list if NO task is expected to fail. |
| 2679 |
- A list of NAME.CYCLE for the tasks that are expected to fail |
| 2680 |
in reference test mode. |
| 2681 |
- None if there is no expectation either way. |
| 2682 |
""" |
| 2683 |
if self.options.reftest: |
| 2684 |
return self.cfg['scheduler']['events']['expected task failures'] |
| 2685 |
elif self.options.abort_if_any_task_fails: |
| 2686 |
return [] |
| 2687 |
else: |
| 2688 |
return None |
| 2689 |
|
| 2690 |
def get_validated_rsync_includes(self): |
| 2691 |
"""Validate and return items to be included in the file installation""" |
| 2692 |
includes = self.cfg['scheduler']['install'] |
| 2693 |
illegal_includes = {} |
| 2694 |
for include in includes: |
| 2695 |
include_path = Path(include) |
| 2696 |
if include_path.is_absolute(): |
| 2697 |
illegal_includes[include] = 'Paths cannot be absolute' |
| 2698 |
elif len(include_path.parts) > 1: |
| 2699 |
illegal_includes[include] = ( |
| 2700 |
'Only top-level files/directories can be configured' |
| 2701 |
) |
| 2702 |
if len(illegal_includes) > 0: |
| 2703 |
raise WorkflowConfigError( |
| 2704 |
'Error in [scheduler]install:\n\t' |
| 2705 |
+ '\n\t'.join( |
| 2706 |
f'"{path}" - {message}.' |
| 2707 |
for path, message in illegal_includes.items() |
| 2708 |
) |
| 2709 |
) |
| 2710 |
return includes |
| 2711 |
|
| 2712 |
def process_metadata_urls(self): |
| 2713 |
"""Process [meta]URL items.""" |
| 2714 |
# workflow metadata |
| 2715 |
url = self.cfg['meta']['URL'] |
| 2716 |
try: |
| 2717 |
self.cfg['meta']['URL'] = url % { |
| 2718 |
'workflow': self.workflow, |
| 2719 |
} |
| 2720 |
except (KeyError, ValueError): |
| 2721 |
try: |
| 2722 |
# Replace workflow and task name in workflow and task URLs. |
| 2723 |
# BACK COMPAT: suite_name |
| 2724 |
# url: |
| 2725 |
# https://github.com/cylc/cylc-flow/pull/4724 |
| 2726 |
# from: |
| 2727 |
# Cylc7 |
| 2728 |
# to: |
| 2729 |
# Cylc8 |
| 2730 |
# remove at: |
| 2731 |
# Cylc8.x |
| 2732 |
self.cfg['meta']['URL'] = url % { |
| 2733 |
# cylc 7 |
| 2734 |
'suite_name': self.workflow, |
| 2735 |
# cylc 8 |
| 2736 |
'workflow': self.workflow, |
| 2737 |
} |
| 2738 |
except (KeyError, ValueError): |
| 2739 |
raise InputError( |
| 2740 |
f'Invalid template [meta]URL: {url}' |
| 2741 |
) from None |
| 2742 |
else: |
| 2743 |
LOG.warning( |
| 2744 |
'Detected deprecated template variables in [meta]URL.' |
| 2745 |
'\nSee the configuration documentation for details.' |
| 2746 |
) |
| 2747 |
|
| 2748 |
# task metadata |
| 2749 |
self.cfg['meta']['URL'] = RE_WORKFLOW_ID_VAR.sub( |
| 2750 |
self.workflow, self.cfg['meta']['URL']) |
| 2751 |
for name, cfg in self.cfg['runtime'].items(): |
| 2752 |
try: |
| 2753 |
cfg['meta']['URL'] = cfg['meta']['URL'] % { |
| 2754 |
'workflow': self.workflow, |
| 2755 |
'task': name, |
| 2756 |
} |
| 2757 |
except (KeyError, ValueError): |
| 2758 |
# BACK COMPAT: suite_name, task_name |
| 2759 |
# url: |
| 2760 |
# https://github.com/cylc/cylc-flow/pull/4724 |
| 2761 |
# from: |
| 2762 |
# Cylc7 |
| 2763 |
# to: |
| 2764 |
# Cylc8 |
| 2765 |
# remove at: |
| 2766 |
# Cylc8.x |
| 2767 |
try: |
| 2768 |
cfg['meta']['URL'] = cfg['meta']['URL'] % { |
| 2769 |
# cylc 7 |
| 2770 |
'suite_name': self.workflow, |
| 2771 |
'task_name': name, |
| 2772 |
# cylc 8 |
| 2773 |
'workflow': self.workflow, |
| 2774 |
'task': name, |
| 2775 |
} |
| 2776 |
except (KeyError, ValueError): |
| 2777 |
raise InputError( |
| 2778 |
f'Invalid template [meta]URL: {url}' |
| 2779 |
) from None |
| 2780 |
else: |
| 2781 |
LOG.warning( |
| 2782 |
'Detected deprecated template variables in' |
| 2783 |
f' [runtime][{name}][meta]URL.' |
| 2784 |
'\nSee the configuration documentation for details.' |
| 2785 |
) |
| 2786 |
cfg['meta']['URL'] = RE_WORKFLOW_ID_VAR.sub( |
| 2787 |
self.workflow, cfg['meta']['URL']) |
| 2788 |
cfg['meta']['URL'] = RE_TASK_NAME_VAR.sub( |
| 2789 |
name, cfg['meta']['URL']) |
| 2790 |
|
| 2791 |
@staticmethod |
| 2792 |
def check_for_owner(tasks: Dict) -> None: |
| 2793 |
"""Raise exception if [runtime][task][remote]owner |
| 2794 |
""" |
| 2795 |
owners = {} |
| 2796 |
for task, tdef in tasks.items(): |
| 2797 |
owner = tdef.get('remote', {}).get('owner', None) |
| 2798 |
if owner: |
| 2799 |
owners[task] = owner |
| 2800 |
if owners: |
| 2801 |
# TODO: Convert URL to a stable or latest release doc after 8.0 |
| 2802 |
# https://github.com/cylc/cylc-flow/issues/4663 |
| 2803 |
msg = ( |
| 2804 |
'"[runtime][task][remote]owner" is obsolete at Cylc 8.' |
| 2805 |
'\nsee https://cylc.github.io/cylc-doc/stable/' |
| 2806 |
'html/7-to-8/major-changes/remote-owner.html' |
| 2807 |
f'\nFirst {min(len(owners), 5)} tasks:' |
| 2808 |
) |
| 2809 |
for task, _ in list(owners.items())[:5]: |
| 2810 |
msg += f'\n * {task}"' |
| 2811 |
raise WorkflowConfigError(msg) |
| 2812 |
|
| 2813 |
def upgrade_clock_triggers(self): |
| 2814 |
"""Convert old-style clock triggers to clock xtriggers. |
| 2815 |
|
| 2816 |
[[special tasks]] |
| 2817 |
clock-trigger = foo(PT1D) |
| 2818 |
|
| 2819 |
becomes: |
| 2820 |
|
| 2821 |
[[xtriggers]] |
| 2822 |
_cylc_wall_clock_foo = wallclock(PT1D) |
| 2823 |
|
| 2824 |
Not done by parsec upgrade because the graph has to be parsed first. |
| 2825 |
""" |
| 2826 |
for item in self.cfg['scheduling']['special tasks']['clock-trigger']: |
| 2827 |
match = RE_CLOCK_OFFSET.match(item) |
| 2828 |
# (Already validated during "special tasks" parsing above.) |
| 2829 |
task_name, offset = match.groups() |
| 2830 |
# Derive an xtrigger label. |
| 2831 |
label = '_'.join(('_cylc', 'wall_clock', task_name)) |
| 2832 |
# Define the xtrigger function. |
| 2833 |
args = [] if offset is None else [offset] |
| 2834 |
xtrig = SubFuncContext(label, 'wall_clock', args, {}) |
| 2835 |
self.xtrigger_collator.add_trig(label, xtrig, self.fdir) |
| 2836 |
# Add it to the task, for each sequence that the task appears in. |
| 2837 |
taskdef = self.get_taskdef(task_name) |
| 2838 |
for seq in taskdef.sequences: |
| 2839 |
taskdef.add_xtrig_label(label, seq) |
| 2840 |
|
| 2841 |
def _upg_wflow_event_names(self) -> None: |
| 2842 |
"""Upgrade any Cylc 7 workflow handler/mail events names.""" |
| 2843 |
for setting in ('handler events', 'mail events'): |
| 2844 |
event_names: Optional[List[str]] = self.cfg['scheduler']['events'][ |
| 2845 |
setting |
| 2846 |
] |
| 2847 |
if not event_names: |
| 2848 |
continue |
| 2849 |
upgraded: Dict[str, str] = {} |
| 2850 |
for i, event in enumerate(event_names): |
| 2851 |
if event in WorkflowEventHandler.EVENTS_DEPRECATED: |
| 2852 |
event_names[i] = upgraded[event] = ( |
| 2853 |
WorkflowEventHandler.EVENTS_DEPRECATED[event] |
| 2854 |
) |
| 2855 |
if upgraded and not cylc.flow.flags.cylc7_back_compat: |
| 2856 |
LOG.warning( |
| 2857 |
f"{upgrader.depr_msg}\n" |
| 2858 |
f" * (8.0.0) [scheduler][events][{setting}] " |
| 2859 |
+ ', '.join(f'{k} -> {v}' for k, v in upgraded.items()) |
| 2860 |
) |