| 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 show [OPTIONS] ARGS |
| 20 |
|
| 21 |
Display workflow and task information, for tasks in the current n-window. |
| 22 |
|
| 23 |
Query a running workflow for: |
| 24 |
# view workflow metadata |
| 25 |
$ cylc show my_workflow |
| 26 |
|
| 27 |
# view task metadata |
| 28 |
$ cylc show my_workflow --task-def my_task |
| 29 |
|
| 30 |
# view prerequisites & outputs for a live task |
| 31 |
$ cylc show my_workflow//1/my_task |
| 32 |
|
| 33 |
Output completion status is shown for all tasks in the current n-window. |
| 34 |
|
| 35 |
Prerequisite satisfaction is not shown for past tasks reloaded from the |
| 36 |
workflow database. |
| 37 |
""" |
| 38 |
|
| 39 |
import asyncio |
| 40 |
import re |
| 41 |
import json |
| 42 |
import sys |
| 43 |
from textwrap import indent |
| 44 |
from typing import Any, Dict, TYPE_CHECKING |
| 45 |
|
| 46 |
from ansimarkup import ansiprint |
| 47 |
|
| 48 |
from metomi.isodatetime.data import ( |
| 49 |
get_timepoint_from_seconds_since_unix_epoch as seconds2point) |
| 50 |
|
| 51 |
from cylc.flow.exceptions import InputError |
| 52 |
from cylc.flow.id import Tokens |
| 53 |
from cylc.flow.id_cli import parse_ids |
| 54 |
from cylc.flow.network.client_factory import get_client |
| 55 |
from cylc.flow.run_modes import RunMode |
| 56 |
from cylc.flow.task_outputs import TaskOutputs |
| 57 |
from cylc.flow.task_state import ( |
| 58 |
TASK_STATUSES_ORDERED, |
| 59 |
TASK_STATUS_RUNNING |
| 60 |
) |
| 61 |
from cylc.flow.option_parsers import ( |
| 62 |
CylcOptionParser as COP, |
| 63 |
ID_MULTI_ARG_DOC, |
| 64 |
Options, |
| 65 |
) |
| 66 |
from cylc.flow.terminal import cli_function |
| 67 |
from cylc.flow.util import BOOL_SYMBOLS |
| 68 |
|
| 69 |
|
| 70 |
if TYPE_CHECKING: |
| 71 |
from optparse import Values |
| 72 |
|
| 73 |
|
| 74 |
WORKFLOW_META_QUERY = ''' |
| 75 |
query ($wFlows: [ID]!) { |
| 76 |
workflows (ids: $wFlows, stripNull: false) { |
| 77 |
meta { |
| 78 |
title |
| 79 |
description |
| 80 |
URL |
| 81 |
userDefined |
| 82 |
} |
| 83 |
} |
| 84 |
} |
| 85 |
''' |
| 86 |
|
| 87 |
TASK_META_QUERY = ''' |
| 88 |
query ($wFlows: [ID]!, $taskIds: [ID]) { |
| 89 |
tasks (workflows: $wFlows, ids: $taskIds, stripNull: false) { |
| 90 |
name |
| 91 |
meta { |
| 92 |
title |
| 93 |
description |
| 94 |
URL |
| 95 |
userDefined |
| 96 |
} |
| 97 |
} |
| 98 |
} |
| 99 |
''' |
| 100 |
|
| 101 |
TASK_PREREQS_QUERY = ''' |
| 102 |
query ($wFlows: [ID]!, $taskIds: [ID]) { |
| 103 |
taskProxies (workflows: $wFlows, ids: $taskIds, stripNull: false) { |
| 104 |
id |
| 105 |
name |
| 106 |
cyclePoint |
| 107 |
state |
| 108 |
isHeld |
| 109 |
isQueued |
| 110 |
isRunahead |
| 111 |
flowNums |
| 112 |
task { |
| 113 |
meta { |
| 114 |
title |
| 115 |
description |
| 116 |
URL |
| 117 |
userDefined |
| 118 |
} |
| 119 |
} |
| 120 |
prerequisites { |
| 121 |
expression |
| 122 |
conditions { |
| 123 |
exprAlias |
| 124 |
taskId |
| 125 |
reqState |
| 126 |
message |
| 127 |
satisfied |
| 128 |
} |
| 129 |
satisfied |
| 130 |
} |
| 131 |
outputs { |
| 132 |
label |
| 133 |
message |
| 134 |
satisfied |
| 135 |
} |
| 136 |
externalTriggers { |
| 137 |
id |
| 138 |
label |
| 139 |
message |
| 140 |
satisfied |
| 141 |
} |
| 142 |
xtriggers { |
| 143 |
id |
| 144 |
label |
| 145 |
satisfied |
| 146 |
} |
| 147 |
runtime { |
| 148 |
completion |
| 149 |
runMode |
| 150 |
} |
| 151 |
} |
| 152 |
} |
| 153 |
''' |
| 154 |
|
| 155 |
|
| 156 |
SATISFIED = BOOL_SYMBOLS[True] |
| 157 |
UNSATISFIED = BOOL_SYMBOLS[False] |
| 158 |
|
| 159 |
|
| 160 |
def print_msg_state(msg, state): |
| 161 |
if state: |
| 162 |
ansiprint(f'<green> {SATISFIED} {msg}</green>') |
| 163 |
else: |
| 164 |
ansiprint(f'<red> {UNSATISFIED} {msg}</red>') |
| 165 |
|
| 166 |
|
| 167 |
def print_completion_state(t_proxy): |
| 168 |
# create task outputs object |
| 169 |
outputs = TaskOutputs(t_proxy["runtime"]["completion"]) |
| 170 |
|
| 171 |
for output in t_proxy['outputs']: |
| 172 |
outputs.add(output['label'], output['message']) |
| 173 |
if output['satisfied']: |
| 174 |
outputs.set_message_complete(output['message']) |
| 175 |
|
| 176 |
ansiprint( |
| 177 |
f'<bold>output completion:</bold>' |
| 178 |
f' {"complete" if outputs.is_complete() else "incomplete"}' |
| 179 |
f'\n{indent(outputs.format_completion_status(ansimarkup=2), " ")}' |
| 180 |
) |
| 181 |
|
| 182 |
|
| 183 |
def flatten_data(data, flat_data=None): |
| 184 |
"""Reduce a nested data structure to a flat one. |
| 185 |
|
| 186 |
Examples: |
| 187 |
It flattens out nested dictionaries: |
| 188 |
>>> flatten_data({}) |
| 189 |
{} |
| 190 |
>>> flatten_data({'a': 1}) |
| 191 |
{'a': 1} |
| 192 |
>>> flatten_data({'a': {'b': 2, 'c': {'d': 4}}}) |
| 193 |
{'b': 2, 'd': 4} |
| 194 |
|
| 195 |
It iterates through any lists that it finds: |
| 196 |
>>> flatten_data({'a': [{'b': 2}, {'c': 3}]}) |
| 197 |
{'b': 2, 'c': 3} |
| 198 |
|
| 199 |
Overriding is determined by iteration order (don't rely on it): |
| 200 |
>>> flatten_data({'a': 1, 'b': {'a': 2}}) |
| 201 |
{'a': 2} |
| 202 |
|
| 203 |
It can't flatten things which aren't dicts: |
| 204 |
>>> flatten_data({'a': ['x', 'y']}) |
| 205 |
Traceback (most recent call last): |
| 206 |
AttributeError: 'str' object has no attribute 'items' |
| 207 |
|
| 208 |
""" |
| 209 |
if flat_data is None: |
| 210 |
flat_data = {} |
| 211 |
for key, value in data.items(): |
| 212 |
if isinstance(value, dict): |
| 213 |
flatten_data(value, flat_data) |
| 214 |
elif isinstance(value, list): |
| 215 |
for member in value: |
| 216 |
flatten_data(member, flat_data) |
| 217 |
else: |
| 218 |
flat_data[key] = value |
| 219 |
return flat_data |
| 220 |
|
| 221 |
|
| 222 |
def get_option_parser(): |
| 223 |
parser = COP( |
| 224 |
__doc__, |
| 225 |
comms=True, |
| 226 |
multitask=True, |
| 227 |
argdoc=[ID_MULTI_ARG_DOC], |
| 228 |
) |
| 229 |
|
| 230 |
parser.add_option( |
| 231 |
'--list-prereqs', |
| 232 |
action="store_true", |
| 233 |
default=False, |
| 234 |
help="Print a task's pre-requisites as a list.", |
| 235 |
) |
| 236 |
|
| 237 |
parser.add_option( |
| 238 |
'--json', |
| 239 |
action="store_true", |
| 240 |
default=False, |
| 241 |
help="Print output in JSON format.", |
| 242 |
) |
| 243 |
|
| 244 |
parser.add_option( |
| 245 |
'--task-def', |
| 246 |
action="append", |
| 247 |
default=None, |
| 248 |
dest='task_defs', |
| 249 |
metavar='TASK_NAME', |
| 250 |
help="View metadata for a task definition (can be used multiple times)" |
| 251 |
) |
| 252 |
|
| 253 |
return parser |
| 254 |
|
| 255 |
|
| 256 |
ShowOptions = Options(get_option_parser()) |
| 257 |
|
| 258 |
|
| 259 |
async def workflow_meta_query(workflow_id, pclient, options, json_filter): |
| 260 |
query = WORKFLOW_META_QUERY |
| 261 |
query_kwargs = { |
| 262 |
'request_string': query, |
| 263 |
'variables': {'wFlows': [workflow_id]} |
| 264 |
} |
| 265 |
# Print workflow info. |
| 266 |
results = await pclient.async_request('graphql', query_kwargs) |
| 267 |
for workflow_id in results['workflows']: |
| 268 |
flat_data = flatten_data(workflow_id) |
| 269 |
if options.json: |
| 270 |
json_filter.update(flat_data) |
| 271 |
else: |
| 272 |
for key, value in sorted(flat_data.items(), reverse=True): |
| 273 |
ansiprint( |
| 274 |
f'<bold>{key}:</bold> {value or "<m>(not given)</m>"}' |
| 275 |
) |
| 276 |
return 0 |
| 277 |
|
| 278 |
|
| 279 |
async def prereqs_and_outputs_query( |
| 280 |
workflow_id, |
| 281 |
tokens_list, |
| 282 |
pclient, |
| 283 |
options, |
| 284 |
json_filter, |
| 285 |
): |
| 286 |
ids_list = [ |
| 287 |
# convert the tokens into standardised IDs |
| 288 |
tokens.relative_id_with_selectors |
| 289 |
for tokens in tokens_list |
| 290 |
] |
| 291 |
|
| 292 |
tp_query = TASK_PREREQS_QUERY |
| 293 |
tp_kwargs = { |
| 294 |
'request_string': tp_query, |
| 295 |
'variables': { |
| 296 |
'wFlows': [workflow_id], |
| 297 |
'taskIds': ids_list, |
| 298 |
} |
| 299 |
} |
| 300 |
results = await pclient.async_request('graphql', tp_kwargs) |
| 301 |
task_proxies = sorted(results['taskProxies'], |
| 302 |
key=lambda proxy: proxy['id']) |
| 303 |
multi = len(task_proxies) > 1 |
| 304 |
for t_proxy in task_proxies: |
| 305 |
task_id = Tokens(t_proxy['id']).relative_id |
| 306 |
state = t_proxy['state'] |
| 307 |
if options.json: |
| 308 |
json_filter.update({task_id: t_proxy}) |
| 309 |
else: |
| 310 |
if multi: |
| 311 |
ansiprint(f'\n<bold>Task ID:</bold> {task_id}') |
| 312 |
prereqs = [] |
| 313 |
for item in t_proxy['prerequisites']: |
| 314 |
prefix = '' |
| 315 |
multi_cond = len(item['conditions']) > 1 |
| 316 |
if multi_cond: |
| 317 |
prereqs.append([ |
| 318 |
True, |
| 319 |
'', |
| 320 |
item['expression'].replace('c', ''), |
| 321 |
item['satisfied'] |
| 322 |
]) |
| 323 |
for cond in item['conditions']: |
| 324 |
if multi_cond and not options.list_prereqs: |
| 325 |
prefix = f'\t{cond["exprAlias"].strip("c")} = ' |
| 326 |
prereqs.append([ |
| 327 |
False, |
| 328 |
prefix, |
| 329 |
f'{cond["taskId"]} {cond["reqState"]}', |
| 330 |
cond['satisfied'] |
| 331 |
]) |
| 332 |
if options.list_prereqs: |
| 333 |
for composite, _, msg, _ in prereqs: |
| 334 |
if not composite: |
| 335 |
print(msg) |
| 336 |
else: |
| 337 |
flat_meta = flatten_data(t_proxy['task']['meta']) |
| 338 |
for key, value in sorted(flat_meta.items(), reverse=True): |
| 339 |
ansiprint( |
| 340 |
f'<bold>{key}:</bold>' |
| 341 |
f' {value or "<m>(not given)</m>"}') |
| 342 |
|
| 343 |
# state and state attributes |
| 344 |
attrs = [] |
| 345 |
if t_proxy['isHeld']: |
| 346 |
attrs.append("held") |
| 347 |
if t_proxy['isQueued']: |
| 348 |
attrs.append("queued") |
| 349 |
if t_proxy['isRunahead']: |
| 350 |
attrs.append("runahead") |
| 351 |
run_mode = t_proxy['runtime']['runMode'] |
| 352 |
if run_mode and RunMode(run_mode) != RunMode.LIVE: |
| 353 |
attrs.append(f"run mode={run_mode}") |
| 354 |
state_msg = state |
| 355 |
if attrs: |
| 356 |
state_msg += f" ({','.join(attrs)})" |
| 357 |
|
| 358 |
ansiprint(f'<bold>state:</bold> {state_msg}') |
| 359 |
|
| 360 |
# flow numbers, if not just 1 |
| 361 |
if t_proxy["flowNums"] != "[1]": |
| 362 |
ansiprint( |
| 363 |
f"<bold>flows:</bold> " |
| 364 |
f"{t_proxy['flowNums'].replace(' ', '')}" |
| 365 |
) |
| 366 |
|
| 367 |
# prerequisites |
| 368 |
pre_txt = "<bold>prerequisites:</bold>" |
| 369 |
if not prereqs: |
| 370 |
ansiprint(f"{pre_txt} (None)") |
| 371 |
elif ( |
| 372 |
TASK_STATUSES_ORDERED.index(state) > |
| 373 |
TASK_STATUSES_ORDERED.index(TASK_STATUS_RUNNING) |
| 374 |
): |
| 375 |
# We only store prerequisites in the DB for n>0. |
| 376 |
ansiprint(f"{pre_txt} (n/a for past tasks)") |
| 377 |
else: |
| 378 |
ansiprint( |
| 379 |
f"{pre_txt}" |
| 380 |
f" ('<red>{UNSATISFIED}</red>': not satisfied)" |
| 381 |
) |
| 382 |
for _, prefix, msg, state in prereqs: |
| 383 |
print_msg_state(f'{prefix}{msg}', state) |
| 384 |
|
| 385 |
# outputs |
| 386 |
ansiprint( |
| 387 |
'<bold>outputs:</bold>' |
| 388 |
f" ('<red>{UNSATISFIED}</red>': not completed)") |
| 389 |
if not t_proxy['outputs']: # (Not possible - standard outputs) |
| 390 |
print(' (None)') |
| 391 |
for output in t_proxy['outputs']: |
| 392 |
info = f'{task_id} {output["label"]}' |
| 393 |
print_msg_state(info, output['satisfied']) |
| 394 |
if ( |
| 395 |
t_proxy['externalTriggers'] |
| 396 |
or t_proxy['xtriggers'] |
| 397 |
): |
| 398 |
ansiprint( |
| 399 |
"<bold>other:</bold>" |
| 400 |
f" ('<red>{UNSATISFIED}</red>': not satisfied)" |
| 401 |
) |
| 402 |
for ext_trig in t_proxy['externalTriggers']: |
| 403 |
state = ext_trig['satisfied'] |
| 404 |
print_msg_state( |
| 405 |
f'{ext_trig["label"]} ... {state}', |
| 406 |
state) |
| 407 |
for xtrig in t_proxy['xtriggers']: |
| 408 |
label = get_wallclock_label(xtrig) or xtrig['id'] |
| 409 |
state = xtrig['satisfied'] |
| 410 |
print_msg_state( |
| 411 |
f'xtrigger "{xtrig["label"]} = {label}"', |
| 412 |
state) |
| 413 |
|
| 414 |
print_completion_state(t_proxy) |
| 415 |
|
| 416 |
if not task_proxies: |
| 417 |
ansiprint( |
| 418 |
"<red>No matching active tasks found: " |
| 419 |
f"{', '.join(ids_list)}</red>", |
| 420 |
file=sys.stderr, |
| 421 |
) |
| 422 |
return 1 |
| 423 |
return 0 |
| 424 |
|
| 425 |
|
| 426 |
def get_wallclock_label(xtrig: Dict[str, Any]) -> str: |
| 427 |
"""Return a label for an xtrigger if it is a wall_clock trigger. |
| 428 |
|
| 429 |
Returns: |
| 430 |
A label or False. |
| 431 |
|
| 432 |
Examples: |
| 433 |
>>> this = get_wallclock_label |
| 434 |
|
| 435 |
>>> this({'id': 'wall_clock(trigger_time=0)'}) |
| 436 |
'wall_clock(trigger_time=1970-01-01T00:00:00Z)' |
| 437 |
|
| 438 |
>>> this({'id': 'wall_clock(trigger_time=440143843)'}) |
| 439 |
'wall_clock(trigger_time=1983-12-13T06:10:43Z)' |
| 440 |
|
| 441 |
""" |
| 442 |
wallclock_trigger = re.findall( |
| 443 |
r'wall_clock\(trigger_time=(.*)\)', xtrig['id']) |
| 444 |
if wallclock_trigger: |
| 445 |
return ( |
| 446 |
'wall_clock(trigger_time=' |
| 447 |
f'{str(seconds2point(wallclock_trigger[0], True))})' |
| 448 |
) |
| 449 |
return '' |
| 450 |
|
| 451 |
|
| 452 |
async def task_meta_query( |
| 453 |
workflow_id, |
| 454 |
task_names, |
| 455 |
pclient, |
| 456 |
options, |
| 457 |
json_filter, |
| 458 |
): |
| 459 |
tasks_query = TASK_META_QUERY |
| 460 |
tasks_kwargs = { |
| 461 |
'request_string': tasks_query, |
| 462 |
'variables': { |
| 463 |
'wFlows': [workflow_id], |
| 464 |
'taskIds': task_names, |
| 465 |
}, |
| 466 |
} |
| 467 |
# Print workflow info. |
| 468 |
results = await pclient.async_request('graphql', tasks_kwargs) |
| 469 |
multi = len(results['tasks']) > 1 |
| 470 |
for task in results['tasks']: |
| 471 |
flat_data = flatten_data(task['meta']) |
| 472 |
if options.json: |
| 473 |
json_filter.update({task['name']: flat_data}) |
| 474 |
else: |
| 475 |
if multi: |
| 476 |
print(f'\nTASK NAME: {task["name"]}') |
| 477 |
for key, value in sorted(flat_data.items(), reverse=True): |
| 478 |
ansiprint( |
| 479 |
f'<bold>{key}:</bold> {value or "<m>(not given)</m>"}') |
| 480 |
return 0 |
| 481 |
|
| 482 |
|
| 483 |
async def show(workflow_id, tokens_list, opts): |
| 484 |
pclient = get_client( |
| 485 |
workflow_id, |
| 486 |
timeout=opts.comms_timeout, |
| 487 |
) |
| 488 |
json_filter: 'Dict' = {} |
| 489 |
|
| 490 |
ret = 0 |
| 491 |
if opts.task_defs: |
| 492 |
ret = await task_meta_query( |
| 493 |
workflow_id, |
| 494 |
opts.task_defs, |
| 495 |
pclient, |
| 496 |
opts, |
| 497 |
json_filter, |
| 498 |
) |
| 499 |
elif not tokens_list: |
| 500 |
ret = await workflow_meta_query( |
| 501 |
workflow_id, |
| 502 |
pclient, |
| 503 |
opts, |
| 504 |
json_filter, |
| 505 |
) |
| 506 |
else: |
| 507 |
ret = await prereqs_and_outputs_query( |
| 508 |
workflow_id, |
| 509 |
tokens_list, |
| 510 |
pclient, |
| 511 |
opts, |
| 512 |
json_filter, |
| 513 |
) |
| 514 |
|
| 515 |
if opts.json: |
| 516 |
print(json.dumps(json_filter, indent=4)) |
| 517 |
|
| 518 |
return ret |
| 519 |
|
| 520 |
|
| 521 |
@cli_function(get_option_parser) |
| 522 |
def main(_, options: 'Values', *ids) -> None: |
| 523 |
"""Implement "cylc show" CLI.""" |
| 524 |
workflow_args, _ = parse_ids( |
| 525 |
*ids, |
| 526 |
constraint='mixed', |
| 527 |
max_workflows=1, |
| 528 |
) |
| 529 |
workflow_id = next(iter(workflow_args)) |
| 530 |
tokens_list = workflow_args[workflow_id] |
| 531 |
|
| 532 |
if tokens_list and options.task_defs: |
| 533 |
raise InputError( |
| 534 |
'Cannot query both live tasks and task definitions.' |
| 535 |
) |
| 536 |
|
| 537 |
ret = asyncio.run(show(workflow_id, tokens_list, options)) |
| 538 |
sys.exit(ret) |