| 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 |
"""Manage broadcast (and external trigger broadcast).""" |
| 17 |
|
| 18 |
import re |
| 19 |
from copy import deepcopy |
| 20 |
from threading import RLock |
| 21 |
from typing import Optional, TYPE_CHECKING |
| 22 |
|
| 23 |
from cylc.flow import LOG |
| 24 |
from cylc.flow.broadcast_report import ( |
| 25 |
CHANGE_FMT, |
| 26 |
CHANGE_PREFIX_SET, |
| 27 |
get_broadcast_change_report, |
| 28 |
get_broadcast_bad_options_report, |
| 29 |
) |
| 30 |
from cylc.flow.cfgspec.workflow import SPEC |
| 31 |
from cylc.flow.cycling.loader import get_point, standardise_point_string |
| 32 |
from cylc.flow.exceptions import PointParsingError |
| 33 |
from cylc.flow.parsec.util import listjoin, pdeepcopy, poverride |
| 34 |
from cylc.flow.parsec.validate import BroadcastConfigValidator |
| 35 |
from cylc.flow.run_modes import WORKFLOW_ONLY_MODES |
| 36 |
from cylc.flow.platforms import ( |
| 37 |
fail_if_platform_and_host_conflict, |
| 38 |
PlatformLookupError, |
| 39 |
) |
| 40 |
from cylc.flow.util import uniq |
| 41 |
|
| 42 |
if TYPE_CHECKING: |
| 43 |
from cylc.flow.id import Tokens |
| 44 |
from cylc.flow.task_proxy import TaskProxy |
| 45 |
|
| 46 |
|
| 47 |
ALL_CYCLE_POINTS_STRS = ["*", "all-cycle-points", "all-cycles"] |
| 48 |
|
| 49 |
|
| 50 |
def addict(target, source): |
| 51 |
"""Recursively add source dict to target dict.""" |
| 52 |
for key, val in source.items(): |
| 53 |
if isinstance(val, dict): |
| 54 |
if key not in target: |
| 55 |
target[key] = {} |
| 56 |
addict(target[key], val) |
| 57 |
else: |
| 58 |
target[key] = val |
| 59 |
|
| 60 |
|
| 61 |
class BroadcastMgr: |
| 62 |
"""Manage broadcast. |
| 63 |
|
| 64 |
Broadcast settings are stored in the form: |
| 65 |
self.broadcasts['*']['root'] = {'environment': {'FOO': 'bar'}} |
| 66 |
self.broadcasts['20100808T06Z']['root'] = {'script': 'stuff'} |
| 67 |
""" |
| 68 |
|
| 69 |
REC_SECTION = re.compile(r"\[([^\]]+)\]") |
| 70 |
|
| 71 |
def __init__(self, schd): |
| 72 |
self.schd = schd |
| 73 |
self.workflow_run_mode = schd.get_run_mode() |
| 74 |
self.workflow_db_mgr = schd.workflow_db_mgr |
| 75 |
self.data_store_mgr = schd.data_store_mgr |
| 76 |
self.linearized_ancestors = {} |
| 77 |
self.broadcasts = {} |
| 78 |
self.ext_triggers = {} # Can use collections.Counter in future |
| 79 |
self.lock = RLock() |
| 80 |
|
| 81 |
def check_ext_triggers(self, itask, ext_trigger_queue): |
| 82 |
"""Get queued ext trigger messages and try to satisfy itask. |
| 83 |
|
| 84 |
Ext-triggers are pushed by the remote end, so we can check for |
| 85 |
new messages and satisfy dependent tasks at the same time. |
| 86 |
Return True if itask has a newly satisfied ext-trigger. |
| 87 |
""" |
| 88 |
while not ext_trigger_queue.empty(): |
| 89 |
ext_trigger = ext_trigger_queue.get_nowait() |
| 90 |
self.ext_triggers.setdefault(ext_trigger, 0) |
| 91 |
self.ext_triggers[ext_trigger] += 1 |
| 92 |
return self._match_ext_trigger(itask) |
| 93 |
|
| 94 |
def clear_broadcast( |
| 95 |
self, point_strings=None, namespaces=None, cancel_settings=None): |
| 96 |
"""Clear broadcasts globally, or for listed namespaces and/or points. |
| 97 |
|
| 98 |
Return a tuple (modified_settings, bad_options), where: |
| 99 |
* modified_settings is similar to the return value of the "put" method, |
| 100 |
but for removed broadcasts. |
| 101 |
* bad_options is a dict in the form: |
| 102 |
{"point_strings": ["20020202", ..."], ...} |
| 103 |
The dict is only populated if there are options not associated with |
| 104 |
previous broadcasts. The keys can be: |
| 105 |
* point_strings: a list of bad point strings. |
| 106 |
* namespaces: a list of bad namespaces. |
| 107 |
* cancel: a list of tuples. Each tuple contains the keys of a bad |
| 108 |
setting. |
| 109 |
""" |
| 110 |
# If cancel_settings defined, only clear specific broadcasts |
| 111 |
cancel_keys_list = self._settings_to_keys_list(cancel_settings) |
| 112 |
|
| 113 |
# Clear broadcasts |
| 114 |
modified_settings = [] |
| 115 |
with self.lock: |
| 116 |
for point_string, point_string_settings in self.broadcasts.items(): |
| 117 |
if point_strings and point_string not in point_strings: |
| 118 |
continue |
| 119 |
for namespace, namespace_settings in ( |
| 120 |
point_string_settings.items()): |
| 121 |
if namespaces and namespace not in namespaces: |
| 122 |
continue |
| 123 |
stuff_stack = [([], namespace_settings)] |
| 124 |
while stuff_stack: |
| 125 |
keys, stuff = stuff_stack.pop() |
| 126 |
for key, value in stuff.items(): |
| 127 |
if isinstance(value, dict): |
| 128 |
stuff_stack.append((keys + [key], value)) |
| 129 |
elif (not cancel_keys_list or |
| 130 |
keys + [key] in cancel_keys_list): |
| 131 |
stuff[key] = None |
| 132 |
if isinstance(value, list): |
| 133 |
value = listjoin(value) |
| 134 |
else: |
| 135 |
value = str(value) |
| 136 |
setting = {key: value} |
| 137 |
for rkey in reversed(keys): |
| 138 |
setting = {rkey: setting} |
| 139 |
modified_settings.append( |
| 140 |
(point_string, namespace, setting)) |
| 141 |
|
| 142 |
# Prune any empty branches |
| 143 |
bad_options = self._get_bad_options( |
| 144 |
self._prune(), point_strings, namespaces, cancel_keys_list) |
| 145 |
|
| 146 |
# Log the broadcast |
| 147 |
self.workflow_db_mgr.put_broadcast(modified_settings, is_cancel=True) |
| 148 |
LOG.info( |
| 149 |
get_broadcast_change_report(modified_settings, is_cancel=True)) |
| 150 |
if bad_options: |
| 151 |
LOG.error(get_broadcast_bad_options_report(bad_options)) |
| 152 |
if modified_settings: |
| 153 |
self.data_store_mgr.delta_broadcast() |
| 154 |
return uniq(modified_settings), bad_options |
| 155 |
|
| 156 |
def expire_broadcast(self, cutoff=None, **kwargs): |
| 157 |
"""Clear all broadcasts targeting cycle points earlier than cutoff.""" |
| 158 |
point_strings = [] |
| 159 |
cutoff_point = None |
| 160 |
if cutoff is not None: |
| 161 |
cutoff_point = get_point(str(cutoff)) |
| 162 |
with self.lock: |
| 163 |
for point_string in self.broadcasts: |
| 164 |
if cutoff_point is None or ( |
| 165 |
point_string not in ALL_CYCLE_POINTS_STRS and |
| 166 |
get_point(point_string) < cutoff_point): |
| 167 |
point_strings.append(point_string) |
| 168 |
if not point_strings: |
| 169 |
return (None, {"expire": [cutoff]}) |
| 170 |
return self.clear_broadcast(point_strings=point_strings, **kwargs) |
| 171 |
|
| 172 |
def get_broadcast(self, tokens: 'Optional[Tokens]' = None) -> dict: |
| 173 |
"""Retrieve all broadcast variables that target a given task ID.""" |
| 174 |
if tokens is None or tokens == 'None': |
| 175 |
# all broadcasts requested |
| 176 |
return self.broadcasts |
| 177 |
ret: dict = {} |
| 178 |
# The order is: |
| 179 |
# all:root -> all:FAM -> ... -> all:task |
| 180 |
# -> tag:root -> tag:FAM -> ... -> tag:task |
| 181 |
for cycle in ALL_CYCLE_POINTS_STRS + [tokens['cycle']]: |
| 182 |
if cycle not in self.broadcasts: |
| 183 |
continue |
| 184 |
for namespace in reversed( |
| 185 |
self.linearized_ancestors[tokens['task']] |
| 186 |
): |
| 187 |
if namespace in self.broadcasts[cycle]: |
| 188 |
addict(ret, self.broadcasts[cycle][namespace]) |
| 189 |
return ret |
| 190 |
|
| 191 |
def get_updated_rtconfig(self, itask: 'TaskProxy') -> dict: |
| 192 |
"""Retrieve updated rtconfig for a single task proxy""" |
| 193 |
overrides = self.get_broadcast( |
| 194 |
itask.tokens |
| 195 |
) |
| 196 |
if overrides: |
| 197 |
rtconfig = pdeepcopy(itask.tdef.rtconfig) |
| 198 |
poverride(rtconfig, overrides, prepend=True) |
| 199 |
else: |
| 200 |
rtconfig = itask.tdef.rtconfig |
| 201 |
return rtconfig |
| 202 |
|
| 203 |
def load_db_broadcast_states(self, row_idx, row): |
| 204 |
"""Load broadcast variables from runtime DB broadcast states row.""" |
| 205 |
if row_idx == 0: |
| 206 |
LOG.info("LOADING broadcast states") |
| 207 |
point, namespace, key, value = row |
| 208 |
sections = [] |
| 209 |
cur_key = key |
| 210 |
if "]" in cur_key: |
| 211 |
sections = self.REC_SECTION.findall(cur_key) |
| 212 |
cur_key = cur_key.rsplit(r"]", 1)[-1] |
| 213 |
with self.lock: |
| 214 |
self.broadcasts.setdefault(point, {}) |
| 215 |
self.broadcasts[point].setdefault(namespace, {}) |
| 216 |
dict_ = self.broadcasts[point][namespace] |
| 217 |
for section in sections: |
| 218 |
dict_.setdefault(section, {}) |
| 219 |
dict_ = dict_[section] |
| 220 |
dict_[cur_key] = value |
| 221 |
LOG.info(CHANGE_FMT.strip() % { |
| 222 |
"change": CHANGE_PREFIX_SET, |
| 223 |
"point": point, |
| 224 |
"namespace": namespace, |
| 225 |
"key": key, |
| 226 |
"value": value}) |
| 227 |
|
| 228 |
# BACK COMPAT: post_load_db_coerce |
| 229 |
# The DB at 8.0.x stores Interval values as neither ISO8601 duration |
| 230 |
# string or DurationFloat. This has been fixed at 8.1.0. |
| 231 |
# url: |
| 232 |
# https://github.com/cylc/cylc-flow/pull/5138 |
| 233 |
# from: |
| 234 |
# 8.0.x |
| 235 |
# to: |
| 236 |
# 8.1.x |
| 237 |
# remove at: |
| 238 |
# 8.x |
| 239 |
def post_load_db_coerce(self): |
| 240 |
"""Coerce DB loaded values to config objects, i.e. DurationFloat.""" |
| 241 |
for namespaces in self.broadcasts.values(): |
| 242 |
for settings in namespaces.values(): |
| 243 |
BroadcastConfigValidator().validate( |
| 244 |
settings, SPEC['runtime']['__MANY__'] |
| 245 |
) |
| 246 |
|
| 247 |
def _match_ext_trigger(self, itask): |
| 248 |
"""Match external triggers for a waiting task proxy.""" |
| 249 |
if not self.ext_triggers or not itask.state.external_triggers: |
| 250 |
return False |
| 251 |
for trig, satisfied in list(itask.state.external_triggers.items()): |
| 252 |
if satisfied: |
| 253 |
continue |
| 254 |
for qmsg, qid in self.ext_triggers.copy(): |
| 255 |
if trig != qmsg: |
| 256 |
continue |
| 257 |
# Matched. |
| 258 |
point_string = itask.tokens['cycle'] |
| 259 |
# Set trigger satisfied. |
| 260 |
itask.state.external_triggers[trig] = True |
| 261 |
# Broadcast the event ID to the cycle point. |
| 262 |
if qid is not None: |
| 263 |
self.put_broadcast( |
| 264 |
[point_string], |
| 265 |
['root'], |
| 266 |
[{'environment': {'CYLC_EXT_TRIGGER_ID': qid}}], |
| 267 |
) |
| 268 |
# Create data-store delta |
| 269 |
self.data_store_mgr.delta_task_ext_trigger( |
| 270 |
itask, qid, qmsg, True) |
| 271 |
self.ext_triggers[(qmsg, qid)] -= 1 |
| 272 |
if not self.ext_triggers[(qmsg, qid)]: |
| 273 |
del self.ext_triggers[(qmsg, qid)] |
| 274 |
return True |
| 275 |
return False |
| 276 |
|
| 277 |
def put_broadcast( |
| 278 |
self, point_strings=None, namespaces=None, settings=None): |
| 279 |
"""Add new broadcast settings (server side interface). |
| 280 |
|
| 281 |
Return a tuple (modified_settings, bad_options) where: |
| 282 |
modified_settings is list of modified settings in the form: |
| 283 |
[("20200202", "foo", {"script": "true"}, ...] |
| 284 |
bad_options is as described in the docstring for self.clear(). |
| 285 |
""" |
| 286 |
modified_settings = [] |
| 287 |
bad_settings = [] |
| 288 |
bad_point_strings = set() |
| 289 |
bad_namespaces = set() |
| 290 |
|
| 291 |
with self.lock: |
| 292 |
for setting in settings or []: |
| 293 |
# Coerce setting to cylc runtime object, |
| 294 |
# i.e. str to DurationFloat. |
| 295 |
coerced_setting = deepcopy(setting) |
| 296 |
try: |
| 297 |
BroadcastConfigValidator().validate( |
| 298 |
coerced_setting, |
| 299 |
SPEC['runtime']['__MANY__'], |
| 300 |
) |
| 301 |
except Exception as exc: |
| 302 |
LOG.error(exc) |
| 303 |
bad_settings.append(setting) |
| 304 |
continue |
| 305 |
|
| 306 |
# Skip and warn if a run mode is broadcast to a workflow |
| 307 |
# running in simulation or dummy mode. |
| 308 |
if ( |
| 309 |
'run mode' in coerced_setting |
| 310 |
and self.workflow_run_mode.value in WORKFLOW_ONLY_MODES |
| 311 |
): |
| 312 |
LOG.warning( |
| 313 |
f'Broadcasting {coerced_setting} to a workflow' |
| 314 |
f' running in {self.workflow_run_mode.value} mode' |
| 315 |
' will have no effect, and will not be actioned.' |
| 316 |
) |
| 317 |
bad_settings.append(setting) |
| 318 |
continue |
| 319 |
|
| 320 |
for point_string in point_strings or []: |
| 321 |
# Standardise the point and check its validity. |
| 322 |
bad_point = False |
| 323 |
try: |
| 324 |
point_string = standardise_point_string(point_string) |
| 325 |
|
| 326 |
except PointParsingError: |
| 327 |
if point_string != '*': |
| 328 |
bad_point_strings.add(point_string) |
| 329 |
bad_point = True |
| 330 |
if not bad_point and point_string not in self.broadcasts: |
| 331 |
self.broadcasts[point_string] = {} |
| 332 |
for namespace in namespaces or []: |
| 333 |
if namespace not in self.linearized_ancestors: |
| 334 |
bad_namespaces.add(namespace) |
| 335 |
elif not bad_point: |
| 336 |
# Check broadcast against config and against |
| 337 |
# existing broadcasts: |
| 338 |
newconfig = pdeepcopy(self.schd.config.get_config( |
| 339 |
['runtime', namespace] |
| 340 |
)) |
| 341 |
poverride( |
| 342 |
newconfig, |
| 343 |
self.broadcasts.get(point_string, {}) |
| 344 |
.get(namespace, {}) |
| 345 |
) |
| 346 |
if self.bc_mixes_old_and_new_platform_settings( |
| 347 |
newconfig, |
| 348 |
namespace, |
| 349 |
coerced_setting, |
| 350 |
): |
| 351 |
bad_settings.append(setting) |
| 352 |
continue |
| 353 |
|
| 354 |
if namespace not in self.broadcasts[point_string]: |
| 355 |
self.broadcasts[point_string][namespace] = {} |
| 356 |
|
| 357 |
# Keep saved/reported setting as workflow |
| 358 |
# config format: |
| 359 |
modified_settings.append( |
| 360 |
(point_string, namespace, setting) |
| 361 |
) |
| 362 |
|
| 363 |
# Apply the broadcast with the "coerced" format: |
| 364 |
addict( |
| 365 |
self.broadcasts[point_string][namespace], |
| 366 |
coerced_setting, |
| 367 |
) |
| 368 |
|
| 369 |
# Log the broadcast |
| 370 |
self.workflow_db_mgr.put_broadcast(modified_settings) |
| 371 |
LOG.info(get_broadcast_change_report(modified_settings)) |
| 372 |
|
| 373 |
bad_options = {} |
| 374 |
if bad_settings: |
| 375 |
bad_options["settings"] = uniq(bad_settings) |
| 376 |
if bad_point_strings: |
| 377 |
bad_options["point_strings"] = sorted(bad_point_strings) |
| 378 |
if bad_namespaces: |
| 379 |
bad_options["namespaces"] = sorted(bad_namespaces) |
| 380 |
if modified_settings: |
| 381 |
self.data_store_mgr.delta_broadcast() |
| 382 |
return uniq(modified_settings), bad_options |
| 383 |
|
| 384 |
@staticmethod |
| 385 |
def bc_mixes_old_and_new_platform_settings( |
| 386 |
task_config, namespace, coerced_setting |
| 387 |
): |
| 388 |
"""Check for combination of old ([remote]host) and new (platform) |
| 389 |
settings in the task config as it will be after merger. |
| 390 |
""" |
| 391 |
task_config.update(coerced_setting) |
| 392 |
try: |
| 393 |
fail_if_platform_and_host_conflict( |
| 394 |
task_config, namespace |
| 395 |
) |
| 396 |
return False |
| 397 |
except PlatformLookupError as exc: |
| 398 |
LOG.error('Cannot apply broadcast:\n' + '\n '.join(exc.args)) |
| 399 |
return True |
| 400 |
|
| 401 |
@staticmethod |
| 402 |
def _cancel_keys_in_prunes(prunes, cancel_keys): |
| 403 |
"""Is cancel_keys pruned?""" |
| 404 |
return (list(cancel_keys) in |
| 405 |
[prune[2:] for prune in prunes if prune[2:]]) |
| 406 |
|
| 407 |
@classmethod |
| 408 |
def _get_bad_options( |
| 409 |
cls, prunes, point_strings, namespaces, cancel_keys_list): |
| 410 |
"""Return unpruned namespaces and/or point_strings options.""" |
| 411 |
cancel_keys_list = [ |
| 412 |
tuple(cancel_keys) for cancel_keys in cancel_keys_list] |
| 413 |
bad_options = { |
| 414 |
"point_strings": None, "namespaces": None, "cancel": None} |
| 415 |
# 1. Populate the bad_options dict where applicable. |
| 416 |
# 2. Remove keys if they are found in "prunes". |
| 417 |
# 3. Remove key in bad_options if it becomes empty. |
| 418 |
for opt_name, opt_list, opt_test in [ |
| 419 |
("point_strings", point_strings, cls._point_string_in_prunes), |
| 420 |
("namespaces", namespaces, cls._namespace_in_prunes), |
| 421 |
("cancel", cancel_keys_list, cls._cancel_keys_in_prunes)]: |
| 422 |
if opt_list: |
| 423 |
bad_options[opt_name] = set(opt_list) |
| 424 |
for opt in opt_list: |
| 425 |
if opt_test(prunes, opt): |
| 426 |
bad_options[opt_name].discard(opt) |
| 427 |
if not bad_options[opt_name]: |
| 428 |
break |
| 429 |
for key, value in list(bad_options.copy().items()): |
| 430 |
if value: |
| 431 |
bad_options[key] = list(value) |
| 432 |
else: |
| 433 |
del bad_options[key] |
| 434 |
return bad_options |
| 435 |
|
| 436 |
@staticmethod |
| 437 |
def _namespace_in_prunes(prunes, namespace): |
| 438 |
"""Is namespace pruned?""" |
| 439 |
return namespace in [prune[1] for prune in prunes if prune[1:]] |
| 440 |
|
| 441 |
@staticmethod |
| 442 |
def _point_string_in_prunes(prunes, point_string): |
| 443 |
"""Is point_string pruned?""" |
| 444 |
return point_string in [prune[0] for prune in prunes] |
| 445 |
|
| 446 |
def _prune(self): |
| 447 |
"""Remove empty leaves left by unsetting broadcast values. |
| 448 |
|
| 449 |
Return a list of pruned broadcasts in the form: |
| 450 |
|
| 451 |
[ |
| 452 |
["20200202", "foo", "script"], |
| 453 |
["20020202", "bar", "environment", "BAR"], |
| 454 |
] |
| 455 |
""" |
| 456 |
with self.lock: |
| 457 |
prunes = [] |
| 458 |
stuff_stack = [([], self.broadcasts, True)] |
| 459 |
while stuff_stack: |
| 460 |
keys, stuff, is_new = stuff_stack.pop() |
| 461 |
if is_new: |
| 462 |
stuff_stack.append((keys, stuff, False)) |
| 463 |
for key, value in stuff.items(): |
| 464 |
if isinstance(value, dict): |
| 465 |
stuff_stack.append((keys + [key], value, True)) |
| 466 |
else: |
| 467 |
for key, value in stuff.copy().items(): |
| 468 |
if value in [None, {}]: |
| 469 |
del stuff[key] |
| 470 |
prunes.append(keys + [key]) |
| 471 |
return prunes |
| 472 |
|
| 473 |
@staticmethod |
| 474 |
def _settings_to_keys_list(broadcasts): |
| 475 |
"""Return a list containing each setting dict keys. |
| 476 |
|
| 477 |
E.g. Each setting in broadcasts may look like: |
| 478 |
{"foo": {"bar": {"baz": 1}}} |
| 479 |
|
| 480 |
An element of the returned list will look like: |
| 481 |
["foo", "bar", "baz"] |
| 482 |
|
| 483 |
""" |
| 484 |
keys_list = [] |
| 485 |
if broadcasts: |
| 486 |
for broadcast in broadcasts: |
| 487 |
stuff_stack = [([], broadcast)] |
| 488 |
while stuff_stack: |
| 489 |
keys, stuff = stuff_stack.pop() |
| 490 |
for key, value in stuff.items(): |
| 491 |
if isinstance(value, dict): |
| 492 |
stuff_stack.append((keys + [key], value)) |
| 493 |
else: |
| 494 |
keys_list.append(keys + [key]) |
| 495 |
return keys_list |