-
Notifications
You must be signed in to change notification settings - Fork 90
/
config.py
2193 lines (1968 loc) · 91.8 KB
/
config.py
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
#!/usr/bin/env python2
# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2019 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 suite definition file
Set local values of variables to give suite 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 suite 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 copy import copy
from fnmatch import fnmatchcase
import os
import re
import traceback
from isodatetime.data import Calendar
from isodatetime.parsers import DurationParser
from parsec.OrderedDict import OrderedDictWithDefaults
from parsec.util import replicate
from cylc import LOG
from cylc.c3mro import C3
from cylc.conditional_simplifier import ConditionalSimplifier
from cylc.exceptions import CylcError
from cylc.graph_parser import GraphParser
from cylc.param_expand import NameExpander
from cylc.cfgspec.glbl_cfg import glbl_cfg
from cylc.cfgspec.suite import RawSuiteConfig
from cylc.cycling.loader import (
get_point, get_point_relative, get_interval, get_interval_cls,
get_sequence, get_sequence_cls, init_cyclers, INTEGER_CYCLING_TYPE,
ISO8601_CYCLING_TYPE)
from cylc.cycling import IntervalParsingError
from cylc.cycling.iso8601 import ingest_time
import cylc.flags
from cylc.graphnode import GraphNodeParser, GraphNodeError
from cylc.print_tree import print_tree
from cylc.subprocctx import SubFuncContext
from cylc.suite_srv_files_mgr import SuiteSrvFilesManager
from cylc.taskdef import TaskDef, TaskDefError
from cylc.task_id import TaskID
from cylc.task_outputs import TASK_OUTPUT_SUCCEEDED
from cylc.task_trigger import TaskTrigger, Dependency
from cylc.wallclock import get_current_time_string, set_utc_mode, get_utc_mode
from cylc.xtrigger_mgr import XtriggerManager
RE_CLOCK_OFFSET = re.compile(r'(' + TaskID.NAME_RE + r')(?:\(\s*(.+)\s*\))?')
RE_EXT_TRIGGER = re.compile(r'(.*)\s*\(\s*(.+)\s*\)\s*')
RE_SEC_MULTI_SEQ = re.compile(r'(?![^(]+\)),')
RE_SUITE_NAME_VAR = re.compile(r'\${?CYLC_SUITE_(REG_)?NAME}?')
RE_TASK_NAME_VAR = re.compile(r'\${?CYLC_TASK_NAME}?')
# Message trigger offset regex.
BCOMPAT_MSG_RE_C6 = re.compile(r'^(.*)\[\s*(([+-])?\s*(.*))?\s*\](.*)$')
def check_varnames(env):
"""Check a list of env var names for legality.
Return a list of bad names (empty implies success).
"""
bad = []
for varname in env:
if not re.match(r'^[a-zA-Z_][\w]*$', varname):
bad.append(varname)
return bad
class SuiteConfigError(Exception):
"""Catch all exception for suite configuration errors."""
pass
# TODO: separate config for run and non-run purposes?
class SuiteConfig(object):
"""Class for suite configuration items and derived quantities."""
Q_DEFAULT = 'default'
TASK_EVENT_TMPL_KEYS = (
'event', 'suite', 'suite_uuid', 'point', 'name', 'submit_num', 'id',
'message', 'batch_sys_name', 'batch_sys_job_id', 'submit_time',
'start_time', 'finish_time', 'user@host', 'try_num')
def __init__(
self,
suite,
fpath,
options=None,
template_vars=None,
is_reload=False,
output_fname=None,
xtrigger_mgr=None,
mem_log_func=None,
run_dir=None,
log_dir=None,
work_dir=None,
share_dir=None,
):
self.mem_log = mem_log_func
if mem_log_func is None:
self.mem_log = lambda *a: False
self.mem_log("config.py:config.py: start init config")
self.suite = suite # suite name
self.fpath = fpath # suite definition
self.fdir = os.path.dirname(fpath)
self.run_dir = run_dir or glbl_cfg().get_derived_host_item(
self.suite, 'suite run directory')
self.log_dir = log_dir or glbl_cfg().get_derived_host_item(
self.suite, 'suite log directory')
self.work_dir = work_dir or glbl_cfg().get_derived_host_item(
self.suite, 'suite work directory')
self.share_dir = share_dir or glbl_cfg().get_derived_host_item(
self.suite, 'suite share directory')
self.options = options
self.naked_dummy_tasks = []
self.edges = {}
self.taskdefs = {}
self.initial_point = None
self.start_point = None
self.final_point = None
self.first_graph = True
self.clock_offsets = {}
self.expiration_offsets = {}
# Old external triggers (client/server)
self.ext_triggers = {}
if xtrigger_mgr is None:
# For validation and graph etc.
self.xtrigger_mgr = XtriggerManager(self.suite)
else:
self.xtrigger_mgr = xtrigger_mgr
self.suite_polling_tasks = {}
self._last_graph_raw_id = None
self._last_graph_raw_edges = []
self.sequences = []
self.actual_first_point = None
self._start_point_for_actual_first_point = None
self.task_param_vars = {}
self.custom_runahead_limit = None
self.max_num_active_cycle_points = None
# runtime hierarchy dicts keyed by namespace name:
self.runtime = {
# lists of parent namespaces
'parents': {},
# lists of C3-linearized ancestor namespaces
'linearized ancestors': {},
# lists of first-parent ancestor namepaces
'first-parent ancestors': {},
# lists of all descendant namespaces
# (not including the final tasks)
'descendants': {},
# lists of all descendant namespaces from the first-parent
# hierarchy (first parents are collapsible in suite
# visualization)
'first-parent descendants': {},
}
# tasks
self.leaves = []
# one up from root
self.feet = []
# Export local environmental suite context before config parsing.
self.process_suite_env()
# parse, upgrade, validate the suite, but don't expand with default
# items
self.mem_log("config.py: before RawSuiteConfig init")
self.pcfg = RawSuiteConfig(fpath, output_fname, template_vars)
self.mem_log("config.py: after RawSuiteConfig 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)")
# First check for the essential scheduling section.
if 'scheduling' not in self.cfg:
raise SuiteConfigError("ERROR: missing [scheduling] section.")
if 'dependencies' not in self.cfg['scheduling']:
raise SuiteConfigError(
"ERROR: missing [scheduling][[dependencies]] section.")
# (The check that 'graph' is defined is below).
# The two runahead limiting schemes are mutually exclusive.
rlim = self.cfg['scheduling'].get('runahead limit')
mact = self.cfg['scheduling'].get('max active cycle points')
if rlim and mact:
raise SuiteConfigError(
"ERROR: use 'runahead limit' OR "
"'max active cycle points', not both")
# Override the suite 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
dependency_map = self.cfg.get('scheduling', {}).get(
'dependencies', {})
if not self.is_graph_defined(dependency_map):
raise SuiteConfigError('No suite dependency graph defined.')
if 'cycling mode' not in self.cfg.get('scheduling', {}):
# Auto-detect integer cycling for pure async graph suites.
if dependency_map.get('graph'):
# There is an async graph setting.
# If it is by itself, it is integer shorthand.
# If there are cycling graphs as well, it is obsolete
# (pre cylc-6) syntax.
just_has_async_graph = True
non_async_item = None
for item, value in dependency_map.items():
if item != 'graph' and value.get('graph'):
just_has_async_graph = False
non_async_item = item
break
icp = self.cfg['scheduling'].get('initial cycle point')
fcp = self.cfg['scheduling'].get('final cycle point')
if just_has_async_graph and not (
icp in [None, "1"] and fcp in [None, icp]):
msg = (
'Conflicting syntax: integer vs cycling suite:'
'\n* Are you missing a [dependencies][R1] section?')
if icp_str:
msg += (
'\n* Did you mean to provide "%s" as the initial '
'cycle point?' % icp_str)
raise SuiteConfigError(msg)
if just_has_async_graph:
# There aren't any other graphs, so set integer cycling.
self.cfg['scheduling']['cycling mode'] = (
INTEGER_CYCLING_TYPE
)
if 'initial cycle point' not in self.cfg['scheduling']:
self.cfg['scheduling']['initial cycle point'] = "1"
if 'final cycle point' not in self.cfg['scheduling']:
self.cfg['scheduling']['final cycle point'] = "1"
else:
# Looks like cylc-5 mixed-async.
raise SuiteConfigError(
'Obsolete syntax: mixed integer [dependencies]graph ' +
'with cycling [dependencies][{0}]'.format(
non_async_item)
)
# allow test suites 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:
parameter_values = self.cfg['cylc']['parameters']
except KeyError:
# (Suite config defaults not put in yet.)
parameter_values = {}
try:
parameter_templates = self.cfg['cylc']['parameter 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.mem_log("config.py: before _expand_runtime")
self._expand_runtime()
self.mem_log("config.py: after _expand_runtime")
self.ns_defn_order = self.cfg['runtime'].keys()
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")
# self.print_inheritance() # (debugging)
# filter task environment variables after inheritance
self.filter_env()
# Now add config defaults. Items added prior to this ends up in the
# sparse dict (e.g. parameter-expanded namepaces).
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)")
# after the call to init_cyclers, we can start getting proper points.
init_cyclers(self.cfg)
# Running in UTC time? (else just use the system clock)
if self.cfg['cylc']['UTC mode'] is None:
set_utc_mode(glbl_cfg().get(['cylc', 'UTC mode']))
else:
set_utc_mode(self.cfg['cylc']['UTC mode'])
# Initial point from suite definition (or CLI override above).
orig_icp = self.cfg['scheduling']['initial cycle point']
if orig_icp is None:
raise SuiteConfigError(
"This suite requires an initial cycle point.")
if orig_icp == "now":
icp = get_current_time_string()
else:
try:
my_now = get_current_time_string()
icp = ingest_time(orig_icp, my_now)
except ValueError as exc:
raise SuiteConfigError(str(exc))
if orig_icp != icp:
self.options.icp = icp
self.initial_point = get_point(icp).standardise()
self.cfg['scheduling']['initial cycle point'] = str(self.initial_point)
if getattr(self.options, 'startcp', None) is not None:
# Warm 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()
else:
# Cold start.
self.start_point = self.initial_point
# Validate initial cycle point against any constraints
if self.cfg['scheduling']['initial cycle point constraints']:
valid_icp = False
for entry in (
self.cfg['scheduling']['initial cycle point 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:
constraints_str = str(
self.cfg['scheduling']['initial cycle point constraints'])
raise SuiteConfigError(
("Initial cycle point %s does not meet the constraints " +
"%s") % (str(self.initial_point), constraints_str)
)
if (self.cfg['scheduling']['final cycle point'] is not None and
self.cfg['scheduling']['final cycle point'].strip() is ""):
self.cfg['scheduling']['final cycle point'] = None
fcp_str = getattr(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 get_interval_cls().get_null().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:
try:
# Relative, ISO8601 cycling.
self.final_point = get_point_relative(
fcp_str, self.initial_point).standardise()
except ValueError:
# (not relative)
pass
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 SuiteConfigError(
"The initial cycle point:" +
str(self.initial_point) + " is after the final cycle point:" +
str(self.final_point) + ".")
# Validate final cycle point against any constraints
if (self.final_point is not None and
self.cfg['scheduling']['final cycle point constraints']):
valid_fcp = False
for entry in (
self.cfg['scheduling']['final cycle point 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:
constraints_str = str(
self.cfg['scheduling']['final cycle point constraints'])
raise SuiteConfigError(
"Final cycle point %s does not meet the constraints %s" % (
str(self.final_point), constraints_str))
# 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 SuiteConfigError(
"ERROR: 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 SuiteConfigError(
"ERROR: Illegal %s spec: %s" % (s_type, item)
)
if (self.cfg['scheduling']['cycling mode'] !=
Calendar.MODE_GREGORIAN):
raise SuiteConfigError(
"ERROR: %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.flags.verbose:
if 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 SuiteConfigError(
"ERROR: Illegal %s spec: %s" % (
s_type, offset_string))
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-trigger':
self.clock_offsets[member] = offset_interval
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-trigger':
self.clock_offsets[name] = offset_interval
elif s_type == 'clock-expire':
self.expiration_offsets[name] = offset_interval
elif s_type == 'external-trigger':
self.ext_triggers[name] = self.dequote(ext_trigger_msg)
self.cfg['scheduling']['special tasks'][s_type] = result
self.collapsed_families_rc = (
self.cfg['visualization']['collapsed families'])
for fam in self.collapsed_families_rc:
if fam not in self.runtime['first-parent descendants']:
raise SuiteConfigError(
'ERROR [visualization]collapsed families: '
'%s is not a first parent' % fam)
if getattr(options, 'collapsed', None):
# (used by the "cylc graph" viewer)
self.closed_families = getattr(self.options, 'collapsed', None)
elif is_reload:
self.closed_families = []
else:
self.closed_families = self.collapsed_families_rc
for cfam in self.closed_families:
if cfam not in self.runtime['descendants']:
self.closed_families.remove(cfam)
if not is_reload and cylc.flags.verbose:
LOG.warning(
'[visualization][collapsed families]: ' +
'family ' + cfam + ' not defined')
self.process_config_env()
self.mem_log("config.py: before load_graph()")
self.load_graph()
if self._is_validate():
GraphNodeParser.get_inst().clear()
self.mem_log("config.py: after load_graph()")
self.compute_runahead_limits()
self.configure_queues()
if self.run_mode('simulation', 'dummy', 'dummy-local'):
self.configure_sim_modes()
self.configure_suite_state_polling_tasks()
# Warn or abort (if --strict) if naked dummy tasks (no runtime
# section) are found in graph or queue config.
if len(self.naked_dummy_tasks) > 0:
if self._is_validate(is_strict=True) or cylc.flags.verbose:
err_msg = ('naked dummy tasks detected (no entry'
' under [runtime]):')
for ndt in self.naked_dummy_tasks:
err_msg += '\n+\t' + str(ndt)
LOG.warning(err_msg)
if self._is_validate(is_strict=True):
raise SuiteConfigError(
'ERROR: strict validation fails naked dummy tasks')
if self._is_validate():
self.check_tasks()
# 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 SuiteConfigError(
"ERROR: external triggers must be used only once.")
ngs = self.cfg['visualization']['node groups']
# If a node group member is a family, include its descendants too.
replace = {}
for ng, mems in ngs.items():
replace[ng] = []
for mem in mems:
replace[ng] += [mem]
if mem in self.runtime['descendants']:
replace[ng] += self.runtime['descendants'][mem]
for ng in replace:
ngs[ng] = replace[ng]
# Define family node groups automatically so that family and
# member nodes can be styled together using the family name.
# Users can override this for individual nodes or sub-groups.
for fam in self.runtime['descendants']:
if fam not in ngs:
ngs[fam] = [fam] + self.runtime['descendants'][fam]
if cylc.flags.verbose:
LOG.debug("Checking [visualization] node attributes")
# TODO - these should probably be done in non-verbose mode too.
# 1. node groups should contain valid namespace names
nspaces = self.cfg['runtime'].keys()
bad = {}
for ng, mems in ngs.items():
n_bad = []
for mem in mems:
if mem not in nspaces:
n_bad.append(mem)
if n_bad:
bad[ng] = n_bad
if bad:
err_msg = "undefined node group members"
for ng, mems in bad.items():
err_msg += "\n+ " + ng + ":\t,".join(mems)
LOG.warning(err_msg)
# 2. node attributes must refer to node groups or namespaces
bad = []
for na in self.cfg['visualization']['node attributes']:
if na not in ngs and na not in nspaces:
bad.append(na)
if bad:
err_msg = "undefined node attribute targets"
for na in bad:
err_msg += "\n+ " + str(na)
LOG.warning(err_msg)
# 3. node attributes must be lists of quoted "key=value" pairs.
fail = False
for node, attrs in (
self.cfg['visualization']['node attributes'].items()):
for attr in attrs:
# Check form is 'name = attr'.
if attr.count('=') != 1:
fail = True
LOG.error(
"[visualization][node attributes]%s = %s" % (
node, attr))
if fail:
raise SuiteConfigError("Node attributes must be of the form "
"'key1=value1', 'key2=value2', etc.")
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)
# CLI override for visualization settings.
for key in ('initial', 'final'):
vis_str = getattr(self.options, 'vis_' + key, None)
if vis_str:
self.cfg['visualization'][key + ' cycle point'] = vis_str
# For static visualization, start point defaults to suite initial
# point; stop point must be explicit with initial point, or None.
if self.cfg['visualization']['initial cycle point'] is None:
self.cfg['visualization']['initial cycle point'] = (
self.cfg['scheduling']['initial cycle point'])
# If viz initial point is None don't accept a final point.
if self.cfg['visualization']['final cycle point'] is not None:
if cylc.flags.verbose:
LOG.warning(
"ignoring [visualization]final cycle point\n"
"(it must be defined with an initial cycle point)")
self.cfg['visualization']['final cycle point'] = None
vfcp = self.cfg['visualization']['final cycle point']
if vfcp:
try:
vfcp = get_point_relative(
self.cfg['visualization']['final cycle point'],
self.initial_point).standardise()
except ValueError:
vfcp = get_point(
self.cfg['visualization']['final cycle point']
).standardise()
else:
vfcp = None
# A viz final point can't be beyond the suite final point.
if vfcp is not None and self.final_point is not None:
if vfcp > self.final_point:
self.cfg['visualization']['final cycle point'] = str(
self.final_point)
# Replace suite and task name in suite and task URLs.
self.cfg['meta']['URL'] = self.cfg['meta']['URL'] % {
'suite_name': self.suite}
# back-compat $CYLC_SUITE_NAME:
self.cfg['meta']['URL'] = RE_SUITE_NAME_VAR.sub(
self.suite, self.cfg['meta']['URL'])
for name, cfg in self.cfg['runtime'].items():
cfg['meta']['URL'] = cfg['meta']['URL'] % {
'suite_name': self.suite, 'task_name': name}
# back-compat $CYLC_SUITE_NAME and $CYLC_TASK_NAME:
cfg['meta']['URL'] = RE_SUITE_NAME_VAR.sub(
self.suite, cfg['meta']['URL'])
cfg['meta']['URL'] = RE_TASK_NAME_VAR.sub(
name, cfg['meta']['URL'])
if self._is_validate():
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")
def _check_circular(self):
"""Check for circular dependence in graph."""
start_point_string = (
self.cfg['visualization']['initial cycle point'])
lhs2rhss = {} # left hand side to right hand sides
rhs2lhss = {} # right hand side to left hand sides
for lhs, rhs in self.get_graph_raw(
start_point_string,
stop_point_string=None,
):
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' % (
TaskID.get(*lhs), TaskID.get(*rhs))
if err_msg:
raise SuiteConfigError(
'ERROR: circular edges detected:' + err_msg)
@staticmethod
def _check_circular_helper(x2ys, y2xs):
"""Topological elimination.
An implementation of Kahn's algorithm for topological sorting, but
only use the part for pulling out starter nodes with no incoming
edges. See https://en.wikipedia.org/wiki/Topological_sorting
x2ys is a map of {x1: [y1, y2, ...], ...}
to map edges using x's as keys, such as x1 => y1, x1 => y2, etc
y2xs is a map of {y3: [x4, x5, ...], ...}
to map edges using y's as keys, such as x4 => y3, x5 => y3, etc
"""
# Starter x nodes are those with no incoming, i.e.
# x nodes that never appear as a y.
sxs = set(x01 for x01 in x2ys if x01 not in y2xs)
while sxs:
sx01 = sxs.pop()
for y01 in x2ys[sx01]:
y2xs[y01].remove(sx01)
if not y2xs[y01]:
if y01 in x2ys:
# No need to look at this again if it does not have any
# outgoing.
sxs.add(y01)
del y2xs[y01]
del x2ys[sx01]
def _expand_name_list(self, orig_names):
"""Expand any parameters in lists of names."""
name_expander = NameExpander(self.parameters)
exp_names = []
for orig_name in orig_names:
exp_names += [name for name, _ in name_expander.expand(orig_name)]
return exp_names
def _expand_runtime(self):
"""Expand [runtime] name lists or parameterized names.
This makes individual runtime namespaces out of any headings that
represent multiple namespaces, like [[foo, bar]] or [[foo<m,n>]].
It requires replicating the sparse runtime OrderedDict into a new
OrderedDict - we can't just stick expanded names on the end because the
order matters (for add-or-override by repeated namespaces).
TODO - this will have an impact on memory footprint for large suites
with a lot of runtime config. We should consider ditching OrderedDict
and instead using an ordinary dict with a separate list of keys.
"""
if (not self.parameters[0] and
not any(',' in ns for ns in self.cfg['runtime'])):
# No parameters, no namespace lists: no expansion needed.
return
newruntime = OrderedDictWithDefaults()
name_expander = NameExpander(self.parameters)
for namespace_heading, namespace_dict in self.cfg['runtime'].items():
for name, indices in name_expander.expand(namespace_heading):
if name not in newruntime:
newruntime[name] = OrderedDictWithDefaults()
replicate(newruntime[name], namespace_dict)
if indices:
# Put parameter values in task environments.
self.task_param_vars[name] = indices
new_environ = OrderedDictWithDefaults()
if 'environment' in newruntime[name]:
for k, v in newruntime[name]['environment'].items():
new_environ[k] = v
newruntime[name]['environment'] = new_environ
if 'inherit' in newruntime[name]:
# Allow inheritance from parameterized namespaces.
parents = newruntime[name]['inherit']
origin = 'inherit = %s' % ', '.join(parents)
repl_parents = []
for parent in parents:
repl_parents.append(
name_expander.expand_parent_params(
parent, indices, origin))
newruntime[name]['inherit'] = repl_parents
self.cfg['runtime'] = newruntime
# Parameter expansion of visualization node attributes. TODO - do vis
# 'node groups' too, or deprecate them (use families in 'node attrs').
name_expander = NameExpander(self.parameters)
expanded_node_attrs = OrderedDictWithDefaults()
if 'visualization' not in self.cfg:
self.cfg['visualization'] = OrderedDictWithDefaults()
if 'node attributes' not in self.cfg['visualization']:
self.cfg['visualization']['node attributes'] = (
OrderedDictWithDefaults())
for node, val in self.cfg['visualization']['node attributes'].items():
for name, _ in name_expander.expand(node):
expanded_node_attrs[name] = val
self.cfg['visualization']['node attributes'] = expanded_node_attrs
@staticmethod
def is_graph_defined(dependency_map):
for item, value in dependency_map.items():
if item == 'graph':
# Async graph.
if value != '':
return True
else:
# Cycling section.
for subitem, subvalue in value.items():
if subitem == 'graph':
if subvalue != '':
return True
return False
def _is_validate(self, is_strict=False):
"""Return whether we are in (strict) validate mode."""
return (
getattr(self.options, 'is_validate', False) and
(not is_strict or getattr(self.options, 'strict', False))
)
@staticmethod
def dequote(s):
"""Strip quotes off a string."""
if (s[0] == s[-1]) and s.startswith(("'", '"')):
return s[1:-1]
return s
def check_env_names(self):
"""Check for illegal environment variable names"""
bad = {}
for label, item in self.cfg['runtime'].items():
for key in ('environment', 'parameter environment templates'):
if key in item:
res = check_varnames(item[key])
if res:
bad[(label, key)] = res
if bad:
err_msg = "bad env variable names:"
for (label, key), names in bad.items():
err_msg += '\nNamespace:\t%s [%s]' % (label, key)
for name in names:
err_msg += "\n\t\t%s" % name
LOG.error(err_msg)
raise SuiteConfigError(
"Illegal environment variable name(s) detected")
def check_param_env_tmpls(self):
"""Check for illegal parameter environment templates"""
parameter_values = dict(
(key, values[0])
for key, values in self.parameters[0].items() if values)
bads = set()
for namespace, item in self.cfg['runtime'].items():
if 'parameter environment templates' not in item:
continue
for name, tmpl in item['parameter environment templates'].items():
try:
value = tmpl % parameter_values
except KeyError:
bads.add((namespace, name, tmpl, 'bad parameter'))
except TypeError:
bads.add((
namespace, name, tmpl,
'wrong data type for parameter'))
except ValueError:
bads.add((namespace, name, tmpl, 'bad template syntax'))
else:
if value == tmpl: # Not a template
bads.add((namespace, name, tmpl, 'not a template'))
if bads:
LOG.error("bad parameter environment template:\n %s" % (
"\n ".join('[%s]%s=%s # %s' % bad for bad in sorted(bads))))
raise SuiteConfigError(
"Illegal parameter environment template(s) detected")
def filter_env(self):
"""Filter environment variables after sparse inheritance"""
for ns in self.cfg['runtime'].values():
try:
oenv = ns['environment']
except KeyError:
# no environment to filter
continue
try:
fincl = ns['environment filter']['include']
except KeyError:
# empty include-filter means include all
fincl = []
try:
fexcl = ns['environment filter']['exclude']
except KeyError:
# empty exclude-filter means exclude none
fexcl = []
if not fincl and not fexcl:
# no filtering to do
continue
nenv = OrderedDictWithDefaults()
for key, val in oenv.items():
if (not fincl or key in fincl) and key not in fexcl:
nenv[key] = val
ns['environment'] = nenv
def compute_family_tree(self):
first_parents = {}
demoted = {}
for name in self.cfg['runtime']:
if name == 'root':
self.runtime['parents'][name] = []
first_parents[name] = []
continue
# get declared parents, with implicit inheritance from root.
pts = self.cfg['runtime'][name].get('inherit', ['root'])
if not pts:
pts = ['root']
for p in pts:
if p == "None":
# see just below
continue
if p not in self.cfg['runtime']:
raise SuiteConfigError(
"ERROR, undefined parent for " + name + ": " + p)
if pts[0] == "None":
if len(pts) < 2:
raise SuiteConfigError(
"ERROR: null parentage for " + name)
demoted[name] = pts[1]
pts = pts[1:]
first_parents[name] = ['root']
else:
first_parents[name] = [pts[0]]
self.runtime['parents'][name] = pts
if cylc.flags.verbose and demoted:
log_msg = "First parent(s) demoted to secondary:"
for n, p in demoted.items():
log_msg += "\n + %s as parent of '%s'" % (p, n)