| 1 |
#!/usr/bin/env python3 |
| 2 |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. |
| 3 |
# Copyright (C) NIWA & British Crown (Met Office) & Contributors. |
| 4 |
# |
| 5 |
# This program is free software: you can redistribute it and/or modify |
| 6 |
# it under the terms of the GNU General Public License as published by |
| 7 |
# the Free Software Foundation, either version 3 of the License, or |
| 8 |
# (at your option) any later version. |
| 9 |
# |
| 10 |
# This program is distributed in the hope that it will be useful, |
| 11 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 |
# GNU General Public License for more details. |
| 14 |
# |
| 15 |
# You should have received a copy of the GNU General Public License |
| 16 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 |
"""Common utilities for Tui.""" |
| 18 |
|
| 19 |
from contextlib import contextmanager |
| 20 |
from getpass import getuser |
| 21 |
from itertools import zip_longest |
| 22 |
import re |
| 23 |
from time import time |
| 24 |
from typing import Any, Dict, Optional, Set, Tuple |
| 25 |
|
| 26 |
import urwid |
| 27 |
|
| 28 |
from cylc.flow import LOG |
| 29 |
from cylc.flow.flow_mgr import stringify_flow_nums |
| 30 |
from cylc.flow.id import Tokens |
| 31 |
from cylc.flow.task_state import ( |
| 32 |
TASK_STATUS_RUNNING |
| 33 |
) |
| 34 |
from cylc.flow.tui import ( |
| 35 |
JOB_COLOURS, |
| 36 |
JOB_ICON, |
| 37 |
TASK_ICONS, |
| 38 |
TASK_MODIFIERS |
| 39 |
) |
| 40 |
from cylc.flow.util import deserialise_set |
| 41 |
from cylc.flow.wallclock import get_unix_time_from_time_string |
| 42 |
|
| 43 |
|
| 44 |
# the Tui user, note this is always the same as the workflow owner |
| 45 |
# (Tui doesn't do multi-user stuff) |
| 46 |
ME = getuser() |
| 47 |
|
| 48 |
|
| 49 |
Node = Dict[str, Any] |
| 50 |
NodeStore = Dict[str, Dict[str, Node]] |
| 51 |
|
| 52 |
|
| 53 |
MODIFIER_ATTR_MAPPING = { |
| 54 |
# text repr: (internal attr, GraphQL attr) |
| 55 |
'held': ('is_held', 'isHeld'), |
| 56 |
'runahead': ('is_runahead', 'isRunahead'), |
| 57 |
'queued': ('is_queued', 'isQueued'), |
| 58 |
'retry scheduled': ('is_retry', 'isRetry'), |
| 59 |
'wallclock': ('is_wallclock', 'isWallclock'), |
| 60 |
'xtriggered': ('is_xtriggered', 'isXtriggered'), |
| 61 |
} |
| 62 |
|
| 63 |
|
| 64 |
@contextmanager |
| 65 |
def suppress_logging(): |
| 66 |
"""Suppress Cylc logging. |
| 67 |
|
| 68 |
Log goes to stdout/err which can pollute Urwid apps. |
| 69 |
Patching sys.stdout/err is insufficient so we set the level to something |
| 70 |
silly for the duration of this context manager then set it back again |
| 71 |
afterwards. |
| 72 |
""" |
| 73 |
orig_level = LOG.level |
| 74 |
LOG.setLevel(99999) |
| 75 |
yield |
| 76 |
LOG.setLevel(orig_level) |
| 77 |
|
| 78 |
|
| 79 |
def get_task_icon( |
| 80 |
status, |
| 81 |
*, |
| 82 |
is_held=False, |
| 83 |
is_queued=False, |
| 84 |
is_runahead=False, |
| 85 |
is_retry=False, |
| 86 |
is_wallclock=False, |
| 87 |
is_xtriggered=False, |
| 88 |
colour='body', |
| 89 |
start_time=None, |
| 90 |
mean_time=None, |
| 91 |
): |
| 92 |
"""Return a Unicode string to represent a task. |
| 93 |
|
| 94 |
Arguments: |
| 95 |
status (str): |
| 96 |
A Cylc task status string. |
| 97 |
is_held (bool): |
| 98 |
True if the task is held. |
| 99 |
is_queued (bool): |
| 100 |
True if the task is queued. |
| 101 |
is_runahead (bool): |
| 102 |
True if the task is runahead limited. |
| 103 |
colour (str): |
| 104 |
Set the icon colour. If not provided, the default foreground text |
| 105 |
colour will be used. |
| 106 |
start_time (str): |
| 107 |
Start date time string. |
| 108 |
mean_time (int): |
| 109 |
Execution mean time. |
| 110 |
|
| 111 |
Returns: |
| 112 |
list - Text content for the urwid.Text widget, |
| 113 |
may be a string, tuple or list, see urwid docs. |
| 114 |
|
| 115 |
""" |
| 116 |
ret = [] |
| 117 |
if is_held: |
| 118 |
ret.append((colour, TASK_MODIFIERS['held'])) |
| 119 |
elif is_runahead: |
| 120 |
ret.append((colour, TASK_MODIFIERS['runahead'])) |
| 121 |
elif is_queued: |
| 122 |
ret.append((colour, TASK_MODIFIERS['queued'])) |
| 123 |
elif is_retry: |
| 124 |
ret.append((colour, TASK_MODIFIERS['retry'])) |
| 125 |
elif is_wallclock: |
| 126 |
ret.append((colour, TASK_MODIFIERS['wallclock'])) |
| 127 |
elif is_xtriggered: |
| 128 |
ret.append((colour, TASK_MODIFIERS['xtriggered'])) |
| 129 |
if ( |
| 130 |
status == TASK_STATUS_RUNNING |
| 131 |
and start_time |
| 132 |
and mean_time |
| 133 |
): |
| 134 |
start_time = get_unix_time_from_time_string(start_time) |
| 135 |
progress = (time() - start_time) / mean_time |
| 136 |
if progress >= 0.75: |
| 137 |
status = f'{TASK_STATUS_RUNNING}:75' |
| 138 |
elif progress >= 0.5: |
| 139 |
status = f'{TASK_STATUS_RUNNING}:50' |
| 140 |
elif progress >= 0.25: |
| 141 |
status = f'{TASK_STATUS_RUNNING}:25' |
| 142 |
else: |
| 143 |
status = f'{TASK_STATUS_RUNNING}:0' |
| 144 |
ret.append((colour, TASK_ICONS[status])) |
| 145 |
return ret |
| 146 |
|
| 147 |
|
| 148 |
def get_status_str(data): |
| 149 |
"""Return a text represenation of a workflow, cycle, family, task or job. |
| 150 |
|
| 151 |
Args: |
| 152 |
data: A data node from the Tui tree (i.e. `value['data']`). |
| 153 |
|
| 154 |
""" |
| 155 |
attrs = [] |
| 156 |
|
| 157 |
# workflow state info |
| 158 |
if data.get('status'): |
| 159 |
attrs.append(data['status']) |
| 160 |
|
| 161 |
# task state info |
| 162 |
if data.get('state'): |
| 163 |
state_attrs = [ |
| 164 |
modifier_text |
| 165 |
for modifier_text, (_, data_attr) in MODIFIER_ATTR_MAPPING.items() |
| 166 |
if data.get(data_attr, None) |
| 167 |
] |
| 168 |
_attr = data['state'] |
| 169 |
if state_attrs: |
| 170 |
_attr += f' ({", ".join(state_attrs)})' |
| 171 |
attrs.append(_attr) |
| 172 |
|
| 173 |
# task flow info |
| 174 |
if data.get('flowNums', '[1]') != '[1]': |
| 175 |
attrs.append(f'flows={format_flow_nums(data["flowNums"])}') |
| 176 |
|
| 177 |
return ', '.join(attrs) |
| 178 |
|
| 179 |
|
| 180 |
def idpop(id_): |
| 181 |
"""Remove the last element of a node id. |
| 182 |
|
| 183 |
Examples: |
| 184 |
>>> idpop('w//c/t/j') |
| 185 |
'w//c/t' |
| 186 |
>>> idpop('c/t/j') |
| 187 |
'//c/t' |
| 188 |
>>> idpop('c/t') |
| 189 |
'//c' |
| 190 |
>>> idpop('c') |
| 191 |
Traceback (most recent call last): |
| 192 |
ValueError: No tokens provided |
| 193 |
>>> idpop('') |
| 194 |
Traceback (most recent call last): |
| 195 |
ValueError: Invalid Cylc identifier: // |
| 196 |
|
| 197 |
""" |
| 198 |
relative = '//' not in id_ |
| 199 |
tokens = Tokens(id_, relative=relative) |
| 200 |
tokens.pop_token() |
| 201 |
return tokens.id |
| 202 |
|
| 203 |
|
| 204 |
def compute_tree(data: dict, prune_families: bool = False) -> Node: |
| 205 |
"""Digest GraphQL data to produce a tree. |
| 206 |
|
| 207 |
Args: |
| 208 |
data: |
| 209 |
The workflow data as returned from the GraphQL query. |
| 210 |
prune_families: |
| 211 |
If True any empty families will be removed from the tree. |
| 212 |
Turn this on if task state filters are active. |
| 213 |
|
| 214 |
""" |
| 215 |
root_node: Node = add_node('root', 'root', create_node_store(), data={}) |
| 216 |
|
| 217 |
for flow in data['workflows']: |
| 218 |
nodes: NodeStore = create_node_store() # nodes for this workflow |
| 219 |
flow_node = add_node( |
| 220 |
'workflow', flow['id'], nodes, data=flow) |
| 221 |
root_node['children'].append(flow_node) |
| 222 |
|
| 223 |
# populate cycle nodes |
| 224 |
for cycle in flow.get('cyclePoints', []): |
| 225 |
cycle['id'] = idpop(cycle['id']) # strip the family off of the id |
| 226 |
cycle_node = add_node('cycle', cycle['id'], nodes, data=cycle) |
| 227 |
flow_node['children'].append(cycle_node) |
| 228 |
|
| 229 |
# populate family nodes |
| 230 |
for family in flow.get('familyProxies', []): |
| 231 |
add_node('family', family['id'], nodes, data=family) |
| 232 |
|
| 233 |
# create cycle/family tree |
| 234 |
for family in flow.get('familyProxies', []): |
| 235 |
family_node = add_node( |
| 236 |
'family', family['id'], nodes) |
| 237 |
first_parent = family['firstParent'] |
| 238 |
if ( |
| 239 |
first_parent |
| 240 |
and first_parent['name'] != 'root' |
| 241 |
): |
| 242 |
parent_node = add_node( |
| 243 |
'family', first_parent['id'], nodes) |
| 244 |
parent_node['children'].append(family_node) |
| 245 |
else: |
| 246 |
add_node( |
| 247 |
'cycle', idpop(family['id']), nodes |
| 248 |
)['children'].append(family_node) |
| 249 |
|
| 250 |
# add leaves |
| 251 |
for task in flow.get('taskProxies', []): |
| 252 |
# If there's no first parent, the child will have been deleted |
| 253 |
# during/after API query resolution. So ignore. |
| 254 |
if not task['firstParent']: |
| 255 |
continue |
| 256 |
task_node = add_node( |
| 257 |
'task', task['id'], nodes, data=task) |
| 258 |
if task['firstParent']['name'] == 'root': |
| 259 |
family_node = add_node( |
| 260 |
'cycle', idpop(task['id']), nodes) |
| 261 |
else: |
| 262 |
family_node = add_node( |
| 263 |
'family', task['firstParent']['id'], nodes) |
| 264 |
family_node['children'].append(task_node) |
| 265 |
for job in task['jobs']: |
| 266 |
job_node = add_node( |
| 267 |
'job', job['id'], nodes, data=job) |
| 268 |
job_info_node = add_node( |
| 269 |
'job_info', job['id'] + '_info', nodes, data=job) |
| 270 |
job_node['children'] = [job_info_node] |
| 271 |
task_node['children'].append(job_node) |
| 272 |
|
| 273 |
# trim empty families / cycles (cycles are just "root" families) |
| 274 |
if prune_families: |
| 275 |
_prune_empty_families(nodes) |
| 276 |
|
| 277 |
# sort |
| 278 |
for type_ in ('workflow', 'cycle', 'family', 'job'): |
| 279 |
for node in nodes[type_].values(): |
| 280 |
# NOTE: jobs are sorted by submit-num in the GraphQL query |
| 281 |
node['children'].sort( |
| 282 |
key=lambda x: NaturalSort(x['id_']) |
| 283 |
) |
| 284 |
|
| 285 |
# spring nodes |
| 286 |
if 'port' not in flow: |
| 287 |
# the "port" field is only available via GraphQL |
| 288 |
# so we are not connected to this workflow yet |
| 289 |
flow_node['children'].append( |
| 290 |
add_node( |
| 291 |
'#spring', |
| 292 |
'#spring', |
| 293 |
nodes, |
| 294 |
data={ |
| 295 |
'id': flow.get('_tui_data', 'Loading ...'), |
| 296 |
} |
| 297 |
) |
| 298 |
) |
| 299 |
|
| 300 |
return root_node |
| 301 |
|
| 302 |
|
| 303 |
def _prune_empty_families(nodes: NodeStore) -> None: |
| 304 |
"""Prune empty families from the tree. |
| 305 |
|
| 306 |
Note, cycles are "root" families. |
| 307 |
|
| 308 |
We can end up with empty families when filtering by task state. We filter |
| 309 |
tasks by state in the GraphQL query (so we don't need to perform this |
| 310 |
filtering client-side), however, we cannot filter families by state because |
| 311 |
the family state is an aggregate representing a collection of tasks (and or |
| 312 |
families). |
| 313 |
|
| 314 |
Args: |
| 315 |
nodes: Dictionary containing all nodes present in the tree. |
| 316 |
|
| 317 |
""" |
| 318 |
# go through all families and cycles |
| 319 |
stack: Set[str] = {*nodes['family'], *nodes['cycle']} |
| 320 |
while stack: |
| 321 |
family_id = stack.pop() |
| 322 |
|
| 323 |
if family_id in nodes['family']: |
| 324 |
# this is a family |
| 325 |
family = nodes['family'][family_id] |
| 326 |
if len(family['children']) > 0: |
| 327 |
continue |
| 328 |
|
| 329 |
# this family is empty -> find its parent (family/cycle) |
| 330 |
_first_parent = family['data']['firstParent'] |
| 331 |
if _first_parent['name'] == 'root': |
| 332 |
parent_type = 'cycle' |
| 333 |
parent_id = idpop(_first_parent['id']) |
| 334 |
else: |
| 335 |
parent_type = 'family' |
| 336 |
parent_id = _first_parent['id'] |
| 337 |
|
| 338 |
elif family_id in nodes['cycle']: |
| 339 |
# this is a cycle |
| 340 |
family = nodes['cycle'][family_id] |
| 341 |
if len(family['children']) > 0: |
| 342 |
continue |
| 343 |
|
| 344 |
# this cycle is empty -> find its parent (workflow) |
| 345 |
parent_type = 'workflow' |
| 346 |
parent_id = idpop(family_id) |
| 347 |
|
| 348 |
else: |
| 349 |
# this node has already been pruned |
| 350 |
continue |
| 351 |
|
| 352 |
# remove the node from its parent |
| 353 |
nodes[parent_type][parent_id]['children'].remove(family) |
| 354 |
if parent_type in {'family', 'cycle'}: |
| 355 |
# recurse up the family tree |
| 356 |
stack.add(parent_id) |
| 357 |
|
| 358 |
|
| 359 |
class NaturalSort: |
| 360 |
"""An object to use as a sort key for sorting strings as a human would. |
| 361 |
|
| 362 |
This recognises numerical patterns within strings. |
| 363 |
|
| 364 |
Examples: |
| 365 |
>>> N = NaturalSort |
| 366 |
|
| 367 |
String comparisons work as normal: |
| 368 |
>>> N('') < N('') |
| 369 |
False |
| 370 |
>>> N('a') < N('b') |
| 371 |
True |
| 372 |
>>> N('b') < N('a') |
| 373 |
False |
| 374 |
|
| 375 |
Integer comparisons work as normal: |
| 376 |
>>> N('9') < N('10') |
| 377 |
True |
| 378 |
>>> N('10') < N('9') |
| 379 |
False |
| 380 |
|
| 381 |
Integers rank higher than strings: |
| 382 |
>>> N('1') < N('a') |
| 383 |
True |
| 384 |
>>> N('a') < N('1') |
| 385 |
False |
| 386 |
|
| 387 |
Integers within strings are sorted numerically: |
| 388 |
>>> N('a9b') < N('a10b') |
| 389 |
True |
| 390 |
>>> N('a10b') < N('a9b') |
| 391 |
False |
| 392 |
|
| 393 |
Lexicographical rules apply when substrings match: |
| 394 |
>>> N('a1b2') < N('a1b2c3') |
| 395 |
True |
| 396 |
>>> N('a1b2c3') < N('a1b2') |
| 397 |
False |
| 398 |
|
| 399 |
Equality works as per regular string rules: |
| 400 |
>>> N('a1b2c3') == N('a1b2c3') |
| 401 |
True |
| 402 |
|
| 403 |
""" |
| 404 |
|
| 405 |
PATTERN = re.compile(r'(\d+)') |
| 406 |
|
| 407 |
def __init__(self, value): |
| 408 |
self.value = tuple( |
| 409 |
int(item) if item.isdigit() else item |
| 410 |
for item in self.PATTERN.split(value) |
| 411 |
# remove empty strings if value ends with a digit |
| 412 |
if item |
| 413 |
) |
| 414 |
|
| 415 |
def __eq__(self, other): |
| 416 |
return self.value == other.value |
| 417 |
|
| 418 |
def __lt__(self, other): |
| 419 |
for this, that in zip_longest(self.value, other.value): |
| 420 |
if this is None: |
| 421 |
return True |
| 422 |
if that is None: |
| 423 |
return False |
| 424 |
this_isstr = isinstance(this, str) |
| 425 |
that_isstr = isinstance(that, str) |
| 426 |
if this_isstr and that_isstr: |
| 427 |
if this == that: |
| 428 |
continue |
| 429 |
return this < that |
| 430 |
this_isint = isinstance(this, int) |
| 431 |
that_isint = isinstance(that, int) |
| 432 |
if this_isint and that_isint: |
| 433 |
if this == that: |
| 434 |
continue |
| 435 |
return this < that |
| 436 |
if this_isint and that_isstr: |
| 437 |
return True |
| 438 |
if this_isstr and that_isint: |
| 439 |
return False |
| 440 |
return False |
| 441 |
|
| 442 |
|
| 443 |
def dummy_flow(data) -> Node: |
| 444 |
return add_node( |
| 445 |
'workflow', |
| 446 |
data['id'], |
| 447 |
create_node_store(), |
| 448 |
data |
| 449 |
) |
| 450 |
|
| 451 |
|
| 452 |
def create_node_store() -> NodeStore: |
| 453 |
"""Returns a "node store" dictionary for use with add_nodes.""" |
| 454 |
return { # node_type: {node_id: node} |
| 455 |
# the root of the tree |
| 456 |
'root': {}, |
| 457 |
# spring nodes load the workflow when visited |
| 458 |
'#spring': {}, |
| 459 |
# workflow//cycle/<task/family>/job |
| 460 |
'workflow': {}, |
| 461 |
'cycle': {}, |
| 462 |
'family': {}, |
| 463 |
'task': {}, |
| 464 |
'job': {}, |
| 465 |
# the node under a job that contains metadata (platform, job_id, etc) |
| 466 |
'job_info': {}, |
| 467 |
} |
| 468 |
|
| 469 |
|
| 470 |
def add_node( |
| 471 |
type_: str, |
| 472 |
id_: str, |
| 473 |
nodes: NodeStore, |
| 474 |
data: Optional[dict] = None, |
| 475 |
) -> Node: |
| 476 |
"""Create a node add it to the store and return it. |
| 477 |
|
| 478 |
Arguments: |
| 479 |
type_ (str): |
| 480 |
A string to represent the node type. |
| 481 |
id_ (str): |
| 482 |
A unique identifier for this node. |
| 483 |
nodes (dict): |
| 484 |
The node store to add the new node to. |
| 485 |
data (dict): |
| 486 |
An optional dictionary of data to add to this node. |
| 487 |
Can be left to None if retrieving a node from the store. |
| 488 |
|
| 489 |
Returns: |
| 490 |
dict - The requested node. |
| 491 |
|
| 492 |
""" |
| 493 |
if id_ not in nodes[type_]: |
| 494 |
nodes[type_][id_] = { |
| 495 |
'children': [], |
| 496 |
'id_': id_, |
| 497 |
'data': data or {}, |
| 498 |
'type_': type_ |
| 499 |
} |
| 500 |
return nodes[type_][id_] |
| 501 |
|
| 502 |
|
| 503 |
def get_job_icon(status): |
| 504 |
"""Return a unicode string to represent a job. |
| 505 |
|
| 506 |
Arguments: |
| 507 |
status (str): A Cylc job status string. |
| 508 |
|
| 509 |
Returns: |
| 510 |
list - Text content for the urwid.Text widget, |
| 511 |
may be a string, tuple or list, see urwid docs. |
| 512 |
|
| 513 |
""" |
| 514 |
return [ |
| 515 |
(f'job_{status}', JOB_ICON) |
| 516 |
] |
| 517 |
|
| 518 |
|
| 519 |
def get_task_status_summary(flow): |
| 520 |
"""Return a task status summary line for this workflow. |
| 521 |
|
| 522 |
Arguments: |
| 523 |
flow (dict): |
| 524 |
GraphQL JSON response for this workflow. |
| 525 |
|
| 526 |
Returns: |
| 527 |
list - Text list for the urwid.Text widget. |
| 528 |
|
| 529 |
""" |
| 530 |
state_totals = flow['stateTotals'] |
| 531 |
return [ |
| 532 |
[ |
| 533 |
' ', |
| 534 |
(f'job_{state}', str(state_totals[state])), |
| 535 |
(f'job_{state}', JOB_ICON) |
| 536 |
] |
| 537 |
for state, colour in JOB_COLOURS.items() |
| 538 |
if state in state_totals |
| 539 |
if state_totals[state] |
| 540 |
] |
| 541 |
|
| 542 |
|
| 543 |
def _render_user(node, data): |
| 544 |
return f'~{ME}' |
| 545 |
|
| 546 |
|
| 547 |
def _render_job_info(node, data): |
| 548 |
key_len = max(len(key) for key in data) |
| 549 |
ret = [ |
| 550 |
f'{key} {" " * (key_len - len(key))} {value}\n' |
| 551 |
for key, value in data.items() |
| 552 |
] |
| 553 |
ret[-1] = ret[-1][:-1] # strip trailing newline |
| 554 |
return ret |
| 555 |
|
| 556 |
|
| 557 |
def _render_job(node, data): |
| 558 |
return [ |
| 559 |
f'#{data["submitNum"]:02d} ', |
| 560 |
get_job_icon(data['state']) |
| 561 |
] |
| 562 |
|
| 563 |
|
| 564 |
def _render_task(node, data): |
| 565 |
start_time = None |
| 566 |
mean_time = None |
| 567 |
try: |
| 568 |
# due to sorting this is the most recent job |
| 569 |
first_child = node.get_child_node(0) |
| 570 |
except IndexError: |
| 571 |
first_child = None |
| 572 |
|
| 573 |
# progress information |
| 574 |
if data['state'] == TASK_STATUS_RUNNING and first_child: |
| 575 |
start_time = first_child.get_value()['data']['startedTime'] |
| 576 |
mean_time = data['task']['meanElapsedTime'] |
| 577 |
|
| 578 |
if data['flowNums'] == '[]': |
| 579 |
# grey out no-flow tasks |
| 580 |
colour = 'diminished' |
| 581 |
else: |
| 582 |
# default foreground colour for everything else |
| 583 |
colour = 'body' |
| 584 |
|
| 585 |
# the task icon |
| 586 |
ret = get_task_icon( |
| 587 |
data['state'], |
| 588 |
colour=colour, |
| 589 |
start_time=start_time, |
| 590 |
mean_time=mean_time, |
| 591 |
**{ |
| 592 |
modifier_attr: data.get(data_attr, False) |
| 593 |
for _, (modifier_attr, data_attr) in MODIFIER_ATTR_MAPPING.items() |
| 594 |
} |
| 595 |
) |
| 596 |
|
| 597 |
# the most recent job status |
| 598 |
ret.append(' ') |
| 599 |
if first_child: |
| 600 |
state = first_child.get_value()['data']['state'] |
| 601 |
ret += [(f'job_{state}', f'{JOB_ICON}'), ' '] |
| 602 |
|
| 603 |
# the task name |
| 604 |
ret.append((colour, f'{data["name"]}')) |
| 605 |
return ret |
| 606 |
|
| 607 |
|
| 608 |
def _render_family(node, data): |
| 609 |
return [ |
| 610 |
get_task_icon( |
| 611 |
data['state'], |
| 612 |
**{ |
| 613 |
modifier_attr: data.get(data_attr, False) |
| 614 |
for _, (modifier_attr, data_attr) |
| 615 |
in MODIFIER_ATTR_MAPPING.items() |
| 616 |
}, |
| 617 |
), |
| 618 |
' ', |
| 619 |
Tokens(data['id']).pop_token()[1] |
| 620 |
] |
| 621 |
|
| 622 |
|
| 623 |
def _render_unknown(node, data): |
| 624 |
try: |
| 625 |
state_totals = get_task_status_summary(data) |
| 626 |
status = data['status'] |
| 627 |
status_msg = [ |
| 628 |
( |
| 629 |
'title', |
| 630 |
_display_workflow_id(data), |
| 631 |
), |
| 632 |
' - ', |
| 633 |
( |
| 634 |
f'workflow_{status}', |
| 635 |
status |
| 636 |
) |
| 637 |
] |
| 638 |
except KeyError: |
| 639 |
return Tokens(data['id']).pop_token()[1] |
| 640 |
|
| 641 |
return [*status_msg, *state_totals] |
| 642 |
|
| 643 |
|
| 644 |
def _display_workflow_id(data): |
| 645 |
return data['name'] |
| 646 |
|
| 647 |
|
| 648 |
RENDER_FUNCTIONS = { |
| 649 |
'user': _render_user, |
| 650 |
'root': _render_user, |
| 651 |
'job_info': _render_job_info, |
| 652 |
'job': _render_job, |
| 653 |
'task': _render_task, |
| 654 |
'cycle': _render_family, |
| 655 |
'family': _render_family, |
| 656 |
} |
| 657 |
|
| 658 |
|
| 659 |
def render_node(node, data, type_): |
| 660 |
"""Render a tree node as text. |
| 661 |
|
| 662 |
Args: |
| 663 |
node (MonitorNode): |
| 664 |
The node to render. |
| 665 |
data (dict): |
| 666 |
Data associated with that node. |
| 667 |
type_ (str): |
| 668 |
The node type (e.g. `task`, `job`, `family`). |
| 669 |
|
| 670 |
""" |
| 671 |
return RENDER_FUNCTIONS.get(type_, _render_unknown)(node, data) |
| 672 |
|
| 673 |
|
| 674 |
def extract_context(selection): |
| 675 |
"""Return a dictionary of all component types in the selection. |
| 676 |
|
| 677 |
Args: |
| 678 |
selection (list): |
| 679 |
List of element id's as extracted from the data store / graphql. |
| 680 |
|
| 681 |
Examples: |
| 682 |
>>> extract_context(['~a/b', '~a/c']) |
| 683 |
{'user': ['a'], 'workflow': ['b', 'c']} |
| 684 |
|
| 685 |
>>> extract_context(['~a/b//c/d/e'] |
| 686 |
... ) # doctest: +NORMALIZE_WHITESPACE |
| 687 |
{'user': ['a'], 'workflow': ['b'], 'cycle': ['c'], |
| 688 |
'task': ['d'], 'job': ['e']} |
| 689 |
|
| 690 |
>>> list(extract_context(['root']).keys()) |
| 691 |
['user'] |
| 692 |
|
| 693 |
""" |
| 694 |
ret = {} |
| 695 |
for item in selection: |
| 696 |
if item == 'root': |
| 697 |
# special handling for the Tui "root" node |
| 698 |
# (this represents the workflow owner which is always the same as |
| 699 |
# user for Tui) |
| 700 |
ret['user'] = ME |
| 701 |
continue |
| 702 |
tokens = Tokens(item) |
| 703 |
for key, value in tokens.items(): |
| 704 |
if ( |
| 705 |
value |
| 706 |
and not key.endswith('_sel') # ignore selectors |
| 707 |
): |
| 708 |
lst = ret.setdefault(key, []) |
| 709 |
if value not in lst: |
| 710 |
lst.append(value) |
| 711 |
return ret |
| 712 |
|
| 713 |
|
| 714 |
def get_text_dimensions(text: str) -> Tuple[int, int]: |
| 715 |
"""Return the monospace size of a block of multiline text. |
| 716 |
|
| 717 |
Examples: |
| 718 |
>>> get_text_dimensions('foo') |
| 719 |
(3, 1) |
| 720 |
|
| 721 |
>>> get_text_dimensions(''' |
| 722 |
... foo bar |
| 723 |
... baz |
| 724 |
... ''') |
| 725 |
(11, 3) |
| 726 |
|
| 727 |
>>> get_text_dimensions('') |
| 728 |
(0, 0) |
| 729 |
|
| 730 |
""" |
| 731 |
lines = text.splitlines() |
| 732 |
return max((0, *(len(line) for line in lines))), len(lines) |
| 733 |
|
| 734 |
|
| 735 |
class ListBoxPlus(urwid.ListBox): |
| 736 |
"""An extended list box that responds to the "home" and "end" keys.""" |
| 737 |
|
| 738 |
def keypress(self, size, key): |
| 739 |
# NOTE: The urwid.ListBox class supports "page up" and "page down" but |
| 740 |
# not "home" and "end". The implementation of these methods is highly |
| 741 |
# non-trivial. |
| 742 |
if key == 'home': |
| 743 |
# press "page up" until we stop moving |
| 744 |
target = self.get_scrollpos(size) |
| 745 |
while True: |
| 746 |
super().keypress(size, 'page up') |
| 747 |
new_target = self.get_scrollpos(size) |
| 748 |
if target == new_target: |
| 749 |
break |
| 750 |
target = new_target |
| 751 |
elif key == 'end': |
| 752 |
# press "page down" until we stop moving |
| 753 |
target = self.get_scrollpos(size) |
| 754 |
while True: |
| 755 |
super().keypress(size, 'page down') |
| 756 |
new_target = self.get_scrollpos(size) |
| 757 |
if target == new_target: |
| 758 |
break |
| 759 |
target = new_target |
| 760 |
else: |
| 761 |
return super().keypress(size, key) |
| 762 |
|
| 763 |
|
| 764 |
def format_flow_nums(serialised_flow_nums: str) -> str: |
| 765 |
"""Return a user-facing representation of task serialised flow nums. |
| 766 |
|
| 767 |
Examples: |
| 768 |
>>> format_flow_nums('[1,2]') |
| 769 |
'1,2' |
| 770 |
>>> format_flow_nums('[]') |
| 771 |
'None' |
| 772 |
|
| 773 |
""" |
| 774 |
return stringify_flow_nums(deserialise_set(serialised_flow_nums)) or 'None' |