| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. |
| 4 |
# Copyright (C) NIWA & British Crown (Met Office) & Contributors. |
| 5 |
# |
| 6 |
# This program is free software: you can redistribute it and/or modify |
| 7 |
# it under the terms of the GNU General Public License as published by |
| 8 |
# the Free Software Foundation, either version 3 of the License, or |
| 9 |
# (at your option) any later version. |
| 10 |
# |
| 11 |
# This program is distributed in the hope that it will be useful, |
| 12 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 |
# GNU General Public License for more details. |
| 15 |
# |
| 16 |
# You should have received a copy of the GNU General Public License |
| 17 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 18 |
|
| 19 |
"""cylc broadcast [OPTIONS] ARGS |
| 20 |
|
| 21 |
Override "[runtime]" configurations in a running workflow. |
| 22 |
|
| 23 |
Uses for broadcast include making temporary changes to task behaviour, and |
| 24 |
task-to-downstream-task communication via environment variables. |
| 25 |
|
| 26 |
See also "cylc reload" which reads in the flow.cylc (or suite.rc) file. |
| 27 |
|
| 28 |
A broadcast can set/override any "[runtime]" configuration for all cycles or |
| 29 |
for a specific cycle. If a task is affected by specific-cycle and all-cycle |
| 30 |
broadcasts at the same time, the specific takes precedence. |
| 31 |
|
| 32 |
Broadcasts can also target all tasks, specific tasks or families of tasks. If a |
| 33 |
task is affected by broadcasts to multiple ancestor namespaces (tasks it |
| 34 |
inherits from), the result is determined by normal "[runtime]" inheritance. |
| 35 |
|
| 36 |
Broadcasts are applied at the time of job submission. |
| 37 |
|
| 38 |
Broadcasts persist, even across restarts. Broadcasts made to specific cycle |
| 39 |
points will expire when the cycle point is older than the oldest active cycle |
| 40 |
point in the workflow. |
| 41 |
|
| 42 |
Active broadcasts can be revoked using the "clear" mode. Any broadcasts |
| 43 |
matching the specified cycle points and namespaces will be revoked. |
| 44 |
|
| 45 |
Note: a "clear" broadcast for a specific cycle or namespace does *not* clear |
| 46 |
all-cycle or all-namespace broadcasts. |
| 47 |
|
| 48 |
Examples: |
| 49 |
# To broadcast a variable to all tasks (quote items with internal spaces): |
| 50 |
$ cylc broadcast -s "[environment]VERSE = the quick brown fox" WORKFLOW |
| 51 |
|
| 52 |
# To do the same with a file: |
| 53 |
$ cat >'broadcast.cylc' <<'__FLOW__' |
| 54 |
> [environment] |
| 55 |
> VERSE = the quick brown fox |
| 56 |
> __FLOW__ |
| 57 |
$ cylc broadcast -F 'broadcast.cylc' WORKFLOW_ID |
| 58 |
|
| 59 |
# view active broadcasts |
| 60 |
$ cylc broadcast --display WORKFLOW_ID |
| 61 |
|
| 62 |
# To cancel the same broadcast: |
| 63 |
$ cylc broadcast --cancel "[environment]VERSE" WORKFLOW_ID |
| 64 |
|
| 65 |
# If -F FILE was used, the same file can be used to cancel the broadcast: |
| 66 |
$ cylc broadcast -G 'broadcast.cylc' WORKFLOW_ID |
| 67 |
|
| 68 |
# Use broadcast with multiple workflows |
| 69 |
$ cylc broadcast [options] WORKFLOW_ID_1// WORKFLOW_ID_2// |
| 70 |
|
| 71 |
Use -d/--display to see active broadcasts. Multiple --cancel options or |
| 72 |
multiple --set and --set-file options can be used on the same command line. |
| 73 |
Multiple --set and --set-file options are cumulative. |
| 74 |
|
| 75 |
The --set-file=FILE option can be used when broadcasting multiple values, or |
| 76 |
when the value contains newline or other metacharacters. If FILE is "-", read |
| 77 |
from standard input. |
| 78 |
|
| 79 |
Broadcast cannot change [runtime] inheritance. |
| 80 |
""" |
| 81 |
|
| 82 |
from ansimarkup import parse as cparse |
| 83 |
import asyncio |
| 84 |
from copy import deepcopy |
| 85 |
from functools import partial |
| 86 |
import os.path |
| 87 |
import re |
| 88 |
import sys |
| 89 |
from tempfile import NamedTemporaryFile |
| 90 |
from typing import Any, Dict, TYPE_CHECKING |
| 91 |
|
| 92 |
from cylc.flow.broadcast_report import ( |
| 93 |
get_broadcast_bad_options_report, |
| 94 |
get_broadcast_change_report, |
| 95 |
) |
| 96 |
from cylc.flow.cfgspec.workflow import SPEC, upg |
| 97 |
from cylc.flow.exceptions import InputError |
| 98 |
from cylc.flow.network.client_factory import get_client |
| 99 |
from cylc.flow.network.multi import call_multi_async |
| 100 |
from cylc.flow.option_parsers import ( |
| 101 |
WORKFLOW_ID_MULTI_ARG_DOC, |
| 102 |
CylcOptionParser as COP, |
| 103 |
) |
| 104 |
from cylc.flow.parsec.config import ParsecConfig |
| 105 |
from cylc.flow.parsec.util import listjoin |
| 106 |
from cylc.flow.parsec.validate import cylc_config_validate |
| 107 |
from cylc.flow.print_tree import get_tree |
| 108 |
from cylc.flow.terminal import cli_function |
| 109 |
|
| 110 |
if TYPE_CHECKING: |
| 111 |
from optparse import Values |
| 112 |
|
| 113 |
|
| 114 |
RAW_DEPR_MSG = ( |
| 115 |
"DEPRECATED: the --raw option will be removed at Cylc 8.7; " |
| 116 |
"use --format=raw instead." |
| 117 |
) |
| 118 |
|
| 119 |
REC_ITEM = re.compile(r'^\[([^\]]*)\](.*)$') |
| 120 |
|
| 121 |
MUTATION = ''' |
| 122 |
mutation ( |
| 123 |
$wFlows: [WorkflowID]!, |
| 124 |
$bMode: BroadcastMode!, |
| 125 |
$cPoints: [BroadcastCyclePoint], |
| 126 |
$nSpaces: [NamespaceName], |
| 127 |
$bSettings: [BroadcastSetting], |
| 128 |
$bCutoff: CyclePoint |
| 129 |
) { |
| 130 |
broadcast ( |
| 131 |
workflows: $wFlows, |
| 132 |
mode: $bMode, |
| 133 |
cyclePoints: $cPoints, |
| 134 |
namespaces: $nSpaces, |
| 135 |
settings: $bSettings, |
| 136 |
cutoff: $bCutoff |
| 137 |
) { |
| 138 |
result |
| 139 |
} |
| 140 |
} |
| 141 |
''' |
| 142 |
|
| 143 |
QUERY = ''' |
| 144 |
query ( |
| 145 |
$wFlows: [ID], |
| 146 |
$nIds: [ID] |
| 147 |
) { |
| 148 |
workflows ( |
| 149 |
ids: $wFlows, |
| 150 |
) { |
| 151 |
id |
| 152 |
broadcasts (ids: $nIds) |
| 153 |
} |
| 154 |
} |
| 155 |
''' |
| 156 |
|
| 157 |
|
| 158 |
def get_padding(settings, level=0, padding=0): |
| 159 |
"""Return the left padding for displaying a setting.""" |
| 160 |
level += 1 |
| 161 |
for key, val in settings.items(): |
| 162 |
tmp = level * 2 + len(key) |
| 163 |
if tmp > padding: |
| 164 |
padding = tmp |
| 165 |
if isinstance(val, dict): |
| 166 |
padding = get_padding(val, level, padding) |
| 167 |
return padding |
| 168 |
|
| 169 |
|
| 170 |
def get_rdict(left, right=None, for_cancel_broadcast=False): |
| 171 |
"""Check+transform left=right into a nested dict. |
| 172 |
|
| 173 |
left can be key, [key], [key1]key2, [key1][key2], [key1][key2]key3, etc. |
| 174 |
""" |
| 175 |
if left == "inherit": |
| 176 |
raise InputError( |
| 177 |
"Inheritance cannot be changed by broadcast") |
| 178 |
rdict = {} |
| 179 |
cur_dict = rdict |
| 180 |
tail = left |
| 181 |
while tail: |
| 182 |
match = REC_ITEM.match(tail) |
| 183 |
if match: |
| 184 |
sect, tail = match.groups() |
| 185 |
if tail: |
| 186 |
# [sect]... = right |
| 187 |
cur_dict[sect.strip()] = {} |
| 188 |
cur_dict = cur_dict[sect.strip()] |
| 189 |
else: |
| 190 |
# [sect] = right |
| 191 |
cur_dict[sect.strip()] = right |
| 192 |
else: |
| 193 |
# item = right |
| 194 |
cur_dict[tail.strip()] = right |
| 195 |
tail = None |
| 196 |
upg( |
| 197 |
{'runtime': {'__MANY__': rdict}}, |
| 198 |
'test', |
| 199 |
broadcast='cancel' if for_cancel_broadcast else True, |
| 200 |
) |
| 201 |
rdict = strip_empty_sections(rdict) |
| 202 |
# Perform validation, but don't coerce the original (deepcopy). |
| 203 |
cylc_config_validate(deepcopy(rdict), SPEC['runtime']['__MANY__']) |
| 204 |
return rdict |
| 205 |
|
| 206 |
|
| 207 |
def strip_empty_sections(data): |
| 208 |
"""Recursively strip data structure of empty dicts. |
| 209 |
|
| 210 |
This is needed post-upgrade as the upgrader can leave empty sections |
| 211 |
behind. |
| 212 |
|
| 213 |
>>> strip_empty_sections( |
| 214 |
... {'job': {}, 'thing limit': 'PT2S', 'whatever': ''}) |
| 215 |
{'thing limit': 'PT2S', 'whatever': ''} |
| 216 |
|
| 217 |
>>> strip_empty_sections({'section': {'subsection': {}}}) |
| 218 |
{} |
| 219 |
""" |
| 220 |
if not isinstance(data, dict): |
| 221 |
return data |
| 222 |
return { |
| 223 |
key: stripped |
| 224 |
for key, val in data.items() |
| 225 |
if (stripped := strip_empty_sections(val)) != {} |
| 226 |
} |
| 227 |
|
| 228 |
|
| 229 |
def files_to_settings(settings, setting_files, cancel_mode=False): |
| 230 |
"""Parse setting files, and append to settings.""" |
| 231 |
cfg = ParsecConfig( |
| 232 |
SPEC['runtime']['__MANY__'], validator=cylc_config_validate) |
| 233 |
for setting_file in setting_files: |
| 234 |
if setting_file == '-': |
| 235 |
with NamedTemporaryFile() as handle: |
| 236 |
handle.write(sys.stdin.read().encode()) |
| 237 |
handle.seek(0, 0) |
| 238 |
cfg.loadcfg(handle.name) |
| 239 |
else: |
| 240 |
cfg.loadcfg(os.path.abspath(setting_file)) |
| 241 |
stack = [([], cfg.get(sparse=True))] |
| 242 |
while stack: |
| 243 |
keys, item = stack.pop() |
| 244 |
if isinstance(item, dict): |
| 245 |
for key, value in item.items(): |
| 246 |
stack.append((keys + [key], value)) |
| 247 |
else: |
| 248 |
settings.append({}) |
| 249 |
cur_setting = settings[-1] |
| 250 |
while keys: |
| 251 |
key = keys.pop(0) |
| 252 |
if keys: |
| 253 |
cur_setting[key] = {} |
| 254 |
cur_setting = cur_setting[key] |
| 255 |
elif cancel_mode: |
| 256 |
cur_setting[key] = None |
| 257 |
else: |
| 258 |
if isinstance(item, list): |
| 259 |
item = listjoin(item) |
| 260 |
else: |
| 261 |
item = str(item) |
| 262 |
cur_setting[key] = item |
| 263 |
|
| 264 |
|
| 265 |
def report_bad_options(bad_options, is_set=False): |
| 266 |
bad_opts = get_broadcast_bad_options_report(bad_options, is_set=is_set) |
| 267 |
if bad_opts is not None: |
| 268 |
return cparse(f'<red>{bad_opts}</red>') |
| 269 |
return bad_opts |
| 270 |
|
| 271 |
|
| 272 |
def get_option_parser() -> COP: |
| 273 |
"""CLI for "cylc broadcast".""" |
| 274 |
parser = COP( |
| 275 |
__doc__, |
| 276 |
comms=True, |
| 277 |
multiworkflow=True, |
| 278 |
argdoc=[WORKFLOW_ID_MULTI_ARG_DOC], |
| 279 |
) |
| 280 |
|
| 281 |
parser.add_option( |
| 282 |
"-p", "--point", metavar="CYCLE_POINT", |
| 283 |
help="Target cycle point. More than one can be added. " |
| 284 |
"Defaults to '*' with --set and --cancel, " |
| 285 |
"and nothing with --clear.", |
| 286 |
action="append", dest="point_strings", default=[]) |
| 287 |
|
| 288 |
parser.add_option( |
| 289 |
"-n", "--namespace", metavar="NAME", |
| 290 |
help="Target namespace. Defaults to 'root' with " |
| 291 |
"--set and --cancel, and nothing with --clear.", |
| 292 |
action="append", dest="namespaces", default=[]) |
| 293 |
|
| 294 |
parser.add_option( |
| 295 |
"-s", "--set", metavar="[SEC]ITEM=VALUE", |
| 296 |
help="A [runtime] config item and value to broadcast.", |
| 297 |
action="append", dest="settings", default=[]) |
| 298 |
|
| 299 |
parser.add_option( |
| 300 |
"-F", "--set-file", "--file", metavar="FILE", |
| 301 |
help="File with config to broadcast. Can be used multiple times.", |
| 302 |
action="append", dest="setting_files", default=[]) |
| 303 |
|
| 304 |
parser.add_option( |
| 305 |
"-c", "--cancel", metavar="[SEC]ITEM", |
| 306 |
help="An item-specific broadcast to cancel.", |
| 307 |
action="append", dest="cancel", default=[]) |
| 308 |
|
| 309 |
parser.add_option( |
| 310 |
"-G", "--cancel-file", metavar="FILE", |
| 311 |
help="File with broadcasts to cancel. Can be used multiple times.", |
| 312 |
action="append", dest="cancel_files", default=[]) |
| 313 |
|
| 314 |
parser.add_option( |
| 315 |
"-C", "--clear", |
| 316 |
help="Cancel all broadcasts, or with -p/--point, " |
| 317 |
"-n/--namespace, cancel all broadcasts to targeted " |
| 318 |
"namespaces and/or cycle points. Use \"-C -p '*'\" " |
| 319 |
"to cancel all all-cycle broadcasts without canceling " |
| 320 |
"all specific-cycle broadcasts.", |
| 321 |
action="store_true", dest="clear", default=False) |
| 322 |
|
| 323 |
parser.add_option( |
| 324 |
"-e", "--expire", metavar="CYCLE_POINT", |
| 325 |
help="Cancel any broadcasts that target cycle " |
| 326 |
"points earlier than, but not inclusive of, CYCLE_POINT.", |
| 327 |
action="store", default=None, dest="expire") |
| 328 |
|
| 329 |
parser.add_option( |
| 330 |
"-d", "--display", |
| 331 |
help="Display active broadcasts.", |
| 332 |
action="store_true", default=False, dest="show") |
| 333 |
|
| 334 |
parser.add_option( |
| 335 |
"-k", "--display-task", metavar="TASK_ID_GLOB", |
| 336 |
help=( |
| 337 |
"Print active broadcasts for a given task " |
| 338 |
"(in the format cycle/task)." |
| 339 |
), |
| 340 |
action="store", default=None, dest="showtask") |
| 341 |
|
| 342 |
parser.add_option( |
| 343 |
"-b", "--box", |
| 344 |
help="Use unicode box characters with -d, -k.", |
| 345 |
action="store_true", default=False, dest="unicode") |
| 346 |
|
| 347 |
# BACK COMPAT: --raw |
| 348 |
# From: < 8.5.1 |
| 349 |
# To: 8.5.1 |
| 350 |
# Remove at: 8.7.0 |
| 351 |
parser.add_option( |
| 352 |
"-r", "--raw", |
| 353 |
help=( |
| 354 |
"With -d/--display or -k/--display-task, write out " |
| 355 |
"the broadcast config structure in raw Python form. " |
| 356 |
f"{RAW_DEPR_MSG}" |
| 357 |
), |
| 358 |
action="store_true", default=False, dest="raw") |
| 359 |
|
| 360 |
parser.add_option( |
| 361 |
'--format', |
| 362 |
help=( |
| 363 |
"With -d/--display or -k/--display-task, write out " |
| 364 |
"the broadcast config structure in one of the following formats: " |
| 365 |
"tree, json, or raw (like json but as a Python dictionary). " |
| 366 |
r"Default: %default." |
| 367 |
), |
| 368 |
action='store', |
| 369 |
dest='format', |
| 370 |
choices=('tree', 'json', 'raw'), |
| 371 |
default='tree', |
| 372 |
) |
| 373 |
|
| 374 |
return parser |
| 375 |
|
| 376 |
|
| 377 |
async def run(options: 'Values', workflow_id): |
| 378 |
"""Implement cylc broadcast.""" |
| 379 |
pclient = get_client(workflow_id, timeout=options.comms_timeout) |
| 380 |
|
| 381 |
# remove any duplicate namespaces |
| 382 |
# see https://github.com/cylc/cylc-flow/issues/6334 |
| 383 |
namespaces = list(set(options.namespaces)) |
| 384 |
|
| 385 |
ret: Dict[str, Any] = { |
| 386 |
'stdout': [], |
| 387 |
'stderr': [], |
| 388 |
'exit': 0, |
| 389 |
} |
| 390 |
|
| 391 |
mutation_kwargs: Dict[str, Any] = { |
| 392 |
'request_string': MUTATION, |
| 393 |
'variables': { |
| 394 |
'wFlows': [workflow_id], |
| 395 |
'bMode': 'Set', |
| 396 |
'cPoints': options.point_strings, |
| 397 |
'nSpaces': namespaces, |
| 398 |
'bSettings': options.settings, |
| 399 |
'bCutoff': options.expire, |
| 400 |
} |
| 401 |
} |
| 402 |
|
| 403 |
query_kwargs: Dict[str, Any] = { |
| 404 |
'request_string': QUERY, |
| 405 |
'variables': { |
| 406 |
'wFlows': [workflow_id], |
| 407 |
'nIds': [] |
| 408 |
} |
| 409 |
|
| 410 |
} |
| 411 |
|
| 412 |
if options.raw: |
| 413 |
ret['stderr'].append(cparse(f"<yellow>{RAW_DEPR_MSG}</yellow>")) |
| 414 |
|
| 415 |
if options.show or options.showtask: |
| 416 |
if options.showtask: |
| 417 |
try: |
| 418 |
query_kwargs['variables']['nIds'] = [options.showtask] |
| 419 |
except ValueError: |
| 420 |
# TODO validate showtask? |
| 421 |
raise InputError( |
| 422 |
'TASK_ID_GLOB must be in the format: cycle/task' |
| 423 |
) from None |
| 424 |
result = await pclient.async_request('graphql', query_kwargs) |
| 425 |
for wflow in result['workflows']: |
| 426 |
settings = wflow['broadcasts'] |
| 427 |
padding = get_padding(settings) * ' ' |
| 428 |
if options.format == 'json': |
| 429 |
import json |
| 430 |
ret['stdout'].append( |
| 431 |
json.dumps(settings, indent=2, sort_keys=True) |
| 432 |
) |
| 433 |
elif options.raw or options.format == 'raw': |
| 434 |
ret['stdout'].append(str(settings)) |
| 435 |
else: |
| 436 |
ret['stdout'].extend( |
| 437 |
get_tree(settings, padding, options.unicode) |
| 438 |
) |
| 439 |
return ret |
| 440 |
|
| 441 |
report_cancel = True |
| 442 |
report_set = False |
| 443 |
if options.clear: |
| 444 |
mutation_kwargs['variables']['bMode'] = 'Clear' |
| 445 |
|
| 446 |
if options.expire: |
| 447 |
mutation_kwargs['variables']['bMode'] = 'Expire' |
| 448 |
|
| 449 |
# implement namespace and cycle point defaults here |
| 450 |
if not namespaces: |
| 451 |
namespaces = ["root"] |
| 452 |
point_strings = options.point_strings |
| 453 |
if not point_strings: |
| 454 |
point_strings = ["*"] |
| 455 |
|
| 456 |
if options.cancel or options.cancel_files: |
| 457 |
settings = [] |
| 458 |
for option_item in options.cancel: |
| 459 |
if "=" in option_item: |
| 460 |
raise InputError( |
| 461 |
"--cancel=[SEC]ITEM does not take a value") |
| 462 |
option_item = option_item.strip() |
| 463 |
if setting := get_rdict(option_item, for_cancel_broadcast=True): |
| 464 |
settings.append(setting) |
| 465 |
files_to_settings(settings, options.cancel_files, options.cancel) |
| 466 |
if not settings: |
| 467 |
raise InputError("No valid settings to broadcast.") |
| 468 |
mutation_kwargs['variables'].update( |
| 469 |
{ |
| 470 |
'bMode': 'Clear', |
| 471 |
'cPoints': point_strings, |
| 472 |
'nSpaces': namespaces, |
| 473 |
'bSettings': settings, |
| 474 |
} |
| 475 |
) |
| 476 |
|
| 477 |
if options.settings or options.setting_files: |
| 478 |
settings = [] |
| 479 |
for option_item in options.settings: |
| 480 |
if "=" not in option_item: |
| 481 |
raise InputError( |
| 482 |
"--set=[SEC]ITEM=VALUE requires a value") |
| 483 |
lhs, rhs = [s.strip() for s in option_item.split("=", 1)] |
| 484 |
if setting := get_rdict(lhs, rhs): |
| 485 |
settings.append(setting) |
| 486 |
files_to_settings(settings, options.setting_files) |
| 487 |
if not settings: |
| 488 |
raise InputError("No valid settings to broadcast.") |
| 489 |
mutation_kwargs['variables'].update( |
| 490 |
{ |
| 491 |
'bMode': 'Set', |
| 492 |
'cPoints': point_strings, |
| 493 |
'nSpaces': namespaces, |
| 494 |
'bSettings': settings, |
| 495 |
} |
| 496 |
) |
| 497 |
report_cancel = False |
| 498 |
report_set = True |
| 499 |
|
| 500 |
results = await pclient.async_request('graphql', mutation_kwargs) |
| 501 |
try: |
| 502 |
bad_options = {} |
| 503 |
for result in results['broadcast']['result']: |
| 504 |
modified_settings, bad_options = result['response'] |
| 505 |
if modified_settings: |
| 506 |
ret['stdout'].append( |
| 507 |
get_broadcast_change_report( |
| 508 |
modified_settings, |
| 509 |
is_cancel=report_cancel, |
| 510 |
) |
| 511 |
) |
| 512 |
bad_result = report_bad_options(bad_options, is_set=report_set) |
| 513 |
except (TypeError, ValueError): |
| 514 |
# Catch internal API server errors |
| 515 |
bad_result = cparse(f'<red>{results}</red>') |
| 516 |
|
| 517 |
if bad_result: |
| 518 |
ret['stderr'].append(f'ERROR: {bad_result}') |
| 519 |
ret['exit'] = 1 |
| 520 |
return ret |
| 521 |
|
| 522 |
|
| 523 |
def report(response): |
| 524 |
return ( |
| 525 |
'\n'.join(response['stdout']), |
| 526 |
'\n'.join(line for line in response['stderr'] if line is not None), |
| 527 |
response['exit'] == 0, |
| 528 |
) |
| 529 |
|
| 530 |
|
| 531 |
@cli_function(get_option_parser) |
| 532 |
def main(_, options: 'Values', *ids) -> None: |
| 533 |
rets = asyncio.run(_main(options, *ids)) |
| 534 |
sys.exit(all(rets.values()) is False) |
| 535 |
|
| 536 |
|
| 537 |
async def _main(options: 'Values', *ids): |
| 538 |
return await call_multi_async( |
| 539 |
partial(run, options), |
| 540 |
*ids, |
| 541 |
constraint='workflows', |
| 542 |
report=report, |
| 543 |
) |