forked from cylc/cylc-flow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.py
More file actions
2786 lines (2489 loc) · 107 KB
/
config.py
File metadata and controls
2786 lines (2489 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Parse and validate the workflow definition file
Set local values of variables to give workflow context before parsing
config, i.e for template filters (Jinja2, python ...etc) and possibly
needed locally by event handlers. This is needed for both running and
non-running workflow parsing (obtaining config/graph info). Potentially
task-specific due to different directory paths on different task hosts,
however, they are overridden by tasks prior to job submission.
Do some consistency checking, then construct task proxy objects and graph
structures.
"""
from contextlib import suppress
from copy import copy
from fnmatch import fnmatchcase
import os
from pathlib import Path
import re
from textwrap import wrap
import traceback
from types import SimpleNamespace
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
Optional,
Set,
Tuple,
Union,
)
from metomi.isodatetime.data import Calendar
from metomi.isodatetime.dumpers import TimePointDumper
from metomi.isodatetime.exceptions import IsodatetimeError
from metomi.isodatetime.parsers import DurationParser
from metomi.isodatetime.timezone import get_local_time_zone_format
from cylc.flow import LOG
from cylc.flow.c3mro import C3
from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
from cylc.flow.cfgspec.workflow import RawWorkflowConfig
from cylc.flow.cycling.integer import IntegerInterval
from cylc.flow.cycling.iso8601 import (
ISO8601Interval,
ingest_time,
)
from cylc.flow.cycling.loader import (
INTEGER_CYCLING_TYPE,
ISO8601_CYCLING_TYPE,
get_dump_format,
get_interval,
get_interval_cls,
get_point,
get_point_relative,
get_sequence,
get_sequence_cls,
init_cyclers,
)
from cylc.flow.exceptions import (
CylcError,
InputError,
IntervalParsingError,
ParamExpandError,
TaskDefError,
WorkflowConfigError,
)
import cylc.flow.flags
from cylc.flow.graph_parser import GraphParser
from cylc.flow.graphnode import GraphNodeParser
from cylc.flow.id import Tokens
from cylc.flow.listify import listify
from cylc.flow.log_level import verbosity_to_env
from cylc.flow.param_expand import NameExpander
from cylc.flow.parsec.OrderedDict import OrderedDictWithDefaults
from cylc.flow.parsec.exceptions import ItemNotFoundError
from cylc.flow.parsec.upgrade import upgrader
from cylc.flow.parsec.util import (
dequote,
replicate,
)
from cylc.flow.pathutil import (
get_cylc_run_dir,
get_workflow_name_from_id,
is_relative_to,
)
from cylc.flow.run_modes import (
WORKFLOW_ONLY_MODES,
RunMode,
)
from cylc.flow.run_modes.simulation import configure_sim_mode
from cylc.flow.run_modes.skip import skip_mode_validate
from cylc.flow.subprocctx import SubFuncContext
from cylc.flow.task_events_mgr import (
EventData,
TaskEventsManager,
get_event_handler_data,
)
from cylc.flow.task_id import TaskID
from cylc.flow.task_outputs import (
TASK_OUTPUT_FAILED,
TASK_OUTPUT_FINISHED,
TASK_OUTPUT_SUCCEEDED,
TaskOutputs,
get_completion_expression,
get_optional_outputs,
get_trigger_completion_variable_maps,
trigger_to_completion_variable,
)
from cylc.flow.task_qualifiers import (
ALT_QUALIFIERS,
TASK_QUALIFIERS,
)
from cylc.flow.task_trigger import (
Dependency,
TaskTrigger,
)
from cylc.flow.taskdef import TaskDef
from cylc.flow.unicode_rules import (
TaskMessageValidator,
TaskNameValidator,
TaskOutputValidator,
XtriggerNameValidator,
)
from cylc.flow.wallclock import (
get_current_time_string,
get_utc_mode,
set_utc_mode,
)
from cylc.flow.workflow_events import WorkflowEventHandler
from cylc.flow.workflow_files import (
NO_TITLE,
WorkflowFiles,
check_deprecation,
)
from cylc.flow.xtrigger_mgr import XtriggerCollator
if TYPE_CHECKING:
from optparse import Values
from cylc.flow.cycling import (
IntervalBase,
PointBase,
SequenceBase,
)
RE_CLOCK_OFFSET = re.compile(
rf'''
^
\s*
({TaskID.NAME_RE}) # task name
(?:\(\s*(.+)\s*\))? # optional (arguments, ...)
\s*
$
''',
re.X,
)
RE_EXT_TRIGGER = re.compile(
r'''
^
\s*
(.*) # task name
\s*
\(\s*(.+)\s*\) # required (arguments, ...)
\s*
$
''',
re.X,
)
RE_SEC_MULTI_SEQ = re.compile(r'(?![^(]+\)),')
RE_WORKFLOW_ID_VAR = re.compile(r'\${?CYLC_WORKFLOW_(REG_)?ID}?')
RE_TASK_NAME_VAR = re.compile(r'\${?CYLC_TASK_NAME}?')
RE_VARNAME = re.compile(r'^[a-zA-Z_][\w]*$')
def check_varnames(env: Iterable[str]) -> List[str]:
"""Check a list of env var names for legality.
Return a list of bad names (empty implies success).
Examples:
>>> check_varnames(['foo', 'BAR', '+baz'])
['+baz']
"""
bad = []
for varname in env:
if not RE_VARNAME.match(varname):
bad.append(varname)
return bad
def interpolate_template(tmpl, params_dict):
"""Try the string interpolation/formatting operator `%` on a template
string with a dictionary of parameters.
E.g. 'a_%(foo)d' % {'foo': 12}
If it fails, raises ParamExpandError, but if the string does not contain
`%(`, it just returns the string.
Examples:
>>> interpolate_template('_%(a)s_', {'a': 'A'})
'_A_'
>>> interpolate_template('%(a)s', {'b': 'B'})
Traceback (most recent call last):
cylc.flow.exceptions.ParamExpandError: bad parameter
>>> interpolate_template('%(a)d', {'a': 'A'})
Traceback (most recent call last):
cylc.flow.exceptions.ParamExpandError: wrong data type for parameter
>>> interpolate_template('%(as', {})
Traceback (most recent call last):
cylc.flow.exceptions.ParamExpandError: bad template syntax
"""
if '%(' not in tmpl:
return tmpl # User probably not trying to use param template
try:
return tmpl % params_dict
except KeyError:
raise ParamExpandError('bad parameter') from None
except TypeError:
raise ParamExpandError('wrong data type for parameter') from None
except ValueError:
raise ParamExpandError('bad template syntax') from None
class WorkflowConfig:
"""Class for workflow configuration items and derived quantities."""
CHECK_CIRCULAR_LIMIT = 100 # If no. tasks > this, don't check circular
VIS_N_POINTS = 3
MAX_WARNING_LINES = 5
def __init__(
self,
workflow: str,
fpath: Union[Path, str],
options: 'Values',
template_vars: Optional[Mapping[str, Any]] = None,
output_fname: Optional[str] = None,
mem_log_func: Optional[Callable[[str], None]] = None,
run_dir: Optional[str] = None,
log_dir: Optional[str] = None,
work_dir: Optional[str] = None,
share_dir: Optional[str] = None,
force_compat_mode: bool = False,
) -> None:
"""
Initialize the workflow config object.
Args:
workflow: workflow ID
fpath: workflow config file path
options: CLI options
force_compat_mode:
If True, forces Cylc to use compatibility mode
overriding compatibility mode checks.
See https://github.com/cylc/cylc-rose/issues/319
"""
check_deprecation(Path(fpath), force_compat_mode=force_compat_mode)
self.mem_log = mem_log_func
if self.mem_log is None:
self.mem_log = lambda x: None
self.mem_log("config.py:config.py: start init config")
self.workflow = workflow
self.workflow_name = get_workflow_name_from_id(self.workflow)
self.fpath: Path = Path(fpath)
self.fdir = str(self.fpath.parent)
self.run_dir = run_dir
self.log_dir = log_dir
self.share_dir = share_dir
self.work_dir = work_dir
self.options = options
self.implicit_tasks: Set[str] = set()
self.edges: Dict[
'SequenceBase', Set[Tuple[str, str, bool, bool]]
] = {}
self.taskdefs: Dict[str, TaskDef] = {}
self.expiration_offsets = {}
self.ext_triggers = {} # Old external triggers (client/server)
self.xtrigger_collator = XtriggerCollator()
self.workflow_polling_tasks = {} # type: ignore # TODO figure out type
self.initial_point: 'PointBase'
self.start_point: 'PointBase'
self.stop_point: Optional['PointBase'] = None
self.final_point: Optional['PointBase'] = None
self.sequences: List['SequenceBase'] = []
self.actual_first_point: Optional['PointBase'] = None
self._start_point_for_actual_first_point: Optional['PointBase'] = None
self.task_param_vars = {} # type: ignore # TODO figure out type
self.runahead_limit: Optional['IntervalBase'] = None
# runtime hierarchy dicts keyed by namespace name:
self.runtime: Dict[str, dict] = { # TODO figure out type
# lists of parent namespaces
'parents': {},
# lists of C3-linearized ancestor namespaces
'linearized ancestors': {},
# lists of first-parent ancestor namespaces
'first-parent ancestors': {},
# sets of all descendant namespaces
# (not including the final tasks)
'descendants': {},
# sets of all descendant namespaces from the first-parent
# hierarchy (first parents are collapsible in visualization)
'first-parent descendants': {},
}
# tasks
self.leaves = [] # TODO figure out type
# one up from root
self.feet = [] # type: ignore # TODO figure out type
# Export local environmental workflow context before config parsing.
self.process_workflow_env()
# parse, upgrade, validate the workflow, but don't expand with default
# items
self.mem_log("config.py: before RawWorkflowConfig init")
if output_fname:
output_fname = os.path.expandvars(output_fname)
self.pcfg = RawWorkflowConfig(
fpath,
output_fname,
template_vars,
self.options
)
self.mem_log("config.py: after RawWorkflowConfig init")
self.mem_log("config.py: before get(sparse=True")
self.cfg = self.pcfg.get(sparse=True)
self.mem_log("config.py: after get(sparse=True)")
if 'scheduler' in self.cfg and 'install' in self.cfg['scheduler']:
self.get_validated_rsync_includes()
# First check for the essential scheduling section.
if 'scheduling' not in self.cfg:
raise WorkflowConfigError("missing [scheduling] section.")
if 'graph' not in self.cfg['scheduling']:
raise WorkflowConfigError("missing [scheduling][[graph]] section.")
# (The check that 'graph' is defined is below).
# Override the workflow defn with an initial point from the CLI.
icp_str = getattr(self.options, 'icp', None)
if icp_str is not None:
self.cfg['scheduling']['initial cycle point'] = icp_str
self.prelim_process_graph()
# allow test workflows with no [runtime]:
if 'runtime' not in self.cfg:
self.cfg['runtime'] = OrderedDictWithDefaults()
if 'root' not in self.cfg['runtime']:
self.cfg['runtime']['root'] = OrderedDictWithDefaults()
try:
# Ugly hack to avoid templates getting included in parameters
parameter_values = {
key: value for key, value in
self.cfg['task parameters'].items()
if key != 'templates'
}
except KeyError:
# (Workflow config defaults not put in yet.)
parameter_values = {}
try:
parameter_templates = self.cfg['task parameters']['templates']
except KeyError:
parameter_templates = {}
# parameter values and templates are normally needed together.
self.parameters = (parameter_values, parameter_templates)
LOG.debug("Expanding [runtime] namespace lists and parameters")
# Set default parameter expansion templates if necessary.
for pname, pvalues in parameter_values.items():
if pvalues and pname not in parameter_templates:
if any(not isinstance(pvalue, int) for pvalue in pvalues):
# Strings, bare parameter values
parameter_templates[pname] = r'_%%(%s)s' % pname
elif any(pvalue < 0 for pvalue in pvalues):
# Integers, with negative value(s)
# Prefix values with signs and parameter names
parameter_templates[pname] = r'_%s%%(%s)+0%dd' % (
pname, pname,
max(len(str(pvalue)) for pvalue in pvalues))
else:
# Integers, positive only
# Prefix values with parameter names
parameter_templates[pname] = r'_%s%%(%s)0%dd' % (
pname, pname, len(str(max(pvalues))))
# Expand parameters in 'special task' lists.
if 'special tasks' in self.cfg['scheduling']:
for spec, names in self.cfg['scheduling']['special tasks'].items():
self.cfg['scheduling']['special tasks'][spec] = (
self._expand_name_list(names))
# Expand parameters in internal queue member lists.
if 'queues' in self.cfg['scheduling']:
for queue, cfg in self.cfg['scheduling']['queues'].items():
if 'members' not in cfg:
continue
self.cfg['scheduling']['queues'][queue]['members'] = (
self._expand_name_list(cfg['members']))
# Check environment variable names and parameter environment templates
# Done before inheritance to avoid repetition
self.check_env_names()
self.check_param_env_tmpls()
self.check_for_owner(self.cfg['runtime'])
self.mem_log("config.py: before _expand_runtime")
self._expand_runtime()
self.mem_log("config.py: after _expand_runtime")
self.ns_defn_order = list(self.cfg['runtime'])
self.mem_log("config.py: before compute_family_tree")
# do sparse inheritance
self.compute_family_tree()
self.mem_log("config.py: after compute_family_tree")
self.mem_log("config.py: before inheritance")
self.compute_inheritance()
self.mem_log("config.py: after inheritance")
# filter task environment variables after inheritance
self.filter_env()
# Now add config defaults. Items added prior to this end up in the
# sparse dict (e.g. parameter-expanded namespaces).
self.mem_log("config.py: before get(sparse=False)")
self.cfg = self.pcfg.get(sparse=False)
self.mem_log("config.py: after get(sparse=False)")
# These 2 must be called before call to init_cyclers(self.cfg):
self.set_experimental_features()
self.process_utc_mode()
self.process_cycle_point_tz()
# after the call to init_cyclers, we can start getting proper points.
init_cyclers(self.cfg)
self.cycling_type = get_interval_cls().get_null().TYPE
self.cycle_point_dump_format = get_dump_format(self.cycling_type)
# Initial point from workflow definition (or CLI override above).
self.process_initial_cycle_point()
self.process_start_cycle_point()
self.process_final_cycle_point()
self.process_stop_cycle_point()
# Parse special task cycle point offsets, and replace family names.
LOG.debug("Parsing [special tasks]")
for s_type in self.cfg['scheduling']['special tasks']:
result = copy(self.cfg['scheduling']['special tasks'][s_type])
extn = ''
for item in self.cfg['scheduling']['special tasks'][s_type]:
name = item
if s_type == 'external-trigger':
match = RE_EXT_TRIGGER.match(item)
if match is None:
raise WorkflowConfigError(
"Illegal %s spec: %s" % (s_type, item)
)
name, ext_trigger_msg = match.groups()
extn = "(" + ext_trigger_msg + ")"
elif s_type in ['clock-trigger', 'clock-expire']:
match = RE_CLOCK_OFFSET.match(item)
if match is None:
raise WorkflowConfigError(
"Illegal %s spec: %s" % (s_type, item)
)
if (
self.cfg['scheduling']['cycling mode'] !=
Calendar.MODE_GREGORIAN
):
raise WorkflowConfigError(
"%s tasks require "
"[scheduling]cycling mode=%s" % (
s_type, Calendar.MODE_GREGORIAN)
)
name, offset_string = match.groups()
if not offset_string:
offset_string = "PT0M"
if (
cylc.flow.flags.verbosity > 0
and offset_string.startswith("-")
):
LOG.warning(
"%s offsets are normally positive: %s" % (
s_type, item))
try:
offset_interval = (
get_interval(offset_string).standardise())
except IntervalParsingError:
raise WorkflowConfigError(
"Illegal %s spec: %s" % (s_type, offset_string)
) from None
extn = "(" + offset_string + ")"
# Replace family names with members.
if name in self.runtime['descendants']:
result.remove(item)
for member in self.runtime['descendants'][name]:
if member in self.runtime['descendants']:
# (sub-family)
continue
result.append(member + extn)
if s_type == 'clock-expire':
self.expiration_offsets[member] = offset_interval
if s_type == 'external-trigger':
self.ext_triggers[member] = ext_trigger_msg
elif s_type == 'clock-expire':
self.expiration_offsets[name] = offset_interval
elif s_type == 'external-trigger':
self.ext_triggers[name] = dequote(ext_trigger_msg)
self.cfg['scheduling']['special tasks'][s_type] = result
self.process_config_env()
self._upg_wflow_event_names()
self.mem_log("config.py: before load_graph()")
self.load_graph()
self.mem_log("config.py: after load_graph()")
self._set_completion_expressions()
self.process_runahead_limit()
run_mode = RunMode.get(self.options)
if run_mode in {RunMode.SIMULATION, RunMode.DUMMY}:
for taskdef in self.taskdefs.values():
configure_sim_mode(taskdef.rtconfig, None, False)
self.configure_workflow_state_polling_tasks()
for taskdef in self.taskdefs.values():
self._check_task_event_names(taskdef)
self._check_task_event_handlers(taskdef)
self._check_special_tasks() # adds to self.implicit_tasks
self._check_explicit_cycling()
self._warn_if_queues_have_implicit_tasks(
self.cfg, self.taskdefs, self.MAX_WARNING_LINES)
self._check_implicit_tasks()
self._check_sequence_bounds()
self.validate_namespace_names()
# Check that external trigger messages are only used once (they have to
# be discarded immediately to avoid triggering the next instance of the
# just-triggered task).
seen = {}
for name, tdef in self.taskdefs.items():
for msg in tdef.external_triggers:
if msg not in seen:
seen[msg] = name
else:
LOG.error(
"External trigger '%s'\n used in tasks %s and %s." % (
msg, name, seen[msg]))
raise WorkflowConfigError(
"external triggers must be used only once.")
self.upgrade_clock_triggers()
self.leaves = self.get_task_name_list()
for ancestors in self.runtime['first-parent ancestors'].values():
try:
foot = ancestors[-2] # one back from 'root'
except IndexError:
pass
else:
if foot not in self.feet:
self.feet.append(foot)
self.feet.sort() # sort effects get_graph_raw output
self.process_metadata_urls()
if getattr(self.options, 'is_validate', False):
self.mem_log("config.py: before _check_circular()")
self._check_circular()
self.mem_log("config.py: after _check_circular()")
self.mem_log("config.py: end init config")
skip_mode_validate(self.taskdefs)
def set_experimental_features(self):
all_ = self.cfg['scheduler']['experimental']['all']
self.experimental = SimpleNamespace(**{
key.replace(' ', '_'): value or all_
for key, value in self.cfg['scheduler']['experimental'].items()
if key != 'all'
})
@staticmethod
def _warn_if_queues_have_implicit_tasks(
config, taskdefs, max_warning_lines
):
"""Warn if queues contain implict tasks.
"""
implicit_q_msg = ''
# Get the names of the first N implicit queue tasks:
for queue in config["scheduling"]["queues"]:
for name in config["scheduling"]["queues"][queue][
"members"
]:
if (
name not in taskdefs
and name not in config['runtime']
and len(implicit_q_msg.split('\n')) <= max_warning_lines
):
implicit_q_msg += f'\n * task {name!r} in queue {queue!r}'
# Warn users if tasks are implied by queues.
if implicit_q_msg:
truncation_msg = (
f"\n...showing first {max_warning_lines} tasks..."
if len(implicit_q_msg.split('\n')) > max_warning_lines
else ""
)
LOG.warning(
'Queues contain tasks not defined in'
f' runtime: {implicit_q_msg}{truncation_msg}'
)
def prelim_process_graph(self) -> None:
"""Ensure graph is not empty; set integer cycling mode and icp/fcp = 1
for simplest "R1 = foo" type graphs.
"""
graphdict = self.cfg['scheduling']['graph']
if not any(graphdict.values()):
raise WorkflowConfigError('No workflow dependency graph defined.')
if (
'cycling mode' not in self.cfg['scheduling'] and
self.cfg['scheduling'].get('initial cycle point', '1') == '1' and
all(item in ['graph', '1', 'R1'] for item in graphdict)
):
# Pure acyclic graph, assume integer cycling mode with '1' cycle
self.cfg['scheduling']['cycling mode'] = INTEGER_CYCLING_TYPE
for key in ('initial cycle point', 'final cycle point'):
if key not in self.cfg['scheduling']:
self.cfg['scheduling'][key] = '1'
def process_utc_mode(self):
"""Set UTC mode from config or from stored value on restart.
Sets:
self.cfg['scheduler']['UTC mode']
The UTC mode flag
"""
cfg_utc_mode = self.cfg['scheduler']['UTC mode']
# Get the original UTC mode if restart:
orig_utc_mode = getattr(self.options, 'utc_mode', None)
if orig_utc_mode is None:
# Not a restart - will save config value
if cfg_utc_mode is not None:
orig_utc_mode = cfg_utc_mode
else:
orig_utc_mode = glbl_cfg().get(['scheduler', 'UTC mode'])
elif cfg_utc_mode is not None and cfg_utc_mode != orig_utc_mode:
LOG.warning(
"UTC mode = {0} specified in configuration, but is stored as "
"{1} from the initial run. The workflow will continue to use "
"UTC mode = {1}"
.format(cfg_utc_mode, orig_utc_mode)
)
self.cfg['scheduler']['UTC mode'] = orig_utc_mode
set_utc_mode(orig_utc_mode)
def process_cycle_point_tz(self):
"""Set the cycle point time zone from config or from stored value
on restart.
Ensure workflows restart with the same cycle point time zone even after
system time zone changes e.g. DST (the value is put in db by
Scheduler).
Sets:
self.cfg['scheduler']['cycle point time zone']
"""
cfg_cp_tz = self.cfg['scheduler'].get('cycle point time zone')
if (
not cylc.flow.flags.cylc7_back_compat
and not cfg_cp_tz
):
cfg_cp_tz = 'Z'
# Get the original workflow run time zone if restart:
orig_cp_tz = getattr(self.options, 'cycle_point_tz', None)
if orig_cp_tz is None:
# Not a restart
if cfg_cp_tz is None:
if get_utc_mode() is True:
orig_cp_tz = 'Z'
else:
orig_cp_tz = get_local_time_zone_format()
else:
orig_cp_tz = cfg_cp_tz
elif cfg_cp_tz is not None:
dmp = TimePointDumper()
if dmp.get_time_zone(cfg_cp_tz) != dmp.get_time_zone(orig_cp_tz):
LOG.warning(
"cycle point time zone = {0} specified in configuration, "
"but there is a stored value of {1} from the initial run. "
"The workflow will continue to run in {1}"
.format(cfg_cp_tz, orig_cp_tz)
)
self.cfg['scheduler']['cycle point time zone'] = orig_cp_tz
def process_initial_cycle_point(self) -> None:
"""Validate and set initial cycle point from flow.cylc or options.
Sets:
self.initial_point
self.cfg['scheduling']['initial cycle point']
self.evaluated_icp
Raises:
WorkflowConfigError - if it fails to validate
"""
orig_icp = self.cfg['scheduling']['initial cycle point']
if self.cycling_type == INTEGER_CYCLING_TYPE:
if orig_icp is None:
orig_icp = '1'
icp = orig_icp
elif self.cycling_type == ISO8601_CYCLING_TYPE:
if orig_icp is None:
raise WorkflowConfigError(
"This workflow requires an initial cycle point.")
if orig_icp == "now":
icp = get_current_time_string()
else:
try:
icp = ingest_time(orig_icp, get_current_time_string())
except IsodatetimeError as exc:
raise WorkflowConfigError(str(exc)) from None
self.evaluated_icp = None
if icp != orig_icp:
# now/next()/previous() was used, need to store
# evaluated point in DB
self.evaluated_icp = icp
self.initial_point = get_point(icp).standardise()
self.cfg['scheduling']['initial cycle point'] = str(self.initial_point)
# Validate initial cycle point against any constraints
constraints = self.cfg['scheduling']['initial cycle point constraints']
if constraints:
valid_icp = False
for entry in constraints:
possible_pt = get_point_relative(
entry, self.initial_point
).standardise()
if self.initial_point == possible_pt:
valid_icp = True
break
if not valid_icp:
raise WorkflowConfigError(
f"Initial cycle point {self.initial_point} does not meet "
f"the constraints {constraints}")
def process_start_cycle_point(self) -> None:
"""Set the start cycle point from options.
Sets:
self.options.startcp
self.start_point
"""
startcp = getattr(self.options, 'startcp', None)
starttask = getattr(self.options, 'starttask', None)
if startcp is not None and starttask is not None:
raise InputError(
"--start-cycle-point and --start-task are mutually exclusive"
)
if startcp:
# Start from a point later than initial point.
if self.options.startcp == 'now':
self.options.startcp = get_current_time_string()
self.start_point = get_point(self.options.startcp).standardise()
elif starttask:
# Start from designated task(s).
# Select the earliest start point for use in pre-initial ignore.
try:
cycle_points = [
Tokens(taskid, relative=True)['cycle']
for taskid in self.options.starttask
]
except ValueError as exc:
raise InputError(str(exc)) from None
self.start_point = min(
get_point(cycle).standardise()
for cycle in cycle_points if cycle
)
else:
# Start from the initial point.
self.start_point = self.initial_point
def process_final_cycle_point(self) -> None:
"""Validate and set the final cycle point from flow.cylc or options.
Sets:
self.final_point
self.cfg['scheduling']['final cycle point']
Raises:
WorkflowConfigError - if it fails to validate
"""
if self.cfg['scheduling']['final cycle point'] == '':
# (Unlike other cycle point settings in config, fcp is treated as
# a string by parsec to allow for expressions like '+P1Y')
self.cfg['scheduling']['final cycle point'] = None
fcp_str = getattr(self.options, 'fcp', None)
if fcp_str == 'reload':
fcp_str = self.options.fcp = None
if fcp_str is None:
fcp_str = self.cfg['scheduling']['final cycle point']
if fcp_str is not None:
# Is the final "point"(/interval) relative to initial?
if self.cycling_type == INTEGER_CYCLING_TYPE:
if "P" in fcp_str:
# Relative, integer cycling.
self.final_point = get_point_relative(
self.cfg['scheduling']['final cycle point'],
self.initial_point
).standardise()
else:
with suppress(IsodatetimeError):
# Relative, ISO8601 cycling.
self.final_point = get_point_relative(
fcp_str, self.initial_point).standardise()
if self.final_point is None:
# Must be absolute.
self.final_point = get_point(fcp_str).standardise()
self.cfg['scheduling']['final cycle point'] = str(self.final_point)
if (self.final_point is not None and
self.initial_point > self.final_point):
raise WorkflowConfigError(
f"The initial cycle point:{self.initial_point} is after the "
f"final cycle point:{self.final_point}.")
# Validate final cycle point against any constraints
constraints = self.cfg['scheduling']['final cycle point constraints']
if constraints and self.final_point is not None:
valid_fcp = False
for entry in constraints:
possible_pt = get_point_relative(
entry, self.final_point).standardise()
if self.final_point == possible_pt:
valid_fcp = True
break
if not valid_fcp:
raise WorkflowConfigError(
f"Final cycle point {self.final_point} does not "
f"meet the constraints {constraints}")
def process_stop_cycle_point(self) -> None:
"""Set the stop after cycle point.
In decreasing priority, it is set:
* From the command line option (``--stopcp=XYZ``) or database.
* From the flow.cylc file (``[scheduling]stop after cycle point``).
However, if ``--stopcp=reload`` on the command line during restart,
the ``[scheduling]stop after cycle point`` value is used.
"""
stopcp_str: Optional[str] = getattr(self.options, 'stopcp', None)
if stopcp_str == 'reload':
stopcp_str = self.options.stopcp = None
if stopcp_str is None:
stopcp_str = self.cfg['scheduling']['stop after cycle point']
if stopcp_str:
self.stop_point = get_point_relative(
stopcp_str,
self.initial_point,
).standardise()
if (
self.final_point is not None
and self.stop_point is not None
and self.stop_point > self.final_point
):
LOG.warning(
f"Stop cycle point '{self.stop_point}' will have no "
"effect as it is after the final cycle "
f"point '{self.final_point}'."
)
self.stop_point = None
stopcp_str = str(self.stop_point) if self.stop_point else None
self.cfg['scheduling']['stop after cycle point'] = stopcp_str
def _check_implicit_tasks(self) -> None:
"""Raise WorkflowConfigError if implicit tasks are found in graph or
queue config, unless allowed by config."""
if not self.implicit_tasks:
return
print_limit = 10
tasks_str = '\n * '.join(list(self.implicit_tasks)[:print_limit])
num = len(self.implicit_tasks)
if num > print_limit:
tasks_str += f"\n and {num} more"
msg = (
"implicit tasks detected (no entry under [runtime]):\n"
f" * {tasks_str}"
)
if self.cfg['scheduler']['allow implicit tasks']:
LOG.debug(msg)
return
# Check if implicit tasks explicitly disallowed
try:
is_disallowed = self.pcfg.get(
['scheduler', 'allow implicit tasks'], sparse=True
) is False
except ItemNotFoundError:
is_disallowed = False
if is_disallowed:
raise WorkflowConfigError(msg)
# Otherwise "[scheduler]allow implicit tasks" is not set
if not cylc.flow.flags.cylc7_back_compat:
msg += (
"\nTo allow implicit tasks, use "
f"'{WorkflowFiles.FLOW_FILE}[scheduler]allow implicit tasks'"
)
# Allow implicit tasks in back-compat mode unless rose-suite.conf
# present (to maintain compat with Rose 2019)
elif not (self.fpath.parent / "rose-suite.conf").is_file():
LOG.debug(msg)
return
raise WorkflowConfigError(msg)
def _check_circular(self):
"""Check for circular dependence in graph."""
if (len(self.taskdefs) > self.CHECK_CIRCULAR_LIMIT and
not getattr(self.options, 'check_circular', False)):
LOG.info(
f"Number of tasks is > {self.CHECK_CIRCULAR_LIMIT}; will not "
"check graph for circular dependencies. To run this check"
" anyway use the option --check-circular.")
return
start_point_str = self.cfg['scheduling']['initial cycle point']
raw_graph = self.get_graph_raw(
start_point_str,
stop_point_str=None,
sort=False,
)
lhs2rhss = {} # left hand side to right hand sides
rhs2lhss = {} # right hand side to left hand sides
for lhs, rhs in raw_graph:
lhs2rhss.setdefault(lhs, set())
lhs2rhss[lhs].add(rhs)
rhs2lhss.setdefault(rhs, set())
rhs2lhss[rhs].add(lhs)
self._check_circular_helper(lhs2rhss, rhs2lhss)
if rhs2lhss:
# Before reporting circular dependence, pick out all the edges with
# no outgoings.
self._check_circular_helper(rhs2lhss, lhs2rhss)
err_msg = ''
for rhs, lhss in sorted(rhs2lhss.items()):
for lhs in sorted(lhss):
err_msg += ' %s => %s' % (
Tokens(
cycle=str(lhs[1]),
task=lhs[0]
).relative_id,