| 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 |
|
| 17 |
"""GraphQL resolvers for use in data accessing and mutation of workflows.""" |
| 18 |
|
| 19 |
from abc import ABCMeta, abstractmethod |
| 20 |
import asyncio |
| 21 |
from contextlib import suppress |
| 22 |
from fnmatch import fnmatchcase |
| 23 |
import logging |
| 24 |
import queue |
| 25 |
from time import time |
| 26 |
from typing import ( |
| 27 |
Any, |
| 28 |
AsyncGenerator, |
| 29 |
Dict, |
| 30 |
List, |
| 31 |
NamedTuple, |
| 32 |
Optional, |
| 33 |
Tuple, |
| 34 |
TYPE_CHECKING, |
| 35 |
cast, |
| 36 |
) |
| 37 |
from uuid import uuid4 |
| 38 |
|
| 39 |
from graphene.utils.str_converters import to_snake_case |
| 40 |
|
| 41 |
from cylc.flow import LOG |
| 42 |
from cylc.flow.commands import COMMANDS |
| 43 |
from cylc.flow.data_store_mgr import ( |
| 44 |
EDGES, FAMILY_PROXIES, TASK_PROXIES, WORKFLOW, |
| 45 |
DELTA_ADDED, create_delta_store |
| 46 |
) |
| 47 |
import cylc.flow.flags |
| 48 |
from cylc.flow.id import Tokens |
| 49 |
from cylc.flow.network.schema import ( |
| 50 |
DEF_TYPES, |
| 51 |
NodesEdges, |
| 52 |
PROXY_NODES, |
| 53 |
SUB_RESOLVERS, |
| 54 |
runtime_schema_to_cfg, |
| 55 |
sort_elements, |
| 56 |
) |
| 57 |
from cylc.flow.util import uniq, iter_uniq |
| 58 |
|
| 59 |
if TYPE_CHECKING: |
| 60 |
from enum import Enum |
| 61 |
from uuid import UUID |
| 62 |
from graphql import GraphQLResolveInfo |
| 63 |
from cylc.flow.data_store_mgr import DataStoreMgr |
| 64 |
from cylc.flow.scheduler import Scheduler |
| 65 |
|
| 66 |
DeltaQueue = queue.Queue[Tuple[str, str, dict]] |
| 67 |
|
| 68 |
|
| 69 |
class TaskMsg(NamedTuple): |
| 70 |
"""Tuple for Scheduler.message_queue""" |
| 71 |
job_id: Tokens |
| 72 |
event_time: str |
| 73 |
severity: str | int |
| 74 |
message: str |
| 75 |
|
| 76 |
|
| 77 |
logger = logging.getLogger(__name__) |
| 78 |
|
| 79 |
DELTA_SLEEP_INTERVAL = 0.5 |
| 80 |
# Delay before carrying on with the next delta, |
| 81 |
# roughly DELTA_PROC_WAIT*DELTA_SLEEP_INTERVAL seconds (if queue is empty). |
| 82 |
DELTA_PROC_WAIT = 10 |
| 83 |
|
| 84 |
|
| 85 |
def filter_none(dictionary): |
| 86 |
"""Filter out `None` items from a dictionary: |
| 87 |
|
| 88 |
Examples: |
| 89 |
>>> filter_none({ |
| 90 |
... 'a': 0, |
| 91 |
... 'b': '', |
| 92 |
... 'c': None |
| 93 |
... }) |
| 94 |
{'a': 0, 'b': ''} |
| 95 |
|
| 96 |
""" |
| 97 |
return { |
| 98 |
key: value |
| 99 |
for key, value in dictionary.items() |
| 100 |
if value is not None |
| 101 |
} |
| 102 |
|
| 103 |
|
| 104 |
# Message Filters |
| 105 |
def collate_workflow_atts(workflow): |
| 106 |
"""Collate workflow filter attributes, setting defaults if non-existent.""" |
| 107 |
# Append new atts to the end of the list, |
| 108 |
# this will retain order used in index access. |
| 109 |
return { |
| 110 |
'user': workflow.owner, |
| 111 |
'workflow': workflow.name, |
| 112 |
'workflow_sel': workflow.status, |
| 113 |
} |
| 114 |
|
| 115 |
|
| 116 |
def workflow_ids_filter(workflow_tokens, items) -> bool: |
| 117 |
"""Match id arguments with workflow attributes. |
| 118 |
|
| 119 |
Return True if workflow matches any id arg. |
| 120 |
""" |
| 121 |
return any( |
| 122 |
( |
| 123 |
( |
| 124 |
not item['user'] |
| 125 |
or fnmatchcase(workflow_tokens['user'], item['user']) |
| 126 |
) |
| 127 |
and ( |
| 128 |
not item['workflow'] |
| 129 |
or fnmatchcase(workflow_tokens['workflow'], item['workflow']) |
| 130 |
) |
| 131 |
and ( |
| 132 |
not item['workflow_sel'] |
| 133 |
or workflow_tokens['workflow_sel'] == item['workflow_sel'] |
| 134 |
) |
| 135 |
) |
| 136 |
for item in uniq(items) |
| 137 |
) |
| 138 |
|
| 139 |
|
| 140 |
def workflow_filter(flow, args, w_atts=None) -> bool: |
| 141 |
"""Filter workflows based on attribute arguments""" |
| 142 |
if w_atts is None: |
| 143 |
w_atts = collate_workflow_atts(flow[WORKFLOW]) |
| 144 |
# The w_atts (workflow attributes) list contains ordered workflow values |
| 145 |
# or defaults (see collate function for index item). |
| 146 |
return ( |
| 147 |
( |
| 148 |
not args.get('workflows') |
| 149 |
or workflow_ids_filter(w_atts, args['workflows']) |
| 150 |
) |
| 151 |
and not ( |
| 152 |
args.get('exworkflows') |
| 153 |
and workflow_ids_filter(w_atts, args['exworkflows']) |
| 154 |
) |
| 155 |
) |
| 156 |
|
| 157 |
|
| 158 |
def get_state_from_selectors(tokens): |
| 159 |
"""Return the highest defined selector in the provided tokens or None. |
| 160 |
|
| 161 |
TODO: |
| 162 |
This is a temporary workaround, the filters here should acquire |
| 163 |
full selector capability in due course. |
| 164 |
|
| 165 |
""" |
| 166 |
for selector in 'cycle_sel', 'task_sel', 'job_sel': |
| 167 |
if tokens.get(selector): |
| 168 |
return tokens[selector] |
| 169 |
|
| 170 |
|
| 171 |
def node_ids_filter(tokens, state, items) -> bool: |
| 172 |
"""Match id arguments with node attributes.""" |
| 173 |
return any( |
| 174 |
( |
| 175 |
# don't match an empty string (globs should be implicit) |
| 176 |
not item.is_null |
| 177 |
# match cycle point |
| 178 |
and ( |
| 179 |
not item['cycle'] |
| 180 |
or fnmatchcase(tokens['cycle'], item['cycle']) |
| 181 |
) |
| 182 |
# match namespace name |
| 183 |
and ( |
| 184 |
not item['task'] |
| 185 |
or fnmatchcase(tokens['task'], item['task']) |
| 186 |
) |
| 187 |
# match job |
| 188 |
and ( |
| 189 |
not item['job'] |
| 190 |
or fnmatchcase(tokens['job'], item['job']) |
| 191 |
) |
| 192 |
# match cycle/task/job state |
| 193 |
and ( |
| 194 |
not ( |
| 195 |
state is not None |
| 196 |
and get_state_from_selectors(item) |
| 197 |
) |
| 198 |
or get_state_from_selectors(item) == state |
| 199 |
) |
| 200 |
) |
| 201 |
for item in iter_uniq(items) |
| 202 |
) |
| 203 |
|
| 204 |
|
| 205 |
def node_filter(node, node_type, args, state): |
| 206 |
"""Filter nodes based on attribute arguments. |
| 207 |
|
| 208 |
Args: |
| 209 |
node: The node to filter (from the data or delta store). |
| 210 |
node_type: The type of the node being filtered. |
| 211 |
args: The query arguments. |
| 212 |
state: The state of the node that is being filtered. |
| 213 |
Note: can be None for non-tasks e.g. task definitions where |
| 214 |
state filtering does not apply. |
| 215 |
|
| 216 |
""" |
| 217 |
tokens: Tokens |
| 218 |
if node_type in DEF_TYPES: |
| 219 |
# namespace nodes don't fit into the universal ID scheme so must |
| 220 |
# be tokenised manually |
| 221 |
tokens = Tokens( |
| 222 |
cycle=None, |
| 223 |
task=node.name, |
| 224 |
job=None, |
| 225 |
) |
| 226 |
else: |
| 227 |
# live objects can be represented by a universal ID |
| 228 |
tokens = Tokens(node.id) |
| 229 |
return ( |
| 230 |
( |
| 231 |
( |
| 232 |
state is None |
| 233 |
or not args.get('states') |
| 234 |
) |
| 235 |
or state in args['states'] |
| 236 |
) |
| 237 |
and ( |
| 238 |
not args.get('exstates') |
| 239 |
or state not in args['exstates'] |
| 240 |
) |
| 241 |
and ( |
| 242 |
args.get('is_held') is None |
| 243 |
or (node.is_held == args['is_held']) |
| 244 |
) |
| 245 |
and ( |
| 246 |
args.get('is_queued') is None |
| 247 |
or (node.is_queued == args['is_queued']) |
| 248 |
) |
| 249 |
and ( |
| 250 |
args.get('mindepth', -1) < 0 |
| 251 |
or node.depth >= args['mindepth'] |
| 252 |
) |
| 253 |
and ( |
| 254 |
args.get('maxdepth', -1) < 0 |
| 255 |
or node.depth <= args['maxdepth'] |
| 256 |
) |
| 257 |
and ( |
| 258 |
args.get('graph_depth', -1) < 0 |
| 259 |
or node.graph_depth <= args['graph_depth'] |
| 260 |
) |
| 261 |
# Now filter node against id arg lists |
| 262 |
and ( |
| 263 |
not args.get('ids') |
| 264 |
or node_ids_filter(tokens, state, args['ids']) |
| 265 |
) |
| 266 |
and ( |
| 267 |
not args.get('exids') |
| 268 |
or not node_ids_filter(tokens, state, args['exids']) |
| 269 |
) |
| 270 |
) |
| 271 |
|
| 272 |
|
| 273 |
def get_flow_data_from_ids(data_store, native_ids): |
| 274 |
"""Return workflow data by id.""" |
| 275 |
w_ids = [] |
| 276 |
for native_id in native_ids: |
| 277 |
w_ids.append( |
| 278 |
Tokens(native_id).workflow_id |
| 279 |
) |
| 280 |
return [ |
| 281 |
data_store[w_id] |
| 282 |
for w_id in iter_uniq(w_ids) |
| 283 |
if w_id in data_store |
| 284 |
] |
| 285 |
|
| 286 |
|
| 287 |
def get_data_elements(flow, nat_ids, element_type): |
| 288 |
"""Return data elements by id.""" |
| 289 |
flow_element = flow[element_type] |
| 290 |
return [ |
| 291 |
flow_element[n_id] |
| 292 |
for n_id in nat_ids |
| 293 |
if n_id in flow_element |
| 294 |
] |
| 295 |
|
| 296 |
|
| 297 |
class BaseResolvers(metaclass=ABCMeta): # noqa: SIM119 |
| 298 |
"""Data access methods for resolving GraphQL queries.""" |
| 299 |
|
| 300 |
def __init__(self, data_store_mgr: 'DataStoreMgr'): |
| 301 |
self.data_store_mgr = data_store_mgr |
| 302 |
# Used with subscriptions for a temporary delta-store, |
| 303 |
# [sub_id][w_id] = store |
| 304 |
self.delta_store: Dict['UUID', Dict[str, dict]] = {} |
| 305 |
# Used to serialised deltas from a single workflow, needed for |
| 306 |
# the management of a common data object. |
| 307 |
self.delta_processing_flows: Dict['UUID', set] = {} |
| 308 |
|
| 309 |
# Query resolvers |
| 310 |
async def get_workflow_by_id(self, args): |
| 311 |
"""Return a workflow store by ID.""" |
| 312 |
try: |
| 313 |
if 'sub_id' in args and args['delta_store']: |
| 314 |
return self.delta_store[args['sub_id']][args['id']][ |
| 315 |
args['delta_type']][WORKFLOW] |
| 316 |
return self.data_store_mgr.data[args['id']][WORKFLOW] |
| 317 |
except KeyError: |
| 318 |
return None |
| 319 |
|
| 320 |
async def get_workflows_data(self, args: Dict[str, Any]): |
| 321 |
"""Return list of data from workflows.""" |
| 322 |
# Both cases just as common so 'if' not 'try' |
| 323 |
if 'sub_id' in args and args['delta_store']: |
| 324 |
return [ |
| 325 |
delta[args['delta_type']] |
| 326 |
for key, delta in self.delta_store[args['sub_id']].items() |
| 327 |
if workflow_filter(self.data_store_mgr.data[key], args) |
| 328 |
] |
| 329 |
return [ |
| 330 |
workflow |
| 331 |
for workflow in self.data_store_mgr.data.values() |
| 332 |
if workflow_filter(workflow, args) |
| 333 |
] |
| 334 |
|
| 335 |
async def get_workflows(self, args): |
| 336 |
"""Return workflow elements.""" |
| 337 |
return sort_elements( |
| 338 |
[flow[WORKFLOW] |
| 339 |
for flow in await self.get_workflows_data(args)], |
| 340 |
args) |
| 341 |
|
| 342 |
# nodes |
| 343 |
def get_node_state(self, node, node_type): |
| 344 |
"""Return state, from node or data-store.""" |
| 345 |
if node_type in DEF_TYPES: |
| 346 |
return None |
| 347 |
# NOTE: dont access "state" directly as the attribute might not exist |
| 348 |
with suppress(Exception): |
| 349 |
return ( |
| 350 |
# try to retrieve the state from the node |
| 351 |
# (could be a delta-store node which might not have a state) |
| 352 |
getattr(node, 'state', None) |
| 353 |
# fall back to the data store (because this could be a |
| 354 |
# delta-store node which might not have the state field set) |
| 355 |
or self.data_store_mgr.data[ |
| 356 |
Tokens(node.id).workflow_id |
| 357 |
][node_type][node.id].state |
| 358 |
) |
| 359 |
|
| 360 |
async def get_nodes_all(self, node_type, args): |
| 361 |
"""Return nodes from all workflows, filter by args.""" |
| 362 |
return sort_elements( |
| 363 |
[ |
| 364 |
node |
| 365 |
for flow in await self.get_workflows_data(args) |
| 366 |
for node in flow[node_type].values() |
| 367 |
if node_filter( |
| 368 |
node, |
| 369 |
node_type, |
| 370 |
args, |
| 371 |
self.get_node_state(node, node_type) |
| 372 |
) |
| 373 |
], |
| 374 |
args, |
| 375 |
) |
| 376 |
|
| 377 |
async def get_nodes_by_ids(self, node_type, args): |
| 378 |
"""Return protobuf node objects for given id.""" |
| 379 |
nat_ids = uniq(args.get('native_ids', [])) |
| 380 |
# Both cases just as common so 'if' not 'try' |
| 381 |
if 'sub_id' in args and args['delta_store']: |
| 382 |
flow_data = [ |
| 383 |
delta[args['delta_type']] |
| 384 |
for delta in get_flow_data_from_ids( |
| 385 |
self.delta_store[args['sub_id']], nat_ids) |
| 386 |
] |
| 387 |
else: |
| 388 |
flow_data = get_flow_data_from_ids( |
| 389 |
self.data_store_mgr.data, nat_ids) |
| 390 |
|
| 391 |
if node_type == PROXY_NODES: |
| 392 |
node_types = [TASK_PROXIES, FAMILY_PROXIES] |
| 393 |
else: |
| 394 |
node_types = [node_type] |
| 395 |
return sort_elements( |
| 396 |
[ |
| 397 |
node |
| 398 |
for flow in flow_data |
| 399 |
for node_type in node_types |
| 400 |
for node in get_data_elements(flow, nat_ids, node_type) |
| 401 |
if node_filter( |
| 402 |
node, |
| 403 |
node_type, |
| 404 |
args, |
| 405 |
self.get_node_state(node, node_type) |
| 406 |
) |
| 407 |
], |
| 408 |
args, |
| 409 |
) |
| 410 |
|
| 411 |
async def get_node_by_id(self, node_type, args): |
| 412 |
"""Return protobuf node object for given id.""" |
| 413 |
n_id = args.get('id') |
| 414 |
w_id = Tokens(n_id).workflow_id |
| 415 |
# Both cases just as common so 'if' not 'try' |
| 416 |
try: |
| 417 |
if 'sub_id' in args and args.get('delta_store'): |
| 418 |
flow = self.delta_store[ |
| 419 |
args['sub_id']][w_id][args['delta_type']] |
| 420 |
else: |
| 421 |
flow = self.data_store_mgr.data[w_id] |
| 422 |
except KeyError: |
| 423 |
return None |
| 424 |
if node_type == PROXY_NODES: |
| 425 |
return ( |
| 426 |
flow[TASK_PROXIES].get(n_id) or |
| 427 |
flow[FAMILY_PROXIES].get(n_id)) |
| 428 |
return flow[node_type].get(n_id) |
| 429 |
|
| 430 |
# edges |
| 431 |
async def get_edges_all(self, args): |
| 432 |
"""Return edges from all workflows, filter by args.""" |
| 433 |
return sort_elements( |
| 434 |
[e |
| 435 |
for flow in await self.get_workflows_data(args) |
| 436 |
for e in flow.get(EDGES).values()], |
| 437 |
args) |
| 438 |
|
| 439 |
async def get_edges_by_ids(self, args): |
| 440 |
"""Return protobuf edge objects for given id.""" |
| 441 |
nat_ids = uniq(args.get('native_ids', [])) |
| 442 |
if 'sub_id' in args and args['delta_store']: |
| 443 |
flow_data = [ |
| 444 |
delta[args['delta_type']] |
| 445 |
for delta in get_flow_data_from_ids( |
| 446 |
self.delta_store[args['sub_id']], nat_ids) |
| 447 |
] |
| 448 |
else: |
| 449 |
flow_data = get_flow_data_from_ids( |
| 450 |
self.data_store_mgr.data, nat_ids) |
| 451 |
|
| 452 |
return sort_elements( |
| 453 |
[edge |
| 454 |
for flow in flow_data |
| 455 |
for edge in get_data_elements(flow, nat_ids, EDGES)], |
| 456 |
args) |
| 457 |
|
| 458 |
async def get_nodes_edges(self, root_nodes, args): |
| 459 |
"""Return nodes and edges within a specified distance of root nodes.""" |
| 460 |
# Initial root node selection. |
| 461 |
nodes = root_nodes |
| 462 |
node_ids = {n.id for n in root_nodes} |
| 463 |
edges = [] |
| 464 |
# NOTE: we don't expect edges to be returned in definition order |
| 465 |
# so it is ok to use `set` here |
| 466 |
edge_ids = set() |
| 467 |
# Setup for edgewise search. |
| 468 |
new_nodes = root_nodes |
| 469 |
for _ in range(args['distance']): |
| 470 |
# Gather edges. |
| 471 |
# Edges should be unique (graph not circular), |
| 472 |
# but duplicates will be present as node holds all associated. |
| 473 |
new_edge_ids = { |
| 474 |
e_id |
| 475 |
for n in new_nodes |
| 476 |
for e_id in n.edges |
| 477 |
}.difference(edge_ids) |
| 478 |
edge_ids.update(new_edge_ids) |
| 479 |
new_edges = [ |
| 480 |
edge |
| 481 |
for flow in get_flow_data_from_ids( |
| 482 |
self.data_store_mgr.data, new_edge_ids) |
| 483 |
for edge in get_data_elements(flow, new_edge_ids, EDGES) |
| 484 |
] |
| 485 |
edges += new_edges |
| 486 |
# Gather nodes. |
| 487 |
# One of source or target will be in current set of nodes. |
| 488 |
# NOTE: we don't expect node-edges to be returned in definition |
| 489 |
# order so it is ok to use `set` here |
| 490 |
new_node_ids = set( |
| 491 |
[e.source for e in new_edges] |
| 492 |
+ [e.target for e in new_edges]).difference(node_ids) |
| 493 |
# Stop searching on no new nodes |
| 494 |
if not new_node_ids: |
| 495 |
break |
| 496 |
node_ids.update(new_node_ids) |
| 497 |
new_nodes = [ |
| 498 |
node |
| 499 |
for flow in get_flow_data_from_ids( |
| 500 |
self.data_store_mgr.data, new_node_ids) |
| 501 |
for node in get_data_elements(flow, new_node_ids, TASK_PROXIES) |
| 502 |
] |
| 503 |
nodes += new_nodes |
| 504 |
|
| 505 |
return NodesEdges( |
| 506 |
nodes=sort_elements(nodes, args), |
| 507 |
edges=sort_elements(edges, args)) |
| 508 |
|
| 509 |
async def subscribe_delta( |
| 510 |
self, root, info: 'GraphQLResolveInfo', args |
| 511 |
) -> AsyncGenerator[Any, None]: |
| 512 |
"""Delta subscription async generator. |
| 513 |
|
| 514 |
Async generator mapping the incoming protobuf deltas to |
| 515 |
yielded GraphQL subscription objects. |
| 516 |
|
| 517 |
""" |
| 518 |
# NOTE: we don't expect workflows to be returned in definition order |
| 519 |
# so it is ok to use `set` here |
| 520 |
workflow_ids = set(args.get('workflows', args.get('ids', ()))) |
| 521 |
|
| 522 |
sub_id = uuid4() |
| 523 |
info.context['sub_id'] = sub_id |
| 524 |
self.delta_store[sub_id] = {} |
| 525 |
|
| 526 |
op_id = root |
| 527 |
op_queue: queue.Queue[Tuple[UUID, str]] = queue.Queue() |
| 528 |
cast('dict', info.context).setdefault( |
| 529 |
'ops_queue', {} |
| 530 |
)[op_id] = op_queue |
| 531 |
self.delta_processing_flows[sub_id] = set() |
| 532 |
delta_processing_flows = self.delta_processing_flows[sub_id] |
| 533 |
|
| 534 |
delta_queues = self.data_store_mgr.delta_queues |
| 535 |
deltas_queue: DeltaQueue = queue.Queue() |
| 536 |
|
| 537 |
counters: Dict[str, int] = {} |
| 538 |
delta_yield_queue: DeltaQueue = queue.Queue() |
| 539 |
flow_delta_queues: Dict[str, queue.Queue[Tuple[str, dict]]] = {} |
| 540 |
try: |
| 541 |
# Iterate over the queue yielding deltas |
| 542 |
w_ids = workflow_ids |
| 543 |
sub_resolver = SUB_RESOLVERS.get(to_snake_case(info.field_name)) |
| 544 |
interval = args['ignore_interval'] |
| 545 |
old_time = 0.0 |
| 546 |
while True: |
| 547 |
if not workflow_ids: |
| 548 |
old_ids = w_ids |
| 549 |
# NOTE: we don't expect workflows to be returned in |
| 550 |
# definition order so it is ok to use `set` here |
| 551 |
w_ids = set(delta_queues.keys()) |
| 552 |
for remove_id in old_ids.difference(w_ids): |
| 553 |
if remove_id in self.delta_store[sub_id]: |
| 554 |
del self.delta_store[sub_id][remove_id] |
| 555 |
for w_id in w_ids: |
| 556 |
if w_id in self.data_store_mgr.data: |
| 557 |
if sub_id not in delta_queues[w_id]: |
| 558 |
delta_queues[w_id][sub_id] = deltas_queue |
| 559 |
# On new yield workflow data-store as added delta |
| 560 |
if args.get('initial_burst'): |
| 561 |
delta_store = create_delta_store( |
| 562 |
workflow_id=w_id) |
| 563 |
delta_store[DELTA_ADDED] = ( |
| 564 |
self.data_store_mgr.data[w_id]) |
| 565 |
delta_store[DELTA_ADDED][ |
| 566 |
WORKFLOW |
| 567 |
].reloaded = True |
| 568 |
deltas_queue.put( |
| 569 |
(w_id, 'initial_burst', delta_store)) |
| 570 |
elif w_id in self.delta_store[sub_id]: |
| 571 |
del self.delta_store[sub_id][w_id] |
| 572 |
try: |
| 573 |
with suppress(queue.Empty): |
| 574 |
w_id, topic, delta_store = deltas_queue.get(False) |
| 575 |
|
| 576 |
if w_id not in flow_delta_queues: |
| 577 |
counters[w_id] = 0 |
| 578 |
flow_delta_queues[w_id] = queue.Queue() |
| 579 |
flow_delta_queues[w_id].put((topic, delta_store)) |
| 580 |
|
| 581 |
# Only yield deltas from the same workflow if previous |
| 582 |
# delta has finished processing. |
| 583 |
for flow_id, flow_queue in flow_delta_queues.items(): |
| 584 |
if flow_queue.empty(): |
| 585 |
continue |
| 586 |
elif flow_id in delta_processing_flows: |
| 587 |
if counters[flow_id] < DELTA_PROC_WAIT: |
| 588 |
continue |
| 589 |
delta_processing_flows.remove(flow_id) |
| 590 |
counters[flow_id] = 0 |
| 591 |
topic, delta_store = flow_queue.get() |
| 592 |
delta_yield_queue.put((flow_id, topic, delta_store)) |
| 593 |
|
| 594 |
w_id, topic, delta_store = delta_yield_queue.get(False) |
| 595 |
|
| 596 |
# Handle shutdown delta, don't ignore. |
| 597 |
if topic == 'shutdown': |
| 598 |
delta_store['shutdown'] = True |
| 599 |
else: |
| 600 |
# ignore deltas that are more frequent than interval. |
| 601 |
new_time = time() |
| 602 |
elapsed = new_time - old_time |
| 603 |
if elapsed <= interval: |
| 604 |
continue |
| 605 |
old_time = new_time |
| 606 |
|
| 607 |
delta_processing_flows.add(w_id) |
| 608 |
op_queue.put((sub_id, w_id)) |
| 609 |
self.delta_store[sub_id][w_id] = delta_store |
| 610 |
if sub_resolver is None: |
| 611 |
yield delta_store |
| 612 |
else: |
| 613 |
result = await sub_resolver(root, info, **args) |
| 614 |
if result: |
| 615 |
yield result |
| 616 |
except queue.Empty: |
| 617 |
await asyncio.sleep(DELTA_SLEEP_INTERVAL) |
| 618 |
for flow_id in delta_processing_flows: |
| 619 |
counters[flow_id] += 1 |
| 620 |
except (GeneratorExit, asyncio.CancelledError): |
| 621 |
raise |
| 622 |
except Exception: |
| 623 |
import traceback |
| 624 |
logger.warning(traceback.format_exc()) |
| 625 |
finally: |
| 626 |
for w_id in w_ids: |
| 627 |
if delta_queues.get(w_id, {}).get(sub_id): |
| 628 |
del delta_queues[w_id][sub_id] |
| 629 |
if sub_id in self.delta_store: |
| 630 |
del self.delta_store[sub_id] |
| 631 |
if sub_id in self.delta_processing_flows: |
| 632 |
del self.delta_processing_flows[sub_id] |
| 633 |
yield None |
| 634 |
|
| 635 |
async def flow_delta_processed(self, context, op_id): |
| 636 |
if 'ops_queue' in context: |
| 637 |
with suppress(queue.Empty, KeyError): |
| 638 |
sub_id, w_id = context['ops_queue'][op_id].get(False) |
| 639 |
self.delta_processing_flows[sub_id].remove(w_id) |
| 640 |
|
| 641 |
@abstractmethod |
| 642 |
async def mutator( |
| 643 |
self, |
| 644 |
info: 'GraphQLResolveInfo', |
| 645 |
command: str, |
| 646 |
w_args: Dict[str, Any], |
| 647 |
kwargs: Dict[str, Any], |
| 648 |
meta: Dict[str, Any] |
| 649 |
) -> List[Dict[str, Any]]: |
| 650 |
... |
| 651 |
|
| 652 |
|
| 653 |
class Resolvers(BaseResolvers): |
| 654 |
"""Workflow Service context GraphQL query and mutation resolvers.""" |
| 655 |
|
| 656 |
schd: 'Scheduler' |
| 657 |
|
| 658 |
def __init__(self, data: 'DataStoreMgr', schd: 'Scheduler') -> None: |
| 659 |
super().__init__(data) |
| 660 |
self.schd = schd |
| 661 |
|
| 662 |
# Mutations |
| 663 |
async def mutator( |
| 664 |
self, |
| 665 |
_info: 'GraphQLResolveInfo', |
| 666 |
command: str, |
| 667 |
w_args: Dict[str, Any], |
| 668 |
kwargs: Dict[str, Any], |
| 669 |
meta: Dict[str, Any] |
| 670 |
) -> List[Dict[str, Any]]: |
| 671 |
"""Mutate workflow.""" |
| 672 |
w_ids = [flow[WORKFLOW].id |
| 673 |
for flow in await self.get_workflows_data(w_args)] |
| 674 |
if not w_ids: |
| 675 |
workflows = list(self.data_store_mgr.data.keys()) |
| 676 |
return [{ |
| 677 |
'response': (False, f'No matching workflow in {workflows}')}] |
| 678 |
w_id = w_ids[0] |
| 679 |
# BACK COMPAT: transform "None" to "[]" |
| 680 |
# url: https://github.com/cylc/cylc-flow/pull/6478 |
| 681 |
# from: <8.5.0 |
| 682 |
# to: >=8.5.0 |
| 683 |
# remove at: 8.x |
| 684 |
# For back compat, with gql-v3 None will not use default_value. |
| 685 |
if 'flow' in kwargs: |
| 686 |
kwargs['flow'] = ( |
| 687 |
kwargs['flow'] |
| 688 |
or [] |
| 689 |
) |
| 690 |
result = await self._mutation_mapper(command, kwargs, meta) |
| 691 |
return [{'id': w_id, 'response': result}] |
| 692 |
|
| 693 |
async def _mutation_mapper( |
| 694 |
self, command: str, kwargs: Dict[str, Any], meta: Dict[str, Any] |
| 695 |
) -> Tuple[bool, str]: |
| 696 |
"""Map to internal command interface. |
| 697 |
|
| 698 |
Some direct methods are in this module. |
| 699 |
Others go to the scheduler command queue. |
| 700 |
|
| 701 |
""" |
| 702 |
user = meta.get('auth_user', self.schd.owner) |
| 703 |
if user == self.schd.owner: |
| 704 |
log_user = "" # don't log user name if owner |
| 705 |
else: |
| 706 |
log_user = f" from {user}" |
| 707 |
|
| 708 |
received_msg = f'Command "{command}" received{log_user}.' |
| 709 |
signature_str = ( |
| 710 |
f"{command}(" |
| 711 |
+ ", ".join( |
| 712 |
f"{key}={getattr(value, 'value', value)}" |
| 713 |
for key, value in kwargs.items() |
| 714 |
if value is not None |
| 715 |
) |
| 716 |
+ ")" |
| 717 |
) |
| 718 |
|
| 719 |
method = getattr(self, command, None) |
| 720 |
if method is not None: |
| 721 |
if ( |
| 722 |
command != "put_messages" |
| 723 |
or user != self.schd.owner |
| 724 |
): |
| 725 |
# Logging task messages as commands is overkill. |
| 726 |
LOG.info(f"{received_msg}\n{signature_str}") |
| 727 |
return method(**kwargs) |
| 728 |
|
| 729 |
try: |
| 730 |
meth = COMMANDS[command] |
| 731 |
except KeyError: |
| 732 |
raise ValueError(f"Command '{command}' not found") from None |
| 733 |
|
| 734 |
try: |
| 735 |
# Initiate the command. Validation may be performed at this point, |
| 736 |
# validators may raise Exceptions (preferably InputErrors) to |
| 737 |
# communicate errors. |
| 738 |
cmd = meth(**kwargs, schd=self.schd) |
| 739 |
await cmd.__anext__() |
| 740 |
except Exception as exc: |
| 741 |
# NOTE: keep this exception vague to prevent a bad command taking |
| 742 |
# down the scheduler |
| 743 |
LOG.warning(f'{received_msg}\n{exc.__class__.__name__}: {exc}') |
| 744 |
if cylc.flow.flags.verbosity > 1: |
| 745 |
LOG.exception(exc) # log full traceback in debug mode |
| 746 |
return (False, str(exc)) |
| 747 |
|
| 748 |
# Queue the command to the scheduler, with a unique command ID |
| 749 |
cmd_uuid = str(uuid4()) |
| 750 |
LOG.info(f"{received_msg} ID={cmd_uuid}\n{signature_str}") |
| 751 |
self.schd.command_queue.put( |
| 752 |
( |
| 753 |
cmd_uuid, |
| 754 |
command, |
| 755 |
cmd, |
| 756 |
) |
| 757 |
) |
| 758 |
return (True, cmd_uuid) |
| 759 |
|
| 760 |
def broadcast( |
| 761 |
self, |
| 762 |
mode: 'Enum', |
| 763 |
cycle_points: Optional[List[str]] = None, |
| 764 |
namespaces: Optional[List[str]] = None, |
| 765 |
settings: Optional[List[Dict[str, str]]] = None, |
| 766 |
cutoff: Any = None |
| 767 |
): |
| 768 |
"""Put or clear broadcasts.""" |
| 769 |
try: |
| 770 |
if settings is not None: |
| 771 |
# Convert schema field names to workflow config setting names |
| 772 |
# if applicable: |
| 773 |
for i, dict_ in enumerate(settings): |
| 774 |
settings[i] = runtime_schema_to_cfg(dict_) |
| 775 |
|
| 776 |
if mode.value == 'put_broadcast': |
| 777 |
return self.schd.task_events_mgr.broadcast_mgr.put_broadcast( |
| 778 |
cycle_points, namespaces, settings) |
| 779 |
if mode.value == 'clear_broadcast': |
| 780 |
return self.schd.task_events_mgr.broadcast_mgr.clear_broadcast( |
| 781 |
point_strings=cycle_points, |
| 782 |
namespaces=namespaces, |
| 783 |
cancel_settings=settings) |
| 784 |
if mode.value == 'expire_broadcast': |
| 785 |
return ( |
| 786 |
self.schd.task_events_mgr.broadcast_mgr.expire_broadcast( |
| 787 |
cutoff |
| 788 |
) |
| 789 |
) |
| 790 |
raise ValueError(f'Unsupported broadcast mode: {mode}') |
| 791 |
except Exception as exc: |
| 792 |
LOG.error(exc) |
| 793 |
return {'error': {'message': str(exc)}} |
| 794 |
|
| 795 |
def put_ext_trigger( |
| 796 |
self, |
| 797 |
message, |
| 798 |
id # noqa: A002 (graphql interface) |
| 799 |
): |
| 800 |
"""Server-side external event trigger interface. |
| 801 |
|
| 802 |
Args: |
| 803 |
message (str): The external trigger message. |
| 804 |
id (str): The unique trigger ID. |
| 805 |
|
| 806 |
Returns: |
| 807 |
tuple: (outcome, message) |
| 808 |
|
| 809 |
outcome (bool) |
| 810 |
True if command successfully queued. |
| 811 |
message (str) |
| 812 |
Information about outcome. |
| 813 |
|
| 814 |
""" |
| 815 |
self.schd.ext_trigger_queue.put((message, id)) |
| 816 |
return (True, 'Event queued') |
| 817 |
|
| 818 |
def put_messages( |
| 819 |
self, |
| 820 |
task_job: str, |
| 821 |
event_time: str, |
| 822 |
messages: List[list] |
| 823 |
) -> Tuple[bool, str]: |
| 824 |
"""Put task messages in queue for processing later by the main loop. |
| 825 |
|
| 826 |
Arguments: |
| 827 |
task_job: |
| 828 |
Job ID in the format ``CYCLE/TASK_NAME/SUBMIT_NUM``. |
| 829 |
event_time: |
| 830 |
Event time as an ISO8601 string. |
| 831 |
messages: |
| 832 |
List in the format ``[[severity, message], ...]``. |
| 833 |
|
| 834 |
Returns: |
| 835 |
outcome: |
| 836 |
True if command successfully queued. |
| 837 |
message: |
| 838 |
Information about outcome. |
| 839 |
|
| 840 |
""" |
| 841 |
for severity, message in messages: |
| 842 |
self.schd.message_queue.put( |
| 843 |
TaskMsg( |
| 844 |
Tokens(task_job, relative=True), |
| 845 |
event_time, |
| 846 |
severity, |
| 847 |
message, |
| 848 |
) |
| 849 |
) |
| 850 |
return (True, f'Messages queued: {len(messages)}') |
| 851 |
|
| 852 |
def set_graph_window_extent( |
| 853 |
self, n_edge_distance: int |
| 854 |
) -> Tuple[bool, str]: |
| 855 |
"""Set data-store graph window to new max edge distance. |
| 856 |
|
| 857 |
Args: |
| 858 |
n_edge_distance: |
| 859 |
Max edge distance 0..n from active node. |
| 860 |
|
| 861 |
Returns: |
| 862 |
tuple: (outcome, message) |
| 863 |
|
| 864 |
outcome |
| 865 |
True if command successfully queued. |
| 866 |
message |
| 867 |
Information about outcome. |
| 868 |
|
| 869 |
""" |
| 870 |
if n_edge_distance >= 0: |
| 871 |
self.schd.data_store_mgr.set_graph_window_extent(n_edge_distance) |
| 872 |
return (True, f'Maximum edge distance set to {n_edge_distance}') |
| 873 |
return (False, 'Edge distance cannot be negative') |