Debian Codegraph @

cylc/flow/network/schema.py

raw
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 API schema via Graphene implementation."""
18
19 from copy import deepcopy
20 from functools import partial
21 import json
22 from operator import attrgetter
23 from typing import (
24 TYPE_CHECKING,
25 Any,
26 AsyncGenerator,
27 Dict,
28 List,
29 Optional,
30 Tuple,
31 cast,
32 )
33
34 import graphene
35 from graphene import (
36 ID,
37 Argument,
38 Boolean,
39 Field,
40 Float,
41 InputObjectType,
42 Int,
43 Interface,
44 Mutation,
45 ObjectType,
46 Schema,
47 String,
48 )
49 from graphene.types.generic import GenericScalar
50 from graphene.types.schema import identity_resolve
51 from graphene.utils.str_converters import to_snake_case
52 from graphql.type.definition import get_named_type
53
54 from cylc.flow import LOG_LEVELS
55 from cylc.flow.broadcast_mgr import (
56 ALL_CYCLE_POINTS_STRS,
57 addict,
58 )
59 from cylc.flow.data_store_mgr import (
60 DELTA_ADDED,
61 DELTA_UPDATED,
62 FAMILIES,
63 FAMILY_PROXIES,
64 JOBS,
65 RUNTIME_CFG_MAP_TO_FIELD,
66 TASK_PROXIES,
67 TASKS,
68 )
69 from cylc.flow.flow_mgr import (
70 FLOW_NEW,
71 FLOW_NONE,
72 )
73 from cylc.flow.id import Tokens
74 from cylc.flow.run_modes import (
75 WORKFLOW_RUN_MODES,
76 RunMode,
77 )
78 from cylc.flow.task_outputs import SORT_ORDERS
79 from cylc.flow.task_state import TASK_STATUSES_ORDERED
80 from cylc.flow.util import sstrip
81 from cylc.flow.workflow_status import StopMode
82
83
84 if TYPE_CHECKING:
85 from enum import Enum
86
87 from graphql import GraphQLResolveInfo
88 from graphql.type.definition import (
89 GraphQLNamedType,
90 GraphQLType,
91 )
92
93 from cylc.flow.network.resolvers import BaseResolvers
94
95
96 def sort_elements(elements, args):
97 """Sort iterable of elements by given attribute."""
98 sort_args = args.get('sort')
99 if sort_args and elements:
100 keys = [
101 to_snake_case(key)
102 for key in sort_args.keys
103 ]
104 if not keys:
105 raise ValueError('You must provide at least one key to sort')
106 keys_not_in_schema = [
107 key for key in keys if not hasattr(elements[0], key)]
108 if keys_not_in_schema:
109 raise ValueError(f'''The following sort keys are not in the
110 schema: {', '.join(keys_not_in_schema)}''')
111 # sort using the keys provided
112 elements.sort(
113 key=attrgetter(*keys),
114 reverse=sort_args.reverse)
115 return elements
116
117
118 PROXY_NODES = 'proxy_nodes'
119
120 # Mapping of GraphQL types to field names:
121 NODE_MAP = {
122 'Task': TASKS,
123 'TaskProxy': TASK_PROXIES,
124 'Family': FAMILIES,
125 'FamilyProxy': FAMILY_PROXIES,
126 'Job': JOBS,
127 'Node': PROXY_NODES,
128 }
129
130 DEF_TYPES = [
131 'families',
132 'family',
133 'tasks',
134 'task',
135 ]
136
137
138 # ** Query Related **#
139
140 # Field args (i.e. for queries etc):
141 class SortArgs(InputObjectType):
142 keys = graphene.List(String, default_value=['id'])
143 reverse = Boolean(default_value=False)
144
145
146 STRIP_NULL_DEFAULT = Argument(
147 Boolean, description="A flag that when enabled strips out those fields "
148 "not set in the protobuf object. And when this flag "
149 "is disabled the default values of Protobuf fields "
150 "are provided (boolean=false, list=[], string=\"\".")
151 DELTA_STORE_DEFAULT = Boolean(default_value=False)
152 DELTA_TYPE_DEFAULT = String(default_value='added')
153
154 # Note: "ex" prefix means "exclude"
155 JOB_ARGS = {
156 'ids': graphene.List(ID, default_value=[]),
157 'exids': graphene.List(ID, default_value=[]),
158 'states': graphene.List(String, default_value=[]),
159 'exstates': graphene.List(String, default_value=[]),
160 'sort': SortArgs(default_value=None),
161 }
162
163 ALL_JOB_ARGS = {
164 'workflows': graphene.List(ID, default_value=[]),
165 'exworkflows': graphene.List(ID, default_value=[]),
166 'ids': graphene.List(ID, default_value=[]),
167 'exids': graphene.List(ID, default_value=[]),
168 'states': graphene.List(String, default_value=[]),
169 'exstates': graphene.List(String, default_value=[]),
170 'sort': SortArgs(default_value=None),
171 }
172
173 DEF_ARGS = {
174 'ids': graphene.List(ID, default_value=[]),
175 'exids': graphene.List(ID, default_value=[]),
176 'mindepth': Int(default_value=-1),
177 'maxdepth': Int(default_value=-1),
178 'sort': SortArgs(default_value=None),
179 }
180
181 ALL_DEF_ARGS = {
182 'workflows': graphene.List(ID, default_value=[]),
183 'exworkflows': graphene.List(ID, default_value=[]),
184 'ids': graphene.List(ID, default_value=[]),
185 'exids': graphene.List(ID, default_value=[]),
186 'mindepth': Int(default_value=-1),
187 'maxdepth': Int(default_value=-1),
188 'sort': SortArgs(default_value=None),
189 }
190
191 PROXY_ARGS = {
192 'ids': graphene.List(ID, default_value=[]),
193 'exids': graphene.List(ID, default_value=[]),
194 'states': graphene.List(String, default_value=[]),
195 'exstates': graphene.List(String, default_value=[]),
196 'is_held': Boolean(),
197 'is_queued': Boolean(),
198 'is_runahead': Boolean(),
199 'mindepth': Int(default_value=-1),
200 'maxdepth': Int(default_value=-1),
201 'graph_depth': Int(default_value=-1),
202 'sort': SortArgs(default_value=None),
203 }
204
205 ALL_PROXY_ARGS = {
206 'workflows': graphene.List(ID, default_value=[]),
207 'exworkflows': graphene.List(ID, default_value=[]),
208 'ids': graphene.List(ID, default_value=[]),
209 'exids': graphene.List(ID, default_value=[]),
210 'states': graphene.List(String, default_value=[]),
211 'exstates': graphene.List(String, default_value=[]),
212 'is_held': Boolean(),
213 'is_queued': Boolean(),
214 'is_runahead': Boolean(),
215 'mindepth': Int(default_value=-1),
216 'maxdepth': Int(default_value=-1),
217 'graph_depth': Int(default_value=-1),
218 'sort': SortArgs(default_value=None),
219 }
220
221 EDGE_ARGS = {
222 'ids': graphene.List(ID, default_value=[]),
223 'exids': graphene.List(ID, default_value=[]),
224 'states': graphene.List(String, default_value=[]),
225 'exstates': graphene.List(String, default_value=[]),
226 'sort': SortArgs(default_value=None),
227 }
228
229 ALL_EDGE_ARGS = {
230 'workflows': graphene.List(ID, default_value=[]),
231 'exworkflows': graphene.List(ID, default_value=[]),
232 'sort': SortArgs(default_value=None),
233 }
234
235 NODES_EDGES_ARGS = {
236 'ids': graphene.List(ID, default_value=[]),
237 'exids': graphene.List(ID, default_value=[]),
238 'states': graphene.List(String, default_value=[]),
239 'exstates': graphene.List(String, default_value=[]),
240 'is_held': Boolean(),
241 'is_queued': Boolean(),
242 'is_runahead': Boolean(),
243 'distance': Int(default_value=1),
244 'mindepth': Int(default_value=-1),
245 'maxdepth': Int(default_value=-1),
246 'sort': SortArgs(default_value=None),
247 }
248
249 NODES_EDGES_ARGS_ALL = {
250 'workflows': graphene.List(ID, default_value=[]),
251 'exworkflows': graphene.List(ID, default_value=[]),
252 'ids': graphene.List(ID, default_value=[]),
253 'exids': graphene.List(ID, default_value=[]),
254 'states': graphene.List(String, default_value=[]),
255 'exstates': graphene.List(String, default_value=[]),
256 'is_held': Boolean(),
257 'is_queued': Boolean(),
258 'is_runahead': Boolean(),
259 'distance': Int(default_value=1),
260 'mindepth': Int(default_value=-1),
261 'maxdepth': Int(default_value=-1),
262 'sort': SortArgs(default_value=None),
263 }
264
265 # Resolvers are used to collate data needed for query resolution.
266 # Treated as implicit static methods;
267 # https://docs.graphene-python.org/en/latest/types
268 # /objecttypes/#implicit-staticmethod
269 # they can exist inside or outside the query object types.
270 #
271 # Here we define them outside the queries so they can be used with
272 # multiple resolution calls, both at root query or object field level.
273 #
274 # The first argument has a naming convention;
275 # https://docs.graphene-python.org/en/latest/types
276 # /objecttypes/#naming-convention
277 # with name 'root' used here, it provides context to the resolvers.
278
279
280 # Resolvers:
281
282 def field_name_from_type(obj_type: 'GraphQLType') -> str:
283 """Return the field name for given a GraphQL type.
284
285 If the type is a list or non-null, the base field is extracted.
286 """
287 named_type = cast('GraphQLNamedType', get_named_type(obj_type))
288 try:
289 return NODE_MAP[named_type.name]
290 except KeyError:
291 raise ValueError(f"'{named_type.name}' is not a node type") from None
292
293
294 def get_resolvers(info: 'GraphQLResolveInfo') -> 'BaseResolvers':
295 """Return the resolvers from the context."""
296 return cast('dict', info.context)['resolvers']
297
298
299 def process_resolver_info(
300 root: Optional[Any], info: 'GraphQLResolveInfo', args: Dict[str, Any]
301 ) -> Tuple[str, Optional[Any]]:
302 """Set and gather info for resolver."""
303 # Add the subscription id to the resolver context
304 # to know which delta-store to use."""
305 if 'sub_id' in info.context:
306 args['sub_id'] = info.context['sub_id']
307
308 field_name: str = to_snake_case(info.field_name)
309 # root is the parent data object.
310 # i.e. PbWorkflow or list of IDs graphene.List(String)
311 if isinstance(root, dict):
312 root_value = root.get(field_name, None)
313 else:
314 root_value = getattr(root, field_name, None)
315
316 return (field_name, root_value)
317
318
319 def get_native_ids(field_ids):
320 """Collect IDs into list form."""
321 if isinstance(field_ids, str):
322 return [field_ids]
323 if isinstance(field_ids, dict):
324 return list(field_ids)
325 return field_ids
326
327
328 async def get_workflows(root, info: 'GraphQLResolveInfo', **args):
329 """Get filtered workflows."""
330
331 _, workflow = process_resolver_info(root, info, args)
332 if workflow is not None:
333 args['ids'] = [workflow.id]
334
335 args['workflows'] = [Tokens(w_id) for w_id in args['ids']]
336 args['exworkflows'] = [Tokens(w_id) for w_id in args['exids']]
337 resolvers = get_resolvers(info)
338 return await resolvers.get_workflows(args)
339
340
341 async def get_workflow_by_id(root, info: 'GraphQLResolveInfo', **args):
342 """Return single workflow element."""
343
344 _, workflow = process_resolver_info(root, info, args)
345 if workflow is not None:
346 args['id'] = workflow.id
347
348 args['workflow'] = args['id']
349 resolvers = get_resolvers(info)
350 return await resolvers.get_workflow_by_id(args)
351
352
353 async def get_nodes_all(
354 root: Optional[Any], info: 'GraphQLResolveInfo', **args
355 ):
356 """Resolver for returning job, task, family nodes"""
357
358 _, field_ids = process_resolver_info(root, info, args)
359
360 if field_ids:
361 if isinstance(field_ids, str):
362 field_ids = [field_ids]
363 elif isinstance(field_ids, dict):
364 field_ids = list(field_ids)
365 args['ids'] = field_ids
366 elif field_ids == []:
367 return []
368
369 node_field_name = field_name_from_type(info.return_type)
370
371 for arg in ('ids', 'exids'):
372 if node_field_name in DEF_TYPES:
373 # namespace nodes don't fit into the universal ID scheme so must
374 # be tokenised manually
375 args[arg] = [
376 Tokens(
377 cycle=None,
378 task=task,
379 job=None,
380 )
381 for task in args[arg]
382 ]
383 else:
384 # live objects can be represented by a universal ID
385 args[arg] = [Tokens(n_id, relative=True) for n_id in args[arg]]
386 for arg in ('workflows', 'exworkflows'):
387 args[arg] = [Tokens(w_id) for w_id in args[arg]]
388 resolvers = get_resolvers(info)
389 return await resolvers.get_nodes_all(node_field_name, args)
390
391
392 async def get_nodes_by_ids(
393 root: Optional[Any], info: 'GraphQLResolveInfo', **args
394 ):
395 """Resolver for returning job, task, family node"""
396 field_name, field_ids = process_resolver_info(root, info, args)
397
398 resolvers = get_resolvers(info)
399 if field_ids == []:
400 parent_id = getattr(root, 'id', None)
401 # Find node ids from parent
402 if parent_id:
403 parent_args = deepcopy(args)
404 parent_args.update(
405 {'id': parent_id, 'delta_store': False}
406 )
407 parent_type = cast(
408 'GraphQLNamedType', get_named_type(info.parent_type)
409 )
410 if parent_type.name in NODE_MAP:
411 parent = await resolvers.get_node_by_id(
412 NODE_MAP[parent_type.name], parent_args
413 )
414 else:
415 parent = await resolvers.get_workflow_by_id(parent_args)
416 field_ids = getattr(parent, field_name, None)
417 if not field_ids:
418 return []
419 if field_ids:
420 args['native_ids'] = get_native_ids(field_ids)
421
422 node_field_name = field_name_from_type(info.return_type)
423
424 args['ids'] = [Tokens(n_id, relative=True) for n_id in args['ids']]
425 args['exids'] = [Tokens(n_id, relative=True) for n_id in args['exids']]
426 return await resolvers.get_nodes_by_ids(node_field_name, args)
427
428
429 async def get_node_by_id(
430 root: Optional[Any], info: 'GraphQLResolveInfo', **args
431 ):
432 """Resolver for returning job, task, family node"""
433
434 field_name, field_id = process_resolver_info(root, info, args)
435
436 if field_name == 'source_node':
437 field_name = 'source'
438 elif field_name == 'target_node':
439 field_name = 'target'
440
441 resolvers = get_resolvers(info)
442 if args.get('id') is None:
443 field_id = getattr(root, field_name, None)
444 # Find node id from parent
445 if not field_id:
446 parent_id = getattr(root, 'id', None)
447 if parent_id:
448 parent_args = deepcopy(args)
449 parent_args.update(
450 {'id': parent_id, 'delta_store': False}
451 )
452 args['id'] = parent_id
453 parent = await resolvers.get_node_by_id(
454 field_name_from_type(info.parent_type),
455 parent_args
456 )
457 field_id = getattr(parent, field_name, None)
458 if field_id:
459 args['id'] = field_id
460 else:
461 return None
462
463 return await resolvers.get_node_by_id(
464 field_name_from_type(info.return_type), args
465 )
466
467
468 async def get_edges_all(root, info: 'GraphQLResolveInfo', **args):
469 """Get all edges from the store filtered by args."""
470
471 process_resolver_info(root, info, args)
472
473 args['workflows'] = [
474 Tokens(w_id) for w_id in args['workflows']
475 ]
476 args['exworkflows'] = [
477 Tokens(w_id) for w_id in args['exworkflows']
478 ]
479 resolvers = get_resolvers(info)
480 return await resolvers.get_edges_all(args)
481
482
483 async def get_edges_by_ids(root, info: 'GraphQLResolveInfo', **args):
484 """Get all edges from the store by id lookup filtered by args."""
485
486 _, field_ids = process_resolver_info(root, info, args)
487
488 if field_ids:
489 args['native_ids'] = get_native_ids(field_ids)
490 elif field_ids == []:
491 return []
492
493 resolvers = get_resolvers(info)
494 return await resolvers.get_edges_by_ids(args)
495
496
497 async def get_nodes_edges(root, info: 'GraphQLResolveInfo', **args):
498 """Resolver for returning job, task, family nodes"""
499
500 process_resolver_info(root, info, args)
501
502 if hasattr(root, 'id'):
503 args['workflows'] = [Tokens(root.id)]
504 args['exworkflows'] = []
505 else:
506 args['workflows'] = [
507 Tokens(w_id) for w_id in args['workflows']
508 ]
509 args['exworkflows'] = [
510 Tokens(w_id) for w_id in args['exworkflows']
511 ]
512
513 args['ids'] = [Tokens(n_id) for n_id in args['ids']]
514 args['exids'] = [Tokens(n_id) for n_id in args['exids']]
515
516 resolvers = get_resolvers(info)
517 root_nodes = await resolvers.get_nodes_all(TASK_PROXIES, args)
518 return await resolvers.get_nodes_edges(root_nodes, args)
519
520
521 def resolve_state_totals(root, info, **args):
522 state_totals = dict.fromkeys(TASK_STATUSES_ORDERED, 0)
523 # Update with converted protobuf map container
524 state_totals.update(
525 dict(getattr(root, to_snake_case(info.field_name), {})))
526 return state_totals
527
528
529 def resolve_state_tasks(root, info, **args):
530 data = dict(getattr(root, to_snake_case(info.field_name), {}))
531 return {
532 state: list(data[state].task_proxies)
533 for state in args['states']
534 if state in data}
535
536
537 async def resolve_broadcasts(root, info: 'GraphQLResolveInfo', **args):
538 """Resolve and parse broadcasts from JSON."""
539 broadcasts = json.loads(
540 getattr(root, to_snake_case(info.field_name), '{}'))
541 resolvers = get_resolvers(info)
542
543 if not args['ids']:
544 return broadcasts
545
546 result: Dict[str, dict] = {}
547 t_type = NODE_MAP['Task']
548 t_args: Dict[str, list] = {'workflows': [Tokens(root.id)]}
549 for n_id in args['ids']:
550 tokens = Tokens(n_id)
551 point_string = tokens['cycle']
552 name = tokens['task']
553 if point_string is None:
554 point_string = '*'
555 for cycle in set(ALL_CYCLE_POINTS_STRS + [point_string]):
556 if cycle not in broadcasts:
557 continue
558 t_args['ids'] = [(None, None, None, name, None, None)]
559 tasks = await resolvers.get_nodes_all(t_type, t_args)
560 for namespace in {ns for t in tasks for ns in t.namespace}:
561 if namespace in broadcasts[cycle]:
562 addict(
563 result,
564 {cycle: {namespace: broadcasts[cycle][namespace]}}
565 )
566 return result
567
568
569 def resolve_json_dump(root, info, **args):
570 field = getattr(root, to_snake_case(info.field_name), '{}') or '{}'
571 return json.loads(field)
572
573
574 def resolve_mapping_to_list(root, info, **args):
575 field = getattr(root, to_snake_case(info.field_name), {}) or {}
576 mapping = {
577 key: field[key]
578 for key in args.get('sort_order', [])
579 if key in field}
580 mapping.update(field)
581 satisfied = args.get('satisfied')
582 elements = sort_elements(
583 [
584 val
585 for val in mapping.values()
586 if satisfied is None or val.satisfied is satisfied
587 ], args)
588 limit = args['limit']
589 if elements and limit:
590 elements = elements[:limit]
591 return elements
592
593
594 # Types:
595 class NodeMeta(ObjectType):
596 class Meta:
597 description = sstrip("""
598 Meta data fields, including custom fields in a generic user-defined
599 dump.
600 """)
601 title = String(default_value=None)
602 description = String(default_value=None)
603 URL = String(default_value=None)
604 user_defined = GenericScalar(resolver=resolve_json_dump)
605
606
607 class TimeZone(ObjectType):
608 class Meta:
609 description = 'Time zone info.'
610 hours = Int()
611 minutes = Int()
612 string_basic = String()
613 string_extended = String()
614
615
616 # The run mode for the workflow.
617 WorkflowRunMode = graphene.Enum(
618 'WorkflowRunMode',
619 [(m.capitalize(), m) for m in WORKFLOW_RUN_MODES],
620 description=lambda x: RunMode(x.value).describe() if x else None,
621 )
622
623 # The run mode for the task.
624 TaskRunMode = graphene.Enum(
625 'TaskRunMode',
626 [(k.capitalize(), k.lower()) for k in RunMode.__members__.keys()],
627 description=lambda x: RunMode(x.value).describe() if x else None,
628 )
629
630
631 class LogRecord(ObjectType):
632 level = String()
633 message = String()
634
635
636 class Workflow(ObjectType):
637 class Meta:
638 description = 'Global workflow info.'
639 id = ID() # noqa: A003 (required for definition)
640 name = String(
641 description='The workflow ID with the ~user/ prefix removed.',
642 )
643 status = String(
644 description='The workflow status e.g. `running`.',
645 )
646 status_msg = String(
647 description='A description of the workflow status.',
648 )
649 host = String(
650 description='The host where the scheduler process is running.',
651 )
652 port = Int(
653 description='The port for sending ZMQ requests to the scheduler.',
654 )
655 pub_port = Int(
656 description=sstrip('''
657 The port for subscribing to ZMQ updates from the scheduler.
658 '''),
659 )
660 owner = String(
661 description='The user account that the workflow is running under.',
662 )
663 tasks = graphene.List(
664 lambda: Task,
665 description="Task definitions.",
666 args=DEF_ARGS,
667 strip_null=STRIP_NULL_DEFAULT,
668 delta_store=DELTA_STORE_DEFAULT,
669 delta_type=DELTA_TYPE_DEFAULT,
670 resolver=get_nodes_by_ids,
671 )
672 families = graphene.List(
673 lambda: Family,
674 description="Family definitions.",
675 args=DEF_ARGS,
676 strip_null=STRIP_NULL_DEFAULT,
677 delta_store=DELTA_STORE_DEFAULT,
678 delta_type=DELTA_TYPE_DEFAULT,
679 resolver=get_nodes_by_ids,
680 )
681 task_proxies = graphene.List(
682 lambda: TaskProxy,
683 description="Task instances.",
684 args=PROXY_ARGS,
685 strip_null=STRIP_NULL_DEFAULT,
686 delta_store=DELTA_STORE_DEFAULT,
687 delta_type=DELTA_TYPE_DEFAULT,
688 resolver=get_nodes_by_ids,
689 )
690 family_proxies = graphene.List(
691 lambda: FamilyProxy,
692 description="Family instances.",
693 args=PROXY_ARGS,
694 strip_null=STRIP_NULL_DEFAULT,
695 delta_store=DELTA_STORE_DEFAULT,
696 delta_type=DELTA_TYPE_DEFAULT,
697 resolver=get_nodes_by_ids,
698 )
699 jobs = graphene.List(
700 lambda: Job,
701 description="Jobs.",
702 args=JOB_ARGS,
703 strip_null=STRIP_NULL_DEFAULT,
704 delta_store=DELTA_STORE_DEFAULT,
705 delta_type=DELTA_TYPE_DEFAULT,
706 resolver=get_nodes_by_ids,
707 )
708 edges = Field(
709 lambda: Edges,
710 args=EDGE_ARGS,
711 strip_null=STRIP_NULL_DEFAULT,
712 delta_store=DELTA_STORE_DEFAULT,
713 delta_type=DELTA_TYPE_DEFAULT,
714 description="Graph edges.",
715 )
716 nodes_edges = Field(
717 lambda: NodesEdges,
718 args=NODES_EDGES_ARGS,
719 strip_null=STRIP_NULL_DEFAULT,
720 delta_store=DELTA_STORE_DEFAULT,
721 delta_type=DELTA_TYPE_DEFAULT,
722 resolver=get_nodes_edges,
723 description='Graph nodes and edges.'
724 )
725 api_version = Int(
726 description='The Cylc scheduler communication protocol version number.'
727 )
728 cylc_version = String(
729 description='The Cylc version this workflow is running under.',
730 )
731 last_updated = Float(
732 description='The time of the most recent state change in the workflow.'
733 )
734 meta = Field(
735 NodeMeta,
736 description="The workflow's `[meta]` section.",
737 )
738 newest_active_cycle_point = String(
739 description='The newest cycle point which has active tasks.'
740 )
741 oldest_active_cycle_point = String(
742 description='The oldest cycle point which has active tasks.'
743 )
744 reloaded = Boolean(
745 description=sstrip('''
746 When subscribing to workflow updates, this field is `True` if the
747 update relates to a workflow reload.
748 '''),
749 )
750 run_mode = String(
751 description="The scheduler's run-mode e.g. `live`.",
752 )
753 is_held_total = Int(
754 description=sstrip('''
755 The number of "held" tasks.
756
757 Deprecated: Use `contains_held`.
758 '''),
759 deprecation_reason='unused',
760 )
761 is_queued_total = Int(
762 description=sstrip('''
763 The number of queued tasks.
764
765 Deprecated: No replacement.
766 '''),
767 deprecation_reason='unused',
768 )
769 is_runahead_total = Int(
770 description=sstrip('''
771 The number of tasks which are held back by the runahead limit.
772
773 Deprecated: No replacement.
774 '''),
775 deprecation_reason='unused',
776 )
777 contains_held = Boolean(
778 description='True if the n=0 window contains any held tasks.'
779 )
780 contains_retry = Boolean(
781 description=sstrip('''
782 True if the n=0 window contains any tasks waiting automatic retry.
783 ''')
784 )
785 state_totals = GenericScalar(
786 resolver=resolve_state_totals,
787 description='The number of n=0 tasks in each state as a JSON object.',
788 )
789 latest_state_tasks = GenericScalar(
790 states=graphene.List(
791 String,
792 description="List of task states to show.",
793 default_value=TASK_STATUSES_ORDERED),
794 resolver=resolve_state_tasks,
795 description='The latest tasks to have entered each task state.',
796 )
797 workflow_log_dir = String(
798 description="The path to the workflow's run directory.",
799 )
800 time_zone_info = Field(
801 TimeZone,
802 description='The scheduler time zone.',
803 )
804 tree_depth = Int() # TODO: what is this? write description
805 ns_def_order = graphene.List(
806 String,
807 description=sstrip('''
808 Namespace definition order.
809
810 The order in which tasks were defined in the workflow
811 configuration.
812 '''),
813 )
814 job_log_names = graphene.List(
815 # TODO: remove, see https://github.com/cylc/cylc-flow/issues/5610
816 String,
817 description='Deprecated, do not use this.',
818 )
819 states = graphene.List(
820 String,
821 description=sstrip('''
822 The task states present in the workflow.
823
824 Similar to stateTotals.
825 '''),
826 )
827 broadcasts = GenericScalar(
828 ids=graphene.List(
829 ID,
830 description=sstrip('''
831 Node IDs, cycle point and/or-just family/task namespace.
832
833 E.g: `["1234/foo", "1234/FAM", "*/FAM"]`
834 '''),
835 default_value=[]
836 ),
837 resolver=resolve_broadcasts,
838 description='Any active workflow broadcasts.'
839 )
840 pruned = Boolean() # TODO: what is this? write description
841 n_edge_distance = Int(
842 description=sstrip('''
843 The maximum graph distance (n) from an active node
844 of the data-store graph window.
845 '''),
846 )
847 log_records = graphene.List(
848 LogRecord,
849 description=sstrip('''
850 Scheduler log messages of level WARNING and above.
851
852 Warning: This is an incrementally updated field. Each update
853 contains a list of **new** log messages, not a list of all
854 messages. It is down to the client to store / preserve previous
855 records.
856 '''),
857 )
858
859
860 class RuntimeSetting(ObjectType):
861 """Key = value setting for a `[runtime][<namespace>]` configuration."""
862 key = String(default_value=None)
863 value = String(default_value=None)
864
865
866 class Runtime(ObjectType):
867 class Meta:
868 description = sstrip("""
869 Subset of runtime fields.
870
871 Existing on 3 different node types:
872 - Task/family definition (from the flow.cylc file)
873 - Task/family cycle instance (includes any broadcasts on top
874 of the definition)
875 - Job (a record of what was run for a particular submit)
876 """)
877 platform = String(default_value=None)
878 script = String(default_value=None)
879 completion = String(default_value=None)
880 init_script = String(default_value=None)
881 env_script = String(default_value=None)
882 err_script = String(default_value=None)
883 exit_script = String(default_value=None)
884 pre_script = String(default_value=None)
885 post_script = String(default_value=None)
886 work_sub_dir = String(default_value=None)
887 execution_polling_intervals = String(default_value=None)
888 execution_retry_delays = String(default_value=None)
889 execution_time_limit = String(default_value=None)
890 submission_polling_intervals = String(default_value=None)
891 submission_retry_delays = String(default_value=None)
892 directives = graphene.List(RuntimeSetting, resolver=resolve_json_dump)
893 environment = graphene.List(RuntimeSetting, resolver=resolve_json_dump)
894 outputs = graphene.List(RuntimeSetting, resolver=resolve_json_dump)
895 run_mode = TaskRunMode(default_value=TaskRunMode.Live)
896
897
898 RUNTIME_FIELD_TO_CFG_MAP = {
899 v: k
900 for k, v in RUNTIME_CFG_MAP_TO_FIELD.items()
901 }
902 """Map Pb/GraphQL Runtime fields' names to workflow config setting names."""
903
904
905 def runtime_schema_to_cfg(runtime: dict) -> dict:
906 """Covert GraphQL Runtime field names to workflow config setting names and
907 perform any necessary processing on the values."""
908 # We have to manually lowercase the run_mode field because we don't define
909 # a proper schema for BroadcastSetting (it's just GenericScalar) so
910 # Graphene has no way to know that it should be a TaskRunMode enum.
911 return {
912 RUNTIME_FIELD_TO_CFG_MAP.get(key, key): (
913 value.lower() if key == 'run_mode' else value
914 )
915 for key, value in runtime.items()
916 }
917
918
919 class Job(ObjectType):
920 class Meta:
921 description = "Jobs."
922
923 id = ID() # noqa: A003 (required for definition)
924 submit_num = Int(
925 description='The submission number for this job, starts at 1.',
926 )
927 state = String(
928 description='The job state e.g. `running` or `succeeded`.',
929 )
930 name = String(
931 description='The name of the task which submitted this job.',
932 )
933 cycle_point = String(
934 description='The cycle of the task which submitted this job.',
935 )
936 task_proxy = Field(
937 lambda: TaskProxy,
938 description="The TaskProxy of the task which submitted this job.",
939 strip_null=STRIP_NULL_DEFAULT,
940 delta_store=DELTA_STORE_DEFAULT,
941 delta_type=DELTA_TYPE_DEFAULT,
942 resolver=get_node_by_id)
943 submitted_time = String(
944 description='The time this job was submitted to the job runner.',
945 )
946 started_time = String(
947 description='The time this job started running (if it has yet).',
948 )
949 finished_time = String(
950 description='The time this job finished running (if it has yet).',
951 )
952 estimated_finish_time = String(
953 description=(
954 "The estimated time this job will finish, if applicable. "
955 "This is based on the task's mean run time, or if not available, "
956 "the execution time limit."
957 ),
958 )
959 job_id = ID(
960 description='The ID of this job in the job runner it was submitted to.'
961 )
962 job_runner_name = String(
963 description='The job runner this job was submitted to.',
964 )
965 execution_time_limit = Float(
966 description='The time limit for this job if configured.',
967 )
968 platform = String(
969 description='The Cylc platform this job was submitted to.',
970 )
971 job_log_dir = String(
972 description="The path to the job's log directory.",
973 )
974 messages = graphene.List(
975 String,
976 description='The list of task messages generated by this job.',
977 )
978 runtime = Field(
979 Runtime,
980 description=sstrip('''
981 The `[runtime]` configuration of the task which submitted this job.
982 '''),
983 )
984
985
986 class Task(ObjectType):
987 class Meta:
988 description = sstrip("""
989 Task definitions.
990
991 These are the task "definitions" as they appear in the
992 configuration as opposed to task "instances" which you will find
993 in the `TaskProxies` field.
994 """)
995
996 id = ID() # noqa: A003 (required for definition)
997 name = String(
998 description='The task name.'
999 )
1000 meta = Field(
1001 NodeMeta,
1002 description="The task's `[meta]` section.",
1003 )
1004 runtime = Field(
1005 Runtime,
1006 description="The task's `[runtime]` section.",
1007 )
1008 mean_elapsed_time = Float(
1009 description="The task's average runtime."
1010 )
1011 depth = Int(
1012 description='The family inheritance depth.'
1013 )
1014 proxies = graphene.List(
1015 lambda: TaskProxy,
1016 description="Associated cycle point proxies",
1017 args=PROXY_ARGS,
1018 strip_null=STRIP_NULL_DEFAULT,
1019 delta_store=DELTA_STORE_DEFAULT,
1020 delta_type=DELTA_TYPE_DEFAULT,
1021 resolver=get_nodes_by_ids)
1022 parents = graphene.List(
1023 lambda: Family,
1024 description="Family definition parent.",
1025 args=DEF_ARGS,
1026 strip_null=STRIP_NULL_DEFAULT,
1027 delta_store=DELTA_STORE_DEFAULT,
1028 delta_type=DELTA_TYPE_DEFAULT,
1029 resolver=get_nodes_by_ids)
1030 namespace = graphene.List(String)
1031 first_parent = Field(
1032 lambda: Family,
1033 description="Task first parent.",
1034 strip_null=STRIP_NULL_DEFAULT,
1035 delta_store=DELTA_STORE_DEFAULT,
1036 delta_type=DELTA_TYPE_DEFAULT,
1037 resolver=get_node_by_id)
1038
1039
1040 class PollTask(ObjectType):
1041 class Meta:
1042 description = 'Polling task edge.'
1043 local_proxy = ID()
1044 workflow = String()
1045 remote_proxy = ID()
1046 req_state = String()
1047 graph_string = String()
1048
1049
1050 class Condition(ObjectType):
1051 class Meta:
1052 description = 'Prerequisite conditions.'
1053 task_id = String()
1054 task_proxy = Field(
1055 lambda: TaskProxy,
1056 description='Associated Task Proxy.',
1057 strip_null=STRIP_NULL_DEFAULT,
1058 delta_store=DELTA_STORE_DEFAULT,
1059 delta_type=DELTA_TYPE_DEFAULT,
1060 resolver=get_node_by_id)
1061 expr_alias = String()
1062 req_state = String()
1063 satisfied = Boolean()
1064 message = String()
1065
1066 def resolve_task_id(root, info, **args):
1067 return getattr(root, 'task_proxy', None)
1068
1069
1070 class Prerequisite(ObjectType):
1071 class Meta:
1072 description = 'Task prerequisite.'
1073 expression = String()
1074 conditions = graphene.List(
1075 Condition,
1076 description='Condition monomers of a task prerequisites.'
1077 )
1078 cycle_points = graphene.List(String)
1079 satisfied = Boolean()
1080
1081
1082 class Output(ObjectType):
1083 class Meta:
1084 description = 'Task output.'
1085 label = String()
1086 message = String()
1087 satisfied = Boolean()
1088 time = Float()
1089
1090
1091 class OutputLabel(String):
1092 """Task output, e.g. `succeeded`."""
1093
1094
1095 class PrerequisiteString(String):
1096 """A task prerequisite, e.g. `2040/foo:succeeded`."""
1097
1098
1099 class XTrigger(ObjectType):
1100 class Meta:
1101 description = 'Task trigger.'
1102 id = String() # noqa: A003 (required for definition)
1103 label = String()
1104 message = String()
1105 satisfied = Boolean()
1106 time = Float()
1107
1108
1109 class TaskProxy(ObjectType):
1110 class Meta:
1111 description = 'Task cycle instance.'
1112 id = ID() # noqa: A003 (required for schema definition)
1113 task = Field(
1114 Task,
1115 description="The task definition relating to this task instance.",
1116 strip_null=STRIP_NULL_DEFAULT,
1117 delta_store=DELTA_STORE_DEFAULT,
1118 delta_type=DELTA_TYPE_DEFAULT,
1119 resolver=get_node_by_id)
1120 runtime = Field(
1121 Runtime,
1122 description="This task's `[runtime]` section.",
1123 )
1124 state = String(
1125 description='The task state e.g. `running`.',
1126 )
1127 name = String(
1128 description="The task's name.",
1129 )
1130 cycle_point = String(
1131 description="The task's cycle point.",
1132 )
1133 namespace = graphene.List(
1134 String,
1135 description='The inheritance order for this task.',
1136 )
1137 is_held = Boolean(
1138 description='True if this task is "held".',
1139 )
1140 is_queued = Boolean(
1141 description=sstrip('''
1142 True if this task is "queued".
1143
1144 This relates to Cylc's internal task queues, not a job runner
1145 queue.
1146 '''),
1147 )
1148 is_runahead = Boolean(
1149 description='True if this task is held back by the "runahead limit".',
1150 )
1151 is_retry = Boolean(
1152 description='True if this task has a scheduled retry.',
1153 )
1154 is_wallclock = Boolean(
1155 description='True if this task has an unsatisfied wallclock trigger.',
1156 )
1157 is_xtriggered = Boolean(
1158 description=sstrip(
1159 'True if this task has an unsatisfied xtrigger'
1160 ' (excluding retry and wallclock xtriggers).'
1161 ),
1162 )
1163 flow_nums = String(
1164 description='The flows this task instance belongs to.',
1165 )
1166 flow_wait = Boolean(
1167 description=sstrip('''
1168 True if this task will wait for an approaching flow before spawning
1169 outputs downstream.
1170 '''),
1171 )
1172 depth = Int(
1173 description='The family inheritance depth.',
1174 )
1175 graph_depth = Int(
1176 description=sstrip('''
1177 The n-window graph edge depth from closet active task(s).
1178 '''),
1179 )
1180 job_submits = Int(
1181 description='The number of job submissions for this task instance.',
1182 )
1183 outputs = graphene.List(
1184 Output,
1185 description="Outputs this task instance has generated.",
1186 sort=SortArgs(default_value=None),
1187 sort_order=graphene.List(
1188 String,
1189 default_value=list(SORT_ORDERS)
1190 ),
1191 limit=Int(default_value=0),
1192 satisfied=Boolean(),
1193 resolver=resolve_mapping_to_list)
1194 external_triggers = graphene.List(
1195 XTrigger,
1196 description="Task external trigger prerequisites.",
1197 sort=SortArgs(default_value=None),
1198 sort_order=graphene.List(String),
1199 limit=Int(default_value=0),
1200 satisfied=Boolean(),
1201 resolver=resolve_mapping_to_list)
1202 xtriggers = graphene.List(
1203 XTrigger,
1204 description="Task xtrigger prerequisites.",
1205 sort=SortArgs(default_value=None),
1206 sort_order=graphene.List(String),
1207 limit=Int(default_value=0),
1208 satisfied=Boolean(),
1209 resolver=resolve_mapping_to_list)
1210 extras = GenericScalar(
1211 # TODO: what is this? write description
1212 resolver=resolve_json_dump,
1213 )
1214 prerequisites = graphene.List(
1215 Prerequisite,
1216 description='The prerequisites of this task.',
1217 )
1218 jobs = graphene.List(
1219 Job,
1220 description="Jobs.",
1221 args=JOB_ARGS,
1222 strip_null=STRIP_NULL_DEFAULT,
1223 delta_store=DELTA_STORE_DEFAULT,
1224 delta_type=DELTA_TYPE_DEFAULT,
1225 resolver=get_nodes_by_ids,
1226 )
1227 parents = graphene.List(
1228 lambda: FamilyProxy,
1229 description="Task parents (i.e. families).",
1230 args=PROXY_ARGS,
1231 strip_null=STRIP_NULL_DEFAULT,
1232 delta_store=DELTA_STORE_DEFAULT,
1233 delta_type=DELTA_TYPE_DEFAULT,
1234 resolver=get_nodes_by_ids,
1235 )
1236 first_parent = Field(
1237 lambda: FamilyProxy,
1238 description="The task's first parent (i.e. its containing family).",
1239 args=PROXY_ARGS,
1240 strip_null=STRIP_NULL_DEFAULT,
1241 delta_store=DELTA_STORE_DEFAULT,
1242 delta_type=DELTA_TYPE_DEFAULT,
1243 resolver=get_node_by_id,
1244 )
1245 ancestors = graphene.List(
1246 lambda: FamilyProxy,
1247 description="First parent ancestors (i.e. inheritance hierarchy).",
1248 args=PROXY_ARGS,
1249 strip_null=STRIP_NULL_DEFAULT,
1250 delta_store=DELTA_STORE_DEFAULT,
1251 delta_type=DELTA_TYPE_DEFAULT,
1252 resolver=get_nodes_by_ids,
1253 )
1254
1255
1256 class Family(ObjectType):
1257 class Meta:
1258 description = 'Task definition, static fields.'
1259 id = ID() # noqa: A003 (required for schema definition)
1260 name = String()
1261 meta = Field(NodeMeta)
1262 runtime = Field(Runtime)
1263 depth = Int()
1264 proxies = graphene.List(
1265 lambda: FamilyProxy,
1266 description='Associated family proxy instances.',
1267 args=PROXY_ARGS,
1268 strip_null=STRIP_NULL_DEFAULT,
1269 delta_store=DELTA_STORE_DEFAULT,
1270 delta_type=DELTA_TYPE_DEFAULT,
1271 resolver=get_nodes_by_ids)
1272 parents = graphene.List(
1273 lambda: Family,
1274 description='Families that this family directly inherits from.',
1275 args=DEF_ARGS,
1276 strip_null=STRIP_NULL_DEFAULT,
1277 delta_store=DELTA_STORE_DEFAULT,
1278 delta_type=DELTA_TYPE_DEFAULT,
1279 resolver=get_nodes_by_ids)
1280 child_tasks = graphene.List(
1281 Task,
1282 description='Tasks that inherit from this family.',
1283 args=DEF_ARGS,
1284 strip_null=STRIP_NULL_DEFAULT,
1285 delta_store=DELTA_STORE_DEFAULT,
1286 delta_type=DELTA_TYPE_DEFAULT,
1287 resolver=get_nodes_by_ids)
1288 child_families = graphene.List(
1289 lambda: Family,
1290 description='Families that inherit from this family.',
1291 args=DEF_ARGS,
1292 strip_null=STRIP_NULL_DEFAULT,
1293 delta_store=DELTA_STORE_DEFAULT,
1294 delta_type=DELTA_TYPE_DEFAULT,
1295 resolver=get_nodes_by_ids)
1296 first_parent = Field(
1297 lambda: Family,
1298 description='Family first parent.',
1299 strip_null=STRIP_NULL_DEFAULT,
1300 delta_store=DELTA_STORE_DEFAULT,
1301 delta_type=DELTA_TYPE_DEFAULT,
1302 resolver=get_node_by_id)
1303
1304
1305 class FamilyProxy(ObjectType):
1306 class Meta:
1307 description = 'Family composite.'
1308 id = ID() # noqa: A003 (required for schema definition)
1309 cycle_point = String()
1310 # name & namespace for filtering/sorting
1311 name = String()
1312 family = Field(
1313 Family,
1314 description='Family definition.',
1315 strip_null=STRIP_NULL_DEFAULT,
1316 delta_store=DELTA_STORE_DEFAULT,
1317 delta_type=DELTA_TYPE_DEFAULT,
1318 resolver=get_node_by_id)
1319 runtime = Field(Runtime)
1320 state = String()
1321 states = graphene.List(String)
1322 state_totals = GenericScalar(resolver=resolve_state_totals)
1323 is_held = Boolean()
1324 is_held_total = Int()
1325 is_queued = Boolean()
1326 is_queued_total = Int()
1327 is_runahead = Boolean()
1328 is_runahead_total = Int()
1329 is_retry = Boolean(
1330 description=(
1331 'True if this family contains a task that has a scheduled retry.'
1332 ),
1333 )
1334 is_wallclock = Boolean(
1335 description=(
1336 'True if this family contains a task that has an'
1337 ' unsatisfied wallclock trigger.'
1338 ),
1339 )
1340 is_xtriggered = Boolean(
1341 description=sstrip(
1342 'True if this family contains a task that has an unsatisfied'
1343 ' xtrigger (excluding retry and wallclock xtriggers).'
1344 ),
1345 )
1346 depth = Int()
1347 graph_depth = Int(
1348 description=sstrip('''
1349 The n-window graph edge smallest child task/family depth
1350 from closet active task(s).
1351 '''),
1352 )
1353 child_tasks = graphene.List(
1354 TaskProxy,
1355 description='Descendant task proxies.',
1356 args=PROXY_ARGS,
1357 strip_null=STRIP_NULL_DEFAULT,
1358 delta_store=DELTA_STORE_DEFAULT,
1359 delta_type=DELTA_TYPE_DEFAULT,
1360 resolver=get_nodes_by_ids)
1361 child_families = graphene.List(
1362 lambda: FamilyProxy,
1363 description='Descendant family proxies.',
1364 args=PROXY_ARGS,
1365 strip_null=STRIP_NULL_DEFAULT,
1366 delta_store=DELTA_STORE_DEFAULT,
1367 delta_type=DELTA_TYPE_DEFAULT,
1368 resolver=get_nodes_by_ids)
1369 first_parent = Field(
1370 lambda: FamilyProxy,
1371 description='Task first parent.',
1372 args=PROXY_ARGS,
1373 strip_null=STRIP_NULL_DEFAULT,
1374 delta_store=DELTA_STORE_DEFAULT,
1375 delta_type=DELTA_TYPE_DEFAULT,
1376 resolver=get_node_by_id)
1377 ancestors = graphene.List(
1378 lambda: FamilyProxy,
1379 description='First parent ancestors.',
1380 args=PROXY_ARGS,
1381 strip_null=STRIP_NULL_DEFAULT,
1382 delta_store=DELTA_STORE_DEFAULT,
1383 delta_type=DELTA_TYPE_DEFAULT,
1384 resolver=get_nodes_by_ids)
1385
1386
1387 class Node(graphene.Union):
1388 class Meta:
1389 types = (TaskProxy, FamilyProxy)
1390
1391 @classmethod
1392 def resolve_type(cls, instance, info):
1393 if hasattr(instance, 'task'):
1394 return TaskProxy
1395 return FamilyProxy
1396
1397
1398 class Edge(ObjectType):
1399 class Meta:
1400 description = 'Dependency edge task/family proxies.'
1401 id = ID() # noqa: A003 (required for schema definition)
1402 source = ID()
1403 source_node = Field(
1404 Node,
1405 strip_null=STRIP_NULL_DEFAULT,
1406 delta_store=DELTA_STORE_DEFAULT,
1407 delta_type=DELTA_TYPE_DEFAULT,
1408 resolver=get_node_by_id)
1409 target = ID()
1410 target_node = Field(
1411 Node,
1412 strip_null=STRIP_NULL_DEFAULT,
1413 delta_store=DELTA_STORE_DEFAULT,
1414 delta_type=DELTA_TYPE_DEFAULT,
1415 resolver=get_node_by_id)
1416 suicide = Boolean()
1417 cond = Boolean()
1418
1419
1420 class Edges(ObjectType):
1421 class Meta:
1422 description = 'Dependency edge.'
1423 edges = graphene.List(
1424 Edge,
1425 args=EDGE_ARGS,
1426 strip_null=STRIP_NULL_DEFAULT,
1427 delta_store=DELTA_STORE_DEFAULT,
1428 delta_type=DELTA_TYPE_DEFAULT,
1429 resolver=get_edges_by_ids)
1430 workflow_polling_tasks = graphene.List(PollTask)
1431 leaves = graphene.List(String)
1432 feet = graphene.List(String)
1433
1434
1435 class NodesEdges(ObjectType):
1436 class Meta:
1437 description = 'Related Nodes & Edges.'
1438 nodes = graphene.List(
1439 TaskProxy,
1440 description='Task nodes from and including root.')
1441 edges = graphene.List(
1442 Edge,
1443 description='Edges associated with the nodes.')
1444
1445
1446 # Query declaration
1447 class Queries(ObjectType):
1448 class Meta:
1449 description = 'Multi-Workflow root level queries.'
1450 workflows = graphene.List(
1451 Workflow,
1452 description=Workflow._meta.description,
1453 ids=graphene.List(ID, default_value=[]),
1454 exids=graphene.List(ID, default_value=[]),
1455 strip_null=STRIP_NULL_DEFAULT,
1456 resolver=get_workflows)
1457 job = Field(
1458 Job,
1459 description=Job._meta.description,
1460 id=ID(required=True),
1461 strip_null=STRIP_NULL_DEFAULT,
1462 resolver=get_node_by_id)
1463 jobs = graphene.List(
1464 Job,
1465 description=Job._meta.description,
1466 args=ALL_JOB_ARGS,
1467 strip_null=STRIP_NULL_DEFAULT,
1468 resolver=get_nodes_all)
1469 task = Field(
1470 Task,
1471 description=Task._meta.description,
1472 id=ID(required=True),
1473 strip_null=STRIP_NULL_DEFAULT,
1474 resolver=get_node_by_id)
1475 tasks = graphene.List(
1476 Task,
1477 description=Task._meta.description,
1478 args=ALL_DEF_ARGS,
1479 strip_null=STRIP_NULL_DEFAULT,
1480 resolver=get_nodes_all)
1481 task_proxy = Field(
1482 TaskProxy,
1483 description=TaskProxy._meta.description,
1484 id=ID(required=True),
1485 strip_null=STRIP_NULL_DEFAULT,
1486 resolver=get_node_by_id)
1487 task_proxies = graphene.List(
1488 TaskProxy,
1489 description=TaskProxy._meta.description,
1490 args=ALL_PROXY_ARGS,
1491 strip_null=STRIP_NULL_DEFAULT,
1492 resolver=get_nodes_all)
1493 family = Field(
1494 Family,
1495 description=Family._meta.description,
1496 id=ID(required=True),
1497 strip_null=STRIP_NULL_DEFAULT,
1498 resolver=get_node_by_id)
1499 families = graphene.List(
1500 Family,
1501 description=Family._meta.description,
1502 args=ALL_DEF_ARGS,
1503 strip_null=STRIP_NULL_DEFAULT,
1504 resolver=get_nodes_all)
1505 family_proxy = Field(
1506 FamilyProxy,
1507 description=FamilyProxy._meta.description,
1508 id=ID(required=True),
1509 strip_null=STRIP_NULL_DEFAULT,
1510 resolver=get_node_by_id)
1511 family_proxies = graphene.List(
1512 FamilyProxy,
1513 description=FamilyProxy._meta.description,
1514 args=ALL_PROXY_ARGS,
1515 strip_null=STRIP_NULL_DEFAULT,
1516 resolver=get_nodes_all)
1517 edges = graphene.List(
1518 Edge,
1519 description=Edge._meta.description,
1520 args=ALL_EDGE_ARGS,
1521 strip_null=STRIP_NULL_DEFAULT,
1522 resolver=get_edges_all)
1523 nodes_edges = Field(
1524 NodesEdges,
1525 description=NodesEdges._meta.description,
1526 args=NODES_EDGES_ARGS_ALL,
1527 strip_null=STRIP_NULL_DEFAULT,
1528 resolver=get_nodes_edges)
1529
1530
1531 # ** Mutation Related ** #
1532
1533
1534 # Generic containers
1535 class GenericResponse(ObjectType):
1536 class Meta:
1537 description = 'Container for command queued response.'
1538
1539 result = GenericScalar()
1540
1541
1542 # Mutators are used to call the internals of the parent program in the
1543 # resolution of mutation requests (or can make external calls themselves).
1544 # Like query resolvers (read above), they are treated as implicit
1545 # static methods, with object context pass in as the first argument.
1546
1547 # Mutators:
1548
1549 async def mutator(
1550 root: Optional[Any],
1551 info: 'GraphQLResolveInfo',
1552 *,
1553 command: Optional[str] = None,
1554 workflows: Optional[List[str]] = None,
1555 exworkflows: Optional[List[str]] = None,
1556 **kwargs: Any
1557 ) -> GenericResponse:
1558 """Call the resolver method that act on the workflow service
1559 via the internal command queue.
1560
1561 This is what a mutation's Meta.resolver should be set to
1562 (or the mutation's mutate() method).
1563
1564 Args:
1565 root: Parent field (if any) value object.
1566 info: GraphQL execution info.
1567 command: Mutation command name (name of method of
1568 cylc.flow.network.resolvers.Resolvers or Scheduler command_<name>
1569 method). If None, uses mutation class name converted to snake_case.
1570 workflows: List of workflow IDs.
1571 exworkflows: List of workflow IDs to exclude.
1572
1573 """
1574 if command is None:
1575 command = to_snake_case(info.field_name)
1576 if workflows is None:
1577 workflows = []
1578 if exworkflows is None:
1579 exworkflows = []
1580 w_args = {
1581 'workflows': [Tokens(w_id) for w_id in workflows],
1582 'exworkflows': [Tokens(w_id) for w_id in exworkflows]
1583 }
1584 if kwargs.get('args', False):
1585 kwargs.update(kwargs.get('args', {}))
1586 kwargs.pop('args')
1587
1588 resolvers = get_resolvers(info)
1589 meta = info.context.get('meta') # type: ignore[union-attr]
1590 res = await resolvers.mutator(info, command, w_args, kwargs, meta)
1591 return GenericResponse(result=res)
1592
1593
1594 # Input types:
1595
1596 class WorkflowID(String):
1597 """A registered workflow."""
1598
1599
1600 class CyclePoint(String):
1601 """An integer or date-time cyclepoint."""
1602
1603
1604 class CyclePointGlob(String):
1605 """A glob for integer or date-time cyclepoints.
1606
1607 The wildcard character (`*`) can be used to perform globbing.
1608 For example `2000*` might match `2000-01-01T00:00Z`.
1609
1610 """
1611
1612
1613 class RuntimeConfiguration(String):
1614 """A configuration item for a task or family e.g. `script`."""
1615
1616
1617 class BroadcastMode(graphene.Enum):
1618 Set = cast('Enum', 'put_broadcast')
1619 Clear = cast('Enum', 'clear_broadcast')
1620 Expire = cast('Enum', 'expire_broadcast')
1621
1622 @property
1623 def description(self):
1624 if self == BroadcastMode.Set:
1625 return 'Create a new broadcast.'
1626 if self == BroadcastMode.Clear:
1627 return (
1628 'Clear existing broadcasts globally or for specified'
1629 ' cycle points and namespaces if provided.'
1630 )
1631 if self == BroadcastMode.Expire:
1632 return (
1633 'Clear all broadcasts for cycle points earlier than the'
1634 ' provided cutoff.'
1635 )
1636 return ''
1637
1638
1639 class BroadcastSetting(GenericScalar):
1640 """A `[runtime]` configuration for a namespace.
1641
1642 Should be a `key=value` pair where sections are wrapped with square
1643 brackets.
1644
1645 Examples:
1646 script=true
1647 [environment]ANSWER=42
1648
1649 Nested sections should only have one set of square brackets e.g:
1650
1651 [section][subsection][subsubsection]=value
1652
1653 """
1654
1655
1656 class BroadcastCyclePoint(graphene.String):
1657 """A cycle point or `*`."""
1658 # (broadcast supports either of those two but not cycle point globs)
1659
1660
1661 class TaskName(String):
1662 """The name a task.
1663
1664 * Must be a task not a family.
1665 * Does not include the cycle point.
1666 * Any parameters must be expanded (e.g. can't be `foo<bar>`).
1667 """
1668
1669
1670 class NamespaceName(String):
1671 """The name of a task or family."""
1672
1673
1674 class NamespaceIDGlob(String):
1675 """A task or family ID e.g. `2000/foo`.
1676
1677 Globs can be used to match tasks or families, e.g, `2*/foo*` might match
1678 `2000/foot`. Cycle point globs will only match active cycles.
1679
1680 Selectors can be used to match active tasks by state, e.g, `*:failed` will
1681 match all failed tasks.
1682 """
1683
1684
1685 class TaskID(String):
1686 """The name of an active task."""
1687
1688
1689 class JobID(String):
1690 """A job submission from an active task."""
1691
1692
1693 class TimePoint(String):
1694 """A date-time in the ISO8601 format."""
1695
1696
1697 LogLevels = graphene.Enum(
1698 'LogLevels',
1699 list(LOG_LEVELS.items()),
1700 description=lambda x: (
1701 f'Logging level: {x.name} = {x.value}.'
1702 if x else ''
1703 )
1704 )
1705
1706
1707 class WorkflowStopMode(graphene.Enum):
1708 """The mode used to stop a running workflow."""
1709
1710 # NOTE: using a different enum because:
1711 # * We only want to offer a subset of stop modes (REQUEST_* only).
1712
1713 Clean = cast('Enum', StopMode.REQUEST_CLEAN.value)
1714 Kill = cast('Enum', StopMode.REQUEST_KILL.value)
1715 Now = cast('Enum', StopMode.REQUEST_NOW.value)
1716 NowNow = cast('Enum', StopMode.REQUEST_NOW_NOW.value)
1717
1718 @property
1719 def description(self):
1720 return StopMode(cast('Enum', self).value).describe()
1721
1722
1723 class Flow(String):
1724 __doc__ = (
1725 f"""An integer or {FLOW_NEW} or {FLOW_NONE}."""
1726 )
1727
1728
1729 # Mutations:
1730
1731 class Broadcast(Mutation):
1732 class Meta:
1733 description = sstrip('''
1734 Override `[runtime]` configurations in a running workflow.
1735
1736 Uses for broadcast include making temporary changes to task
1737 behaviour, and task-to-downstream-task communication via
1738 environment variables.
1739
1740 A broadcast can set/override any `[runtime]` configuration for all
1741 cycles or for a specific cycle. If a task is affected by
1742 specific-cycle and all-cycle broadcasts at the same time, the
1743 specific takes precedence.
1744
1745 Broadcasts can also target all tasks, specific tasks or families of
1746 tasks. If a task is affected by broadcasts to multiple ancestor
1747 namespaces (tasks it inherits from), the result is determined by
1748 normal `[runtime]` inheritance.
1749
1750 Broadcasts are applied at the time of job submission.
1751
1752 Broadcasts persist, even across restarts. Broadcasts made to
1753 specific cycle points will expire when the cycle point is older
1754 than the oldest active cycle point in the workflow.
1755
1756 Active broadcasts can be revoked using the "clear" mode.
1757 Any broadcasts matching the specified cycle points and
1758 namespaces will be revoked.
1759
1760 Note: a "clear" broadcast for a specific cycle or namespace does
1761 *not* clear all-cycle or all-namespace broadcasts.
1762
1763 Valid for: paused, running workflows.
1764 ''')
1765 resolver = mutator
1766
1767 class Arguments:
1768 workflows = graphene.List(WorkflowID, required=True)
1769
1770 mode = BroadcastMode(
1771 default_value=BroadcastMode.Set,
1772 description='What type of broadcast is this?',
1773 required=True
1774 )
1775 cycle_points = graphene.List(
1776 BroadcastCyclePoint,
1777 description=sstrip('''
1778 List of cycle points to target (or `*` to cancel all all-cycle
1779 broadcasts without canceling all specific-cycle broadcasts).
1780 '''),
1781 default_value=['*'])
1782 namespaces = graphene.List(
1783 NamespaceName,
1784 description='List of namespaces (tasks or families) to target.',
1785 default_value=['root']
1786 )
1787 settings = graphene.List(
1788 BroadcastSetting,
1789 description=sstrip('''
1790 The `[runtime]` configuration to override with this broadcast
1791 (e.g. `script = true` or `[environment]ANSWER=42`).
1792 '''),
1793 # e.g. `{environment: {variable_name: "value",. . .}. . .}`.
1794 )
1795 cutoff = CyclePoint(
1796 description=(
1797 'Clear broadcasts earlier than cutoff cycle point.'
1798 ' (for use with "Expire" mode).'
1799 )
1800 )
1801
1802 result = GenericScalar()
1803
1804
1805 class SetHoldPoint(Mutation):
1806 class Meta:
1807 description = sstrip('''
1808 Set workflow hold after cycle point. All tasks after this point
1809 will be held.
1810
1811 Valid for: paused, running workflows.
1812 ''')
1813 resolver = mutator
1814
1815 class Arguments:
1816 workflows = graphene.List(WorkflowID, required=True)
1817 point = CyclePoint(
1818 description='Hold all tasks after the specified cycle point.',
1819 required=True
1820 )
1821
1822 result = GenericScalar()
1823
1824
1825 class Pause(Mutation):
1826 class Meta:
1827 description = sstrip('''
1828 Pause a workflow.
1829 This suspends submission of tasks.
1830
1831 Valid for: running workflows.
1832 ''')
1833 resolver = mutator
1834
1835 class Arguments:
1836 workflows = graphene.List(WorkflowID, required=True)
1837
1838 result = GenericScalar()
1839
1840
1841 class Message(Mutation):
1842 class Meta:
1843 description = sstrip('''
1844 Record task messages.
1845
1846 Send messages to:
1847 - The job stdout/stderr.
1848 - The job status file, if there is one.
1849 - The scheduler, if communication is possible.
1850
1851 Jobs use this to record and report status such
1852 as success and failure. Applications run by jobs can use
1853 this command to report messages and to report registered task
1854 outputs.
1855
1856 Valid for: paused, running, stopping workflows.
1857 ''')
1858 resolver = partial(mutator, command='put_messages')
1859
1860 class Arguments:
1861 workflows = graphene.List(WorkflowID, required=True)
1862 task_job = String(required=True)
1863 event_time = String(default_value=None)
1864 messages = graphene.List(
1865 graphene.List(String),
1866 description='List in the form `[[severity, message], ...]`.',
1867 default_value=None
1868 )
1869
1870 result = GenericScalar()
1871
1872
1873 class ReleaseHoldPoint(Mutation):
1874 class Meta:
1875 description = sstrip('''
1876 Release all tasks and unset the workflow hold point, if set.
1877
1878 Held tasks do not submit their jobs even if ready to run.
1879
1880 Valid for: paused, running workflows.
1881 ''')
1882 resolver = mutator
1883
1884 class Arguments:
1885 workflows = graphene.List(WorkflowID, required=True)
1886
1887 result = GenericScalar()
1888
1889
1890 class Resume(Mutation):
1891 class Meta:
1892 description = sstrip('''
1893 Resume a paused workflow.
1894
1895 See also the opposite command `pause`.
1896
1897 Valid for: paused workflows.
1898 ''')
1899 resolver = mutator
1900
1901 class Arguments:
1902 workflows = graphene.List(WorkflowID, required=True)
1903
1904 result = GenericScalar()
1905
1906
1907 class Reload(Mutation):
1908 class Meta:
1909 description = sstrip('''
1910 Reload the configuration of a running workflow.
1911
1912 All settings including task definitions, with the exception of
1913 workflow log config, can be changed on reload. Changes to task
1914 definitions take effect immediately, unless a task is already
1915 running at reload time.
1916
1917 If the workflow was started with Jinja2 template variables on the
1918 command line (cylc play --set "FOO='bar'" REG) the same template
1919 settings apply to the reload (only changes to the flow.cylc
1920 file itself are reloaded).
1921
1922 If the modified workflow config does not parse, failure to reload
1923 will be reported but no harm will be done to the running workflow.
1924
1925 Valid for: paused, running workflows.
1926 ''')
1927 resolver = partial(mutator, command='reload_workflow')
1928
1929 class Arguments:
1930 workflows = graphene.List(WorkflowID, required=True)
1931
1932 reload_global = Boolean(
1933 default_value=False,
1934 required=False,
1935 description="Reload global config as well as the workflow config")
1936
1937 result = GenericScalar()
1938
1939
1940 class SetVerbosity(Mutation):
1941 class Meta:
1942 description = sstrip('''
1943 Change the logging severity level of a running workflow.
1944
1945 Only messages at or above the chosen severity level will be logged.
1946 For example, if you choose `WARNING`, only warning, error and
1947 critical level messages will be logged.
1948
1949 Valid for: paused, running workflows.
1950 ''')
1951 resolver = mutator
1952
1953 class Arguments:
1954 workflows = graphene.List(WorkflowID, required=True)
1955 level = LogLevels(required=True)
1956
1957 result = GenericScalar()
1958
1959
1960 class SetGraphWindowExtent(Mutation):
1961 class Meta:
1962 description = sstrip('''
1963 Set the maximum graph distance (n) from an active node
1964 of the data-store graph window.
1965
1966 Valid for: paused, running workflows.
1967 ''')
1968 resolver = mutator
1969
1970 class Arguments:
1971 workflows = graphene.List(WorkflowID, required=True)
1972 n_edge_distance = Int(required=True)
1973
1974 result = GenericScalar()
1975
1976
1977 class Stop(Mutation):
1978 class Meta:
1979 description = sstrip(f'''
1980 Tell a workflow to shut down or stop a specified
1981 flow from spawning any further.
1982
1983 By default stopping workflows wait for submitted and running tasks
1984 to complete before shutting down. You can change this behaviour
1985 with the "mode" option.
1986
1987 Tasks that become ready after the shutdown is ordered will be
1988 submitted immediately if the workflow is restarted.
1989 Remaining task event handlers, job poll and kill commands, will
1990 be executed prior to shutdown, unless
1991 the stop mode is `{WorkflowStopMode.Now.name}`.
1992
1993 Valid for: paused, running, stopping workflows.
1994 ''')
1995 resolver = mutator
1996
1997 class Arguments:
1998 workflows = graphene.List(WorkflowID, required=True)
1999 mode = WorkflowStopMode(default_value=WorkflowStopMode.Clean)
2000 cycle_point = CyclePoint(
2001 description='Stop after the workflow reaches this cycle.'
2002 )
2003 clock_time = TimePoint(
2004 description='Stop after wall-clock time passes this point.'
2005 )
2006 task = TaskID(
2007 description='Stop after this task succeeds.'
2008 )
2009 flow_num = Int(
2010 description='Number of flow to stop.'
2011 )
2012
2013 result = GenericScalar()
2014
2015
2016 class ExtTrigger(Mutation):
2017 class Meta:
2018 description = sstrip('''
2019 Report an external event message to a scheduler.
2020
2021 External triggers allow any program to send
2022 messages to the Cylc scheduler. Cylc can use such
2023 messages as signals that an external prerequisite has
2024 been satisfied.
2025
2026 The ID argument should be unique to each external
2027 trigger event. When an incoming message satisfies
2028 a task's external trigger the message ID is broadcast
2029 to all downstream tasks in the cycle point as
2030 `$CYLC_EXT_TRIGGER_ID`. Tasks can use
2031 `$CYLC_EXT_TRIGGER_ID`, for example, to
2032 identify a new data file that the external
2033 triggering system is responding to.
2034
2035 Use the retry options in case the target workflow is down or out of
2036 contact.
2037
2038 Note: To manually trigger a task use "Trigger" not
2039 "ExtTrigger".
2040
2041 Valid for: paused, running workflows.
2042 ''')
2043 resolver = partial(mutator, command='put_ext_trigger')
2044
2045 class Arguments:
2046 workflows = graphene.List(WorkflowID, required=True)
2047 message = String(
2048 description='External trigger message.',
2049 required=True
2050 )
2051 id = String( # noqa: A003 (required for schema definition)
2052 description='Unique trigger ID.',
2053 required=True
2054 )
2055
2056 result = GenericScalar()
2057
2058
2059 class TaskMutation:
2060 class Arguments:
2061 workflows = graphene.List(
2062 WorkflowID,
2063 required=True
2064 )
2065 tasks = graphene.List(
2066 NamespaceIDGlob,
2067 required=True
2068 )
2069
2070 result = GenericScalar()
2071
2072
2073 class FlowMutationArguments:
2074 flow = graphene.List(
2075 graphene.NonNull(Flow),
2076 default_value=[],
2077 description=sstrip(f'''
2078 The flow(s) to set or trigger these tasks in.
2079
2080 By default, active tasks (n=0) stay in their assigned flow(s) and
2081 inactive tasks (n>0) will be assigned to all active flows.
2082
2083 Otherwise give a list of integers or one of the following strings:
2084 * {FLOW_NEW} - an automatically generated new flow number
2085 * {FLOW_NONE} - activity won't flow on (ignored for active tasks)
2086 ''')
2087 )
2088 flow_wait = Boolean(
2089 default_value=False,
2090 description=sstrip('''
2091 Should the workflow "wait" or "continue on" from this task?
2092
2093 If `false` the scheduler will spawn and run downstream tasks
2094 as normal (default).
2095
2096 If `true` the scheduler will not spawn the downstream tasks
2097 unless it has been caught by the same flow at a later time.
2098
2099 For example you might set this to True to trigger a task
2100 ahead of a flow, where you don't want the scheduler to
2101 "continue on" from this task until the flow has caught up
2102 with it.
2103 ''')
2104 )
2105 flow_descr = String(
2106 description=sstrip('''
2107 If starting a new flow, this field can be used to provide the
2108 new flow with a description for later reference.
2109 ''')
2110 )
2111
2112
2113 class Hold(Mutation, TaskMutation):
2114 class Meta:
2115 description = sstrip('''
2116 Hold tasks within a workflow.
2117
2118 Held tasks do not submit their jobs even if ready to run.
2119
2120 Valid for: paused, running workflows.
2121 ''')
2122 resolver = mutator
2123
2124
2125 class Release(Mutation, TaskMutation):
2126 class Meta:
2127 description = sstrip('''
2128 Release held tasks within a workflow.
2129
2130 See also the opposite command `hold`.
2131
2132 Valid for: paused, running workflows.
2133 ''')
2134 resolver = mutator
2135
2136
2137 class Kill(Mutation, TaskMutation):
2138 # TODO: This should be a job mutation?
2139 class Meta:
2140 description = sstrip('''
2141 Kill running or submitted jobs.
2142
2143 Valid for: paused, running, stopping workflows.
2144 ''')
2145 resolver = partial(mutator, command='kill_tasks')
2146
2147
2148 class Poll(Mutation, TaskMutation):
2149 class Meta:
2150 description = sstrip('''
2151 Poll (query) jobs to verify and update their statuses.
2152
2153 This checks the job status file and queries the
2154 job runner on the job platform.
2155
2156 Pollable tasks are those in the n=0 window with
2157 an associated job ID, including incomplete finished
2158 tasks.
2159
2160 Valid for: paused, running, stopping workflows.
2161 ''')
2162 resolver = partial(mutator, command='poll_tasks')
2163
2164 class Arguments(TaskMutation.Arguments):
2165 ...
2166
2167
2168 class Remove(Mutation, TaskMutation):
2169 class Meta:
2170 description = sstrip('''
2171 Remove one or more task instances from a running workflow.
2172
2173 Valid for: paused, running, stopping workflows.
2174 ''')
2175 resolver = partial(mutator, command='remove_tasks')
2176
2177 class Arguments(TaskMutation.Arguments):
2178 flow = graphene.List(
2179 graphene.NonNull(Flow),
2180 default_value=[],
2181 description=sstrip('''
2182 "Remove the tasks from the specified flows."
2183
2184 This should be a list of flow numbers.
2185 By default, tasks will be removed from all flows.
2186 ''')
2187 )
2188
2189
2190 class SetPrereqsAndOutputs(Mutation, TaskMutation):
2191 class Meta:
2192 description = sstrip("""
2193 Set task prerequisites or outputs.
2194
2195 By default, set all required outputs for target task(s) (including
2196 `submitted`, `started` and `succeeded` even if they are optional).
2197
2198 Setting prerequisites contributes to the task's readiness to run.
2199
2200 Setting outputs contributes to the task's completion, sets the
2201 corresponding prerequisites of child tasks, and sets any implied
2202 outputs:
2203 - `started` implies `submitted`.
2204 - `succeeded` and `failed` imply `started`.
2205 - custom outputs and `expired` do not imply any other outputs.
2206
2207 Valid for: paused, running, stopping workflows.
2208 """)
2209 resolver = partial(mutator, command='set')
2210
2211 class Arguments(TaskMutation.Arguments, FlowMutationArguments):
2212 outputs = graphene.List(
2213 OutputLabel,
2214 description='List of task outputs to set complete.'
2215 )
2216 prerequisites = graphene.List(
2217 PrerequisiteString,
2218 description='List of task prerequisites to set satisfied.'
2219 )
2220
2221
2222 class Trigger(Mutation, TaskMutation):
2223 class Meta:
2224 description = sstrip('''
2225 Manually trigger tasks, even in a paused workflow.
2226
2227 Triggering a task that is not yet queued will queue it.
2228
2229 Triggering a queued task runs it immediately.
2230
2231 Cylc queues restrict the number of jobs that can be active
2232 (submitted or running) at once. They release tasks to run
2233 when their active task count drops below the queue limit.
2234 So, depending on the active task count, you may need to
2235 trigger a task twice to make it run immediately.
2236
2237 Attempts to trigger active tasks will be ignored.
2238
2239 Valid for: paused, running workflows.
2240 ''')
2241 resolver = partial(mutator, command='force_trigger_tasks')
2242
2243 # BACK COMPAT: on_resume
2244 # Arg no longer used but retained for older clients.
2245 # From: 8.6
2246 # Remove at: 8.7
2247 class Arguments(TaskMutation.Arguments, FlowMutationArguments):
2248 on_resume = Boolean(
2249 default_value=False,
2250 description=sstrip('''
2251 DEPRECATED: this option is no longer needed and will be
2252 ignored by the scheduler.
2253 ''')
2254 )
2255
2256
2257 def _mut_field(cls):
2258 """Convert a mutation class into a field.
2259
2260 Sets the field metadata appropriately.
2261
2262 Args:
2263 field (class):
2264 Subclass of graphene.Mutation
2265
2266 Returns:
2267 graphene.Field
2268
2269 """
2270 return cls.Field(description=cls._meta.description)
2271
2272
2273 # Mutation declarations
2274
2275 class Mutations(ObjectType):
2276 # workflow actions
2277 broadcast = _mut_field(Broadcast)
2278 ext_trigger = _mut_field(ExtTrigger)
2279 message = _mut_field(Message)
2280 pause = _mut_field(Pause)
2281 reload = _mut_field(Reload)
2282 resume = _mut_field(Resume)
2283 set_verbosity = _mut_field(SetVerbosity)
2284 set_graph_window_extent = _mut_field(SetGraphWindowExtent)
2285 stop = _mut_field(Stop)
2286 set_hold_point = _mut_field(SetHoldPoint)
2287 release_hold_point = _mut_field(ReleaseHoldPoint)
2288
2289 # task actions
2290 hold = _mut_field(Hold)
2291 kill = _mut_field(Kill)
2292 poll = _mut_field(Poll)
2293 release = _mut_field(Release)
2294 remove = _mut_field(Remove)
2295 set = _mut_field(SetPrereqsAndOutputs) # noqa A003
2296 trigger = _mut_field(Trigger)
2297
2298 # job actions
2299 # TODO
2300
2301
2302 # ** Subscription Related ** #
2303
2304 # Used for the root entry points to yield the correct data
2305 # from within the subscription async gen resolver.
2306 SUB_RESOLVERS = {
2307 'workflows': get_workflows,
2308 'job': get_node_by_id,
2309 'jobs': get_nodes_all,
2310 'task': get_node_by_id,
2311 'tasks': get_nodes_all,
2312 'task_proxy': get_node_by_id,
2313 'task_proxies': get_nodes_all,
2314 'family': get_node_by_id,
2315 'families': get_nodes_all,
2316 'family_proxy': get_node_by_id,
2317 'family_proxies': get_nodes_all,
2318 'edges': get_edges_all,
2319 'nodes_edges': get_nodes_edges,
2320 }
2321
2322
2323 def delta_subs(
2324 root, info: 'GraphQLResolveInfo', **args) -> AsyncGenerator[Any, None]:
2325 """Generates the root data from the async gen resolver."""
2326 return get_resolvers(info).subscribe_delta(root, info, args)
2327
2328
2329 class Pruned(ObjectType):
2330 class Meta:
2331 description = sstrip('''
2332 Objects (e.g. workflows, tasks, jobs) which have been removed from
2333 the store.
2334 ''')
2335 workflow = String()
2336 families = graphene.List(String)
2337 family_proxies = graphene.List(String)
2338 jobs = graphene.List(String)
2339 tasks = graphene.List(String)
2340 task_proxies = graphene.List(String)
2341 edges = graphene.List(String)
2342
2343
2344 class Delta(Interface):
2345 """Interface for delta types.
2346
2347 Since we usually subscribe to the same fields for both added/updated
2348 deltas this interface makes writing fragments easier.
2349
2350 NOTE: This interface is specialised to the "added" type, other types must
2351 override fields as required.
2352 """
2353
2354 families = graphene.List(
2355 Family,
2356 description='Family definitions.',
2357 args=DEF_ARGS,
2358 strip_null=Boolean(),
2359 delta_store=Boolean(default_value=True),
2360 delta_type=String(default_value=DELTA_ADDED),
2361 resolver=get_nodes_by_ids
2362 )
2363 family_proxies = graphene.List(
2364 FamilyProxy,
2365 description='Family cycle instances.',
2366 args=PROXY_ARGS,
2367 strip_null=Boolean(),
2368 delta_store=Boolean(default_value=True),
2369 delta_type=String(default_value=DELTA_ADDED),
2370 resolver=get_nodes_by_ids
2371 )
2372 jobs = graphene.List(
2373 Job,
2374 description='Jobs.',
2375 args=JOB_ARGS,
2376 strip_null=Boolean(),
2377 delta_store=Boolean(default_value=True),
2378 delta_type=String(default_value=DELTA_ADDED),
2379 resolver=get_nodes_by_ids
2380 )
2381 tasks = graphene.List(
2382 Task,
2383 description='Task definitions.',
2384 args=DEF_ARGS,
2385 strip_null=Boolean(),
2386 delta_store=Boolean(default_value=True),
2387 delta_type=String(default_value=DELTA_ADDED),
2388 resolver=get_nodes_by_ids
2389 )
2390 task_proxies = graphene.List(
2391 TaskProxy,
2392 description='Task cycle instances.',
2393 args=PROXY_ARGS,
2394 strip_null=Boolean(),
2395 delta_store=Boolean(default_value=True),
2396 delta_type=String(default_value=DELTA_ADDED),
2397 resolver=get_nodes_by_ids
2398 )
2399 edges = graphene.List(
2400 Edge,
2401 description='Graph edges',
2402 args=EDGE_ARGS,
2403 strip_null=Boolean(),
2404 delta_store=Boolean(default_value=True),
2405 delta_type=String(default_value=DELTA_ADDED),
2406 resolver=get_edges_by_ids
2407 )
2408 workflow = Field(
2409 Workflow,
2410 description=Workflow._meta.description,
2411 strip_null=Boolean(),
2412 delta_store=Boolean(default_value=True),
2413 delta_type=String(default_value=DELTA_ADDED),
2414 resolver=get_workflow_by_id
2415 )
2416
2417
2418 class Added(ObjectType):
2419 class Meta:
2420 description = 'Added node/edge deltas.'
2421 interfaces = (Delta,)
2422
2423
2424 class Updated(ObjectType):
2425 class Meta:
2426 description = 'Updated node/edge deltas.'
2427 interfaces = (Delta,)
2428
2429 families = graphene.List(
2430 Family,
2431 description='Family definitions.',
2432 args=DEF_ARGS,
2433 strip_null=Boolean(),
2434 delta_store=Boolean(default_value=True),
2435 delta_type=String(default_value=DELTA_UPDATED),
2436 resolver=get_nodes_by_ids
2437 )
2438 family_proxies = graphene.List(
2439 FamilyProxy,
2440 description='Family cycle instances.',
2441 args=PROXY_ARGS,
2442 strip_null=Boolean(),
2443 delta_store=Boolean(default_value=True),
2444 delta_type=String(default_value=DELTA_UPDATED),
2445 resolver=get_nodes_by_ids
2446 )
2447 jobs = graphene.List(
2448 Job,
2449 description='Jobs.',
2450 args=JOB_ARGS,
2451 strip_null=Boolean(),
2452 delta_store=Boolean(default_value=True),
2453 delta_type=String(default_value=DELTA_UPDATED),
2454 resolver=get_nodes_by_ids
2455 )
2456 tasks = graphene.List(
2457 Task,
2458 description='Task definitions.',
2459 args=DEF_ARGS,
2460 strip_null=Boolean(),
2461 delta_store=Boolean(default_value=True),
2462 delta_type=String(default_value=DELTA_UPDATED),
2463 resolver=get_nodes_by_ids
2464 )
2465 task_proxies = graphene.List(
2466 TaskProxy,
2467 description='Task cycle instances.',
2468 args=PROXY_ARGS,
2469 strip_null=Boolean(),
2470 delta_store=Boolean(default_value=True),
2471 delta_type=String(default_value=DELTA_UPDATED),
2472 resolver=get_nodes_by_ids
2473 )
2474 edges = graphene.List(
2475 Edge,
2476 description='Graph edges.',
2477 args=EDGE_ARGS,
2478 strip_null=Boolean(),
2479 delta_store=Boolean(default_value=True),
2480 delta_type=String(default_value=DELTA_UPDATED),
2481 resolver=get_edges_by_ids
2482 )
2483 workflow = Field(
2484 Workflow,
2485 description=Workflow._meta.description,
2486 strip_null=Boolean(),
2487 delta_store=Boolean(default_value=True),
2488 delta_type=String(default_value=DELTA_UPDATED),
2489 resolver=get_workflow_by_id
2490 )
2491
2492
2493 class Deltas(ObjectType):
2494 class Meta:
2495 description = 'Grouped deltas of the WFS publish.'
2496 id = ID() # noqa: A003 (required for schema definition)
2497 shutdown = Boolean(default_value=False)
2498 added = Field(
2499 Added,
2500 description=Added._meta.description,
2501 strip_null=Boolean(),
2502 )
2503 updated = Field(
2504 Updated,
2505 description=Updated._meta.description,
2506 strip_null=Boolean(),
2507 )
2508 pruned = Field(
2509 Pruned,
2510 description=Pruned._meta.description,
2511 strip_null=Boolean(),
2512 )
2513
2514
2515 # TODO: Change to use subscribe arg/default. graphql-core has a subscribe field
2516 # for both Meta and Field, graphene at v3.4.3 does not.. As a workaround
2517 # the subscribe function is looked up via the following mapping:
2518 # See https://github.com/cylc/cylc-flow/issues/6688
2519 SUB_RESOLVER_MAPPING = {
2520 'deltas': delta_subs,
2521 'workflows': delta_subs,
2522 'job': delta_subs,
2523 'jobs': delta_subs,
2524 'task': delta_subs,
2525 'tasks': delta_subs,
2526 'taskProxy': delta_subs,
2527 'taskProxies': delta_subs,
2528 'family': delta_subs,
2529 'families': delta_subs,
2530 'familyProxy': delta_subs,
2531 'familyProxies': delta_subs,
2532 'edges': delta_subs,
2533 'nodesEdges': delta_subs,
2534 }
2535
2536
2537 class Subscriptions(ObjectType):
2538 """Defines the subscriptions available in the schema."""
2539 class Meta:
2540 description = 'Multi-Workflow root level subscriptions.'
2541
2542 deltas = Field(
2543 Deltas,
2544 description=Deltas._meta.description,
2545 workflows=graphene.List(
2546 ID, description="List of full ID, i.e. `~user/workflow_id`."
2547 ),
2548 strip_null=Boolean(default_value=False),
2549 initial_burst=Boolean(default_value=True),
2550 ignore_interval=Float(default_value=0.0),
2551 resolver=identity_resolve
2552 )
2553 workflows = graphene.List(
2554 Workflow,
2555 description=Workflow._meta.description,
2556 ids=graphene.List(ID, default_value=[]),
2557 exids=graphene.List(ID, default_value=[]),
2558 # TODO: Change these defaults post #3500 in coordination with WUI
2559 strip_null=Boolean(default_value=False),
2560 delta_store=Boolean(default_value=False),
2561 delta_type=String(default_value=DELTA_ADDED),
2562 initial_burst=Boolean(default_value=True),
2563 ignore_interval=Float(default_value=2.5),
2564 resolver=identity_resolve
2565 )
2566 job = Field(
2567 Job,
2568 description=Job._meta.description,
2569 id=ID(required=True),
2570 strip_null=Boolean(default_value=True),
2571 delta_store=Boolean(default_value=True),
2572 delta_type=String(default_value=DELTA_ADDED),
2573 initial_burst=Boolean(default_value=True),
2574 ignore_interval=Float(default_value=0.0),
2575 resolver=identity_resolve
2576 )
2577 jobs = graphene.List(
2578 Job,
2579 description=Job._meta.description,
2580 args=ALL_JOB_ARGS,
2581 strip_null=Boolean(default_value=True),
2582 delta_store=Boolean(default_value=True),
2583 delta_type=String(default_value=DELTA_ADDED),
2584 initial_burst=Boolean(default_value=True),
2585 ignore_interval=Float(default_value=0.0),
2586 resolver=identity_resolve
2587 )
2588 task = Field(
2589 Task,
2590 description=Task._meta.description,
2591 id=ID(required=True),
2592 strip_null=Boolean(default_value=True),
2593 delta_store=Boolean(default_value=True),
2594 delta_type=String(default_value=DELTA_ADDED),
2595 initial_burst=Boolean(default_value=True),
2596 ignore_interval=Float(default_value=0.0),
2597 resolver=identity_resolve
2598 )
2599 tasks = graphene.List(
2600 Task,
2601 description=Task._meta.description,
2602 args=ALL_DEF_ARGS,
2603 strip_null=Boolean(default_value=True),
2604 delta_store=Boolean(default_value=True),
2605 delta_type=String(default_value=DELTA_ADDED),
2606 initial_burst=Boolean(default_value=True),
2607 ignore_interval=Float(default_value=0.0),
2608 resolver=identity_resolve
2609 )
2610 task_proxy = Field(
2611 TaskProxy,
2612 description=TaskProxy._meta.description,
2613 id=ID(required=True),
2614 strip_null=Boolean(default_value=True),
2615 delta_store=Boolean(default_value=True),
2616 delta_type=String(default_value=DELTA_ADDED),
2617 initial_burst=Boolean(default_value=True),
2618 ignore_interval=Float(default_value=0.0),
2619 resolver=identity_resolve
2620 )
2621 task_proxies = graphene.List(
2622 TaskProxy,
2623 description=TaskProxy._meta.description,
2624 args=ALL_PROXY_ARGS,
2625 strip_null=Boolean(default_value=True),
2626 delta_store=Boolean(default_value=True),
2627 delta_type=String(default_value=DELTA_ADDED),
2628 initial_burst=Boolean(default_value=True),
2629 ignore_interval=Float(default_value=0.0),
2630 resolver=identity_resolve
2631 )
2632 family = Field(
2633 Family,
2634 description=Family._meta.description,
2635 id=ID(required=True),
2636 strip_null=Boolean(default_value=True),
2637 delta_store=Boolean(default_value=True),
2638 delta_type=String(default_value=DELTA_ADDED),
2639 initial_burst=Boolean(default_value=True),
2640 ignore_interval=Float(default_value=0.0),
2641 resolver=identity_resolve
2642 )
2643 families = graphene.List(
2644 Family,
2645 description=Family._meta.description,
2646 args=ALL_DEF_ARGS,
2647 strip_null=Boolean(default_value=True),
2648 delta_store=Boolean(default_value=True),
2649 delta_type=String(default_value=DELTA_ADDED),
2650 initial_burst=Boolean(default_value=True),
2651 ignore_interval=Float(default_value=0.0),
2652 resolver=identity_resolve
2653 )
2654 family_proxy = Field(
2655 FamilyProxy,
2656 description=FamilyProxy._meta.description,
2657 id=ID(required=True),
2658 strip_null=Boolean(default_value=True),
2659 delta_store=Boolean(default_value=True),
2660 delta_type=String(default_value=DELTA_ADDED),
2661 initial_burst=Boolean(default_value=True),
2662 ignore_interval=Float(default_value=0.0),
2663 resolver=identity_resolve
2664 )
2665 family_proxies = graphene.List(
2666 FamilyProxy,
2667 description=FamilyProxy._meta.description,
2668 args=ALL_PROXY_ARGS,
2669 strip_null=Boolean(default_value=True),
2670 delta_store=Boolean(default_value=True),
2671 delta_type=String(default_value=DELTA_ADDED),
2672 initial_burst=Boolean(default_value=True),
2673 ignore_interval=Float(default_value=0.0),
2674 resolver=identity_resolve
2675 )
2676 edges = graphene.List(
2677 Edge,
2678 description=Edge._meta.description,
2679 args=ALL_EDGE_ARGS,
2680 strip_null=Boolean(default_value=True),
2681 delta_store=Boolean(default_value=True),
2682 delta_type=String(default_value=DELTA_ADDED),
2683 initial_burst=Boolean(default_value=True),
2684 ignore_interval=Float(default_value=0.0),
2685 resolver=identity_resolve
2686 )
2687 nodes_edges = Field(
2688 NodesEdges,
2689 description=NodesEdges._meta.description,
2690 args=NODES_EDGES_ARGS_ALL,
2691 strip_null=Boolean(default_value=True),
2692 delta_store=Boolean(default_value=True),
2693 delta_type=String(default_value=DELTA_ADDED),
2694 initial_burst=Boolean(default_value=True),
2695 ignore_interval=Float(default_value=0.0),
2696 resolver=identity_resolve
2697 )
2698
2699
2700 schema = Schema(query=Queries, subscription=Subscriptions, mutation=Mutations)