| 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 the workflow data store. |
| 17 |
|
| 18 |
The data store is generated here, in a Workflow Service (WS), and synced to the |
| 19 |
User Interface Server (UIS) via protobuf messages. Used as resolving data with |
| 20 |
GraphQL, both in the WS and UIS, it is then provisioned to the CLI and GUI. |
| 21 |
|
| 22 |
This data store is comprised of Protobuf message objects (data elements), |
| 23 |
which are used as data containers for their respective type. |
| 24 |
|
| 25 |
Changes to the data store are accumulated on a main loop iteration as deltas |
| 26 |
in the form of protobuf messages, and then applied to the local data-store. |
| 27 |
These deltas are populated with the minimal information; only the elements |
| 28 |
and only the fields of those elements that have changed. It is done this way |
| 29 |
for the efficient transport and consistent application to remotely synced |
| 30 |
data-stores. |
| 31 |
|
| 32 |
Static data elements are generated on workflow start/restart/reload, which |
| 33 |
includes workflow, task, and family definition objects. |
| 34 |
|
| 35 |
The cycle point nodes/edges (i.e. task/family proxies) generation is triggered |
| 36 |
individually on transition to n=0. Each active task is generated |
| 37 |
along with any children and parents via a graph walk out to a specified maximum |
| 38 |
graph distance (n_edge_distance), that can be externally altered (via API). |
| 39 |
Collectively this forms the N-Distance-Window on the workflow graph. |
| 40 |
|
| 41 |
Pruning of data-store elements is done using the collection/set of nodes |
| 42 |
generated at the boundary of an active node's graph walk and registering active |
| 43 |
node's parents against them. Once active, these boundary nodes act as the prune |
| 44 |
triggers for the associated parent nodes. Set operations are used to do a diff |
| 45 |
between the nodes of active paths (paths whose node is in n=0) and the nodes of |
| 46 |
flagged paths (whose boundary node(s) have become active). |
| 47 |
This method is used to avoid "blinking", where a task becomes non-active then |
| 48 |
is removed (along with it's window/walk) before a descendant is added, causing |
| 49 |
it to disapear then reappear in the store (and, hence, UIs). |
| 50 |
|
| 51 |
Updates are created by the event/task/job managers. |
| 52 |
|
| 53 |
Data elements include a "stamp" field, which is a timestamped ID for use |
| 54 |
in assessing changes in the data store, for comparisons of a store sync. |
| 55 |
|
| 56 |
Packaging methods are included for dissemination of protobuf messages. |
| 57 |
|
| 58 |
""" |
| 59 |
|
| 60 |
from collections import ( |
| 61 |
Counter, |
| 62 |
deque, |
| 63 |
) |
| 64 |
from contextlib import suppress |
| 65 |
from copy import deepcopy |
| 66 |
import json |
| 67 |
from time import time |
| 68 |
from typing import ( |
| 69 |
TYPE_CHECKING, |
| 70 |
Any, |
| 71 |
Dict, |
| 72 |
List, |
| 73 |
Literal, |
| 74 |
Optional, |
| 75 |
Set, |
| 76 |
Tuple, |
| 77 |
) |
| 78 |
import zlib |
| 79 |
|
| 80 |
from cylc.flow import ( |
| 81 |
LOG, |
| 82 |
__version__ as CYLC_VERSION, |
| 83 |
) |
| 84 |
from cylc.flow.cycling.loader import get_point |
| 85 |
from cylc.flow.data_messages_pb2 import ( |
| 86 |
AllDeltas, |
| 87 |
EDeltas, |
| 88 |
FDeltas, |
| 89 |
FPDeltas, |
| 90 |
JDeltas, |
| 91 |
PbEdge, |
| 92 |
PbEntireWorkflow, |
| 93 |
PbFamily, |
| 94 |
PbFamilyProxy, |
| 95 |
PbJob, |
| 96 |
PbLogRecord, |
| 97 |
PbRuntime, |
| 98 |
PbTask, |
| 99 |
PbTaskProxy, |
| 100 |
PbWorkflow, |
| 101 |
TDeltas, |
| 102 |
TPDeltas, |
| 103 |
WDeltas, |
| 104 |
) |
| 105 |
from cylc.flow.exceptions import WorkflowConfigError |
| 106 |
from cylc.flow.id import Tokens |
| 107 |
from cylc.flow.network import API |
| 108 |
from cylc.flow.parsec.util import ( |
| 109 |
listjoin, |
| 110 |
pdeepcopy, |
| 111 |
poverride, |
| 112 |
) |
| 113 |
from cylc.flow.run_modes import RunMode |
| 114 |
from cylc.flow.task_job_logs import ( |
| 115 |
JOB_LOG_OPTS, |
| 116 |
get_task_job_log, |
| 117 |
) |
| 118 |
from cylc.flow.task_proxy import TaskProxy |
| 119 |
from cylc.flow.task_state import ( |
| 120 |
TASK_STATUS_FAILED, |
| 121 |
TASK_STATUS_RUNNING, |
| 122 |
TASK_STATUS_SUBMIT_FAILED, |
| 123 |
TASK_STATUS_SUBMITTED, |
| 124 |
TASK_STATUS_SUCCEEDED, |
| 125 |
TASK_STATUS_WAITING, |
| 126 |
TASK_STATUSES_FINAL, |
| 127 |
TASK_STATUSES_ORDERED, |
| 128 |
) |
| 129 |
from cylc.flow.task_state_prop import extract_group_state |
| 130 |
from cylc.flow.taskdef import ( |
| 131 |
generate_graph_children, |
| 132 |
generate_graph_parents, |
| 133 |
) |
| 134 |
from cylc.flow.util import ( |
| 135 |
deserialise_set, |
| 136 |
serialise_set, |
| 137 |
) |
| 138 |
from cylc.flow.wallclock import ( |
| 139 |
TIME_ZONE_LOCAL_INFO, |
| 140 |
TIME_ZONE_UTC_INFO, |
| 141 |
get_time_string_from_unix_time as time2str, |
| 142 |
get_unix_time_from_time_string as str2time, |
| 143 |
get_utc_mode, |
| 144 |
) |
| 145 |
from cylc.flow.workflow_status import ( |
| 146 |
get_workflow_status, |
| 147 |
get_workflow_status_msg, |
| 148 |
) |
| 149 |
|
| 150 |
|
| 151 |
if TYPE_CHECKING: |
| 152 |
from cylc.flow.cycling import PointBase |
| 153 |
from cylc.flow.flow_mgr import FlowNums |
| 154 |
from cylc.flow.prerequisite import Prerequisite |
| 155 |
from cylc.flow.scheduler import Scheduler |
| 156 |
from cylc.flow.taskdef import TaskDef |
| 157 |
|
| 158 |
EDGES = 'edges' |
| 159 |
FAMILIES = 'families' |
| 160 |
FAMILY_PROXIES = 'family_proxies' |
| 161 |
JOBS = 'jobs' |
| 162 |
TASKS = 'tasks' |
| 163 |
TASK_PROXIES = 'task_proxies' |
| 164 |
WORKFLOW = 'workflow' |
| 165 |
ALL_DELTAS = 'all' |
| 166 |
DELTA_ADDED = 'added' |
| 167 |
DELTA_UPDATED = 'updated' |
| 168 |
DELTA_PRUNED = 'pruned' |
| 169 |
LATEST_STATE_TASKS_QUEUE_SIZE = 5 |
| 170 |
|
| 171 |
MESSAGE_MAP = { |
| 172 |
EDGES: PbEdge, |
| 173 |
FAMILIES: PbFamily, |
| 174 |
FAMILY_PROXIES: PbFamilyProxy, |
| 175 |
JOBS: PbJob, |
| 176 |
TASKS: PbTask, |
| 177 |
TASK_PROXIES: PbTaskProxy, |
| 178 |
WORKFLOW: PbWorkflow, |
| 179 |
} |
| 180 |
|
| 181 |
DATA_TEMPLATE = { |
| 182 |
EDGES: {}, |
| 183 |
FAMILIES: {}, |
| 184 |
FAMILY_PROXIES: {}, |
| 185 |
JOBS: {}, |
| 186 |
TASKS: {}, |
| 187 |
TASK_PROXIES: {}, |
| 188 |
WORKFLOW: PbWorkflow(), |
| 189 |
} |
| 190 |
|
| 191 |
DELTAS_MAP = { |
| 192 |
EDGES: EDeltas, |
| 193 |
FAMILIES: FDeltas, |
| 194 |
FAMILY_PROXIES: FPDeltas, |
| 195 |
JOBS: JDeltas, |
| 196 |
TASKS: TDeltas, |
| 197 |
TASK_PROXIES: TPDeltas, |
| 198 |
WORKFLOW: WDeltas, |
| 199 |
ALL_DELTAS: AllDeltas, |
| 200 |
} |
| 201 |
|
| 202 |
DELTA_FIELDS = {DELTA_ADDED, DELTA_UPDATED, DELTA_PRUNED} |
| 203 |
|
| 204 |
JOB_STATUSES_ALL = [ |
| 205 |
TASK_STATUS_SUBMITTED, |
| 206 |
TASK_STATUS_SUBMIT_FAILED, |
| 207 |
TASK_STATUS_RUNNING, |
| 208 |
TASK_STATUS_SUCCEEDED, |
| 209 |
TASK_STATUS_FAILED, |
| 210 |
] |
| 211 |
|
| 212 |
# Faster lookup where order not needed. |
| 213 |
JOB_STATUS_SET = set(JOB_STATUSES_ALL) |
| 214 |
|
| 215 |
# Protobuf message merging appends repeated field results on merge, |
| 216 |
# unlike singular fields which are overwritten. This behaviour is |
| 217 |
# desirable in many cases, but there are exceptions. |
| 218 |
# The following is used to flag which fields require clearing before |
| 219 |
# merging from respective deltas messages. |
| 220 |
CLEAR_FIELD_MAP = { |
| 221 |
EDGES: set(), |
| 222 |
FAMILIES: set(), |
| 223 |
FAMILY_PROXIES: {'state_totals', 'states'}, |
| 224 |
JOBS: {'messages'}, |
| 225 |
TASKS: set(), |
| 226 |
TASK_PROXIES: {'prerequisites'}, |
| 227 |
WORKFLOW: {'latest_state_tasks', 'state_totals', 'states'}, |
| 228 |
} |
| 229 |
|
| 230 |
# Protobuf "repeated" fields (aka lists) that should retain only the most |
| 231 |
# recent N items |
| 232 |
DEQUE_FIELD_MAP = { |
| 233 |
# NodeType: {field_name: max_length} |
| 234 |
WORKFLOW: {'log_records': 10} |
| 235 |
} |
| 236 |
|
| 237 |
# Data types for protobuf memory reset |
| 238 |
RESET_PROTOBUF_TYPES = { |
| 239 |
TASKS, |
| 240 |
TASK_PROXIES, |
| 241 |
FAMILIES, |
| 242 |
FAMILY_PROXIES, |
| 243 |
WORKFLOW, |
| 244 |
} |
| 245 |
|
| 246 |
# internal runtime to protobuf field name mapping |
| 247 |
RUNTIME_CFG_MAP_TO_FIELD = { |
| 248 |
'completion': 'completion', |
| 249 |
'directives': 'directives', |
| 250 |
'environment': 'environment', |
| 251 |
'env-script': 'env_script', |
| 252 |
'err-script': 'err_script', |
| 253 |
'execution polling intervals': 'execution_polling_intervals', |
| 254 |
'execution retry delays': 'execution_retry_delays', |
| 255 |
'execution time limit': 'execution_time_limit', |
| 256 |
'exit-script': 'exit_script', |
| 257 |
'init-script': 'init_script', |
| 258 |
'outputs': 'outputs', |
| 259 |
'post-script': 'post_script', |
| 260 |
'platform': 'platform', |
| 261 |
'pre-script': 'pre_script', |
| 262 |
'run mode': 'run_mode', |
| 263 |
'script': 'script', |
| 264 |
'submission polling intervals': 'submission_polling_intervals', |
| 265 |
'submission retry delays': 'submission_retry_delays', |
| 266 |
'work sub-directory': 'work_sub_dir', |
| 267 |
} |
| 268 |
RUNTIME_LIST_JOINS = { |
| 269 |
'execution polling intervals', |
| 270 |
'execution retry delays', |
| 271 |
'submission polling intervals', |
| 272 |
'submission retry delays', |
| 273 |
} |
| 274 |
RUNTIME_JSON_DUMPS = {'directives', 'environment', 'outputs'} |
| 275 |
RUNTIME_STRINGIFYS = {'execution time limit'} |
| 276 |
|
| 277 |
|
| 278 |
def setbuff(obj, key, value): |
| 279 |
"""Set an attribute on a protobuf object. |
| 280 |
|
| 281 |
Although `None` is a valid value for an `optional` field in protobuf e.g: |
| 282 |
|
| 283 |
>>> job = PbJob(job_id=None) |
| 284 |
|
| 285 |
Attempting to set a field to none after initiation results in error: |
| 286 |
|
| 287 |
>>> job.job_id = None |
| 288 |
Traceback (most recent call last): |
| 289 |
TypeError: ... |
| 290 |
|
| 291 |
For safety this method only sets the attribute if the value is not None. |
| 292 |
|
| 293 |
Note: |
| 294 |
If the above doctest fails, then the behaviour of protobuf has changed |
| 295 |
and this wrapper might not be necessary any more. |
| 296 |
|
| 297 |
See: |
| 298 |
https://github.com/cylc/cylc-flow/issues/5388 |
| 299 |
|
| 300 |
Example: |
| 301 |
>>> from types import SimpleNamespace |
| 302 |
>>> obj = SimpleNamespace() |
| 303 |
>>> setbuff(obj, 'a', 1); obj |
| 304 |
namespace(a=1) |
| 305 |
>>> setbuff(obj, 'b', None); obj |
| 306 |
namespace(a=1) |
| 307 |
|
| 308 |
""" |
| 309 |
if value is not None: |
| 310 |
setattr(obj, key, value) |
| 311 |
|
| 312 |
|
| 313 |
def generate_checksum(in_strings): |
| 314 |
"""Generate cross platform & python checksum from strings.""" |
| 315 |
# can't use hash(), it's not the same across 32-64bit or python invocations |
| 316 |
return zlib.adler32(''.join(sorted(in_strings)).encode()) & 0xffffffff |
| 317 |
|
| 318 |
|
| 319 |
def task_mean_elapsed_time(tdef: 'TaskDef') -> float | None: |
| 320 |
"""Calculate task mean elapsed time.""" |
| 321 |
if tdef.elapsed_times: |
| 322 |
return round(sum(tdef.elapsed_times) / len(tdef.elapsed_times)) |
| 323 |
return tdef.rtconfig.get('execution time limit', None) |
| 324 |
|
| 325 |
|
| 326 |
def runtime_from_config(rtconfig): |
| 327 |
"""Populate runtime object from config.""" |
| 328 |
try: |
| 329 |
platform = rtconfig['platform']['name'] |
| 330 |
except (KeyError, TypeError): |
| 331 |
platform = rtconfig['platform'] |
| 332 |
directives = rtconfig['directives'] |
| 333 |
environment = rtconfig['environment'] |
| 334 |
outputs = rtconfig['outputs'] |
| 335 |
return PbRuntime( |
| 336 |
platform=platform, |
| 337 |
script=rtconfig['script'], |
| 338 |
completion=rtconfig['completion'], |
| 339 |
init_script=rtconfig['init-script'], |
| 340 |
env_script=rtconfig['env-script'], |
| 341 |
err_script=rtconfig['err-script'], |
| 342 |
exit_script=rtconfig['exit-script'], |
| 343 |
pre_script=rtconfig['pre-script'], |
| 344 |
post_script=rtconfig['post-script'], |
| 345 |
work_sub_dir=rtconfig['work sub-directory'], |
| 346 |
run_mode=rtconfig['run mode'], |
| 347 |
execution_time_limit=str(rtconfig['execution time limit'] or ''), |
| 348 |
execution_polling_intervals=listjoin( |
| 349 |
rtconfig['execution polling intervals'] |
| 350 |
), |
| 351 |
execution_retry_delays=listjoin( |
| 352 |
rtconfig['execution retry delays'] |
| 353 |
), |
| 354 |
submission_polling_intervals=listjoin( |
| 355 |
rtconfig['submission polling intervals'] |
| 356 |
), |
| 357 |
submission_retry_delays=listjoin( |
| 358 |
rtconfig['submission retry delays'] |
| 359 |
), |
| 360 |
directives=json.dumps( |
| 361 |
[ |
| 362 |
{'key': key, 'value': value} |
| 363 |
for key, value in directives.items() |
| 364 |
] |
| 365 |
), |
| 366 |
environment=json.dumps( |
| 367 |
[ |
| 368 |
{'key': key, 'value': value} |
| 369 |
for key, value in environment.items() |
| 370 |
] |
| 371 |
), |
| 372 |
outputs=json.dumps( |
| 373 |
[ |
| 374 |
{'key': key, 'value': value} |
| 375 |
for key, value in outputs.items() |
| 376 |
] |
| 377 |
) |
| 378 |
) |
| 379 |
|
| 380 |
|
| 381 |
def runtime_from_partial(rtconfig, runtimeold: Optional[PbRuntime] = None): |
| 382 |
"""Populate runtime object from partial/full config. |
| 383 |
|
| 384 |
Potentially slower than the non-partial one, due to tha the setattr calls, |
| 385 |
but does not have expected fields. |
| 386 |
""" |
| 387 |
runtime = PbRuntime() |
| 388 |
if runtimeold is not None: |
| 389 |
runtime.CopyFrom(runtimeold) |
| 390 |
for key, val in rtconfig.items(): |
| 391 |
if val is None or key not in RUNTIME_CFG_MAP_TO_FIELD: |
| 392 |
continue |
| 393 |
elif key in RUNTIME_LIST_JOINS: |
| 394 |
setattr(runtime, RUNTIME_CFG_MAP_TO_FIELD[key], listjoin(val)) |
| 395 |
elif key in RUNTIME_JSON_DUMPS: |
| 396 |
setattr( |
| 397 |
runtime, |
| 398 |
RUNTIME_CFG_MAP_TO_FIELD[key], |
| 399 |
json.dumps( |
| 400 |
[ |
| 401 |
{'key': k, 'value': v} |
| 402 |
for k, v in val.items() |
| 403 |
] |
| 404 |
) |
| 405 |
) |
| 406 |
elif key == 'platform' and isinstance(val, dict): |
| 407 |
with suppress(KeyError, TypeError): |
| 408 |
setattr(runtime, RUNTIME_CFG_MAP_TO_FIELD[key], val['name']) |
| 409 |
elif key in RUNTIME_STRINGIFYS: |
| 410 |
setattr(runtime, RUNTIME_CFG_MAP_TO_FIELD[key], str(val or '')) |
| 411 |
else: |
| 412 |
setattr(runtime, RUNTIME_CFG_MAP_TO_FIELD[key], val) |
| 413 |
return runtime |
| 414 |
|
| 415 |
|
| 416 |
def reset_protobuf_object(msg_class, msg_orig): |
| 417 |
"""Reset upb-protobuf object to clear memory build-up.""" |
| 418 |
# See: https://github.com/protocolbuffers/protobuf/issues/19674 |
| 419 |
# The new message instantiation needs happen on a separate line. |
| 420 |
new_msg = msg_class() |
| 421 |
new_msg.CopyFrom(msg_orig) |
| 422 |
return new_msg |
| 423 |
|
| 424 |
|
| 425 |
def apply_delta(key, delta, data): |
| 426 |
"""Apply delta to specific data-store workflow and type.""" |
| 427 |
# Assimilate new data |
| 428 |
if getattr(delta, 'added', False): |
| 429 |
if key != WORKFLOW: |
| 430 |
data[key].update({e.id: e for e in delta.added}) |
| 431 |
elif delta.added.ListFields(): |
| 432 |
data[key].CopyFrom(delta.added) |
| 433 |
|
| 434 |
# Merge in updated fields |
| 435 |
if getattr(delta, 'updated', False): |
| 436 |
# Flag for clearing memory accumulation. |
| 437 |
reset_protobuf = False |
| 438 |
if key in RESET_PROTOBUF_TYPES: |
| 439 |
reset_protobuf = True |
| 440 |
if key == WORKFLOW: |
| 441 |
# Clear fields that require overwrite with delta |
| 442 |
field_set = {f.name for f, _ in delta.updated.ListFields()} |
| 443 |
for field in CLEAR_FIELD_MAP[key]: |
| 444 |
if field in field_set or delta.updated.states_updated: |
| 445 |
data[key].ClearField(field) |
| 446 |
|
| 447 |
# Apply the updated delta |
| 448 |
data[key].MergeFrom(delta.updated) |
| 449 |
|
| 450 |
# Deque (i.e. length restrict) selected fields |
| 451 |
for field_name, max_len in DEQUE_FIELD_MAP.get(key, {}).items(): |
| 452 |
if field_name in field_set: |
| 453 |
lst = getattr(data[key], field_name) |
| 454 |
while len(lst) > max_len: |
| 455 |
lst.pop(0) |
| 456 |
|
| 457 |
# Reset upb memory allocation post delta merge. |
| 458 |
if reset_protobuf: |
| 459 |
data[key] = reset_protobuf_object(MESSAGE_MAP[key], data[key]) |
| 460 |
else: |
| 461 |
for element in delta.updated: |
| 462 |
try: |
| 463 |
data_element = data[key][element.id] |
| 464 |
# Clear fields that require overwrite with delta |
| 465 |
for field, _ in element.ListFields(): |
| 466 |
if field.name in CLEAR_FIELD_MAP[key]: |
| 467 |
data_element.ClearField(field.name) |
| 468 |
data_element.MergeFrom(element) |
| 469 |
|
| 470 |
# Reset upb memory allocation post delta merge. |
| 471 |
if reset_protobuf: |
| 472 |
data[key][element.id] = reset_protobuf_object( |
| 473 |
MESSAGE_MAP[key], |
| 474 |
data_element |
| 475 |
) |
| 476 |
except KeyError as exc: |
| 477 |
# Ensure data-sync doesn't fail with |
| 478 |
# network issues, sync reconcile/validate will catch. |
| 479 |
LOG.debug( |
| 480 |
'Missing Data-Store element ' |
| 481 |
'on update application: %s' % str(exc) |
| 482 |
) |
| 483 |
continue |
| 484 |
|
| 485 |
# Prune data elements |
| 486 |
if hasattr(delta, 'pruned'): |
| 487 |
# UIS flag to prune workflow, set externally. |
| 488 |
if key == WORKFLOW: |
| 489 |
if delta.HasField('pruned'): |
| 490 |
data[WORKFLOW].pruned = True |
| 491 |
return |
| 492 |
# Prune data elements by id |
| 493 |
for del_id in delta.pruned: |
| 494 |
if del_id not in data[key]: |
| 495 |
continue |
| 496 |
# Remove relationships. |
| 497 |
# The suppression of key/value errors is to avoid |
| 498 |
# elements and their relationships missing on reload. |
| 499 |
if key == TASK_PROXIES: |
| 500 |
# remove relationship from task |
| 501 |
with suppress(KeyError, ValueError): |
| 502 |
data[TASKS][data[key][del_id].task].proxies.remove(del_id) |
| 503 |
# remove relationship from parent/family |
| 504 |
with suppress(KeyError, ValueError): |
| 505 |
data[FAMILY_PROXIES][ |
| 506 |
data[key][del_id].first_parent |
| 507 |
].child_tasks.remove(del_id) |
| 508 |
# remove relationship from workflow |
| 509 |
with suppress(KeyError, ValueError): |
| 510 |
getattr(data[WORKFLOW], key).remove(del_id) |
| 511 |
elif key == FAMILY_PROXIES: |
| 512 |
with suppress(KeyError, ValueError): |
| 513 |
data[FAMILIES][ |
| 514 |
data[key][del_id].family |
| 515 |
].proxies.remove(del_id) |
| 516 |
with suppress(KeyError, ValueError): |
| 517 |
data[FAMILY_PROXIES][ |
| 518 |
data[key][del_id].first_parent |
| 519 |
].child_families.remove(del_id) |
| 520 |
with suppress(KeyError, ValueError): |
| 521 |
getattr(data[WORKFLOW], key).remove(del_id) |
| 522 |
elif key == EDGES: |
| 523 |
edge = data[key][del_id] |
| 524 |
with suppress(KeyError, ValueError): |
| 525 |
data[TASK_PROXIES][edge.source].edges.remove(del_id) |
| 526 |
with suppress(KeyError, ValueError): |
| 527 |
data[TASK_PROXIES][edge.target].edges.remove(del_id) |
| 528 |
with suppress(KeyError, ValueError): |
| 529 |
getattr(data[WORKFLOW], key).edges.remove(del_id) |
| 530 |
elif key == JOBS: |
| 531 |
# Jobs are only removed if their task is, so only need |
| 532 |
# to remove relationship from workflow. |
| 533 |
with suppress(KeyError, ValueError): |
| 534 |
getattr(data[WORKFLOW], key).remove(del_id) |
| 535 |
# remove/prune element from data-store |
| 536 |
del data[key][del_id] |
| 537 |
|
| 538 |
|
| 539 |
def create_delta_store(delta=None, workflow_id=None): |
| 540 |
"""Create a mini data-store out of the all deltas message. |
| 541 |
|
| 542 |
Args: |
| 543 |
delta (cylc.flow.data_messages_pb2.AllDeltas): |
| 544 |
The message of accumulated deltas for publish/push. |
| 545 |
workflow_id (str): |
| 546 |
The workflow ID. |
| 547 |
|
| 548 |
Returns: |
| 549 |
dict |
| 550 |
|
| 551 |
""" |
| 552 |
if not isinstance(delta, AllDeltas): |
| 553 |
delta = AllDeltas() |
| 554 |
delta_store = { |
| 555 |
DELTA_ADDED: deepcopy(DATA_TEMPLATE), |
| 556 |
DELTA_UPDATED: deepcopy(DATA_TEMPLATE), |
| 557 |
DELTA_PRUNED: { |
| 558 |
key: [] |
| 559 |
for key in DATA_TEMPLATE.keys() |
| 560 |
if key is not WORKFLOW |
| 561 |
}, |
| 562 |
} |
| 563 |
if workflow_id is not None: |
| 564 |
delta_store['id'] = workflow_id |
| 565 |
# ListFields returns a list fields that have been set (not all). |
| 566 |
for field, value in delta.ListFields(): |
| 567 |
for sub_field, sub_value in value.ListFields(): |
| 568 |
if sub_field.name in delta_store: |
| 569 |
if ( |
| 570 |
field.name == WORKFLOW |
| 571 |
or sub_field.name == DELTA_PRUNED |
| 572 |
): |
| 573 |
field_data = sub_value |
| 574 |
else: |
| 575 |
field_data = { |
| 576 |
s.id: s |
| 577 |
for s in sub_value |
| 578 |
} |
| 579 |
delta_store[sub_field.name][field.name] = field_data |
| 580 |
return delta_store |
| 581 |
|
| 582 |
|
| 583 |
class DataStoreMgr: |
| 584 |
"""Manage the workflow data store. |
| 585 |
|
| 586 |
Attributes: |
| 587 |
.ancestors (dict): |
| 588 |
Local store of config.get_first_parent_ancestors() |
| 589 |
.data (dict): |
| 590 |
.edges (dict): |
| 591 |
cylc.flow.data_messages_pb2.PbEdge by internal ID. |
| 592 |
.families (dict): |
| 593 |
cylc.flow.data_messages_pb2.PbFamily by name (internal ID). |
| 594 |
.family_proxies (dict): |
| 595 |
cylc.flow.data_messages_pb2.PbFamilyProxy by internal ID. |
| 596 |
.jobs (dict): |
| 597 |
cylc.flow.data_messages_pb2.PbJob by internal ID. |
| 598 |
.tasks (dict): |
| 599 |
cylc.flow.data_messages_pb2.PbTask by name (internal ID). |
| 600 |
.task_proxies (dict): |
| 601 |
cylc.flow.data_messages_pb2.PbTaskProxy by internal ID. |
| 602 |
.workflow (cylc.flow.data_messages_pb2.PbWorkflow) |
| 603 |
Message containing the global information of the workflow. |
| 604 |
.descendants (dict): |
| 605 |
Local store of config.get_first_parent_descendants() |
| 606 |
.n_edge_distance (int): |
| 607 |
Maximum distance of the data-store graph from the active pool. |
| 608 |
.parents (dict): |
| 609 |
Local store of config.get_parent_lists() |
| 610 |
.publish_deltas (list): |
| 611 |
Collection of the latest applied deltas for publishing. |
| 612 |
.schd (cylc.flow.scheduler.Scheduler): |
| 613 |
Workflow scheduler object. |
| 614 |
.workflow_id (str): |
| 615 |
ID of the workflow service containing owner and name. |
| 616 |
|
| 617 |
Arguments: |
| 618 |
schd (cylc.flow.scheduler.Scheduler): |
| 619 |
Workflow scheduler instance. |
| 620 |
""" |
| 621 |
|
| 622 |
ERR_PREFIX_JOBID_MATCH = 'No matching jobs found: ' |
| 623 |
ERR_PREFIX_JOB_NOT_ON_SEQUENCE = 'Invalid cycle point for job: ' |
| 624 |
|
| 625 |
def __init__(self, schd, n_edge_distance=1): |
| 626 |
self.schd: Scheduler = schd |
| 627 |
self.id_ = Tokens( |
| 628 |
user=self.schd.owner, |
| 629 |
workflow=self.schd.workflow, |
| 630 |
) # TODO: rename and move to scheduler |
| 631 |
self.workflow_id = self.id_.workflow_id |
| 632 |
self.ancestors = {} |
| 633 |
self.descendants = {} |
| 634 |
self.parents = {} |
| 635 |
self.state_update_families = set() |
| 636 |
self.updated_state_families = set() |
| 637 |
# Update workflow state totals once more post delta application. |
| 638 |
self.state_update_follow_on = False |
| 639 |
self.n_edge_distance = n_edge_distance |
| 640 |
self.next_n_edge_distance = None |
| 641 |
self.latest_state_tasks = { |
| 642 |
state: deque(maxlen=LATEST_STATE_TASKS_QUEUE_SIZE) |
| 643 |
for state in TASK_STATUSES_ORDERED |
| 644 |
} |
| 645 |
self.xtrigger_tasks: Dict[str, Set[Tuple[str, str]]] = {} |
| 646 |
# Managed data types |
| 647 |
self.data = { |
| 648 |
self.workflow_id: deepcopy(DATA_TEMPLATE) |
| 649 |
} |
| 650 |
self.added = deepcopy(DATA_TEMPLATE) |
| 651 |
self.updated = deepcopy(DATA_TEMPLATE) |
| 652 |
self.deltas = { |
| 653 |
EDGES: EDeltas(), |
| 654 |
FAMILIES: FDeltas(), |
| 655 |
FAMILY_PROXIES: FPDeltas(), |
| 656 |
JOBS: JDeltas(), |
| 657 |
TASKS: TDeltas(), |
| 658 |
TASK_PROXIES: TPDeltas(), |
| 659 |
WORKFLOW: WDeltas(), |
| 660 |
} |
| 661 |
# internal delta |
| 662 |
self.delta_queues = {self.workflow_id: {}} |
| 663 |
self.publish_deltas = [] |
| 664 |
|
| 665 |
# internal n-window |
| 666 |
self.all_task_pool = set() |
| 667 |
self.all_n_window_nodes = set() |
| 668 |
self.n_window_nodes = {} |
| 669 |
self.n_window_edges = set() |
| 670 |
# The walk information for window nodes, which is used for |
| 671 |
# pre-populating new walks (if possible) and node depth calculations. |
| 672 |
self.n_window_node_walks = {} |
| 673 |
self.n_window_completed_walks = set() |
| 674 |
self.n_window_depths = {} |
| 675 |
self.update_window_depths = False |
| 676 |
self.db_load_task_proxies: Dict[str, Tuple[TaskProxy, bool]] = {} |
| 677 |
# Family node IDs that have been pruned. Sent with deltas and used for |
| 678 |
# exclusion from state total and other calculations. |
| 679 |
self.family_pruned_ids = set() |
| 680 |
# Boundary nodes are those nodes at the boundary of the window, and |
| 681 |
# these are used to trigger pruning for associated nodes. |
| 682 |
# self.prune_trigger_nodes collects walk node IDs associated with a |
| 683 |
# boundary node so that nodes of isolates, adjacent paths, and it's |
| 684 |
# own path can be flagged for pruning. |
| 685 |
self.prune_trigger_nodes = {} |
| 686 |
# Node ids flagged for pruning. |
| 687 |
# Those not in active paths (the walk paths of active tasks) will be |
| 688 |
# pruned. |
| 689 |
self.prune_flagged_nodes = set() |
| 690 |
# Set of removed task proxies to avoid applying/sending new deltas. |
| 691 |
self.pruned_task_proxies = set() |
| 692 |
|
| 693 |
self.updates_pending = False |
| 694 |
self.updates_pending_follow_on = False |
| 695 |
self.publish_pending = False |
| 696 |
|
| 697 |
def initiate_data_model(self, reloaded=False): |
| 698 |
"""Initiate or Update data model on start/restart/reload. |
| 699 |
|
| 700 |
Args: |
| 701 |
reloaded (bool, optional): |
| 702 |
Reset data-store before regenerating. |
| 703 |
|
| 704 |
""" |
| 705 |
# Reset attributes/data-store on reload: |
| 706 |
if reloaded: |
| 707 |
self.__init__(self.schd, self.n_edge_distance) |
| 708 |
|
| 709 |
# Static elements |
| 710 |
self.generate_definition_elements() |
| 711 |
|
| 712 |
# Update workflow statuses and totals (assume needed) |
| 713 |
self.update_workflow(True) |
| 714 |
|
| 715 |
# Apply current deltas |
| 716 |
self.batch_deltas() |
| 717 |
self.apply_delta_batch() |
| 718 |
# Clear deltas after application |
| 719 |
self.clear_delta_store() |
| 720 |
self.clear_delta_batch() |
| 721 |
|
| 722 |
# Gather the store as batch of deltas for publishing |
| 723 |
self.batch_deltas(True) |
| 724 |
self.apply_delta_checksum() |
| 725 |
self.publish_deltas = self.get_publish_deltas() |
| 726 |
|
| 727 |
self.updates_pending = False |
| 728 |
|
| 729 |
# Clear second batch after publishing |
| 730 |
self.clear_delta_batch() |
| 731 |
|
| 732 |
def generate_definition_elements(self): |
| 733 |
"""Generate static definition data elements. |
| 734 |
|
| 735 |
Populates the tasks, families, and workflow elements |
| 736 |
with data from and/or derived from the workflow definition. |
| 737 |
|
| 738 |
""" |
| 739 |
config = self.schd.config |
| 740 |
update_time = time() |
| 741 |
tasks = self.added[TASKS] |
| 742 |
families = self.added[FAMILIES] |
| 743 |
workflow = self.added[WORKFLOW] |
| 744 |
workflow.id = self.workflow_id |
| 745 |
workflow.n_edge_distance = self.n_edge_distance |
| 746 |
workflow.last_updated = update_time |
| 747 |
workflow.stamp = f'{workflow.id}@{workflow.last_updated}' |
| 748 |
# Treat play/restart as hard reload of definition. |
| 749 |
workflow.reloaded = True |
| 750 |
|
| 751 |
graph = workflow.edges |
| 752 |
graph.leaves[:] = config.leaves |
| 753 |
graph.feet[:] = config.feet |
| 754 |
for key, info in config.workflow_polling_tasks.items(): |
| 755 |
graph.workflow_polling_tasks.add( |
| 756 |
local_proxy=key, |
| 757 |
workflow=info[0], |
| 758 |
remote_proxy=info[1], |
| 759 |
req_state=info[2], |
| 760 |
graph_string=info[3], |
| 761 |
) |
| 762 |
|
| 763 |
ancestors = config.get_first_parent_ancestors() |
| 764 |
descendants = config.get_first_parent_descendants() |
| 765 |
parents = config.get_parent_lists() |
| 766 |
|
| 767 |
# Create definition elements for graphed tasks. |
| 768 |
for name, tdef in config.taskdefs.items(): |
| 769 |
t_id = self.definition_id(name) |
| 770 |
t_stamp = f'{t_id}@{update_time}' |
| 771 |
task = PbTask( |
| 772 |
stamp=t_stamp, |
| 773 |
id=t_id, |
| 774 |
name=name, |
| 775 |
depth=len(ancestors[name]) - 1, |
| 776 |
) |
| 777 |
task.namespace[:] = tdef.namespace_hierarchy |
| 778 |
task.first_parent = self.definition_id(ancestors[name][1]) |
| 779 |
user_defined_meta = {} |
| 780 |
for key, val in dict(tdef.describe()).items(): |
| 781 |
if key in ['title', 'description', 'URL']: |
| 782 |
setbuff(task.meta, key, val) |
| 783 |
else: |
| 784 |
user_defined_meta[key] = val |
| 785 |
task.meta.user_defined = json.dumps(user_defined_meta) |
| 786 |
elapsed_time = task_mean_elapsed_time(tdef) |
| 787 |
if elapsed_time: |
| 788 |
task.mean_elapsed_time = elapsed_time |
| 789 |
task.parents.extend([ |
| 790 |
self.definition_id(p_name) |
| 791 |
for p_name in parents[name] |
| 792 |
]) |
| 793 |
task.runtime.CopyFrom(runtime_from_config(tdef.rtconfig)) |
| 794 |
tasks[t_id] = task |
| 795 |
|
| 796 |
# Created family definition elements for first parent |
| 797 |
# ancestors of graphed tasks. |
| 798 |
for key, names in ancestors.items(): |
| 799 |
for name in names: |
| 800 |
if ( |
| 801 |
key == name or |
| 802 |
name in families |
| 803 |
): |
| 804 |
continue |
| 805 |
f_id = self.definition_id(name) |
| 806 |
f_stamp = f'{f_id}@{update_time}' |
| 807 |
family = PbFamily( |
| 808 |
stamp=f_stamp, |
| 809 |
id=f_id, |
| 810 |
name=name, |
| 811 |
depth=len(ancestors[name]) - 1, |
| 812 |
) |
| 813 |
famcfg = config.cfg['runtime'][name] |
| 814 |
user_defined_meta = {} |
| 815 |
for key, val in famcfg.get('meta', {}).items(): |
| 816 |
if key in ['title', 'description', 'URL']: |
| 817 |
setbuff(family.meta, key, val) |
| 818 |
else: |
| 819 |
user_defined_meta[key] = val |
| 820 |
family.meta.user_defined = json.dumps(user_defined_meta) |
| 821 |
family.parents.extend( |
| 822 |
self.definition_id(p_name) |
| 823 |
for p_name in parents[name] |
| 824 |
) |
| 825 |
with suppress(IndexError): |
| 826 |
family.first_parent = ( |
| 827 |
self.definition_id(ancestors[name][1]) |
| 828 |
) |
| 829 |
family.runtime.CopyFrom(runtime_from_config(famcfg)) |
| 830 |
families[f_id] = family |
| 831 |
|
| 832 |
for name, parent_list in parents.items(): |
| 833 |
if not parent_list: |
| 834 |
continue |
| 835 |
fam = parent_list[0] |
| 836 |
f_id = self.definition_id(fam) |
| 837 |
if f_id in families: |
| 838 |
ch_id = self.definition_id(name) |
| 839 |
if name in config.taskdefs: |
| 840 |
families[f_id].child_tasks.append(ch_id) |
| 841 |
else: |
| 842 |
families[f_id].child_families.append(ch_id) |
| 843 |
|
| 844 |
# Populate static fields of workflow |
| 845 |
workflow.api_version = API |
| 846 |
workflow.cylc_version = CYLC_VERSION |
| 847 |
workflow.name = self.schd.workflow |
| 848 |
workflow.owner = self.schd.owner |
| 849 |
workflow.host = self.schd.host |
| 850 |
workflow.port = self.schd.server.port or -1 |
| 851 |
workflow.pub_port = self.schd.server.pub_port or -1 |
| 852 |
user_defined_meta = {} |
| 853 |
for key, val in config.cfg['meta'].items(): |
| 854 |
if key in ['title', 'description', 'URL']: |
| 855 |
setbuff(workflow.meta, key, val) |
| 856 |
else: |
| 857 |
user_defined_meta[key] = val |
| 858 |
workflow.meta.user_defined = json.dumps(user_defined_meta) |
| 859 |
workflow.tree_depth = max([ |
| 860 |
len(val) |
| 861 |
for val in config.get_first_parent_ancestors(pruned=True).values() |
| 862 |
]) - 1 |
| 863 |
|
| 864 |
if get_utc_mode(): |
| 865 |
time_zone_info = TIME_ZONE_UTC_INFO |
| 866 |
else: |
| 867 |
time_zone_info = TIME_ZONE_LOCAL_INFO |
| 868 |
for key, val in time_zone_info.items(): |
| 869 |
setbuff(workflow.time_zone_info, key, val) |
| 870 |
workflow.run_mode = RunMode.get(config.options).value |
| 871 |
workflow.cycling_mode = config.cfg['scheduling']['cycling mode'] |
| 872 |
workflow.workflow_log_dir = self.schd.workflow_log_dir |
| 873 |
workflow.job_log_names.extend(list(JOB_LOG_OPTS.values())) |
| 874 |
workflow.ns_def_order.extend(config.ns_defn_order) |
| 875 |
|
| 876 |
workflow.broadcasts = json.dumps(self.schd.broadcast_mgr.broadcasts) |
| 877 |
|
| 878 |
workflow.tasks.extend(list(tasks)) |
| 879 |
workflow.families.extend(list(families)) |
| 880 |
|
| 881 |
self.ancestors = ancestors |
| 882 |
self.descendants = descendants |
| 883 |
self.parents = parents |
| 884 |
|
| 885 |
def increment_graph_window( |
| 886 |
self, |
| 887 |
source_tokens: Tokens, |
| 888 |
point: 'PointBase', |
| 889 |
is_manual_submit: bool = False, |
| 890 |
itask: Optional['TaskProxy'] = None |
| 891 |
) -> None: |
| 892 |
"""Generate graph window about active task proxy to n-edge-distance. |
| 893 |
|
| 894 |
Fills in graph walk from existing walks if possible, otherwise expands |
| 895 |
the graph front from whereever hasn't been walked. |
| 896 |
Walk nodes are grouped into locations which are tag according to |
| 897 |
parent child path, i.e. 'cpc' would be children-parents-children away |
| 898 |
from active/start task. Which not only provide a way to cheaply rewalk, |
| 899 |
but also the edge distance from origin. |
| 900 |
The futherest child boundary nodes are registered as prune triggers for |
| 901 |
the origin's parents, so when they become active the parents are |
| 902 |
assessed for pruning eligibility. |
| 903 |
|
| 904 |
Args: |
| 905 |
source_tokens |
| 906 |
point |
| 907 |
is_manual_submit |
| 908 |
itask: |
| 909 |
Active/Other task proxy, passed in with pool invocation. |
| 910 |
""" |
| 911 |
|
| 912 |
# common refrences |
| 913 |
active_id = source_tokens.id |
| 914 |
all_walks = self.n_window_node_walks |
| 915 |
taskdefs = self.schd.config.taskdefs |
| 916 |
final_point = self.schd.config.final_point |
| 917 |
|
| 918 |
# walk keys/tags |
| 919 |
# Children location tag |
| 920 |
c_tag = 'c' |
| 921 |
# Parents location tag |
| 922 |
p_tag = 'p' |
| 923 |
|
| 924 |
# Setup walk fields: |
| 925 |
# - locations (locs): i.e. 'cpc' children-parents-children from origin, |
| 926 |
# with their respective node ids. |
| 927 |
# - orphans: task no longer exists in workflow. |
| 928 |
# - done_locs: set of locactions that have been walked over. |
| 929 |
# - done_ids: set of node ids that have been walked (from initial |
| 930 |
# walk filling, that may not have been the entire walk). |
| 931 |
# If walk already completed, must have gone from non-active to active |
| 932 |
# again.. So redo walk (as walk nodes may be pruned). |
| 933 |
if ( |
| 934 |
active_id not in all_walks |
| 935 |
or active_id in self.n_window_completed_walks |
| 936 |
): |
| 937 |
all_walks[active_id] = { |
| 938 |
'locations': {}, |
| 939 |
'orphans': set(), |
| 940 |
'done_locs': set(), |
| 941 |
'done_ids': set(), |
| 942 |
'walk_ids': {active_id}, |
| 943 |
'depths': { |
| 944 |
depth: set() |
| 945 |
for depth in range(1, self.n_edge_distance + 1) |
| 946 |
} |
| 947 |
} |
| 948 |
if active_id in self.n_window_completed_walks: |
| 949 |
self.n_window_completed_walks.remove(active_id) |
| 950 |
active_walk = all_walks[active_id] |
| 951 |
active_locs = active_walk['locations'] |
| 952 |
if source_tokens['task'] not in taskdefs: |
| 953 |
active_walk['orphans'].add(active_id) |
| 954 |
|
| 955 |
# Generate task proxy node |
| 956 |
self.n_window_nodes[active_id] = set() |
| 957 |
|
| 958 |
self.generate_ghost_task( |
| 959 |
source_tokens, |
| 960 |
point, |
| 961 |
is_parent=False, |
| 962 |
itask=itask, |
| 963 |
replace_existing=True, |
| 964 |
) |
| 965 |
|
| 966 |
# Pre-populate from previous walks |
| 967 |
# Will check all location permutations. |
| 968 |
# There may be short cuts for parent locs, however children will more |
| 969 |
# likely be incomplete walks with no 'done_locs' and using parent's |
| 970 |
# children will required sifting out cousin branches. |
| 971 |
working_locs: List[str] = [] |
| 972 |
if self.n_edge_distance > 1: |
| 973 |
if c_tag in active_locs: |
| 974 |
working_locs.extend(('cc', 'cp')) |
| 975 |
if p_tag in active_locs: |
| 976 |
working_locs.extend(('pp', 'pc')) |
| 977 |
n_depth = 2 |
| 978 |
while working_locs: |
| 979 |
for w_loc in working_locs: |
| 980 |
loc_done = True |
| 981 |
# Most will be incomplete walks, however, we can check. |
| 982 |
# i.e. parents of children may all exist. |
| 983 |
if w_loc[:-1] in active_locs: |
| 984 |
for loc_id in active_locs[w_loc[:-1]]: |
| 985 |
if loc_id not in all_walks: |
| 986 |
loc_done = False |
| 987 |
break |
| 988 |
else: |
| 989 |
continue |
| 990 |
# find child nodes of parent location, |
| 991 |
# i.e. 'cpcc' = 'cpc' + 'c' |
| 992 |
w_set = set().union(*( |
| 993 |
all_walks[loc_id]['locations'][w_loc[-1]] |
| 994 |
for loc_id in active_locs[w_loc[:-1]] |
| 995 |
if ( |
| 996 |
loc_id in all_walks |
| 997 |
and w_loc[-1] in all_walks[loc_id]['locations'] |
| 998 |
) |
| 999 |
)) |
| 1000 |
w_set.difference_update(active_walk['walk_ids']) |
| 1001 |
if w_set: |
| 1002 |
active_locs[w_loc] = w_set |
| 1003 |
active_walk['walk_ids'].update(w_set) |
| 1004 |
active_walk['depths'][n_depth].update(w_set) |
| 1005 |
# If child/parent nodes have been pruned we will need |
| 1006 |
# to regenerate them. |
| 1007 |
if ( |
| 1008 |
loc_done |
| 1009 |
and not w_set.difference(self.all_n_window_nodes) |
| 1010 |
): |
| 1011 |
active_walk['done_locs'].add(w_loc[:-1]) |
| 1012 |
active_walk['done_ids'].update( |
| 1013 |
active_locs[w_loc[:-1]] |
| 1014 |
) |
| 1015 |
working_locs = [ |
| 1016 |
new_loc |
| 1017 |
for loc in working_locs |
| 1018 |
if loc in active_locs and len(loc) < self.n_edge_distance |
| 1019 |
for new_loc in (loc + c_tag, loc + p_tag) |
| 1020 |
] |
| 1021 |
n_depth += 1 |
| 1022 |
|
| 1023 |
# Graph walk |
| 1024 |
node_tokens: Tokens |
| 1025 |
child_tokens: Tokens |
| 1026 |
parent_tokens: Tokens |
| 1027 |
walk_incomplete = True |
| 1028 |
while walk_incomplete: |
| 1029 |
walk_incomplete = False |
| 1030 |
# Only walk locations not fully explored |
| 1031 |
locations = [ |
| 1032 |
loc |
| 1033 |
for loc in active_locs |
| 1034 |
if ( |
| 1035 |
|
| 1036 |
len(loc) < self.n_edge_distance |
| 1037 |
and loc not in active_walk['done_locs'] |
| 1038 |
) |
| 1039 |
] |
| 1040 |
# Origin/Active usually first or isolate nodes |
| 1041 |
if ( |
| 1042 |
not active_walk['done_ids'] |
| 1043 |
and not locations |
| 1044 |
and active_id not in active_walk['orphans'] |
| 1045 |
and self.n_edge_distance != 0 |
| 1046 |
): |
| 1047 |
locations = [''] |
| 1048 |
# Explore/walk locations |
| 1049 |
for location in locations: |
| 1050 |
if not location: |
| 1051 |
loc_nodes = {active_id} |
| 1052 |
else: |
| 1053 |
loc_nodes = active_locs[location] |
| 1054 |
active_walk['done_locs'].add(location) |
| 1055 |
c_loc = location + c_tag |
| 1056 |
p_loc = location + p_tag |
| 1057 |
c_ids = set() |
| 1058 |
p_ids = set() |
| 1059 |
n_depth = len(location) + 1 |
| 1060 |
# Exclude walked nodes at this location. |
| 1061 |
# This also helps avoid walking in a circle. |
| 1062 |
for node_id in loc_nodes.difference(active_walk['done_ids']): |
| 1063 |
active_walk['done_ids'].add(node_id) |
| 1064 |
node_tokens = Tokens(node_id) |
| 1065 |
# Don't expand window about orphan task. |
| 1066 |
try: |
| 1067 |
tdef = taskdefs[node_tokens['task']] |
| 1068 |
except KeyError: |
| 1069 |
active_walk['orphans'].add(node_id) |
| 1070 |
continue |
| 1071 |
# Use existing children/parents from other walks. |
| 1072 |
# (note: nodes/edges should already be generated) |
| 1073 |
c_done = False |
| 1074 |
p_done = False |
| 1075 |
if node_id in all_walks and node_id is not active_id: |
| 1076 |
with suppress(KeyError): |
| 1077 |
# If children have been pruned, don't skip, |
| 1078 |
# re-generate them (uncommon or impossible?). |
| 1079 |
if not all_walks[node_id]['locations'][ |
| 1080 |
c_tag |
| 1081 |
].difference(self.all_n_window_nodes): |
| 1082 |
c_ids.update( |
| 1083 |
all_walks[node_id]['locations'][c_tag] |
| 1084 |
) |
| 1085 |
c_done = True |
| 1086 |
with suppress(KeyError): |
| 1087 |
# If parent have been pruned, don't skip, |
| 1088 |
# re-generate them (more common case). |
| 1089 |
if not all_walks[node_id]['locations'][ |
| 1090 |
p_tag |
| 1091 |
].difference(self.all_n_window_nodes): |
| 1092 |
p_ids.update( |
| 1093 |
all_walks[node_id]['locations'][p_tag] |
| 1094 |
) |
| 1095 |
p_done = True |
| 1096 |
if p_done and c_done: |
| 1097 |
continue |
| 1098 |
|
| 1099 |
# Children/downstream nodes |
| 1100 |
# TODO: xtrigger is workflow_state edges too |
| 1101 |
# see: https://github.com/cylc/cylc-flow/issues/4582 |
| 1102 |
# Reference set for workflow relations |
| 1103 |
nc_ids = set() |
| 1104 |
if not c_done: |
| 1105 |
if itask is not None and n_depth == 1: |
| 1106 |
graph_children = itask.graph_children |
| 1107 |
else: |
| 1108 |
graph_children = generate_graph_children( |
| 1109 |
tdef, |
| 1110 |
get_point(node_tokens['cycle']) |
| 1111 |
) |
| 1112 |
for items in graph_children.values(): |
| 1113 |
for child_name, child_point, _ in items: |
| 1114 |
if final_point and child_point > final_point: |
| 1115 |
continue |
| 1116 |
child_tokens = self.id_.duplicate( |
| 1117 |
cycle=str(child_point), |
| 1118 |
task=child_name, |
| 1119 |
) |
| 1120 |
self.generate_ghost_task( |
| 1121 |
child_tokens, |
| 1122 |
child_point, |
| 1123 |
False, |
| 1124 |
None, |
| 1125 |
n_depth |
| 1126 |
) |
| 1127 |
self.generate_edge(node_tokens, child_tokens) |
| 1128 |
nc_ids.add(child_tokens.id) |
| 1129 |
|
| 1130 |
# Parents/upstream nodes |
| 1131 |
np_ids = set() |
| 1132 |
if not p_done: |
| 1133 |
for ( |
| 1134 |
parent_name, |
| 1135 |
parent_point, |
| 1136 |
_, |
| 1137 |
) in generate_graph_parents( |
| 1138 |
tdef, get_point(node_tokens['cycle']), taskdefs |
| 1139 |
): |
| 1140 |
if final_point and parent_point > final_point: |
| 1141 |
continue |
| 1142 |
parent_tokens = self.id_.duplicate( |
| 1143 |
cycle=str(parent_point), |
| 1144 |
task=parent_name, |
| 1145 |
) |
| 1146 |
self.generate_ghost_task( |
| 1147 |
parent_tokens, |
| 1148 |
parent_point, |
| 1149 |
True, |
| 1150 |
None, |
| 1151 |
n_depth |
| 1152 |
) |
| 1153 |
# reverse for parent |
| 1154 |
self.generate_edge(parent_tokens, node_tokens) |
| 1155 |
np_ids.add(parent_tokens.id) |
| 1156 |
|
| 1157 |
# Register new walk |
| 1158 |
if node_id not in all_walks: |
| 1159 |
all_walks[node_id] = { |
| 1160 |
'locations': {}, |
| 1161 |
'done_ids': set(), |
| 1162 |
'done_locs': set(), |
| 1163 |
'orphans': set(), |
| 1164 |
'walk_ids': {node_id} | nc_ids | np_ids, |
| 1165 |
'depths': { |
| 1166 |
depth: set() |
| 1167 |
for depth in range(1, self.n_edge_distance + 1) |
| 1168 |
} |
| 1169 |
} |
| 1170 |
if nc_ids: |
| 1171 |
all_walks[node_id]['locations'][c_tag] = nc_ids |
| 1172 |
all_walks[node_id]['depths'][1].update(nc_ids) |
| 1173 |
c_ids.update(nc_ids) |
| 1174 |
if np_ids: |
| 1175 |
all_walks[node_id]['locations'][p_tag] = np_ids |
| 1176 |
all_walks[node_id]['depths'][1].update(np_ids) |
| 1177 |
p_ids.update(np_ids) |
| 1178 |
|
| 1179 |
# Create location association |
| 1180 |
c_ids.difference_update(active_walk['walk_ids']) |
| 1181 |
if c_ids: |
| 1182 |
active_locs.setdefault(c_loc, set()).update(c_ids) |
| 1183 |
p_ids.difference_update(active_walk['walk_ids']) |
| 1184 |
if p_ids: |
| 1185 |
active_locs.setdefault(p_loc, set()).update(p_ids) |
| 1186 |
if p_ids or c_ids: |
| 1187 |
walk_incomplete = True |
| 1188 |
active_walk['walk_ids'].update(c_ids, p_ids) |
| 1189 |
active_walk['depths'][n_depth].update(c_ids, p_ids) |
| 1190 |
|
| 1191 |
self.n_window_completed_walks.add(active_id) |
| 1192 |
self.n_window_nodes[active_id].update(active_walk['walk_ids']) |
| 1193 |
|
| 1194 |
# Generate internal edges > self.n_edge_distance |
| 1195 |
# Only nodes at max allowable depth may have missing edges going to |
| 1196 |
# other nodes within the window, and these other window nodes will also |
| 1197 |
# be on the boundary (otherwise they would've been in a walk). |
| 1198 |
outer_nodes = active_walk['depths'].get(self.n_edge_distance, set()) |
| 1199 |
for outer_id in outer_nodes: |
| 1200 |
outer_tokens = Tokens(outer_id) |
| 1201 |
tdef = taskdefs[outer_tokens['task']] |
| 1202 |
graph_children = generate_graph_children( |
| 1203 |
tdef, |
| 1204 |
get_point(outer_tokens['cycle']) |
| 1205 |
) |
| 1206 |
for items in graph_children.values(): |
| 1207 |
for child_name, child_point, _ in items: |
| 1208 |
child_tokens = self.id_.duplicate( |
| 1209 |
cycle=str(child_point), |
| 1210 |
task=child_name, |
| 1211 |
) |
| 1212 |
if child_tokens.id in outer_nodes: |
| 1213 |
self.generate_edge(outer_tokens, child_tokens) |
| 1214 |
|
| 1215 |
# This part is vital to constructing a set of boundary nodes |
| 1216 |
# associated with the n=0 window of current active node. |
| 1217 |
# Only trigger pruning for furthest set of boundary nodes |
| 1218 |
boundary_nodes: Set[str] = set() |
| 1219 |
max_level: int = 0 |
| 1220 |
with suppress(ValueError): |
| 1221 |
max_level = max( |
| 1222 |
len(loc) |
| 1223 |
for loc in active_locs |
| 1224 |
if p_tag not in loc |
| 1225 |
) |
| 1226 |
# add the most distant child as a trigger to prune it. |
| 1227 |
boundary_nodes.update(*( |
| 1228 |
active_locs[loc] |
| 1229 |
for loc in active_locs |
| 1230 |
if p_tag not in loc and len(loc) >= max_level |
| 1231 |
)) |
| 1232 |
if not boundary_nodes and not max_level: |
| 1233 |
# Could be self-reference node foo:failed => foo |
| 1234 |
boundary_nodes = {active_id} |
| 1235 |
# associate |
| 1236 |
for tp_id in boundary_nodes: |
| 1237 |
self.prune_trigger_nodes.setdefault(tp_id, set()).update( |
| 1238 |
active_walk['walk_ids'] |
| 1239 |
) |
| 1240 |
self.prune_trigger_nodes[tp_id].discard(tp_id) |
| 1241 |
# flag manual triggers for pruning on deletion. |
| 1242 |
if is_manual_submit: |
| 1243 |
self.prune_trigger_nodes.setdefault(active_id, set()).add( |
| 1244 |
active_id |
| 1245 |
) |
| 1246 |
if active_walk['orphans']: |
| 1247 |
self.prune_trigger_nodes.setdefault(active_id, set()).union( |
| 1248 |
active_walk['orphans'] |
| 1249 |
) |
| 1250 |
# Check if active node is another's boundary node |
| 1251 |
# to flag its paths for pruning. |
| 1252 |
if active_id in self.prune_trigger_nodes: |
| 1253 |
self.prune_flagged_nodes.update( |
| 1254 |
self.prune_trigger_nodes[active_id]) |
| 1255 |
del self.prune_trigger_nodes[active_id] |
| 1256 |
|
| 1257 |
def generate_edge( |
| 1258 |
self, |
| 1259 |
parent_tokens: Tokens, |
| 1260 |
child_tokens: Tokens, |
| 1261 |
) -> None: |
| 1262 |
"""Construct edge of child and parent task proxy node.""" |
| 1263 |
# Initiate edge element. |
| 1264 |
e_id = self.edge_id(parent_tokens, child_tokens) |
| 1265 |
if e_id in self.n_window_edges: |
| 1266 |
return |
| 1267 |
if ( |
| 1268 |
e_id not in self.data[self.workflow_id][EDGES] |
| 1269 |
and e_id not in self.added[EDGES] |
| 1270 |
): |
| 1271 |
self.added[EDGES][e_id] = PbEdge( |
| 1272 |
id=e_id, |
| 1273 |
source=parent_tokens.id, |
| 1274 |
target=child_tokens.id |
| 1275 |
) |
| 1276 |
# Add edge id to node field for resolver reference |
| 1277 |
self.updated[TASK_PROXIES].setdefault( |
| 1278 |
child_tokens.id, |
| 1279 |
PbTaskProxy(id=child_tokens.id)).edges.append(e_id) |
| 1280 |
self.updated[TASK_PROXIES].setdefault( |
| 1281 |
parent_tokens.id, |
| 1282 |
PbTaskProxy(id=parent_tokens.id)).edges.append(e_id) |
| 1283 |
getattr(self.updated[WORKFLOW], EDGES).edges.append(e_id) |
| 1284 |
self.n_window_edges.add(e_id) |
| 1285 |
|
| 1286 |
def remove_pool_node(self, name, point): |
| 1287 |
"""Remove ID reference and flag isolate node/branch for pruning.""" |
| 1288 |
tp_id = self.id_.duplicate( |
| 1289 |
cycle=str(point), |
| 1290 |
task=name, |
| 1291 |
).id |
| 1292 |
if tp_id in self.all_task_pool: |
| 1293 |
self.all_task_pool.remove(tp_id) |
| 1294 |
self.updates_pending = True |
| 1295 |
# flagged isolates/end-of-branch nodes for pruning on removal |
| 1296 |
if ( |
| 1297 |
tp_id in self.prune_trigger_nodes and |
| 1298 |
tp_id in self.prune_trigger_nodes[tp_id] |
| 1299 |
): |
| 1300 |
self.prune_flagged_nodes.update(self.prune_trigger_nodes[tp_id]) |
| 1301 |
# If, at the time of removal, no desendents are active then only |
| 1302 |
# flag the node not the entire walk. |
| 1303 |
elif ( |
| 1304 |
tp_id in self.n_window_nodes and |
| 1305 |
self.n_window_nodes[tp_id].isdisjoint(self.all_task_pool) |
| 1306 |
): |
| 1307 |
self.prune_flagged_nodes.add(tp_id) |
| 1308 |
elif tp_id in self.n_window_node_walks: |
| 1309 |
self.prune_flagged_nodes.update( |
| 1310 |
self.n_window_node_walks[tp_id]['walk_ids'] |
| 1311 |
) |
| 1312 |
if tp_id in self.prune_trigger_nodes: |
| 1313 |
del self.prune_trigger_nodes[tp_id] |
| 1314 |
self.update_window_depths = True |
| 1315 |
self.updates_pending = True |
| 1316 |
|
| 1317 |
def add_pool_node(self, name, point): |
| 1318 |
"""Add external ID reference for internal task pool node.""" |
| 1319 |
tp_id = self.id_.duplicate( |
| 1320 |
cycle=str(point), |
| 1321 |
task=name, |
| 1322 |
).id |
| 1323 |
self.all_task_pool.add(tp_id) |
| 1324 |
self.update_window_depths = True |
| 1325 |
|
| 1326 |
def generate_ghost_task( |
| 1327 |
self, |
| 1328 |
tokens: Tokens, |
| 1329 |
point: 'PointBase', |
| 1330 |
is_parent: bool = False, |
| 1331 |
itask: Optional['TaskProxy'] = None, |
| 1332 |
n_depth: int = 0, |
| 1333 |
replace_existing: bool = False, |
| 1334 |
) -> None: |
| 1335 |
"""Create task-point element populated with static data. |
| 1336 |
|
| 1337 |
Args: |
| 1338 |
source_tokens |
| 1339 |
point |
| 1340 |
is_parent: Used to determine whether to load DB state. |
| 1341 |
itask: Update task-node from corresponding task proxy object. |
| 1342 |
n_depth: n-window graph edge distance. |
| 1343 |
replace_existing: Replace any existing data for task as it may |
| 1344 |
be out of date (e.g. flow nums). |
| 1345 |
""" |
| 1346 |
tp_id = tokens.id |
| 1347 |
if ( |
| 1348 |
tp_id in self.data[self.workflow_id][TASK_PROXIES] |
| 1349 |
or tp_id in self.added[TASK_PROXIES] |
| 1350 |
): |
| 1351 |
if replace_existing and itask is not None: |
| 1352 |
self.delta_from_task_proxy(itask) |
| 1353 |
return |
| 1354 |
|
| 1355 |
name = tokens['task'] |
| 1356 |
point_string = tokens['cycle'] |
| 1357 |
t_id = self.definition_id(name) |
| 1358 |
|
| 1359 |
if itask is None: |
| 1360 |
itask = self.schd.pool.get_task(point_string, name) or TaskProxy( |
| 1361 |
self.id_, |
| 1362 |
self.schd.config.get_taskdef(name), |
| 1363 |
point, |
| 1364 |
flow_nums=None, |
| 1365 |
submit_num=0, |
| 1366 |
data_mode=True, |
| 1367 |
sequential_xtrigger_labels=( |
| 1368 |
self.schd.xtrigger_mgr.xtriggers.sequential_xtrigger_labels |
| 1369 |
), |
| 1370 |
) |
| 1371 |
|
| 1372 |
is_orphan = False |
| 1373 |
if name not in self.schd.config.taskdefs: |
| 1374 |
is_orphan = True |
| 1375 |
self.generate_orphan_task(itask) |
| 1376 |
|
| 1377 |
# Most of the time the definition node will be in the store. |
| 1378 |
try: |
| 1379 |
task_def = self.data[self.workflow_id][TASKS][t_id] |
| 1380 |
except KeyError: |
| 1381 |
try: |
| 1382 |
task_def = self.added[TASKS][t_id] |
| 1383 |
except KeyError: |
| 1384 |
# Task removed from workflow definition. |
| 1385 |
return |
| 1386 |
|
| 1387 |
update_time = time() |
| 1388 |
tp_stamp = f'{tp_id}@{update_time}' |
| 1389 |
tproxy = PbTaskProxy( |
| 1390 |
stamp=tp_stamp, |
| 1391 |
id=tp_id, |
| 1392 |
task=t_id, |
| 1393 |
cycle_point=point_string, |
| 1394 |
is_held=( |
| 1395 |
(name, point) |
| 1396 |
in self.schd.pool.tasks_to_hold |
| 1397 |
), |
| 1398 |
depth=task_def.depth, |
| 1399 |
graph_depth=n_depth, |
| 1400 |
name=name, |
| 1401 |
# Set default before history DB batch application |
| 1402 |
flow_nums=serialise_set(set()), |
| 1403 |
) |
| 1404 |
self.all_n_window_nodes.add(tp_id) |
| 1405 |
self.n_window_depths.setdefault(n_depth, set()).add(tp_id) |
| 1406 |
|
| 1407 |
tproxy.namespace[:] = task_def.namespace |
| 1408 |
if is_orphan: |
| 1409 |
tproxy.ancestors[:] = [ |
| 1410 |
self.id_.duplicate( |
| 1411 |
cycle=point_string, |
| 1412 |
task='root', |
| 1413 |
).id |
| 1414 |
] |
| 1415 |
else: |
| 1416 |
tproxy.ancestors[:] = [ |
| 1417 |
self.id_.duplicate( |
| 1418 |
cycle=point_string, |
| 1419 |
task=a_name, |
| 1420 |
).id |
| 1421 |
for a_name in self.ancestors[task_def.name] |
| 1422 |
if a_name != task_def.name |
| 1423 |
] |
| 1424 |
tproxy.first_parent = tproxy.ancestors[0] |
| 1425 |
|
| 1426 |
self.added[TASK_PROXIES][tp_id] = tproxy |
| 1427 |
getattr(self.updated[WORKFLOW], TASK_PROXIES).append(tp_id) |
| 1428 |
self.updated[TASKS].setdefault( |
| 1429 |
t_id, |
| 1430 |
PbTask( |
| 1431 |
stamp=f'{t_id}@{update_time}', |
| 1432 |
id=t_id, |
| 1433 |
) |
| 1434 |
).proxies.append(tp_id) |
| 1435 |
self.generate_ghost_family(tproxy.first_parent, child_task=tp_id) |
| 1436 |
self.state_update_families.add(tproxy.first_parent) |
| 1437 |
|
| 1438 |
# Active, but not in the data-store yet (new). |
| 1439 |
if tp_id in self.n_window_nodes: |
| 1440 |
self._process_internal_task_proxy(itask, tproxy) |
| 1441 |
# Has run before, so get history. |
| 1442 |
# Cannot batch as task is active (all jobs retrieved at once). |
| 1443 |
if itask.submit_num > 0: |
| 1444 |
flow_db = self.schd.workflow_db_mgr.pri_dao |
| 1445 |
for row in flow_db.select_jobs_for_datastore( |
| 1446 |
{itask.identity} |
| 1447 |
): |
| 1448 |
self.insert_db_job(1, row) |
| 1449 |
else: |
| 1450 |
# Batch non-active node for load of DB history. |
| 1451 |
self.db_load_task_proxies[itask.identity] = ( |
| 1452 |
itask, |
| 1453 |
is_parent, |
| 1454 |
) |
| 1455 |
|
| 1456 |
self.updates_pending = True |
| 1457 |
|
| 1458 |
return |
| 1459 |
|
| 1460 |
def generate_orphan_task(self, itask): |
| 1461 |
"""Generate orphan task definition.""" |
| 1462 |
update_time = time() |
| 1463 |
tdef = itask.tdef |
| 1464 |
name = tdef.name |
| 1465 |
t_id = self.definition_id(name) |
| 1466 |
t_stamp = f'{t_id}@{update_time}' |
| 1467 |
task = PbTask( |
| 1468 |
stamp=t_stamp, |
| 1469 |
id=t_id, |
| 1470 |
name=name, |
| 1471 |
depth=1, |
| 1472 |
) |
| 1473 |
task.namespace[:] = tdef.namespace_hierarchy |
| 1474 |
task.first_parent = self.definition_id('root') |
| 1475 |
user_defined_meta = {} |
| 1476 |
for key, val in dict(tdef.describe()).items(): |
| 1477 |
if key in ['title', 'description', 'URL']: |
| 1478 |
setbuff(task.meta, key, val) |
| 1479 |
else: |
| 1480 |
user_defined_meta[key] = val |
| 1481 |
task.meta.user_defined = json.dumps(user_defined_meta) |
| 1482 |
elapsed_time = task_mean_elapsed_time(tdef) |
| 1483 |
if elapsed_time: |
| 1484 |
task.mean_elapsed_time = elapsed_time |
| 1485 |
task.parents[:] = [task.first_parent] |
| 1486 |
|
| 1487 |
task.runtime.CopyFrom(runtime_from_config(tdef.rtconfig)) |
| 1488 |
|
| 1489 |
self.added[TASKS][t_id] = task |
| 1490 |
|
| 1491 |
def generate_ghost_family(self, fp_id, child_fam=None, child_task=None): |
| 1492 |
"""Generate the family-point elements from given ID if non-existent. |
| 1493 |
|
| 1494 |
Adds the ID of the child proxy that called for it's creation. Also |
| 1495 |
generates parents recursively to root if they don't exist. |
| 1496 |
|
| 1497 |
Args: |
| 1498 |
fp_id (str): |
| 1499 |
Family proxy ID |
| 1500 |
child_fam (str): |
| 1501 |
Family proxy ID |
| 1502 |
child_task (str): |
| 1503 |
Task proxy ID |
| 1504 |
|
| 1505 |
Returns: |
| 1506 |
|
| 1507 |
None |
| 1508 |
|
| 1509 |
""" |
| 1510 |
|
| 1511 |
update_time = time() |
| 1512 |
families = self.data[self.workflow_id][FAMILIES] |
| 1513 |
if not families: |
| 1514 |
families = self.added[FAMILIES] |
| 1515 |
fp_data = self.data[self.workflow_id][FAMILY_PROXIES] |
| 1516 |
fp_added = self.added[FAMILY_PROXIES] |
| 1517 |
fp_updated = self.updated[FAMILY_PROXIES] |
| 1518 |
if fp_id in fp_data: |
| 1519 |
fp_delta = fp_data[fp_id] |
| 1520 |
fp_parent = fp_updated.setdefault(fp_id, PbFamilyProxy(id=fp_id)) |
| 1521 |
elif fp_id in fp_added: |
| 1522 |
fp_delta = fp_added[fp_id] |
| 1523 |
fp_parent = fp_added.setdefault(fp_id, PbFamilyProxy(id=fp_id)) |
| 1524 |
else: |
| 1525 |
tokens = Tokens(fp_id) |
| 1526 |
point_string = tokens['cycle'] |
| 1527 |
name = tokens['task'] |
| 1528 |
fam = families[self.definition_id(name)] |
| 1529 |
fp_delta = PbFamilyProxy( |
| 1530 |
stamp=f'{fp_id}@{update_time}', |
| 1531 |
id=fp_id, |
| 1532 |
cycle_point=point_string, |
| 1533 |
name=fam.name, |
| 1534 |
family=fam.id, |
| 1535 |
depth=fam.depth, |
| 1536 |
) |
| 1537 |
fp_delta.ancestors[:] = [ |
| 1538 |
self.id_.duplicate( |
| 1539 |
cycle=point_string, |
| 1540 |
task=a_name, |
| 1541 |
).id |
| 1542 |
for a_name in self.ancestors[fam.name] |
| 1543 |
if a_name != fam.name |
| 1544 |
] |
| 1545 |
if fp_delta.ancestors: |
| 1546 |
fp_delta.first_parent = fp_delta.ancestors[0] |
| 1547 |
|
| 1548 |
fp_delta.runtime.CopyFrom( |
| 1549 |
runtime_from_config( |
| 1550 |
self._apply_broadcasts_to_runtime( |
| 1551 |
tokens, |
| 1552 |
self.schd.config.cfg['runtime'][fam.name] |
| 1553 |
) |
| 1554 |
) |
| 1555 |
) |
| 1556 |
|
| 1557 |
self.added[FAMILY_PROXIES][fp_id] = fp_delta |
| 1558 |
fp_parent = fp_delta |
| 1559 |
# Add ref ID to family element |
| 1560 |
f_delta = PbFamily(id=fam.id, stamp=f'{fam.id}@{update_time}') |
| 1561 |
f_delta.proxies.append(fp_id) |
| 1562 |
self.updated[FAMILIES].setdefault( |
| 1563 |
fam.id, PbFamily(id=fam.id)).MergeFrom(f_delta) |
| 1564 |
# Add ref ID to workflow element |
| 1565 |
getattr(self.updated[WORKFLOW], FAMILY_PROXIES).append(fp_id) |
| 1566 |
# Generate this families parent if it not root. |
| 1567 |
if fp_delta.first_parent: |
| 1568 |
self.generate_ghost_family( |
| 1569 |
fp_delta.first_parent, child_fam=fp_id) |
| 1570 |
if child_fam is None: |
| 1571 |
fp_parent.child_tasks.append(child_task) |
| 1572 |
elif child_fam not in fp_parent.child_families: |
| 1573 |
fp_parent.child_families.append(child_fam) |
| 1574 |
|
| 1575 |
def apply_task_proxy_db_history(self): |
| 1576 |
"""Extract and apply DB history on given task proxies.""" |
| 1577 |
if not self.db_load_task_proxies: |
| 1578 |
return |
| 1579 |
|
| 1580 |
flow_db = self.schd.workflow_db_mgr.pri_dao |
| 1581 |
|
| 1582 |
task_ids = set(self.db_load_task_proxies.keys()) |
| 1583 |
# Batch load rows with matching cycle & name column pairs. |
| 1584 |
prereq_ids = set() |
| 1585 |
for ( |
| 1586 |
cycle, name, flow_nums_str, status, submit_num, outputs_str |
| 1587 |
) in flow_db.select_tasks_for_datastore(task_ids): |
| 1588 |
tokens = self.id_.duplicate( |
| 1589 |
cycle=cycle, |
| 1590 |
task=name, |
| 1591 |
) |
| 1592 |
relative_id = tokens.relative_id |
| 1593 |
itask, is_parent = self.db_load_task_proxies[relative_id] |
| 1594 |
itask.submit_num = submit_num |
| 1595 |
flow_nums = deserialise_set(flow_nums_str) |
| 1596 |
# Do not set states and outputs for inactive tasks in flow. |
| 1597 |
if ( |
| 1598 |
itask.flow_nums and |
| 1599 |
flow_nums != itask.flow_nums and |
| 1600 |
not is_parent |
| 1601 |
): |
| 1602 |
itask.state_reset(TASK_STATUS_WAITING, silent=True) |
| 1603 |
continue |
| 1604 |
else: |
| 1605 |
itask.flow_nums = flow_nums |
| 1606 |
itask.state_reset(status, silent=True) |
| 1607 |
if ( |
| 1608 |
outputs_str is not None |
| 1609 |
and itask.state( |
| 1610 |
TASK_STATUS_RUNNING, |
| 1611 |
TASK_STATUS_FAILED, |
| 1612 |
TASK_STATUS_SUCCEEDED |
| 1613 |
) |
| 1614 |
): |
| 1615 |
for message in json.loads(outputs_str): |
| 1616 |
itask.state.outputs.set_message_complete(message) |
| 1617 |
# Gather tasks with flow id. |
| 1618 |
prereq_ids.add(f'{relative_id}/{flow_nums_str}') |
| 1619 |
|
| 1620 |
# Batch load prerequisites of tasks according to flow. |
| 1621 |
prereqs_map: Dict[str, dict] = {} |
| 1622 |
for ( |
| 1623 |
cycle, name, prereq_name, |
| 1624 |
prereq_cycle, prereq_output, satisfied |
| 1625 |
) in flow_db.select_prereqs_for_datastore(prereq_ids): |
| 1626 |
tokens = self.id_.duplicate( |
| 1627 |
cycle=cycle, |
| 1628 |
task=name, |
| 1629 |
) |
| 1630 |
prereqs_map.setdefault(tokens.relative_id, {})[ |
| 1631 |
(prereq_cycle, prereq_name, prereq_output) |
| 1632 |
] = satisfied if satisfied != '0' else False |
| 1633 |
|
| 1634 |
for ikey, prereqs in prereqs_map.items(): |
| 1635 |
itask_prereq: Prerequisite |
| 1636 |
for itask_prereq in ( |
| 1637 |
self.db_load_task_proxies[ikey][0].state.prerequisites |
| 1638 |
): |
| 1639 |
for key in itask_prereq: |
| 1640 |
itask_prereq[key] = prereqs.get(key, False) |
| 1641 |
# (False if prereq is not in the DB: new dependencies |
| 1642 |
# added to an already-spawned task before restart.) |
| 1643 |
|
| 1644 |
# Extract info from itasks to data-store. |
| 1645 |
for itask, _is_parent in self.db_load_task_proxies.values(): |
| 1646 |
self._process_internal_task_proxy( |
| 1647 |
itask, |
| 1648 |
self.added[TASK_PROXIES][self.id_.duplicate(itask.tokens).id] |
| 1649 |
) |
| 1650 |
|
| 1651 |
# Batch load jobs from DB. |
| 1652 |
for row in flow_db.select_jobs_for_datastore(task_ids): |
| 1653 |
self.insert_db_job(1, row) |
| 1654 |
|
| 1655 |
self.db_load_task_proxies.clear() |
| 1656 |
|
| 1657 |
def _process_internal_task_proxy( |
| 1658 |
self, |
| 1659 |
itask: 'TaskProxy', |
| 1660 |
tproxy: PbTaskProxy, |
| 1661 |
): |
| 1662 |
"""Extract information from internal task proxy object.""" |
| 1663 |
|
| 1664 |
update_time = time() |
| 1665 |
|
| 1666 |
tproxy.state = itask.state.status |
| 1667 |
tproxy.flow_nums = serialise_set(itask.flow_nums) |
| 1668 |
|
| 1669 |
prereq_list = [] |
| 1670 |
for prereq in itask.state.prerequisites: |
| 1671 |
# Protobuf messages populated within |
| 1672 |
prereq_obj = prereq.api_dump() |
| 1673 |
if prereq_obj: |
| 1674 |
prereq_list.append(prereq_obj) |
| 1675 |
del tproxy.prerequisites[:] |
| 1676 |
tproxy.prerequisites.extend(prereq_list) |
| 1677 |
|
| 1678 |
for label, message, satisfied in itask.state.outputs: |
| 1679 |
output = tproxy.outputs[label] |
| 1680 |
output.label = label |
| 1681 |
output.message = message |
| 1682 |
output.satisfied = satisfied |
| 1683 |
output.time = update_time |
| 1684 |
|
| 1685 |
for trig, satisfied in itask.state.external_triggers.items(): |
| 1686 |
ext_trig = tproxy.external_triggers[trig] |
| 1687 |
ext_trig.id = trig |
| 1688 |
ext_trig.satisfied = satisfied |
| 1689 |
|
| 1690 |
for label, satisfied in itask.state.xtriggers.items(): |
| 1691 |
# Reload may have removed xtrigger of orphan task |
| 1692 |
if label not in self.schd.xtrigger_mgr.xtriggers.functx_map: |
| 1693 |
continue |
| 1694 |
sig = self.schd.xtrigger_mgr.get_xtrig_ctx( |
| 1695 |
itask, label).get_signature() |
| 1696 |
xtrig = tproxy.xtriggers[f'{label}={sig}'] |
| 1697 |
xtrig.id = sig |
| 1698 |
xtrig.label = label |
| 1699 |
xtrig.satisfied = satisfied |
| 1700 |
self.xtrigger_tasks.setdefault(sig, set()).add((tproxy.id, label)) |
| 1701 |
|
| 1702 |
self._set_task_xtrigger_modifiers(tproxy) |
| 1703 |
|
| 1704 |
if tproxy.state in self.latest_state_tasks: |
| 1705 |
tp_ref = itask.identity |
| 1706 |
tp_queue = self.latest_state_tasks[tproxy.state] |
| 1707 |
if tp_ref in tp_queue: |
| 1708 |
tp_queue.remove(tp_ref) |
| 1709 |
self.latest_state_tasks[tproxy.state].appendleft(tp_ref) |
| 1710 |
|
| 1711 |
tproxy.runtime.CopyFrom( |
| 1712 |
runtime_from_config( |
| 1713 |
self._apply_broadcasts_to_runtime( |
| 1714 |
itask.tokens, |
| 1715 |
itask.tdef.rtconfig |
| 1716 |
) |
| 1717 |
) |
| 1718 |
) |
| 1719 |
|
| 1720 |
def _apply_broadcasts_to_runtime(self, tokens, rtconfig): |
| 1721 |
# Handle broadcasts |
| 1722 |
overrides = self.schd.broadcast_mgr.get_broadcast(tokens) |
| 1723 |
if overrides: |
| 1724 |
rtconfig = pdeepcopy(rtconfig) |
| 1725 |
poverride(rtconfig, overrides, prepend=True) |
| 1726 |
return rtconfig |
| 1727 |
|
| 1728 |
def insert_job( |
| 1729 |
self, |
| 1730 |
itask: 'TaskProxy', |
| 1731 |
status: str, |
| 1732 |
job_conf: dict, |
| 1733 |
) -> None: |
| 1734 |
"""Insert job into data-store. |
| 1735 |
|
| 1736 |
Args: |
| 1737 |
status: The task's state. |
| 1738 |
job_conf: |
| 1739 |
Dictionary of job configuration used to generate |
| 1740 |
the job script. |
| 1741 |
(see TaskJobManager._prep_submit_task_job_impl) |
| 1742 |
|
| 1743 |
""" |
| 1744 |
if status not in JOB_STATUS_SET: |
| 1745 |
# Ignore task-only states e.g. preparing |
| 1746 |
# https://github.com/cylc/cylc-flow/issues/4994 |
| 1747 |
return |
| 1748 |
|
| 1749 |
sub_num = job_conf['submit_num'] |
| 1750 |
tp_tokens = self.id_.duplicate(itask.tokens) |
| 1751 |
tproxy: Optional[PbTaskProxy] |
| 1752 |
tp_id, tproxy = self.store_node_fetcher(tp_tokens) |
| 1753 |
if not tproxy: |
| 1754 |
return |
| 1755 |
update_time = time() |
| 1756 |
j_tokens = tp_tokens.duplicate(job=str(sub_num)) |
| 1757 |
j_id, job = self.store_node_fetcher(j_tokens) |
| 1758 |
if job: |
| 1759 |
# Job already exists (i.e. post-submission submit failure) |
| 1760 |
return |
| 1761 |
|
| 1762 |
j_buf = PbJob( |
| 1763 |
stamp=f'{j_id}@{update_time}', |
| 1764 |
id=j_id, |
| 1765 |
submit_num=sub_num, |
| 1766 |
state=status, |
| 1767 |
task_proxy=tp_id, |
| 1768 |
name=tproxy.name, |
| 1769 |
cycle_point=tproxy.cycle_point, |
| 1770 |
execution_time_limit=job_conf.get('execution_time_limit'), |
| 1771 |
platform=job_conf['platform']['name'], |
| 1772 |
job_runner_name=job_conf.get('job_runner_name'), |
| 1773 |
job_id=itask.summary.get('submit_method_id'), |
| 1774 |
) |
| 1775 |
# Not all fields are populated with some submit-failures, |
| 1776 |
# so use task cfg as base. |
| 1777 |
j_buf.runtime.CopyFrom( |
| 1778 |
runtime_from_partial(job_conf, tproxy.runtime) |
| 1779 |
) |
| 1780 |
|
| 1781 |
# Add in log files. |
| 1782 |
j_buf.job_log_dir = get_task_job_log( |
| 1783 |
self.schd.workflow, tproxy.cycle_point, tproxy.name, sub_num) |
| 1784 |
|
| 1785 |
self.added[JOBS][j_id] = j_buf |
| 1786 |
getattr(self.updated[WORKFLOW], JOBS).append(j_id) |
| 1787 |
tp_delta = self.updated[TASK_PROXIES].setdefault( |
| 1788 |
tp_id, |
| 1789 |
PbTaskProxy( |
| 1790 |
stamp=f'{tp_id}@{update_time}', |
| 1791 |
id=tp_id, |
| 1792 |
) |
| 1793 |
) |
| 1794 |
tp_delta.job_submits = sub_num |
| 1795 |
tp_delta.jobs.append(j_id) |
| 1796 |
self.updates_pending = True |
| 1797 |
|
| 1798 |
def insert_db_job(self, row_idx, row): |
| 1799 |
"""Load job element from DB post restart.""" |
| 1800 |
if row_idx == 0: |
| 1801 |
LOG.info("LOADING job data") |
| 1802 |
( |
| 1803 |
point_string, |
| 1804 |
name, |
| 1805 |
submit_num, |
| 1806 |
time_submit, |
| 1807 |
submit_status, |
| 1808 |
time_run, |
| 1809 |
time_run_exit, |
| 1810 |
run_status, |
| 1811 |
job_runner_name, |
| 1812 |
job_id, |
| 1813 |
platform_name |
| 1814 |
) = row |
| 1815 |
tp_tokens = self.id_.duplicate( |
| 1816 |
cycle=point_string, |
| 1817 |
task=name, |
| 1818 |
) |
| 1819 |
tproxy: Optional[PbTaskProxy] |
| 1820 |
tp_id, tproxy = self.store_node_fetcher(tp_tokens) |
| 1821 |
if not tproxy: |
| 1822 |
return |
| 1823 |
j_tokens = tp_tokens.duplicate(job=str(submit_num)) |
| 1824 |
j_id = j_tokens.id |
| 1825 |
|
| 1826 |
if run_status is not None: |
| 1827 |
if run_status == 0: |
| 1828 |
status = TASK_STATUS_SUCCEEDED |
| 1829 |
else: |
| 1830 |
status = TASK_STATUS_FAILED |
| 1831 |
elif time_run is not None: |
| 1832 |
status = TASK_STATUS_RUNNING |
| 1833 |
elif submit_status is not None: |
| 1834 |
if submit_status == 0: |
| 1835 |
status = TASK_STATUS_SUBMITTED |
| 1836 |
else: |
| 1837 |
status = TASK_STATUS_SUBMIT_FAILED |
| 1838 |
else: |
| 1839 |
return |
| 1840 |
|
| 1841 |
try: |
| 1842 |
update_time = time() |
| 1843 |
j_buf = PbJob( |
| 1844 |
stamp=f'{j_id}@{update_time}', |
| 1845 |
id=j_id, |
| 1846 |
submit_num=submit_num, |
| 1847 |
state=status, |
| 1848 |
task_proxy=tp_id, |
| 1849 |
submitted_time=time_submit, |
| 1850 |
started_time=time_run, |
| 1851 |
finished_time=time_run_exit, |
| 1852 |
job_runner_name=job_runner_name, |
| 1853 |
job_id=job_id, |
| 1854 |
platform=platform_name, |
| 1855 |
name=name, |
| 1856 |
cycle_point=tproxy.cycle_point, |
| 1857 |
) |
| 1858 |
# Add in log files. |
| 1859 |
j_buf.job_log_dir = get_task_job_log( |
| 1860 |
self.schd.workflow, point_string, name, submit_num) |
| 1861 |
except WorkflowConfigError: |
| 1862 |
LOG.exception(( |
| 1863 |
'ignoring job %s from the workflow run database\n' |
| 1864 |
'(its task definition has probably been deleted).' |
| 1865 |
) % j_id) |
| 1866 |
except Exception: |
| 1867 |
LOG.exception('could not load job %s' % j_id) |
| 1868 |
else: |
| 1869 |
self.added[JOBS][j_id] = j_buf |
| 1870 |
getattr(self.updated[WORKFLOW], JOBS).append(j_id) |
| 1871 |
tp_delta = self.updated[TASK_PROXIES].setdefault( |
| 1872 |
tp_id, |
| 1873 |
PbTaskProxy( |
| 1874 |
stamp=f'{tp_id}@{update_time}', |
| 1875 |
id=tp_id, |
| 1876 |
) |
| 1877 |
) |
| 1878 |
tp_delta.job_submits = max((submit_num, tp_delta.job_submits)) |
| 1879 |
tp_delta.jobs.append(j_id) |
| 1880 |
self.updates_pending = True |
| 1881 |
|
| 1882 |
def update_data_structure(self): |
| 1883 |
"""Workflow batch updates in the data structure.""" |
| 1884 |
|
| 1885 |
# Avoids changing window edge distance during edge/node creation |
| 1886 |
if self.next_n_edge_distance is not None: |
| 1887 |
self.n_edge_distance = self.next_n_edge_distance |
| 1888 |
self.window_resize_rewalk() |
| 1889 |
self.next_n_edge_distance = None |
| 1890 |
|
| 1891 |
# load database history for flagged nodes |
| 1892 |
self.apply_task_proxy_db_history() |
| 1893 |
|
| 1894 |
self.updates_pending_follow_on = False |
| 1895 |
self.prune_data_store() |
| 1896 |
|
| 1897 |
# Find depth changes and create deltas |
| 1898 |
if self.update_window_depths: |
| 1899 |
self.window_depth_finder() |
| 1900 |
|
| 1901 |
if self.updates_pending: |
| 1902 |
# update |
| 1903 |
self.update_family_proxies() |
| 1904 |
|
| 1905 |
# Update workflow statuses and totals if needed |
| 1906 |
self.update_workflow() |
| 1907 |
|
| 1908 |
# Don't process updated deltas of pruned nodes |
| 1909 |
self.dedupe_pruned_updated_task_proxies() |
| 1910 |
|
| 1911 |
# Gather deltas |
| 1912 |
self.batch_deltas() |
| 1913 |
# Apply all deltas |
| 1914 |
self.apply_delta_batch() |
| 1915 |
|
| 1916 |
if self.updates_pending: |
| 1917 |
self.apply_delta_checksum() |
| 1918 |
# Gather this batch of deltas for publish |
| 1919 |
self.publish_deltas = self.get_publish_deltas() |
| 1920 |
|
| 1921 |
self.updates_pending = self.updates_pending_follow_on |
| 1922 |
|
| 1923 |
# Clear deltas |
| 1924 |
self.clear_delta_batch() |
| 1925 |
self.clear_delta_store() |
| 1926 |
|
| 1927 |
def update_workflow_states(self): |
| 1928 |
"""Batch workflow state updates.""" |
| 1929 |
|
| 1930 |
# update the workflow state in the data store |
| 1931 |
self.update_workflow() |
| 1932 |
|
| 1933 |
# push out update deltas |
| 1934 |
self.batch_deltas() |
| 1935 |
self.apply_delta_batch() |
| 1936 |
self.apply_delta_checksum() |
| 1937 |
self.publish_deltas = self.get_publish_deltas() |
| 1938 |
|
| 1939 |
def window_resize_rewalk(self) -> None: |
| 1940 |
"""Re-create data-store n-window on resize.""" |
| 1941 |
# Gather pre-resize window nodes |
| 1942 |
if not self.all_n_window_nodes: |
| 1943 |
self.all_n_window_nodes = set().union(*( |
| 1944 |
v |
| 1945 |
for k, v in self.n_window_nodes.items() |
| 1946 |
if k in self.all_task_pool |
| 1947 |
)) |
| 1948 |
|
| 1949 |
# Clear window walks, and walk from scratch. |
| 1950 |
self.prune_flagged_nodes.clear() |
| 1951 |
self.prune_trigger_nodes.clear() |
| 1952 |
self.n_window_node_walks.clear() |
| 1953 |
for tp_id in self.all_task_pool: |
| 1954 |
tokens = Tokens(tp_id) |
| 1955 |
tproxy: PbTaskProxy |
| 1956 |
_, tproxy = self.store_node_fetcher(tokens) |
| 1957 |
self.increment_graph_window( |
| 1958 |
tokens, |
| 1959 |
get_point(tokens['cycle']), |
| 1960 |
) |
| 1961 |
# Flag difference between old and new window for pruning. |
| 1962 |
self.prune_flagged_nodes.update( |
| 1963 |
self.all_n_window_nodes.difference(*( |
| 1964 |
v |
| 1965 |
for k, v in self.n_window_nodes.items() |
| 1966 |
if k in self.all_task_pool |
| 1967 |
)) |
| 1968 |
) |
| 1969 |
self.update_window_depths = True |
| 1970 |
|
| 1971 |
def window_depth_finder(self): |
| 1972 |
"""Recalculate window depths, creating depth deltas.""" |
| 1973 |
# Setup new window depths |
| 1974 |
n_window_depths: Dict[int, Set[str]] = { |
| 1975 |
0: self.all_task_pool.copy() |
| 1976 |
} |
| 1977 |
|
| 1978 |
depth = 1 |
| 1979 |
# Since starting from smaller depth, exclude those whose depth has |
| 1980 |
# already been found. |
| 1981 |
depth_found_tasks: Set[str] = self.all_task_pool.copy() |
| 1982 |
while depth <= self.n_edge_distance: |
| 1983 |
n_window_depths[depth] = set().union(*( |
| 1984 |
self.n_window_node_walks[n_id]['depths'][depth] |
| 1985 |
for n_id in self.all_task_pool |
| 1986 |
if ( |
| 1987 |
n_id in self.n_window_node_walks |
| 1988 |
and depth in self.n_window_node_walks[n_id]['depths'] |
| 1989 |
) |
| 1990 |
)).difference(depth_found_tasks) |
| 1991 |
depth_found_tasks.update(n_window_depths[depth]) |
| 1992 |
# Calculate next depth parameters. |
| 1993 |
depth += 1 |
| 1994 |
|
| 1995 |
# Create deltas of those whose depth has changed, a node should only |
| 1996 |
# appear once across all depths. |
| 1997 |
# So the diff will only contain it at a single depth and if it didn't |
| 1998 |
# appear at the same depth previously. |
| 1999 |
update_time = time() |
| 2000 |
for depth, node_set in n_window_depths.items(): |
| 2001 |
node_set_diff = node_set.difference( |
| 2002 |
self.n_window_depths.setdefault(depth, set()) |
| 2003 |
) |
| 2004 |
if not self.updates_pending and node_set_diff: |
| 2005 |
self.updates_pending = True |
| 2006 |
for tp_id in node_set_diff: |
| 2007 |
tp_delta = self.updated[TASK_PROXIES].setdefault( |
| 2008 |
tp_id, PbTaskProxy(id=tp_id) |
| 2009 |
) |
| 2010 |
tp_delta.stamp = f'{tp_id}@{update_time}' |
| 2011 |
tp_delta.graph_depth = depth |
| 2012 |
# Set old to new. |
| 2013 |
self.n_window_depths = n_window_depths |
| 2014 |
self.update_window_depths = False |
| 2015 |
|
| 2016 |
def prune_data_store(self): |
| 2017 |
"""Remove flagged nodes and edges not in the set of active paths.""" |
| 2018 |
|
| 2019 |
self.family_pruned_ids.clear() |
| 2020 |
|
| 2021 |
if not self.prune_flagged_nodes: |
| 2022 |
return |
| 2023 |
|
| 2024 |
# Keep all nodes in the path of active tasks. |
| 2025 |
self.all_n_window_nodes = set().union(*( |
| 2026 |
v |
| 2027 |
for k, v in self.n_window_nodes.items() |
| 2028 |
if k in self.all_task_pool |
| 2029 |
)) |
| 2030 |
# Gather all nodes in the paths of tasks flagged for pruning. |
| 2031 |
out_paths_nodes = self.prune_flagged_nodes.union(*( |
| 2032 |
v |
| 2033 |
for k, v in self.n_window_nodes.items() |
| 2034 |
if k in self.prune_flagged_nodes |
| 2035 |
)) |
| 2036 |
# Trim out any nodes in the runahead pool |
| 2037 |
out_paths_nodes.difference(self.all_task_pool) |
| 2038 |
# Prune only nodes not in the paths of active nodes |
| 2039 |
node_ids = out_paths_nodes.difference(self.all_n_window_nodes) |
| 2040 |
# Absolute triggers may be present in task pool, so recheck. |
| 2041 |
# Clear the rest. |
| 2042 |
self.prune_flagged_nodes.intersection_update(self.all_task_pool) |
| 2043 |
# Clear any boundary prune triggers not in the window. |
| 2044 |
# This can happen where the graph has paths not taken, i.e.: |
| 2045 |
# ``` |
| 2046 |
# foo => a |
| 2047 |
# foo:failed => b |
| 2048 |
# ``` |
| 2049 |
# So if `foo` then `a`, which when active/removed is the prune trigger |
| 2050 |
# for `foo`.. However, `b` is not used so delete the trigger here. |
| 2051 |
for trigger_id in set( |
| 2052 |
self.prune_trigger_nodes).difference(self.all_n_window_nodes): |
| 2053 |
del self.prune_trigger_nodes[trigger_id] |
| 2054 |
|
| 2055 |
tp_data = self.data[self.workflow_id][TASK_PROXIES] |
| 2056 |
tp_added = self.added[TASK_PROXIES] |
| 2057 |
parent_ids = set() |
| 2058 |
for tp_id in list(node_ids): |
| 2059 |
if tp_id in self.n_window_nodes: |
| 2060 |
del self.n_window_nodes[tp_id] |
| 2061 |
if tp_id in tp_data: |
| 2062 |
node = tp_data[tp_id] |
| 2063 |
elif tp_id in tp_added: |
| 2064 |
node = tp_added[tp_id] |
| 2065 |
else: |
| 2066 |
node_ids.remove(tp_id) |
| 2067 |
continue |
| 2068 |
self.n_window_edges.difference_update(node.edges) |
| 2069 |
if tp_id in self.n_window_node_walks: |
| 2070 |
del self.n_window_node_walks[tp_id] |
| 2071 |
if tp_id in self.n_window_completed_walks: |
| 2072 |
self.n_window_completed_walks.remove(tp_id) |
| 2073 |
for xid in node.xtriggers: |
| 2074 |
with suppress(KeyError): |
| 2075 |
label, sig = xid.split('=', 1) |
| 2076 |
self.xtrigger_tasks[sig].remove((tp_id, label)) |
| 2077 |
if not self.xtrigger_tasks[sig]: |
| 2078 |
del self.xtrigger_tasks[sig] |
| 2079 |
|
| 2080 |
self.deltas[TASK_PROXIES].pruned.append(tp_id) |
| 2081 |
self.deltas[JOBS].pruned.extend(node.jobs) |
| 2082 |
self.deltas[EDGES].pruned.extend(node.edges) |
| 2083 |
parent_ids.add(node.first_parent) |
| 2084 |
|
| 2085 |
checked_ids = set() |
| 2086 |
while parent_ids: |
| 2087 |
self._family_ascent_point_prune( |
| 2088 |
next(iter(parent_ids)), |
| 2089 |
node_ids, parent_ids, checked_ids, self.family_pruned_ids) |
| 2090 |
if self.family_pruned_ids: |
| 2091 |
self.deltas[FAMILY_PROXIES].pruned.extend(self.family_pruned_ids) |
| 2092 |
if node_ids: |
| 2093 |
self.pruned_task_proxies.update(node_ids) |
| 2094 |
self.updates_pending = True |
| 2095 |
self.updates_pending_follow_on = True |
| 2096 |
|
| 2097 |
def _family_ascent_point_prune( |
| 2098 |
self, fp_id, node_ids, parent_ids, checked_ids, prune_ids): |
| 2099 |
"""Find and prune family recursively checking child families. |
| 2100 |
|
| 2101 |
Recursively map out child families to the bottom from the origin |
| 2102 |
family. The work back up to origin checking these families are active. |
| 2103 |
|
| 2104 |
""" |
| 2105 |
fp_updated = self.updated[FAMILY_PROXIES] |
| 2106 |
fam_node = self.data[self.workflow_id][FAMILY_PROXIES].get( |
| 2107 |
fp_id, |
| 2108 |
self.added[FAMILY_PROXIES].get(fp_id, None) |
| 2109 |
) |
| 2110 |
# Should never be None, |
| 2111 |
# leaving in as protection against potential race conditions. |
| 2112 |
if fam_node is not None: |
| 2113 |
# Gather child families, then check/update recursively |
| 2114 |
for child_id in fam_node.child_families: |
| 2115 |
if child_id in checked_ids: |
| 2116 |
continue |
| 2117 |
self._family_ascent_point_prune( |
| 2118 |
child_id, node_ids, parent_ids, checked_ids, prune_ids) |
| 2119 |
child_tasks = set(fam_node.child_tasks) |
| 2120 |
child_families = set(fam_node.child_families) |
| 2121 |
# Add in any new children |
| 2122 |
if fp_id in fp_updated: |
| 2123 |
if fp_updated[fp_id].child_tasks: |
| 2124 |
child_tasks.update(fp_updated[fp_id].child_tasks) |
| 2125 |
if fp_updated[fp_id].child_families: |
| 2126 |
child_families.update(fp_updated[fp_id].child_families) |
| 2127 |
# If any child tasks or families are in window, |
| 2128 |
# then don't prune this family. |
| 2129 |
if ( |
| 2130 |
child_tasks.difference(node_ids) |
| 2131 |
or child_families.difference(prune_ids) |
| 2132 |
): |
| 2133 |
# If any child tasks or families will be pruned, |
| 2134 |
# then update family states. |
| 2135 |
if ( |
| 2136 |
child_tasks.intersection(node_ids) |
| 2137 |
or child_families.intersection(prune_ids) |
| 2138 |
): |
| 2139 |
self.state_update_families.add(fp_id) |
| 2140 |
else: |
| 2141 |
if fam_node.first_parent: |
| 2142 |
parent_ids.add(fam_node.first_parent) |
| 2143 |
# Don't process updated deltas of pruned node |
| 2144 |
if fp_id in fp_updated: |
| 2145 |
del fp_updated[fp_id] |
| 2146 |
prune_ids.add(fp_id) |
| 2147 |
checked_ids.add(fp_id) |
| 2148 |
if fp_id in parent_ids: |
| 2149 |
parent_ids.remove(fp_id) |
| 2150 |
|
| 2151 |
def dedupe_pruned_updated_task_proxies(self): |
| 2152 |
"""Remove updated task proxies that will also be pruned in this batch. |
| 2153 |
|
| 2154 |
This will avoid processing and sending deltas that will immediately |
| 2155 |
be pruned. Kept separate from other pruning to allow for update |
| 2156 |
information to be included in summaries. |
| 2157 |
|
| 2158 |
""" |
| 2159 |
tp_data = self.data[self.workflow_id][TASK_PROXIES] |
| 2160 |
tp_added = self.added[TASK_PROXIES] |
| 2161 |
tp_updated = self.updated[TASK_PROXIES] |
| 2162 |
for tp_id in self.pruned_task_proxies: |
| 2163 |
if tp_id in tp_updated: |
| 2164 |
if tp_id in tp_data: |
| 2165 |
node: PbTaskProxy = tp_data[tp_id] |
| 2166 |
elif tp_id in tp_added: |
| 2167 |
node = tp_added[tp_id] |
| 2168 |
else: |
| 2169 |
continue |
| 2170 |
update_node: PbTaskProxy = tp_updated.pop(tp_id) |
| 2171 |
# Remove this task's added/updated jobs in this batch too: |
| 2172 |
for j_id in set(node.jobs).union(update_node.jobs): |
| 2173 |
for record in (self.added, self.updated): |
| 2174 |
record[JOBS].pop(j_id, None) |
| 2175 |
self.n_window_edges.difference_update(update_node.edges) |
| 2176 |
self.deltas[EDGES].pruned.extend(update_node.edges) |
| 2177 |
self.pruned_task_proxies.clear() |
| 2178 |
|
| 2179 |
def update_family_proxies(self): |
| 2180 |
"""Update state & summary of flagged families and ancestors. |
| 2181 |
|
| 2182 |
Tasks whose state are updated flag their first parent, as a family |
| 2183 |
to be updated, by adding their ID to a set. |
| 2184 |
This set is iterated over here until empty, with each members child |
| 2185 |
families checked/updated and first parent added to the set (flagged). |
| 2186 |
Order doesn't matter, as every family will be checked/updated once at |
| 2187 |
most (as an ancestor will-be/has-been added to the set of updated |
| 2188 |
families). |
| 2189 |
|
| 2190 |
""" |
| 2191 |
self.updated_state_families.clear() |
| 2192 |
while self.state_update_families: |
| 2193 |
self._family_ascent_point_update( |
| 2194 |
next(iter(self.state_update_families))) |
| 2195 |
if self.updated_state_families: |
| 2196 |
self.state_update_follow_on = True |
| 2197 |
|
| 2198 |
@staticmethod |
| 2199 |
def from_delta_or_node(tp_delta, tp_node, label): |
| 2200 |
"""Get an item from task proxy delta if available, falling back to |
| 2201 |
node otherwise.""" |
| 2202 |
this = tp_delta |
| 2203 |
if this is None or not this.HasField(label): |
| 2204 |
this = tp_node |
| 2205 |
return getattr(this, label) or None |
| 2206 |
|
| 2207 |
def _family_ascent_point_update(self, fp_id): |
| 2208 |
"""Updates the given family and children recursively. |
| 2209 |
|
| 2210 |
First the child families that haven't been checked/updated are acted |
| 2211 |
on first by calling this function. This recursion ends at the family |
| 2212 |
first called with this function, which then adds it's first parent |
| 2213 |
ancestor to the set of families flagged for update. |
| 2214 |
|
| 2215 |
State totals of families reflect zero n-window (n=0). |
| 2216 |
Family group state, however, is determined from all (n>=0) child |
| 2217 |
task and family states. |
| 2218 |
""" |
| 2219 |
all_nodes = self.all_n_window_nodes |
| 2220 |
fp_added = self.added[FAMILY_PROXIES] |
| 2221 |
fp_data = self.data[self.workflow_id][FAMILY_PROXIES] |
| 2222 |
fp_updated = self.updated[FAMILY_PROXIES] |
| 2223 |
if fp_id in fp_data: |
| 2224 |
fam_node = fp_data[fp_id] |
| 2225 |
elif fp_id in fp_added: |
| 2226 |
fam_node = fp_added[fp_id] |
| 2227 |
else: |
| 2228 |
# TODO: Shouldn't need with event driven updates |
| 2229 |
# as nodes will be updated before removal. |
| 2230 |
if fp_id in self.state_update_families: |
| 2231 |
self.updated_state_families.add(fp_id) |
| 2232 |
self.state_update_families.remove(fp_id) |
| 2233 |
return |
| 2234 |
fam_updated_node = fp_updated.get(fp_id) |
| 2235 |
# Gather child families, then check/update recursively. |
| 2236 |
# Use all new and existing child families that are not destined |
| 2237 |
# to be pruned. |
| 2238 |
child_fams = set(fam_node.child_families) |
| 2239 |
if fam_updated_node: |
| 2240 |
child_fams.update(fam_updated_node.child_families) |
| 2241 |
child_fams.difference_update(self.family_pruned_ids) |
| 2242 |
for child_fam_id in child_fams: |
| 2243 |
if child_fam_id in self.updated_state_families: |
| 2244 |
continue |
| 2245 |
self._family_ascent_point_update(child_fam_id) |
| 2246 |
if fp_id in self.state_update_families: |
| 2247 |
tp_data = self.data[self.workflow_id][TASK_PROXIES] |
| 2248 |
tp_updated = self.updated[TASK_PROXIES] |
| 2249 |
tp_added = self.added[TASK_PROXIES] |
| 2250 |
|
| 2251 |
# Count child family states, set is_held, is_queued, is_runahead |
| 2252 |
state_set = set() # n>=0 child states |
| 2253 |
active_counter = Counter({}) # n=0 child state totals |
| 2254 |
is_held_total = 0 |
| 2255 |
is_queued_total = 0 |
| 2256 |
is_runahead_total = 0 |
| 2257 |
is_retry = False |
| 2258 |
is_wallclock = False |
| 2259 |
is_xtriggered = False |
| 2260 |
graph_depth = self.n_edge_distance |
| 2261 |
# Gather the counts and totals of child families. |
| 2262 |
for child_id in child_fams: |
| 2263 |
child_node = fp_updated.get(child_id, fp_data.get(child_id)) |
| 2264 |
if child_node is not None: |
| 2265 |
# if child family is active/n=0 |
| 2266 |
if child_node.graph_depth == 0: |
| 2267 |
is_held_total += child_node.is_held_total |
| 2268 |
is_queued_total += child_node.is_queued_total |
| 2269 |
is_runahead_total += child_node.is_runahead_total |
| 2270 |
is_retry |= child_node.is_retry |
| 2271 |
is_wallclock |= child_node.is_wallclock |
| 2272 |
is_xtriggered |= child_node.is_xtriggered |
| 2273 |
# add active child state totals to active count. |
| 2274 |
active_counter += Counter( |
| 2275 |
dict(child_node.state_totals) |
| 2276 |
) |
| 2277 |
state_set.add(child_node.state) |
| 2278 |
if child_node.graph_depth < graph_depth: |
| 2279 |
graph_depth = child_node.graph_depth |
| 2280 |
# Gather all child task states. |
| 2281 |
# Use all new and existing child tasks that are not destined |
| 2282 |
# to be pruned. |
| 2283 |
child_tasks = set(fam_node.child_tasks) |
| 2284 |
if fam_updated_node: |
| 2285 |
child_tasks.update(fam_updated_node.child_tasks) |
| 2286 |
child_tasks.difference_update(self.pruned_task_proxies) |
| 2287 |
for tp_id in child_tasks: |
| 2288 |
is_active = False |
| 2289 |
if all_nodes and tp_id not in all_nodes: |
| 2290 |
continue |
| 2291 |
|
| 2292 |
tp_delta = tp_updated.get(tp_id) |
| 2293 |
tp_node = tp_added.get(tp_id, tp_data.get(tp_id)) |
| 2294 |
|
| 2295 |
tp_depth = tp_delta |
| 2296 |
if tp_depth is None or not tp_depth.HasField('graph_depth'): |
| 2297 |
tp_depth = tp_node |
| 2298 |
if tp_depth.graph_depth < graph_depth: |
| 2299 |
graph_depth = tp_depth.graph_depth |
| 2300 |
|
| 2301 |
if tp_id in self.all_task_pool: |
| 2302 |
is_active = True |
| 2303 |
|
| 2304 |
tp_state = self.from_delta_or_node(tp_delta, tp_node, 'state') |
| 2305 |
|
| 2306 |
state_set.add(tp_state) |
| 2307 |
# if child task is active add states/held/queued/runahead |
| 2308 |
# to totals |
| 2309 |
if is_active: |
| 2310 |
active_counter[tp_state] += 1 |
| 2311 |
|
| 2312 |
if self.from_delta_or_node(tp_delta, tp_node, 'is_held'): |
| 2313 |
is_held_total += 1 |
| 2314 |
|
| 2315 |
if self.from_delta_or_node(tp_delta, tp_node, 'is_queued'): |
| 2316 |
is_queued_total += 1 |
| 2317 |
|
| 2318 |
if self.from_delta_or_node( |
| 2319 |
tp_delta, tp_node, 'is_runahead' |
| 2320 |
): |
| 2321 |
is_runahead_total += 1 |
| 2322 |
|
| 2323 |
if self.from_delta_or_node(tp_delta, tp_node, 'is_retry'): |
| 2324 |
is_retry = True |
| 2325 |
|
| 2326 |
if self.from_delta_or_node(tp_delta, tp_node, 'is_wallclock'): |
| 2327 |
is_wallclock = True |
| 2328 |
|
| 2329 |
if self.from_delta_or_node(tp_delta, tp_node, 'is_xtriggered'): |
| 2330 |
is_xtriggered = True |
| 2331 |
|
| 2332 |
# created delta data element |
| 2333 |
fp_delta = PbFamilyProxy( |
| 2334 |
id=fp_id, |
| 2335 |
stamp=f'{fp_id}@{time()}', |
| 2336 |
# use the state of all children to determine the group state. |
| 2337 |
state=extract_group_state(state_set), |
| 2338 |
is_held=(is_held_total > 0), |
| 2339 |
is_held_total=is_held_total, |
| 2340 |
is_queued=(is_queued_total > 0), |
| 2341 |
is_queued_total=is_queued_total, |
| 2342 |
is_runahead=(is_runahead_total > 0), |
| 2343 |
is_runahead_total=is_runahead_total, |
| 2344 |
is_retry=is_retry, |
| 2345 |
is_wallclock=is_wallclock, |
| 2346 |
is_xtriggered=is_xtriggered, |
| 2347 |
graph_depth=graph_depth, |
| 2348 |
) |
| 2349 |
fp_delta.states[:] = active_counter.keys() |
| 2350 |
# Reset all totals to reflect either active or inactive totals. |
| 2351 |
for state in TASK_STATUSES_ORDERED: |
| 2352 |
fp_delta.state_totals[state] = active_counter.get(state, 0) |
| 2353 |
fp_updated.setdefault(fp_id, PbFamilyProxy()).MergeFrom(fp_delta) |
| 2354 |
# mark as updated in case parent family is updated next |
| 2355 |
self.updated_state_families.add(fp_id) |
| 2356 |
# mark parent for update |
| 2357 |
if fam_node.first_parent: |
| 2358 |
self.state_update_families.add(fam_node.first_parent) |
| 2359 |
self.state_update_families.remove(fp_id) |
| 2360 |
|
| 2361 |
def set_graph_window_extent(self, n_edge_distance: int) -> None: |
| 2362 |
"""Set what the max edge distance will change to. |
| 2363 |
|
| 2364 |
Args: |
| 2365 |
n_edge_distance: |
| 2366 |
Maximum edge distance from active node. |
| 2367 |
|
| 2368 |
""" |
| 2369 |
if n_edge_distance != self.n_edge_distance: |
| 2370 |
self.next_n_edge_distance = n_edge_distance |
| 2371 |
self.updates_pending = True |
| 2372 |
|
| 2373 |
def update_workflow(self, reloaded=False): |
| 2374 |
"""Update workflow element status and state totals.""" |
| 2375 |
# Create new message and copy existing message content |
| 2376 |
data = self.data[self.workflow_id] |
| 2377 |
w_data = data[WORKFLOW] |
| 2378 |
w_delta = self.updated[WORKFLOW] |
| 2379 |
delta_set = False |
| 2380 |
|
| 2381 |
# new updates/deltas not applied yet |
| 2382 |
# so need to search/use updated states if available. |
| 2383 |
if self.updated_state_families or self.state_update_follow_on: |
| 2384 |
if not self.updated_state_families: |
| 2385 |
self.state_update_follow_on = False |
| 2386 |
state_counter = Counter({}) |
| 2387 |
is_held_total = 0 |
| 2388 |
is_queued_total = 0 |
| 2389 |
is_runahead_total = 0 |
| 2390 |
contains_retry = False |
| 2391 |
for root_id in set( |
| 2392 |
[n.id |
| 2393 |
for n in data[FAMILY_PROXIES].values() |
| 2394 |
if n.name == 'root'] + |
| 2395 |
[n.id |
| 2396 |
for n in self.added[FAMILY_PROXIES].values() |
| 2397 |
if n.name == 'root'] |
| 2398 |
): |
| 2399 |
root_node_updated = self.updated[FAMILY_PROXIES].get(root_id) |
| 2400 |
if root_node_updated is not None and root_node_updated.state: |
| 2401 |
root_node = root_node_updated |
| 2402 |
else: |
| 2403 |
root_node = data[FAMILY_PROXIES].get(root_id) |
| 2404 |
if root_node is not None and root_node.graph_depth == 0: |
| 2405 |
is_held_total += root_node.is_held_total |
| 2406 |
is_queued_total += root_node.is_queued_total |
| 2407 |
is_runahead_total += root_node.is_runahead_total |
| 2408 |
state_counter += Counter(dict(root_node.state_totals)) |
| 2409 |
contains_retry = contains_retry or root_node.is_retry |
| 2410 |
w_delta.states[:] = state_counter.keys() |
| 2411 |
for state, state_cnt in state_counter.items(): |
| 2412 |
w_delta.state_totals[state] = state_cnt |
| 2413 |
|
| 2414 |
w_delta.states_updated = True |
| 2415 |
w_delta.contains_held = bool(is_held_total) |
| 2416 |
w_delta.contains_retry = contains_retry |
| 2417 |
|
| 2418 |
# BACK COMPAT: is_held_total, is_queued_total, is_runahead_total |
| 2419 |
# From: 8.6.2 |
| 2420 |
# These fields were added, but have probably never been used. |
| 2421 |
# They are marked as deprecated in GraphQL pending possible |
| 2422 |
# deletion in a future release (to cut down on message cruft) |
| 2423 |
w_delta.is_held_total = is_held_total |
| 2424 |
w_delta.is_queued_total = is_queued_total |
| 2425 |
w_delta.is_runahead_total = is_runahead_total |
| 2426 |
|
| 2427 |
delta_set = True |
| 2428 |
|
| 2429 |
for state, tp_queue in self.latest_state_tasks.items(): |
| 2430 |
w_delta.latest_state_tasks[state].task_proxies[:] = tp_queue |
| 2431 |
|
| 2432 |
# Set status & msg if changed. |
| 2433 |
status = get_workflow_status(self.schd).value |
| 2434 |
status_msg = get_workflow_status_msg(self.schd) |
| 2435 |
if w_data.status != status or w_data.status_msg != status_msg: |
| 2436 |
w_delta.status = status |
| 2437 |
w_delta.status_msg = status_msg |
| 2438 |
delta_set = True |
| 2439 |
|
| 2440 |
if reloaded is not w_data.reloaded: |
| 2441 |
w_delta.reloaded = reloaded |
| 2442 |
|
| 2443 |
if w_data.n_edge_distance != self.n_edge_distance: |
| 2444 |
w_delta.n_edge_distance = self.n_edge_distance |
| 2445 |
delta_set = True |
| 2446 |
|
| 2447 |
if self.schd.pool.active_tasks: |
| 2448 |
pool_points = set(self.schd.pool.active_tasks) |
| 2449 |
|
| 2450 |
oldest_point = str(min(pool_points)) |
| 2451 |
if w_data.oldest_active_cycle_point != oldest_point: |
| 2452 |
w_delta.oldest_active_cycle_point = oldest_point |
| 2453 |
delta_set = True |
| 2454 |
newest_point = str(max(pool_points)) |
| 2455 |
if w_data.newest_active_cycle_point != newest_point: |
| 2456 |
w_delta.newest_active_cycle_point = newest_point |
| 2457 |
delta_set = True |
| 2458 |
|
| 2459 |
if delta_set: |
| 2460 |
w_delta.id = self.workflow_id |
| 2461 |
w_delta.last_updated = time() |
| 2462 |
w_delta.stamp = f'{w_delta.id}@{w_delta.last_updated}' |
| 2463 |
|
| 2464 |
def delta_workflow_ports(self): |
| 2465 |
"""Set or update the workflow comms ports.""" |
| 2466 |
w_delta = self.updated[WORKFLOW] |
| 2467 |
w_delta.id = self.workflow_id |
| 2468 |
w_delta.last_updated = time() |
| 2469 |
w_delta.stamp = f'{w_delta.id}@{w_delta.last_updated}' |
| 2470 |
|
| 2471 |
w_delta.port = self.schd.server.port |
| 2472 |
w_delta.pub_port = self.schd.server.pub_port |
| 2473 |
self.updates_pending = True |
| 2474 |
|
| 2475 |
def delta_broadcast(self): |
| 2476 |
"""Collects broadcasts on change event.""" |
| 2477 |
w_delta = self.updated[WORKFLOW] |
| 2478 |
w_delta.id = self.workflow_id |
| 2479 |
w_delta.last_updated = time() |
| 2480 |
w_delta.stamp = f'{w_delta.id}@{w_delta.last_updated}' |
| 2481 |
|
| 2482 |
w_delta.broadcasts = json.dumps(self.schd.broadcast_mgr.broadcasts) |
| 2483 |
self._generate_broadcast_node_deltas( |
| 2484 |
self.data[self.workflow_id][TASK_PROXIES], |
| 2485 |
TASK_PROXIES |
| 2486 |
) |
| 2487 |
self._generate_broadcast_node_deltas( |
| 2488 |
self.added[TASK_PROXIES], |
| 2489 |
TASK_PROXIES |
| 2490 |
) |
| 2491 |
self._generate_broadcast_node_deltas( |
| 2492 |
self.data[self.workflow_id][FAMILY_PROXIES], |
| 2493 |
FAMILY_PROXIES |
| 2494 |
) |
| 2495 |
self._generate_broadcast_node_deltas( |
| 2496 |
self.added[FAMILY_PROXIES], |
| 2497 |
FAMILY_PROXIES |
| 2498 |
) |
| 2499 |
|
| 2500 |
self.updates_pending = True |
| 2501 |
|
| 2502 |
def _generate_broadcast_node_deltas(self, node_data, node_type): |
| 2503 |
rt_cfg = self.schd.config.cfg['runtime'] |
| 2504 |
# NOTE: node_data may change during operation so make a copy |
| 2505 |
# see https://github.com/cylc/cylc-flow/pull/6397 |
| 2506 |
for node_id, node in list(node_data.items()): |
| 2507 |
# Avoid removed tasks with deltas queued during reload. |
| 2508 |
if node.name not in rt_cfg: |
| 2509 |
continue |
| 2510 |
tokens = Tokens(node_id) |
| 2511 |
new_runtime = runtime_from_config( |
| 2512 |
self._apply_broadcasts_to_runtime(tokens, rt_cfg[node.name]) |
| 2513 |
) |
| 2514 |
new_sruntime = new_runtime.SerializeToString( |
| 2515 |
deterministic=True |
| 2516 |
) |
| 2517 |
old_sruntime = node.runtime.SerializeToString( |
| 2518 |
deterministic=True |
| 2519 |
) |
| 2520 |
if new_sruntime != old_sruntime: |
| 2521 |
node_delta = self.updated[node_type].setdefault( |
| 2522 |
node_id, MESSAGE_MAP[node_type](id=node_id)) |
| 2523 |
node_delta.runtime.CopyFrom(new_runtime) |
| 2524 |
|
| 2525 |
def delta_log_record(self, level: str, message: str) -> None: |
| 2526 |
"""Append a log record to the data store. |
| 2527 |
|
| 2528 |
Args: |
| 2529 |
level: |
| 2530 |
The log level name e.g. INFO or WARNING. |
| 2531 |
message: |
| 2532 |
The formatted log message. Note, we are deliberately NOT |
| 2533 |
formatting the timestamp, level, etc into this message, these |
| 2534 |
should be added as discrete fields if they desired in the |
| 2535 |
future. |
| 2536 |
|
| 2537 |
""" |
| 2538 |
w_delta = self.updated[WORKFLOW] |
| 2539 |
w_delta.id = self.workflow_id |
| 2540 |
w_delta.last_updated = time() |
| 2541 |
w_delta.stamp = f'{w_delta.id}@{w_delta.last_updated}' |
| 2542 |
|
| 2543 |
if not hasattr(w_delta, 'log_records'): |
| 2544 |
w_delta.log_records = [] |
| 2545 |
|
| 2546 |
w_delta.log_records.append(PbLogRecord(level=level, message=message)) |
| 2547 |
|
| 2548 |
self.updates_pending = True |
| 2549 |
|
| 2550 |
# ----------- |
| 2551 |
# Task Deltas |
| 2552 |
# ----------- |
| 2553 |
def delta_task_state(self, itask: 'TaskProxy') -> None: |
| 2554 |
"""Create delta for change in task proxy state. |
| 2555 |
|
| 2556 |
Args: |
| 2557 |
itask (cylc.flow.task_proxy.TaskProxy): |
| 2558 |
Update task-node from corresponding task proxy |
| 2559 |
objects from the workflow task pool. |
| 2560 |
|
| 2561 |
""" |
| 2562 |
tproxy: Optional[PbTaskProxy] |
| 2563 |
tp_id, tproxy = self.store_node_fetcher(itask.tokens) |
| 2564 |
if not tproxy: |
| 2565 |
return |
| 2566 |
update_time = time() |
| 2567 |
|
| 2568 |
# update task instance |
| 2569 |
tp_delta: PbTaskProxy = self.updated[TASK_PROXIES].setdefault( |
| 2570 |
tp_id, PbTaskProxy(id=tp_id) |
| 2571 |
) |
| 2572 |
tp_delta.stamp = f'{tp_id}@{update_time}' |
| 2573 |
for field in ('is_held', 'is_queued', 'is_runahead'): |
| 2574 |
val = getattr(itask.state, field) |
| 2575 |
if ( |
| 2576 |
# only update the fields that have changed compared to store: |
| 2577 |
getattr(tproxy, field) != val |
| 2578 |
# or changed since earlier delta that is not yet sent: |
| 2579 |
or getattr(tp_delta, field) != val |
| 2580 |
): |
| 2581 |
setattr(tp_delta, field, val) |
| 2582 |
if ( |
| 2583 |
tproxy.state != itask.state.status |
| 2584 |
or tp_delta.state != itask.state.status |
| 2585 |
): |
| 2586 |
tp_delta.state = itask.state.status |
| 2587 |
if tp_delta.state in self.latest_state_tasks: |
| 2588 |
tp_ref = itask.identity |
| 2589 |
tp_queue = self.latest_state_tasks[tp_delta.state] |
| 2590 |
if tp_ref in tp_queue: |
| 2591 |
tp_queue.remove(tp_ref) |
| 2592 |
self.latest_state_tasks[tp_delta.state].appendleft(tp_ref) |
| 2593 |
# if state is final work out new task mean. |
| 2594 |
if tp_delta.state in TASK_STATUSES_FINAL: |
| 2595 |
elapsed_time = task_mean_elapsed_time(itask.tdef) |
| 2596 |
if elapsed_time: |
| 2597 |
t_id = self.definition_id(tproxy.name) |
| 2598 |
t_delta = PbTask( |
| 2599 |
stamp=f'{t_id}@{update_time}', |
| 2600 |
mean_elapsed_time=elapsed_time |
| 2601 |
) |
| 2602 |
self.updated[TASKS].setdefault( |
| 2603 |
t_id, |
| 2604 |
PbTask(id=t_id)).MergeFrom(t_delta) |
| 2605 |
self.state_update_families.add(tproxy.first_parent) |
| 2606 |
self.updates_pending = True |
| 2607 |
|
| 2608 |
def delta_task_held( |
| 2609 |
self, name: str, cycle: 'PointBase', is_held: bool |
| 2610 |
) -> None: |
| 2611 |
"""Create delta for change in task proxy held state. |
| 2612 |
|
| 2613 |
Args: |
| 2614 |
itask: |
| 2615 |
The TaskProxy to hold/release OR a tuple of the form |
| 2616 |
(name, cycle, is_held). |
| 2617 |
|
| 2618 |
""" |
| 2619 |
tokens = self.id_.duplicate( |
| 2620 |
task=name, |
| 2621 |
cycle=str(cycle), |
| 2622 |
) |
| 2623 |
tproxy: Optional[PbTaskProxy] |
| 2624 |
tp_id, tproxy = self.store_node_fetcher(tokens) |
| 2625 |
if not tproxy: |
| 2626 |
return |
| 2627 |
tp_delta = self.updated[TASK_PROXIES].setdefault( |
| 2628 |
tp_id, PbTaskProxy(id=tp_id)) |
| 2629 |
tp_delta.stamp = f'{tp_id}@{time()}' |
| 2630 |
tp_delta.is_held = is_held |
| 2631 |
self.state_update_families.add(tproxy.first_parent) |
| 2632 |
self.updates_pending = True |
| 2633 |
|
| 2634 |
def delta_task_flow_nums(self, itask: TaskProxy) -> None: |
| 2635 |
"""Create delta for change in task proxy flow numbers. |
| 2636 |
|
| 2637 |
Args: |
| 2638 |
itask: TaskProxy with updated flow numbers. |
| 2639 |
""" |
| 2640 |
tproxy: Optional[PbTaskProxy] |
| 2641 |
tp_id, tproxy = self.store_node_fetcher(itask.tokens) |
| 2642 |
if not tproxy: |
| 2643 |
return |
| 2644 |
self._delta_task_flow_nums(tp_id, itask.flow_nums) |
| 2645 |
|
| 2646 |
def delta_remove_task_flow_nums( |
| 2647 |
self, task: str, removed: 'FlowNums' |
| 2648 |
) -> None: |
| 2649 |
"""Create delta for removal of flow numbers from a task proxy. |
| 2650 |
|
| 2651 |
Args: |
| 2652 |
task: Relative ID of task. |
| 2653 |
removed: Flow numbers to remove from the task proxy in the |
| 2654 |
data store. |
| 2655 |
""" |
| 2656 |
tproxy: Optional[PbTaskProxy] |
| 2657 |
tp_id, tproxy = self.store_node_fetcher( |
| 2658 |
Tokens(task, relative=True).duplicate(**self.id_) |
| 2659 |
) |
| 2660 |
if not tproxy: |
| 2661 |
return |
| 2662 |
new_flow_nums = deserialise_set(tproxy.flow_nums).difference(removed) |
| 2663 |
self._delta_task_flow_nums(tp_id, new_flow_nums) |
| 2664 |
|
| 2665 |
def _delta_task_flow_nums(self, tp_id: str, flow_nums: 'FlowNums') -> None: |
| 2666 |
tp_delta: PbTaskProxy = self.updated[TASK_PROXIES].setdefault( |
| 2667 |
tp_id, PbTaskProxy(id=tp_id) |
| 2668 |
) |
| 2669 |
tp_delta.stamp = f'{tp_id}@{time()}' |
| 2670 |
tp_delta.flow_nums = serialise_set(flow_nums) |
| 2671 |
self.updates_pending = True |
| 2672 |
|
| 2673 |
def delta_task_output( |
| 2674 |
self, |
| 2675 |
itask: TaskProxy, |
| 2676 |
message: str, |
| 2677 |
) -> None: |
| 2678 |
"""Create delta for change in task proxy output. |
| 2679 |
|
| 2680 |
Args: |
| 2681 |
itask (cylc.flow.task_proxy.TaskProxy): |
| 2682 |
Update task-node from corresponding task proxy |
| 2683 |
objects from the workflow task pool. |
| 2684 |
|
| 2685 |
""" |
| 2686 |
# TODO: Restore incremental update when we have a protocol to do so |
| 2687 |
# https://github.com/cylc/cylc-flow/issues/6307 |
| 2688 |
return self.delta_task_outputs(itask) |
| 2689 |
|
| 2690 |
# tproxy: Optional[PbTaskProxy] |
| 2691 |
# tp_id, tproxy = self.store_node_fetcher(itask.tokens) |
| 2692 |
# if not tproxy: |
| 2693 |
# return |
| 2694 |
# outputs = itask.state.outputs |
| 2695 |
# label = outputs.get_trigger(message) |
| 2696 |
# # update task instance |
| 2697 |
# update_time = time() |
| 2698 |
# tp_delta = self.updated[TASK_PROXIES].setdefault( |
| 2699 |
# tp_id, PbTaskProxy(id=tp_id)) |
| 2700 |
# tp_delta.stamp = f'{tp_id}@{update_time}' |
| 2701 |
# output = tp_delta.outputs[label] |
| 2702 |
# output.label = label |
| 2703 |
# output.message = message |
| 2704 |
# output.satisfied = outputs.is_message_complete(message) |
| 2705 |
# output.time = update_time |
| 2706 |
# self.updates_pending = True |
| 2707 |
|
| 2708 |
def delta_task_outputs(self, itask: TaskProxy) -> None: |
| 2709 |
"""Create delta for change in all task proxy outputs. |
| 2710 |
|
| 2711 |
Args: |
| 2712 |
itask (cylc.flow.task_proxy.TaskProxy): |
| 2713 |
Update task-node from corresponding task proxy |
| 2714 |
objects from the workflow task pool. |
| 2715 |
|
| 2716 |
""" |
| 2717 |
tproxy: Optional[PbTaskProxy] |
| 2718 |
tp_id, tproxy = self.store_node_fetcher(itask.tokens) |
| 2719 |
if not tproxy: |
| 2720 |
return |
| 2721 |
update_time = time() |
| 2722 |
tp_delta = self.updated[TASK_PROXIES].setdefault( |
| 2723 |
tp_id, PbTaskProxy(id=tp_id)) |
| 2724 |
tp_delta.stamp = f'{tp_id}@{update_time}' |
| 2725 |
for trigger, message, satisfied in itask.state.outputs: |
| 2726 |
output = tp_delta.outputs[trigger] |
| 2727 |
output.label = trigger |
| 2728 |
output.message = message |
| 2729 |
output.satisfied = satisfied |
| 2730 |
output.time = update_time |
| 2731 |
|
| 2732 |
self.updates_pending = True |
| 2733 |
|
| 2734 |
def delta_task_prerequisite(self, itask: TaskProxy) -> None: |
| 2735 |
"""Create delta for change in task proxy prerequisite. |
| 2736 |
|
| 2737 |
Args: |
| 2738 |
itask (cylc.flow.task_proxy.TaskProxy): |
| 2739 |
Update task-node from corresponding task proxy |
| 2740 |
objects from the workflow task pool. |
| 2741 |
|
| 2742 |
""" |
| 2743 |
tproxy: Optional[PbTaskProxy] |
| 2744 |
tp_id, tproxy = self.store_node_fetcher(itask.tokens) |
| 2745 |
if not tproxy: |
| 2746 |
return |
| 2747 |
update_time = time() |
| 2748 |
|
| 2749 |
tp_delta = self.updated[TASK_PROXIES].setdefault( |
| 2750 |
tp_id, PbTaskProxy(id=tp_id)) |
| 2751 |
tp_delta.stamp = f'{tp_id}@{update_time}' |
| 2752 |
prereq_list = [] |
| 2753 |
for prereq in itask.state.prerequisites: |
| 2754 |
# Protobuf messages populated within |
| 2755 |
prereq_obj = prereq.api_dump() |
| 2756 |
if prereq_obj: |
| 2757 |
prereq_list.append(prereq_obj) |
| 2758 |
del tp_delta.prerequisites[:] |
| 2759 |
tp_delta.prerequisites.extend(prereq_list) |
| 2760 |
self.updates_pending = True |
| 2761 |
|
| 2762 |
def delta_task_ext_trigger( |
| 2763 |
self, itask: TaskProxy, trig: str, message: str, satisfied: bool, |
| 2764 |
) -> None: |
| 2765 |
"""Create delta for change in task proxy external_trigger. |
| 2766 |
|
| 2767 |
Args: |
| 2768 |
itask: |
| 2769 |
Update task-node from corresponding task proxy |
| 2770 |
objects from the workflow task pool. |
| 2771 |
trig: Trigger ID. |
| 2772 |
message: Trigger message. |
| 2773 |
|
| 2774 |
""" |
| 2775 |
tproxy: Optional[PbTaskProxy] |
| 2776 |
tp_id, tproxy = self.store_node_fetcher(itask.tokens) |
| 2777 |
if not tproxy: |
| 2778 |
return |
| 2779 |
# update task instance |
| 2780 |
update_time = time() |
| 2781 |
tp_delta = self.updated[TASK_PROXIES].setdefault( |
| 2782 |
tp_id, PbTaskProxy(id=tp_id)) |
| 2783 |
tp_delta.stamp = f'{tp_id}@{update_time}' |
| 2784 |
ext_trigger = tp_delta.external_triggers[trig] |
| 2785 |
ext_trigger.id = tproxy.external_triggers[trig].id |
| 2786 |
ext_trigger.message = message |
| 2787 |
ext_trigger.satisfied = satisfied |
| 2788 |
ext_trigger.time = update_time |
| 2789 |
self.updates_pending = True |
| 2790 |
|
| 2791 |
@staticmethod |
| 2792 |
def _set_task_xtrigger_modifiers(node_or_delta): |
| 2793 |
# update the xtrigger task modifiers |
| 2794 |
node_or_delta.is_retry = False |
| 2795 |
node_or_delta.is_wallclock = False |
| 2796 |
node_or_delta.is_xtriggered = False |
| 2797 |
for xtrigger in node_or_delta.xtriggers.values(): |
| 2798 |
if xtrigger.satisfied: |
| 2799 |
continue |
| 2800 |
if ( |
| 2801 |
xtrigger.label.startswith('_cylc_retry') |
| 2802 |
or xtrigger.label.startswith('_cylc_submit_retry') |
| 2803 |
): |
| 2804 |
node_or_delta.is_retry = True |
| 2805 |
elif xtrigger.id.startswith('wall_clock'): |
| 2806 |
node_or_delta.is_wallclock = True |
| 2807 |
else: |
| 2808 |
node_or_delta.is_xtriggered = True |
| 2809 |
|
| 2810 |
def _delta_xtrigger( |
| 2811 |
self, |
| 2812 |
tp_id: str, |
| 2813 |
label: str, |
| 2814 |
sig: str, |
| 2815 |
satisfied: bool, |
| 2816 |
update_time: float, |
| 2817 |
) -> None: |
| 2818 |
"""Helper for the two xtrigger delta methods.""" |
| 2819 |
# fetch the task from the store |
| 2820 |
tp_id, tproxy = self.store_node_fetcher(Tokens(tp_id)) |
| 2821 |
if not tproxy: |
| 2822 |
return |
| 2823 |
|
| 2824 |
# create or fetch the updated delta |
| 2825 |
tp_delta = self.updated[TASK_PROXIES].setdefault( |
| 2826 |
tp_id, PbTaskProxy(id=tp_id) |
| 2827 |
) |
| 2828 |
tp_delta.stamp = f'{tp_id}@{update_time}' |
| 2829 |
xid = f'{label}={sig}' |
| 2830 |
|
| 2831 |
# populate all xtriggers on the delta if not already present |
| 2832 |
if not tp_delta.xtriggers: |
| 2833 |
# NOTE: if one xtrigger changes, we must include all in the |
| 2834 |
# delta, see https://github.com/cylc/cylc-flow/issues/6307 |
| 2835 |
for _xid, xtrigger in tproxy.xtriggers.items(): |
| 2836 |
if _xid == xid: |
| 2837 |
# don't copy the xtrigger we are changing |
| 2838 |
continue |
| 2839 |
_xtrigger = tp_delta.xtriggers[_xid] |
| 2840 |
_xtrigger.id = xtrigger.id |
| 2841 |
_xtrigger.label = xtrigger.label |
| 2842 |
_xtrigger.satisfied = xtrigger.satisfied |
| 2843 |
_xtrigger.time = xtrigger.time |
| 2844 |
|
| 2845 |
# modify the xtrigger that has changed |
| 2846 |
xtrigger = tp_delta.xtriggers[xid] |
| 2847 |
xtrigger.id = sig |
| 2848 |
xtrigger.label = label |
| 2849 |
xtrigger.satisfied = satisfied |
| 2850 |
xtrigger.time = update_time |
| 2851 |
|
| 2852 |
# update the xtrigger task modifiers |
| 2853 |
self._set_task_xtrigger_modifiers(tp_delta) |
| 2854 |
|
| 2855 |
# ensure family modifier counts are updated |
| 2856 |
self.state_update_families.add(tproxy.first_parent) |
| 2857 |
|
| 2858 |
self.updates_pending = True |
| 2859 |
|
| 2860 |
def delta_xtrigger(self, sig: str, succeeded: bool) -> None: |
| 2861 |
"""Create delta for xtrigger completion. |
| 2862 |
|
| 2863 |
Args: |
| 2864 |
sig: xtrigger function call signature. |
| 2865 |
succeeded: xtrigger completed successfully or not. |
| 2866 |
|
| 2867 |
""" |
| 2868 |
update_time = time() |
| 2869 |
# update all dependent task instances |
| 2870 |
for tp_id, label in self.xtrigger_tasks.get(sig, set()): |
| 2871 |
self._delta_xtrigger(tp_id, label, sig, succeeded, update_time) |
| 2872 |
|
| 2873 |
def delta_task_xtrigger( |
| 2874 |
self, itask: 'TaskProxy', label: str, sig: str, satisfied: bool |
| 2875 |
) -> None: |
| 2876 |
"""Create delta for a change in xtrigger prerequisite satisfaction. |
| 2877 |
|
| 2878 |
(Xtrigger satisfaction is normally handled by the xtrigger_mgr for all |
| 2879 |
dependent tasks, but "cylc set" can satisfy individual prerequisites). |
| 2880 |
|
| 2881 |
Args: |
| 2882 |
itask: scheduler trask proxy that has changed status. |
| 2883 |
sig: xtrigger function call signature. |
| 2884 |
satisfied: satisfied or not. |
| 2885 |
|
| 2886 |
""" |
| 2887 |
tp_id = self.id_.duplicate( |
| 2888 |
cycle=str(itask.point), |
| 2889 |
task=itask.tdef.name, |
| 2890 |
).id |
| 2891 |
self._delta_xtrigger(tp_id, label, sig, satisfied, time()) |
| 2892 |
|
| 2893 |
def delta_from_task_proxy(self, itask: TaskProxy) -> None: |
| 2894 |
"""Create delta from existing pool task proxy. |
| 2895 |
|
| 2896 |
Args: |
| 2897 |
itask (cylc.flow.task_proxy.TaskProxy): |
| 2898 |
Update task-node from corresponding task proxy |
| 2899 |
objects from the workflow task pool. |
| 2900 |
|
| 2901 |
""" |
| 2902 |
tproxy: Optional[PbTaskProxy] |
| 2903 |
tp_id, tproxy = self.store_node_fetcher(itask.tokens) |
| 2904 |
if not tproxy: |
| 2905 |
return |
| 2906 |
update_time = time() |
| 2907 |
tp_delta = self.updated[TASK_PROXIES].setdefault( |
| 2908 |
tp_id, PbTaskProxy(id=tp_id)) |
| 2909 |
tp_delta.stamp = f'{tp_id}@{update_time}' |
| 2910 |
self._process_internal_task_proxy(itask, tp_delta) |
| 2911 |
self.updates_pending = True |
| 2912 |
|
| 2913 |
# ----------- |
| 2914 |
# Job Deltas |
| 2915 |
# ----------- |
| 2916 |
def delta_job_msg(self, tokens: Tokens, msg: str) -> bool: |
| 2917 |
"""Add message to job. |
| 2918 |
|
| 2919 |
Returns False if the job was not found in the data store. |
| 2920 |
""" |
| 2921 |
j_id, job = self.store_node_fetcher(tokens) |
| 2922 |
if not job: |
| 2923 |
return False |
| 2924 |
j_delta = self.updated[JOBS].setdefault( |
| 2925 |
j_id, |
| 2926 |
PbJob(id=j_id) |
| 2927 |
) |
| 2928 |
j_delta.stamp = f'{j_id}@{time()}' |
| 2929 |
# in case existing delta has not been processed |
| 2930 |
if j_delta.messages: |
| 2931 |
j_delta.messages.append(msg) |
| 2932 |
else: |
| 2933 |
j_delta.messages[:] = job.messages |
| 2934 |
j_delta.messages.append(msg) |
| 2935 |
self.updates_pending = True |
| 2936 |
return True |
| 2937 |
|
| 2938 |
def delta_job_attr( |
| 2939 |
self, |
| 2940 |
itask: 'TaskProxy', |
| 2941 |
attr_key: str, |
| 2942 |
attr_val: Any, |
| 2943 |
) -> None: |
| 2944 |
"""Set job attribute.""" |
| 2945 |
j_id, job = self.store_node_fetcher(itask.job_tokens) |
| 2946 |
if not job: |
| 2947 |
return |
| 2948 |
j_delta = PbJob(stamp=f'{j_id}@{time()}') |
| 2949 |
setbuff(j_delta, attr_key, attr_val) |
| 2950 |
self.updated[JOBS].setdefault( |
| 2951 |
j_id, |
| 2952 |
PbJob(id=j_id) |
| 2953 |
).MergeFrom(j_delta) |
| 2954 |
self.updates_pending = True |
| 2955 |
|
| 2956 |
def delta_job_state( |
| 2957 |
self, |
| 2958 |
itask: 'TaskProxy', |
| 2959 |
status: str, |
| 2960 |
) -> None: |
| 2961 |
"""Set job state.""" |
| 2962 |
if status not in JOB_STATUS_SET: |
| 2963 |
# Ignore task-only states e.g. preparing |
| 2964 |
return |
| 2965 |
j_id, job = self.store_node_fetcher(itask.job_tokens) |
| 2966 |
if not job or ( |
| 2967 |
# Don't cause backwards state change: |
| 2968 |
JOB_STATUSES_ALL.index(status) <= JOB_STATUSES_ALL.index(job.state) |
| 2969 |
and not itask.job_vacated |
| 2970 |
): |
| 2971 |
return |
| 2972 |
j_delta = PbJob( |
| 2973 |
stamp=f'{j_id}@{time()}', |
| 2974 |
state=status |
| 2975 |
) |
| 2976 |
self.updated[JOBS].setdefault( |
| 2977 |
j_id, |
| 2978 |
PbJob(id=j_id) |
| 2979 |
).MergeFrom(j_delta) |
| 2980 |
self.updates_pending = True |
| 2981 |
|
| 2982 |
def delta_job_time( |
| 2983 |
self, |
| 2984 |
itask: 'TaskProxy', |
| 2985 |
event_key: Literal['submitted', 'started', 'finished'], |
| 2986 |
time_str: str, |
| 2987 |
) -> None: |
| 2988 |
"""Set an event time in job pool object.""" |
| 2989 |
j_id, job = self.store_node_fetcher(itask.job_tokens) |
| 2990 |
if not job: |
| 2991 |
return |
| 2992 |
j_delta = PbJob(stamp=f'{j_id}@{time()}') |
| 2993 |
time_attr = f'{event_key}_time' |
| 2994 |
setbuff(j_delta, time_attr, time_str) |
| 2995 |
if ( |
| 2996 |
event_key == 'started' |
| 2997 |
and (run_time := task_mean_elapsed_time(itask.tdef)) is not None |
| 2998 |
): |
| 2999 |
j_delta.estimated_finish_time = ( |
| 3000 |
time2str(str2time(time_str) + run_time) if time_str else '' |
| 3001 |
) |
| 3002 |
self.updated[JOBS].setdefault( |
| 3003 |
j_id, |
| 3004 |
PbJob(id=j_id) |
| 3005 |
).MergeFrom(j_delta) |
| 3006 |
self.updates_pending = True |
| 3007 |
|
| 3008 |
def store_node_fetcher(self, tokens: Tokens) -> Tuple[str, Any]: |
| 3009 |
"""Check that task proxy is in or being added to the store""" |
| 3010 |
node_type = { |
| 3011 |
'task': TASK_PROXIES, |
| 3012 |
'job': JOBS, |
| 3013 |
}[tokens.lowest_token] |
| 3014 |
node_id = tokens.id |
| 3015 |
if node_id in self.added[node_type]: |
| 3016 |
return (node_id, self.added[node_type][node_id]) |
| 3017 |
elif node_id in self.data[self.workflow_id][node_type]: |
| 3018 |
return (node_id, self.data[self.workflow_id][node_type][node_id]) |
| 3019 |
return (node_id, False) |
| 3020 |
|
| 3021 |
def batch_deltas(self, reloaded=False): |
| 3022 |
"""Batch gathered deltas.""" |
| 3023 |
# Gather cumulative update element |
| 3024 |
if reloaded: |
| 3025 |
self.gather_delta_elements(self.data[self.workflow_id], 'added') |
| 3026 |
else: |
| 3027 |
self.gather_delta_elements(self.added, 'added') |
| 3028 |
self.gather_delta_elements(self.updated, 'updated') |
| 3029 |
|
| 3030 |
# set reloaded flag on deltas |
| 3031 |
for delta in self.deltas.values(): |
| 3032 |
if delta.ListFields() or reloaded: |
| 3033 |
delta.reloaded = reloaded |
| 3034 |
|
| 3035 |
def gather_delta_elements(self, store, delta_type): |
| 3036 |
"""Gather deltas from store.""" |
| 3037 |
for key, elements in store.items(): |
| 3038 |
if elements: |
| 3039 |
if key == WORKFLOW: |
| 3040 |
if elements.ListFields(): |
| 3041 |
getattr(self.deltas[WORKFLOW], delta_type).CopyFrom( |
| 3042 |
elements) |
| 3043 |
continue |
| 3044 |
getattr(self.deltas[key], delta_type).extend(elements.values()) |
| 3045 |
|
| 3046 |
def apply_delta_batch(self): |
| 3047 |
"""Apply delta batch to local data-store.""" |
| 3048 |
data = self.data[self.workflow_id] |
| 3049 |
for key, delta in self.deltas.items(): |
| 3050 |
if delta.ListFields(): |
| 3051 |
apply_delta(key, delta, data) |
| 3052 |
|
| 3053 |
def apply_delta_checksum(self): |
| 3054 |
"""Construct checksum on deltas for export.""" |
| 3055 |
data = self.data[self.workflow_id] |
| 3056 |
update_time = time() |
| 3057 |
for key, delta in self.deltas.items(): |
| 3058 |
if delta.ListFields(): |
| 3059 |
delta.time = update_time |
| 3060 |
if hasattr(delta, 'checksum'): |
| 3061 |
if key == EDGES: |
| 3062 |
s_att = 'id' |
| 3063 |
else: |
| 3064 |
s_att = 'stamp' |
| 3065 |
delta.checksum = generate_checksum( |
| 3066 |
[getattr(e, s_att) |
| 3067 |
for e in data[key].values()] |
| 3068 |
) |
| 3069 |
|
| 3070 |
def clear_delta_batch(self): |
| 3071 |
"""Clear current deltas.""" |
| 3072 |
# Potential shared reference, avoid clearing |
| 3073 |
self.deltas = { |
| 3074 |
EDGES: EDeltas(), |
| 3075 |
FAMILIES: FDeltas(), |
| 3076 |
FAMILY_PROXIES: FPDeltas(), |
| 3077 |
JOBS: JDeltas(), |
| 3078 |
TASKS: TDeltas(), |
| 3079 |
TASK_PROXIES: TPDeltas(), |
| 3080 |
WORKFLOW: WDeltas(), |
| 3081 |
} |
| 3082 |
|
| 3083 |
def clear_delta_store(self): |
| 3084 |
"""Clear current delta store.""" |
| 3085 |
# Potential shared reference, avoid clearing |
| 3086 |
self.added = deepcopy(DATA_TEMPLATE) |
| 3087 |
self.updated = deepcopy(DATA_TEMPLATE) |
| 3088 |
|
| 3089 |
# Message collation and dissemination methods: |
| 3090 |
def get_entire_workflow(self): |
| 3091 |
"""Gather data elements into single Protobuf message. |
| 3092 |
|
| 3093 |
Returns: |
| 3094 |
cylc.flow.data_messages_pb2.PbEntireWorkflow |
| 3095 |
|
| 3096 |
""" |
| 3097 |
|
| 3098 |
data = self.data[self.workflow_id] |
| 3099 |
|
| 3100 |
workflow_msg = PbEntireWorkflow() |
| 3101 |
workflow_msg.workflow.CopyFrom(data[WORKFLOW]) |
| 3102 |
workflow_msg.tasks.extend(data[TASKS].values()) |
| 3103 |
workflow_msg.task_proxies.extend(data[TASK_PROXIES].values()) |
| 3104 |
workflow_msg.jobs.extend(data[JOBS].values()) |
| 3105 |
workflow_msg.families.extend(data[FAMILIES].values()) |
| 3106 |
workflow_msg.family_proxies.extend(data[FAMILY_PROXIES].values()) |
| 3107 |
workflow_msg.edges.extend(data[EDGES].values()) |
| 3108 |
|
| 3109 |
return workflow_msg |
| 3110 |
|
| 3111 |
def get_publish_deltas(self): |
| 3112 |
"""Return deltas for publishing.""" |
| 3113 |
all_deltas = DELTAS_MAP[ALL_DELTAS]() |
| 3114 |
result = [] |
| 3115 |
for key, delta in self.deltas.items(): |
| 3116 |
if delta.ListFields(): |
| 3117 |
result.append( |
| 3118 |
(key.encode('utf-8'), delta, 'SerializeToString')) |
| 3119 |
getattr(all_deltas, key).CopyFrom(delta) |
| 3120 |
result.append( |
| 3121 |
(ALL_DELTAS.encode('utf-8'), all_deltas, 'SerializeToString') |
| 3122 |
) |
| 3123 |
self.publish_pending = True |
| 3124 |
return deepcopy(result) |
| 3125 |
|
| 3126 |
def get_data_elements(self, element_type): |
| 3127 |
"""Get elements of a given type in the form of a delta. |
| 3128 |
|
| 3129 |
Args: |
| 3130 |
element_type (str): |
| 3131 |
Key from DELTAS_MAP dictionary. |
| 3132 |
|
| 3133 |
Returns: |
| 3134 |
object |
| 3135 |
protobuf (DELTAS_MAP[element_type]) message. |
| 3136 |
|
| 3137 |
""" |
| 3138 |
if element_type not in DELTAS_MAP: |
| 3139 |
return DELTAS_MAP[WORKFLOW]() |
| 3140 |
data = self.data[self.workflow_id] |
| 3141 |
pb_msg = DELTAS_MAP[element_type]() |
| 3142 |
pb_msg.time = data[WORKFLOW].last_updated |
| 3143 |
if element_type == WORKFLOW: |
| 3144 |
pb_msg.added.CopyFrom(data[WORKFLOW]) |
| 3145 |
else: |
| 3146 |
pb_msg.added.extend(data[element_type].values()) |
| 3147 |
return pb_msg |
| 3148 |
|
| 3149 |
def definition_id(self, namespace: str) -> str: |
| 3150 |
return self.id_.duplicate(cycle=f'$namespace|{namespace}').id |
| 3151 |
|
| 3152 |
def edge_id(self, left_tokens: Tokens, right_tokens: Tokens) -> str: |
| 3153 |
return self.id_.duplicate( |
| 3154 |
cycle=( |
| 3155 |
f'$edge|{left_tokens.relative_id}|{right_tokens.relative_id}' |
| 3156 |
) |
| 3157 |
).id |