Debian Codegraph @

cylc/flow/parsec/validate.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 """Validate a nested dict parsed from a config file against a spec file.
17
18 Check all items are legal.
19 Check all values are legal (type; min, max, allowed options).
20 Coerce value type from string (to int, float, list, etc.).
21 Coerce more value type from string (to time point, duration, xtriggers, etc.).
22 Also provides default values from the spec as a nested dict.
23 """
24
25 import re
26 import shlex
27 from collections import deque
28 from textwrap import dedent
29 from typing import List, Dict, Any, Optional, Tuple
30
31 from metomi.isodatetime.data import Duration, TimePoint
32 from metomi.isodatetime.dumpers import TimePointDumper
33 from metomi.isodatetime.parsers import TimePointParser, DurationParser
34 from metomi.isodatetime.exceptions import IsodatetimeError, ISO8601SyntaxError
35
36 from cylc.flow import LOG
37 from cylc.flow.parsec.exceptions import (
38 ListValueError, IllegalValueError, IllegalItemError)
39 from cylc.flow.subprocctx import SubFuncContext
40
41
42 class ParsecValidator:
43 """Type validator and coercer for configurations.
44
45 Attributes:
46 .coercers (dict):
47 Map value type keys with coerce methods.
48 """
49
50 # quoted value regex reference:
51 # http://stackoverflow.com/questions/5452655/
52 # python-regex-to-match-text-in-single-quotes-
53 # ignoring-escaped-quotes-and-tabs-n
54
55 # quoted list values not at end of line
56 _REC_SQ_L_VALUE = re.compile(r"'([^'\\]*(?:\\.[^'\\]*)*)'")
57 _REC_DQ_L_VALUE = re.compile(r'"([^"\\]*(?:\\.[^"\\]*)*)"')
58 # quoted values with ignored trailing comments
59 _REC_SQ_VALUE = re.compile(r"'([^'\\]*(?:\\.[^'\\]*)*)'(?:\s*(?:#.*)?)?$")
60 _REC_DQ_VALUE = re.compile(r'"([^"\\]*(?:\\.[^"\\]*)*)"(?:\s*(?:#.*)?)?$')
61
62 _REC_UQLP = re.compile(r"""(['"]?)(.*?)\1(,|$)""")
63 _REC_SQV = re.compile(r"((?:^[^']*(?:'[^']*')*[^']*)*)(#.*)$")
64 _REC_DQV = re.compile('((?:^[^"]*(?:"[^"]*")*[^"]*)*)(#.*)$')
65 # quoted multi-line values
66 _REC_MULTI_LINE_SINGLE = re.compile(
67 r"\A'''(.*?)'''\s*(?:#.*)?\Z", re.MULTILINE | re.DOTALL)
68 _REC_MULTI_LINE_DOUBLE = re.compile(
69 r'\A"""(.*?)"""\s*(?:#.*)?\Z', re.MULTILINE | re.DOTALL)
70 # integer range syntax START..END[..STEP]
71 _REC_INT_RANGE = re.compile(
72 r'\A([+\-]?\d+)\s*\.\.\s*([+\-]?\d+)(?:\s*\.\.\s*(\d+))?\Z')
73 # Parameterized names containing at least one comma.
74 _REC_MULTI_PARAM = re.compile(r'<[\w]+,.*?>')
75
76 SELF_REFERENCE_PATTERNS = ['localhost', '127.0.0.1', '0.0.0.0'] # nosec
77 # * these strings are used for validation purposes
78 # * they are not used for binding
79
80 # Value type constants
81 V_BOOLEAN = 'V_BOOLEAN'
82 V_FLOAT = 'V_FLOAT'
83 V_FLOAT_LIST = 'V_FLOAT_LIST'
84 V_INTEGER = 'V_INTEGER'
85 V_INTEGER_LIST = 'V_INTEGER_LIST'
86 V_RANGE = 'V_RANGE'
87 V_STRING = 'V_STRING'
88 V_STRING_LIST = 'V_STRING_LIST'
89 V_SPACELESS_STRING_LIST = 'V_SPACELESS_STRING_LIST'
90 V_ABSOLUTE_HOST_LIST = 'V_ABSOLUTE_HOST_LIST'
91
92 V_TYPE_HELP = {
93 # V_TYPE: (quick_name, help_string, examples_list, see_also)
94 V_BOOLEAN: (
95 'boolean',
96 'A boolean in Python format',
97 ['True', 'False']
98 ),
99 V_FLOAT: (
100 'float',
101 'A number in integer, decimal or exponential format',
102 ['1', '1.1', '1.1e11']
103 ),
104 V_FLOAT_LIST: (
105 'float list',
106 'A comma separated list of floats.',
107 ['1, 1.1, 1.1e11']
108 ),
109 V_INTEGER: (
110 'integer',
111 'An integer.',
112 ['1', '2', '3']
113 ),
114 V_INTEGER_LIST: (
115 'integer list',
116 'A comma separated list of integers.',
117 ['1, 2, 3', '1..3', '1..3, 7']
118 ),
119 V_RANGE: (
120 'integer range',
121 'An integer range specified by a minimum and maximum value.',
122 {
123 '1..5': 'The numbers 1 to 5 inclusive.',
124 }
125 ),
126 V_STRING: (
127 'string',
128 'Plain text.',
129 ['Hello World!']
130 ),
131 V_STRING_LIST: (
132 'list',
133 'A comma separated list of strings.',
134 ['a, b c, d']
135 ),
136 V_SPACELESS_STRING_LIST: (
137 'spaceless list',
138 'A comma separated list of strings which cannot contain spaces.',
139 ['a, b, c']
140 ),
141 V_ABSOLUTE_HOST_LIST: (
142 'absolute host list',
143 (
144 'A comma separated list of hostnames which does not contain '
145 'any self references '
146 f'(i.e. does not contain {", ".join(SELF_REFERENCE_PATTERNS)})'
147 ),
148 ['foo', 'bar', 'baz']
149 )
150 }
151
152 def __init__(self):
153 self.coercers = {
154 self.V_BOOLEAN: self.coerce_boolean,
155 self.V_FLOAT: self.coerce_float,
156 self.V_FLOAT_LIST: self.coerce_float_list,
157 self.V_INTEGER: self.coerce_int,
158 self.V_INTEGER_LIST: self.coerce_int_list,
159 self.V_RANGE: self.coerce_range,
160 self.V_STRING: self.coerce_str,
161 self.V_STRING_LIST: self.coerce_str_list,
162 self.V_SPACELESS_STRING_LIST: self.coerce_spaceless_str_list,
163 self.V_ABSOLUTE_HOST_LIST: self.coerce_absolute_host_list
164 }
165
166 def validate(self, cfg_root, spec_root):
167 """Validate and coerce a nested dict against a parsec spec.
168
169 Args:
170 cfg_root (dict):
171 A nested dict representing the raw configuration.
172 spec_root (dict):
173 A nested dict containing the spec for the configuration.
174
175 Raises:
176 IllegalItemError: on bad configuration items.
177 IllegalValueError: on bad configuration values.
178 """
179 queue = deque([[cfg_root, spec_root, []]])
180 while queue:
181 # Walk items, breadth first
182 cfg, spec, keys = queue.popleft()
183 for key, value in cfg.items():
184 if key not in spec:
185 if '__MANY__' not in spec:
186 raise IllegalItemError(keys, key)
187 else:
188 # only accept the item if its value is of the same type
189 # as that of the __MANY__ item, i.e. dict or not-dict.
190 val_is_dict = isinstance(value, dict)
191 spc_is_dict = not spec['__MANY__'].is_leaf()
192 if (
193 keys != ['scheduling', 'graph'] and
194 not val_is_dict and
195 ' ' in key
196 ):
197 # Item names shouldn't have consecutive spaces
198 # (GitHub #2417)
199 raise IllegalItemError(
200 keys, key, 'consecutive spaces')
201 if not (
202 (val_is_dict and spc_is_dict)
203 or (not val_is_dict and not spc_is_dict)
204 ):
205 raise IllegalItemError(keys, key)
206 speckey = '__MANY__'
207
208 else:
209 speckey = key
210 specval = spec[speckey]
211
212 cfg_is_section = isinstance(value, dict)
213 spec_is_section = not specval.is_leaf()
214 if cfg_is_section and not spec_is_section:
215 # config is a [section] but it should be a setting=
216 raise IllegalItemError(
217 keys,
218 key,
219 msg=f'"{key}" should be a setting not a [section]',
220 )
221 if (not cfg_is_section) and spec_is_section:
222 # config is a setting= but it should be a [section]
223 raise IllegalItemError(
224 keys,
225 key,
226 msg=f'"{key}" should be a [section] not a setting',
227 )
228
229 if cfg_is_section and spec_is_section:
230 # Item is dict, push to queue
231 queue.append([value, specval, keys + [key]])
232 elif value is not None and not spec_is_section:
233 # Item is value, coerce according to value type
234 cfg[key] = self.coercers[specval.vdr](value, keys + [key])
235 if specval.options:
236 voptions = {*specval.options, *specval.depr_options}
237 if isinstance(cfg[key], list):
238 bad = [
239 str(i) for i in cfg[key] if i not in voptions
240 ]
241 if bad:
242 exc = IllegalValueError(
243 'option', [*keys, key], ', '.join(bad)
244 )
245 if specval.warn_options:
246 LOG.warning(
247 f'{exc}'
248 '\nInvalid items have been removed'
249 )
250 cfg[key] = [
251 x for x in cfg[key] if x not in bad
252 ]
253 else:
254 raise exc
255 elif cfg[key] not in voptions:
256 raise IllegalValueError(
257 'option', [*keys, key], cfg[key]
258 )
259
260 __call__ = validate
261
262 @classmethod
263 def coerce_boolean(cls, value, keys):
264 """Coerce value to a boolean.
265
266 Examples:
267 >>> ParsecValidator.coerce_boolean('True', None)
268 True
269 >>> ParsecValidator.coerce_boolean('true', None)
270 True
271
272 """
273 value = cls.strip_and_unquote(keys, value)
274 if value in ['True', 'true']:
275 return True
276 elif value in ['False', 'false']:
277 return False
278 elif value in ['', None]: # noqa: SIM106
279 return None
280 else:
281 raise IllegalValueError('boolean', keys, value)
282
283 @classmethod
284 def coerce_float(cls, value, keys):
285 """Coerce value to a float.
286
287 Examples:
288 >>> ParsecValidator.coerce_float('1', None)
289 1.0
290 >>> ParsecValidator.coerce_float('1.1', None)
291 1.1
292 >>> ParsecValidator.coerce_float('1.1e1', None)
293 11.0
294
295 """
296 value = cls.strip_and_unquote(keys, value)
297 if value in ['', None]:
298 return None
299 try:
300 return float(value)
301 except ValueError as exc:
302 raise IllegalValueError('float', keys, value, exc=exc) from None
303
304 @classmethod
305 def coerce_float_list(cls, value, keys):
306 """Coerce list values with optional multipliers to float.
307
308 Examples:
309 >>> ParsecValidator.coerce_float_list('1, 1.1, 1.1e1', None)
310 [1.0, 1.1, 11.0]
311
312 """
313 values = cls.strip_and_unquote_list(keys, value)
314 return cls.expand_list(values, keys, float)
315
316 @classmethod
317 def coerce_int(cls, value, keys):
318 """Coerce value to an integer.
319
320 Examples:
321 >>> ParsecValidator.coerce_int('1', None)
322 1
323
324 """
325 value = cls.strip_and_unquote(keys, value)
326 if value in ['', None]:
327 return None
328 try:
329 return int(value)
330 except ValueError as exc:
331 raise IllegalValueError('int', keys, value, exc=exc) from None
332
333 @classmethod
334 def coerce_int_list(cls, value, keys):
335 """Coerce list values with optional multipliers to integer.
336
337 Examples:
338 >>> ParsecValidator.coerce_int_list('1, 2, 3', None)
339 [1, 2, 3]
340 >>> ParsecValidator.coerce_int_list('1..3', None)
341 [1, 2, 3]
342
343 """
344 items = []
345 for item in cls.strip_and_unquote_list(keys, value):
346 values = cls.parse_int_range(item)
347 if values is None:
348 items.extend(cls.expand_list([item], keys, int))
349 else:
350 items.extend(values)
351 return items
352
353 @classmethod
354 def coerce_range(cls, value, keys):
355 """A single min/max pair defining an integer range.
356
357 Examples:
358 >>> ParsecValidator.coerce_range('1..3', None)
359 (1, 3)
360 >>> ParsecValidator.coerce_range('1..3, 5', 'k')
361 Traceback (most recent call last):
362 cylc.flow.parsec.exceptions.ListValueError:
363 (type=list) k = 1..3, 5 - (Only one min..max pair is permitted)
364 >>> ParsecValidator.coerce_range('1..z', 'k')
365 Traceback (most recent call last):
366 cylc.flow.parsec.exceptions.ListValueError:
367 (type=list) k = 1..z - (Integer range must be in the
368 format min..max)
369 >>> ParsecValidator.coerce_range('1', 'k')
370 Traceback (most recent call last):
371 cylc.flow.parsec.exceptions.ListValueError:
372 (type=list) k = 1 - (Integer range must be in the
373 format min..max)
374
375 """
376 items = cls.strip_and_unquote_list(keys, value)
377 if len(items) != 1:
378 raise ListValueError(
379 keys,
380 value,
381 msg='Only one min..max pair is permitted',
382 )
383 item = items[0]
384 match = cls._REC_INT_RANGE.match(item)
385 if not match:
386 raise ListValueError(
387 keys,
388 value,
389 msg='Integer range must be in the format min..max',
390 )
391 min_, max_ = match.groups()[0:2]
392 return Range((int(min_), int(max_)))
393
394 @classmethod
395 def coerce_str(cls, value, keys) -> str:
396 """Coerce value to a string.
397
398 Examples:
399 >>> ParsecValidator.coerce_str('abc', None)
400 'abc'
401 >>> ParsecValidator.coerce_str(['abc', 'def'], None)
402 'abc\\ndef'
403
404 """
405 if isinstance(value, list):
406 # handle graph string merging
407 vraw: List[str] = []
408 vals = [value]
409 while vals:
410 val = vals.pop()
411 if isinstance(val, list):
412 vals.extend(reversed(val)) # reverse to preserve order
413 else:
414 vraw.append(cls.strip_and_unquote(keys, val))
415 value = '\n'.join(vraw)
416 else:
417 value = cls.strip_and_unquote(keys, value)
418 return value
419
420 @classmethod
421 def coerce_str_list(cls, value, keys):
422 """Coerce value to a list of strings.
423
424 >>> ParsecValidator.coerce_str_list('a, b, c', None)
425 ['a', 'b', 'c']
426 >>> ParsecValidator.coerce_str_list('a, b c , d', None)
427 ['a', 'b c', 'd']
428
429 """
430 return cls.strip_and_unquote_list(keys, value)
431
432 @classmethod
433 def coerce_spaceless_str_list(cls, value, keys):
434 """Coerce value to a list of strings ensuring no values contain spaces.
435
436 Examples:
437 >>> ParsecValidator.coerce_spaceless_str_list(
438 ... 'a, b, c', None)
439 ['a', 'b', 'c']
440
441 >>> ParsecValidator.coerce_spaceless_str_list(
442 ... 'a, b c, d', ['foo']) # doctest: +NORMALIZE_WHITESPACE
443 Traceback (most recent call last):
444 cylc.flow.parsec.exceptions.ListValueError: \
445 (type=list) foo = a, b c, d - \
446 (list item "b c" cannot contain a space character)
447
448 """
449 lst = cls.strip_and_unquote_list(keys, value)
450 for item in lst:
451 if ' ' in item:
452 raise ListValueError(
453 keys, value,
454 msg='list item "%s" cannot contain a space character' %
455 item)
456 return lst
457
458 @classmethod
459 def coerce_absolute_host_list(cls, value, keys):
460 """Do not permit self reference in host names.
461
462 Examples:
463 >>> ParsecValidator.coerce_absolute_host_list(
464 ... 'foo, bar, baz', None)
465 ['foo', 'bar', 'baz']
466
467 >>> ParsecValidator.coerce_absolute_host_list(
468 ... 'foo, bar, 127.0.0.1:8080, baz', ['pub']
469 ... ) # doctest: +NORMALIZE_WHITESPACE
470 Traceback (most recent call last):
471 cylc.flow.parsec.exceptions.ListValueError: \
472 (type=list) pub = foo, bar, 127.0.0.1:8080, baz - \
473 (ambiguous host "127.0.0.1:8080")
474
475 """
476 hosts = cls.coerce_spaceless_str_list(value, keys)
477 for host in hosts:
478 if any(host.startswith(pattern)
479 for pattern in cls.SELF_REFERENCE_PATTERNS):
480 raise ListValueError(
481 keys, value, msg='ambiguous host "%s"' % host)
482 return hosts
483
484 @classmethod
485 def expand_list(cls, values, keys, type_):
486 """Handle multiplier syntax N*VALUE in a list.
487
488 Examples:
489 >>> ParsecValidator.expand_list(['1', '2*3'], None, int)
490 [1, 3, 3]
491
492 """
493 lvalues = []
494 for item in values:
495 try:
496 mult, val = item.split('*', 1)
497 except ValueError:
498 # too few values to unpack: no multiplier
499 try:
500 lvalues.append(type_(item))
501 except ValueError as exc:
502 raise IllegalValueError(
503 'list', keys, item, exc=exc
504 ) from None
505 else:
506 # mult * val
507 try:
508 lvalues += int(mult) * [type_(val)]
509 except ValueError as exc:
510 raise IllegalValueError(
511 'list', keys, item, exc=exc
512 ) from None
513 return lvalues
514
515 @classmethod
516 def parse_int_range(cls, value):
517 """Parse a value containing an integer range START..END[..STEP].
518
519 Return (list):
520 A list containing the integer values in range,
521 or None if value does not contain an integer range.
522
523 Examples:
524 >>> ParsecValidator.parse_int_range('1..3')
525 [1, 2, 3]
526
527 """
528 match = cls._REC_INT_RANGE.match(value)
529 if match:
530 lower, upper, step = match.groups()
531 if not step:
532 step = 1
533 return list(range(int(lower), int(upper) + 1, int(step)))
534 else:
535 return None
536
537 @classmethod
538 def _unquote(cls, keys: List[str], value: str) -> Optional[str]:
539 """Unquote value."""
540 for substr, rec in (
541 ("'''", cls._REC_MULTI_LINE_SINGLE),
542 ('"""', cls._REC_MULTI_LINE_DOUBLE),
543 ('"', cls._REC_DQ_VALUE),
544 ("'", cls._REC_SQ_VALUE)
545 ):
546 if value.startswith(substr):
547 match = rec.match(value)
548 if not match:
549 raise IllegalValueError("string", keys, value)
550 return match[1]
551 return None
552
553 @classmethod
554 def strip_and_unquote(cls, keys: List[str], value: str) -> str:
555 """Remove leading and trailing spaces and unquote value.
556
557 Args:
558 keys:
559 Keys in nested dict that represents the raw configuration.
560 value:
561 String value in raw configuration.
562
563 Return:
564 Processed value.
565
566 Examples:
567 >>> ParsecValidator.strip_and_unquote(None, '" foo "')
568 'foo'
569
570 """
571 val = cls._unquote(keys, value)
572 if val is None:
573 val = value.split(r'#', 1)[0]
574
575 # Note strip() removes leading and trailing whitespace, including
576 # initial newlines on a multiline string:
577 return dedent(val).strip()
578
579 @classmethod
580 def strip_and_unquote_list(cls, keys, value):
581 """Remove leading and trailing spaces and unquote list value.
582
583 Args:
584 keys (list):
585 Keys in nested dict that represents the raw configuration.
586 value (str):
587 String value in raw configuration that is supposed to be a
588 comma separated list.
589
590 Return (list):
591 Processed value as a list.
592
593 Examples:
594 >>> ParsecValidator.strip_and_unquote_list(None, ' 1 , "2", 3')
595 ['1', '"2"', '3']
596
597 >>> ParsecValidator.strip_and_unquote_list(None, '" 1 , 2", 3')
598 ['1 , 2', '3']
599
600 """
601 if value.startswith('"') or value.startswith("'"):
602 lexer = shlex.shlex(value, posix=True, punctuation_chars=",")
603 lexer.commenters = '#'
604 lexer.whitespace_split = False
605 lexer.whitespace = "\t\n\r"
606 lexer.wordchars += " "
607 values = [t.strip() for t in lexer if t != "," and t.strip()]
608 else:
609 # unquoted values (may contain internal quoted strings with list
610 # delimiters inside 'em!)
611 for quotation, rec in (('"', cls._REC_DQV), ("'", cls._REC_SQV)):
612 if quotation in value:
613 match = rec.match(value)
614 if match:
615 value = match.groups()[0]
616 break
617 else:
618 value = value.split(r'#', 1)[0].strip()
619 values = list(cls._unquoted_list_parse(keys, value))
620 # allow trailing commas
621 if values[-1] == '':
622 values = values[0:-1]
623 return values
624
625 @classmethod
626 def _unquoted_list_parse(cls, keys, value):
627 """Split comma separated list, and unquote each value.
628
629 Examples:
630 >>> list(ParsecValidator._unquoted_list_parse(None, '"1", 2'))
631 ['1', '2']
632
633 """
634 # http://stackoverflow.com/questions/4982531/
635 # how-do-i-split-a-comma-delimited-string-in-python-except-
636 # for-the-commas-that-are
637
638 # First detect multi-parameter lists like <m,n>.
639 if cls._REC_MULTI_PARAM.search(value):
640 raise ListValueError(
641 keys, value,
642 msg="names containing commas must be quoted"
643 "(e.g. 'foo<m,n>')")
644 pos = 0
645 while True:
646 match = cls._REC_UQLP.search(value, pos)
647 result = match.group(2).strip()
648 separator = match.group(3)
649 yield result
650 if not separator:
651 break
652 pos = match.end(0)
653
654
655 def parsec_validate(cfg_root, spec_root):
656 """Short for "ParsecValidator().validate(...)"."""
657 return ParsecValidator().validate(cfg_root, spec_root)
658
659
660 class DurationFloat(float):
661 """Duration in floating point seconds, but stringify as ISO8601 format."""
662
663 def __str__(self):
664 return str(Duration(seconds=self, standardize=True))
665
666
667 class Range(tuple):
668
669 def __str__(self):
670 return f'{self[0]} .. {self[1]}'
671
672
673 class CylcConfigValidator(ParsecValidator):
674 """Type validator and coercer for Cylc configurations.
675
676 Attributes:
677 .coercers (dict):
678 Map value type keys with coerce methods.
679 """
680 # Parameterized names containing at least one comma.
681 _REC_NAME_SUFFIX = re.compile(r'\A[\w\-+%@]+\Z')
682 _REC_TRIG_FUNC = re.compile(r'(\w+)\((.*)\)(?::(\w+))?')
683
684 # Value type constants
685 V_CYCLE_POINT = 'V_CYCLE_POINT'
686 V_CYCLE_POINT_FORMAT = 'V_CYCLE_POINT_FORMAT'
687 V_CYCLE_POINT_TIME_ZONE = 'V_CYCLE_POINT_TIME_ZONE'
688 V_CYCLE_POINT_WITH_OFFSETS = 'V_CYCLE_POINT_WITH_OFFSETS'
689 V_INTERVAL = 'V_INTERVAL'
690 V_INTERVAL_LIST = 'V_INTERVAL_LIST'
691 V_PARAMETER_LIST = 'V_PARAMETER_LIST'
692 V_XTRIGGER = 'V_XTRIGGER'
693
694 V_TYPE_HELP: dict = {
695 # V_TYPE: (quick_name, help_string, examples_list, see_also)
696 V_CYCLE_POINT: (
697 'cycle point',
698 'An integer or date-time cycle point as appropriate.',
699 {
700 '1': 'An integer cycle point.',
701 '2000-01-01T00:00Z': 'A date-time cycle point.',
702 'now': 'The current date-time.',
703 'next(T-00)':
704 'The current date-time rounded up to the nearest'
705 ' whole hour.'
706 },
707 [
708 ('std:term', 'cycle point'),
709 ('std:term', 'ISO8601 duration')
710 ]
711 ),
712 V_CYCLE_POINT_FORMAT: (
713 'cycle point format',
714 (
715 'A time format for date-time cycle points in ``isodatetime`` '
716 '"print" or "parse" format. '
717 'See ``isodatetime --help`` for more information.'
718 ),
719 {
720 'CCYYMM': '``isodatetime`` print format.',
721 '%Y%m': '``isodatetime`` parse format.'
722 }
723 ),
724 V_CYCLE_POINT_TIME_ZONE: (
725 'cycle point time zone',
726 'A time zone for date-time cycle points in ISO8601 format.',
727 {
728 'Z': 'UTC / GMT.',
729 '+13': 'UTC plus 13 hours.',
730 '-0830': 'UTC minus 8 hours and 30 minutes.'
731 }
732 ),
733 V_CYCLE_POINT_WITH_OFFSETS: (
734 'cycle point with support for offsets',
735 'An integer or date-time cycle point, with optional offset(s).',
736 {
737 '1': 'An integer cycle point.',
738 '1 +P5': (
739 'An integer cycle point with an offset'
740 ' (this evaluates as ``6``).'
741 ),
742 '+P5': (
743 'An integer cycle point offset.'
744 ' This offset is added to the initial cycle point'
745 ),
746 '2000-01-01T00:00Z': 'A date-time cycle point.',
747 '2000-02-29T00:00Z +P1D +P1M': (
748 'A date-time cycle point with offsets'
749 ' (this evaluates as ``2000-04-01T00:00Z``).'
750 ),
751 }
752 ),
753 V_INTERVAL: (
754 'time interval',
755 'An ISO8601 duration.',
756 {
757 'P1Y': 'Every year.',
758 'PT6H': 'Every six hours.'
759 },
760 [('std:term', 'ISO8601 duration')]
761 ),
762 V_INTERVAL_LIST: (
763 'time interval list',
764 (
765 'A comma separated list of time intervals. '
766 'These can include multipliers.'
767 ),
768 {
769 'P1Y, P2Y, P3Y': 'After 1, 2 and 3 years.',
770 'PT1M, 2*PT1H, P1D': 'After 1 minute, 1 hour, 1 hour and 1 day'
771 },
772 [('std:term', 'ISO8601 duration')]
773 ),
774 V_PARAMETER_LIST: (
775 'parameter list',
776 (
777 'A comma separated list of Cylc parameter values. '
778 'This can include strings, integers and integer ranges.'
779 ),
780 {
781 'foo, bar, baz': 'List of string parameters.',
782 '1, 2, 3': 'List of integer parameters.',
783 '1..3': 'The same as 1, 2, 3.',
784 '1..5..2': 'The same as 1, 3, 5.',
785 '1..5..2, 8': 'Range and integers can be mixed.',
786 },
787 [('ref', 'User Guide Param')]
788 ),
789 V_XTRIGGER: (
790 'xtrigger function signature',
791 (
792 'A function signature similar to how it would be written in '
793 'Python.\n``<function>(<arg>, <kwarg>=<value>):<interval>``'
794 ),
795 {
796 'mytrigger(42, cycle_point=%(point)):PT10S':
797 'Run function ``mytrigger`` every 10 seconds.'
798 },
799 [('ref', 'Section External Triggers')]
800 )
801 }
802
803 def __init__(self):
804 ParsecValidator.__init__(self)
805 self.coercers.update({
806 self.V_CYCLE_POINT: self.coerce_cycle_point,
807 self.V_CYCLE_POINT_FORMAT: self.coerce_cycle_point_format,
808 self.V_CYCLE_POINT_TIME_ZONE: self.coerce_cycle_point_time_zone,
809 # NOTE: This type exists for documentation reasons
810 # it doesn't actually process offsets, that happens later
811 self.V_CYCLE_POINT_WITH_OFFSETS: self.coerce_str,
812 self.V_INTERVAL: self.coerce_interval,
813 self.V_INTERVAL_LIST: self.coerce_interval_list,
814 self.V_PARAMETER_LIST: self.coerce_parameter_list,
815 self.V_XTRIGGER: self.coerce_xtrigger,
816 })
817
818 @classmethod
819 def coerce_cycle_point(cls, value, keys):
820 """Coerce value to a cycle point.
821
822 Examples:
823 >>> CylcConfigValidator.coerce_cycle_point('2000', None)
824 '2000'
825 >>> CylcConfigValidator.coerce_cycle_point('now', None)
826 'now'
827 >>> CylcConfigValidator.coerce_cycle_point('next(T-00)', None)
828 'next(T-00)'
829
830 """
831 if not value:
832 return None
833 value = cls.strip_and_unquote(keys, value)
834 if value == 'now':
835 # Handle this later in config.py when workflow UTC mode is known.
836 return value
837 if "next" in value or "previous" in value:
838 # Handle this later, as for "now".
839 return value
840 if value.isdigit():
841 # Could be an old date-time cycle point format, or integer format.
842 return value
843 if "P" not in value and (
844 value.startswith('-') or value.startswith('+')):
845 # We don't know the value given for num expanded year digits...
846 for i in range(1, 101):
847 try:
848 TimePointParser(num_expanded_year_digits=i).parse(value)
849 except IsodatetimeError:
850 continue
851 return value
852 raise IllegalValueError('cycle point', keys, value)
853 if "P" in value:
854 # ICP is an offset
855 parser = DurationParser()
856 try:
857 if value.startswith("-"):
858 # parser doesn't allow negative duration with this setup?
859 parser.parse(value[1:])
860 else:
861 parser.parse(value)
862 return value
863 except IsodatetimeError as exc:
864 raise IllegalValueError(
865 'cycle point', keys, value, exc=exc
866 ) from None
867 try:
868 TimePointParser().parse(value)
869 except IsodatetimeError as exc:
870 if isinstance(exc, ISO8601SyntaxError):
871 # Don't know cycling mode yet, so override ISO8601-specific msg
872 details = {'msg': "Invalid cycle point"}
873 else:
874 details = {'exc': exc}
875 raise IllegalValueError(
876 'cycle point', keys, value, **details
877 ) from None
878 return value
879
880 @classmethod
881 def coerce_cycle_point_format(cls, value, keys):
882 """Coerce to a cycle point format.
883
884 Examples:
885 >>> CylcConfigValidator.coerce_cycle_point_format(
886 ... 'CCYYMM', None)
887 'CCYYMM'
888 >>> CylcConfigValidator.coerce_cycle_point_format(
889 ... '%Y%m', None)
890 '%Y%m'
891
892 """
893 value = cls.strip_and_unquote(keys, value)
894 if not value:
895 return None
896 test_timepoint = TimePoint(year=2001, month_of_year=3, day_of_month=1,
897 hour_of_day=4, minute_of_hour=30,
898 second_of_minute=54)
899 if '/' in value:
900 raise IllegalValueError(
901 'cycle point format', keys, value, msg=(
902 'Illegal character: "/".'
903 ' Datetimes are used in Cylc file paths.'
904 )
905 )
906 if ':' in value:
907 raise IllegalValueError(
908 'cycle point format', keys, value, msg=(
909 'Illegal character: ":".'
910 ' Datetimes are used in Cylc file paths.'
911 )
912 )
913 if '%' in value:
914 try:
915 TimePointDumper().strftime(test_timepoint, value)
916 except IsodatetimeError as exc:
917 raise IllegalValueError(
918 'cycle point format', keys, value, exc=exc
919 ) from None
920 return value
921 if 'X' in value:
922 for i in range(1, 101):
923 dumper = TimePointDumper(num_expanded_year_digits=i)
924 try:
925 dumper.dump(test_timepoint, value)
926 except IsodatetimeError:
927 continue
928 return value
929 raise IllegalValueError('cycle point format', keys, value)
930 dumper = TimePointDumper()
931 try:
932 dumper.dump(test_timepoint, value)
933 except IsodatetimeError as exc:
934 raise IllegalValueError(
935 'cycle point format', keys, value, exc=exc
936 ) from None
937 return value
938
939 @classmethod
940 def coerce_cycle_point_time_zone(cls, value, keys):
941 """Coerce value to a cycle point time zone format.
942
943 Examples:
944 >>> CylcConfigValidator.coerce_cycle_point_time_zone(
945 ... 'Z', None)
946 'Z'
947 >>> CylcConfigValidator.coerce_cycle_point_time_zone(
948 ... '+13', None)
949 '+13'
950 >>> CylcConfigValidator.coerce_cycle_point_time_zone(
951 ... '-0800', None)
952 '-0800'
953
954 """
955 value = cls.strip_and_unquote(keys, value)
956 if not value:
957 return None
958 test_timepoint = TimePoint(year=2001, month_of_year=3, day_of_month=1,
959 hour_of_day=4, minute_of_hour=30,
960 second_of_minute=54)
961 dumper = TimePointDumper()
962 test_timepoint_string = dumper.dump(test_timepoint, 'CCYYMMDDThhmmss')
963 test_timepoint_string += value
964 parser = TimePointParser(allow_only_basic=True)
965 try:
966 parser.parse(test_timepoint_string)
967 except ValueError as exc: # not IsodatetimeError as too specific
968 raise IllegalValueError(
969 'cycle point time zone format', keys, value, exc=exc
970 ) from None
971 return value
972
973 @classmethod
974 def coerce_interval(cls, value, keys):
975 """Coerce an ISO 8601 interval into seconds.
976
977 Examples:
978 >>> CylcConfigValidator.coerce_interval('PT1H', None)
979 3600.0
980
981 """
982 value = cls.strip_and_unquote(keys, value)
983 if not value:
984 # Allow explicit empty values.
985 return None
986 try:
987 interval = DurationParser().parse(value)
988 except IsodatetimeError as exc:
989 raise IllegalValueError(
990 "ISO 8601 interval", keys, value, exc=exc
991 ) from None
992 return DurationFloat(interval.get_seconds())
993
994 @classmethod
995 def coerce_interval_list(cls, value, keys):
996 """Coerce a list of intervals into seconds.
997
998 Examples:
999 >>> CylcConfigValidator.coerce_interval_list('PT1H, PT2H', None)
1000 [3600.0, 7200.0]
1001
1002 """
1003 return cls.expand_list(
1004 cls.strip_and_unquote_list(keys, value),
1005 keys,
1006 lambda v: cls.coerce_interval(v, keys))
1007
1008 @classmethod
1009 def coerce_parameter_list(cls, value, keys):
1010 """Coerce parameter list.
1011
1012 Args:
1013 value (str):
1014 This can be a list of str values. Each str value must conform
1015 to the same restriction as a task name.
1016 Otherwise, this can be a mixture of int ranges and int values.
1017 keys (list):
1018 Keys in nested dict that represents the raw configuration.
1019
1020 Return (list):
1021 A list of strings or a list of sorted integers.
1022
1023 Raise:
1024 IllegalValueError:
1025 If value has both str and int range or if a str value breaks
1026 the task name restriction.
1027
1028 Examples:
1029 >>> CylcConfigValidator.coerce_parameter_list('1..4, 6', None)
1030 [1, 2, 3, 4, 6]
1031
1032 >>> CylcConfigValidator.coerce_parameter_list('a, b, c', None)
1033 ['a', 'b', 'c']
1034
1035 >>> CylcConfigValidator.coerce_parameter_list('084_132', None)
1036 ['084_132']
1037
1038 >>> CylcConfigValidator.coerce_parameter_list('072, a', None)
1039 ['072', 'a']
1040 """
1041 items = []
1042 can_only_be = None # A flag to prevent mixing str and int range
1043 for item in cls.strip_and_unquote_list(keys, value):
1044 values = cls.parse_int_range(item)
1045 if values is not None:
1046 if can_only_be is str:
1047 raise IllegalValueError(
1048 'parameter', keys, value, 'mixing int range and str')
1049 can_only_be = int
1050 items.extend(values)
1051 elif cls._REC_NAME_SUFFIX.match(item): # noqa: SIM106
1052 try:
1053 if '_' in item:
1054 # Disable PEP-515 int coercion; go to except block:
1055 raise ValueError()
1056 int(item)
1057 except ValueError:
1058 if can_only_be is int:
1059 raise IllegalValueError(
1060 'parameter',
1061 keys,
1062 value,
1063 'mixing int range and str',
1064 ) from None
1065 can_only_be = str
1066 items.append(item)
1067 else:
1068 raise IllegalValueError(
1069 'parameter', keys, value, '%s: bad value' % item)
1070
1071 if can_only_be is str:
1072 return items
1073
1074 try:
1075 return [int(item) for item in items]
1076 except ValueError:
1077 return items
1078
1079 @staticmethod
1080 def parse_xtrig_arglist(value: str) -> Tuple[List[Any], Dict[str, Any]]:
1081 """Parse Pythonic-like arg/kwarg signatures.
1082
1083 A stateful parser treats all args/kwargs as strings with
1084 implicit quoting.
1085
1086 Examples:
1087 >>> parse = CylcConfigValidator.parse_xtrig_arglist
1088
1089 # Parse pythonic syntax
1090 >>> parse('a, b, c, d=1, e=2,')
1091 (['a', 'b', 'c'], {'d': '1', 'e': '2'})
1092 >>> parse('a, "1,2,3", b=",=",')
1093 (['a', '"1,2,3"'], {'b': '",="'})
1094 >>> parse('a, "b c", '"'d=e '")
1095 (['a', '"b c"', "'d=e '"], {})
1096
1097 # Parse implicit (i.e. unquoted) strings
1098 >>> parse('%(cycle)s, %(task)s, output=succeeded')
1099 (['%(cycle)s', '%(task)s'], {'output': 'succeeded'})
1100
1101 """
1102 # results
1103 args = []
1104 kwargs = {}
1105 # state
1106 in_str = False # are we inside a quoted string
1107 in_kwarg = False # are we after the = sign of a kwarg
1108 buffer = '' # the current argument being parsed
1109 kwarg_buffer = '' # the key of a kwarg if in_kwarg == True
1110 # parser
1111 for char in value:
1112 if char in {'"', "'"}:
1113 in_str = not in_str
1114 buffer += char
1115 elif not in_str and char == ',':
1116 if in_kwarg:
1117 kwargs[kwarg_buffer.strip()] = buffer.strip()
1118 in_kwarg = False
1119 kwarg_buffer = ''
1120 else:
1121 args.append(buffer.strip())
1122 buffer = ''
1123 elif char == '=' and not in_str and not in_kwarg:
1124 in_kwarg = True
1125 kwarg_buffer = buffer
1126 buffer = ''
1127 else:
1128 buffer += char
1129
1130 # reached the end of the string
1131 if buffer:
1132 if in_kwarg:
1133 kwargs[kwarg_buffer.strip()] = buffer.strip()
1134 else:
1135 args.append(buffer.strip())
1136
1137 return args, kwargs
1138
1139 @classmethod
1140 def coerce_xtrigger(cls, value, keys):
1141 """Coerce a string into an xtrigger function context object.
1142
1143 func_name(*func_args, **func_kwargs)
1144 Checks for legal string templates in arg values too.
1145
1146 Examples:
1147 >>> xtrig = CylcConfigValidator.coerce_xtrigger
1148
1149 >>> ctx = xtrig('a(b, c):PT1M', [None])
1150 >>> ctx.get_signature()
1151 'a(b, c)'
1152 >>> ctx.intvl
1153 60.0
1154
1155 # cast types
1156 >>> x = xtrig('a(1, 1.1, True, abc, x=True, y=1.1)', [None])
1157 >>> x.func_args
1158 [1, 1.1, True, 'abc']
1159 >>> x.func_kwargs
1160 {'x': True, 'y': 1.1}
1161
1162 """
1163 label = keys[-1]
1164 value = cls.strip_and_unquote(keys, value)
1165 if not value:
1166 raise IllegalValueError("xtrigger", keys, value)
1167 match = cls._REC_TRIG_FUNC.match(value)
1168 if match is None:
1169 raise IllegalValueError("xtrigger", keys, value)
1170 fname, fargs, intvl = match.groups()
1171 if intvl:
1172 intvl = cls.coerce_interval(intvl, keys)
1173
1174 # parse args
1175 args, kwargs = CylcConfigValidator.parse_xtrig_arglist(fargs or '')
1176
1177 # cast types
1178 args = [
1179 CylcConfigValidator._coerce_type(arg)
1180 for arg in args
1181 ]
1182 kwargs = {
1183 key: CylcConfigValidator._coerce_type(value)
1184 for key, value in kwargs.items()
1185 }
1186
1187 return SubFuncContext(label, fname, args, kwargs, intvl)
1188
1189 @classmethod
1190 def _coerce_type(cls, value):
1191 """Convert value to int, float, bool, or None, if possible.
1192
1193 Examples:
1194 >>> CylcConfigValidator._coerce_type('1')
1195 1
1196 >>> CylcConfigValidator._coerce_type('1.1')
1197 1.1
1198 >>> CylcConfigValidator._coerce_type('True')
1199 True
1200 >>> CylcConfigValidator._coerce_type('abc')
1201 'abc'
1202 >>> CylcConfigValidator._coerce_type('None')
1203
1204 """
1205 try:
1206 val = int(value)
1207 except ValueError:
1208 try:
1209 val = float(value)
1210 except ValueError:
1211 if value == 'False':
1212 val = False
1213 elif value == 'True':
1214 val = True
1215 elif value == 'None':
1216 val = None
1217 else:
1218 # Leave as string.
1219 val = cls.strip_and_unquote([], value)
1220 return val
1221
1222
1223 class BroadcastConfigValidator(CylcConfigValidator):
1224 """Validate and Coerce DB loaded broadcast config to internal objects."""
1225 def __init__(self):
1226 CylcConfigValidator.__init__(self)
1227
1228 @classmethod
1229 def coerce_str(cls, value, keys) -> str:
1230 """Coerce value to a string. Unquotes & strips lead/trail whitespace.
1231
1232 Prevents ParsecValidator from assuming '#' means comments;
1233 '#' has valid uses in shell script such as parameter substitution.
1234
1235 Examples:
1236 >>> BroadcastConfigValidator.coerce_str('echo "${FOO#*bar}"', None)
1237 'echo "${FOO#*bar}"'
1238 """
1239 val = ParsecValidator._unquote(keys, value) or value
1240 return dedent(val).strip()
1241
1242 @classmethod
1243 def strip_and_unquote_list(cls, keys, value):
1244 """Remove leading and trailing spaces and unquote list value.
1245
1246 Args:
1247 keys (list):
1248 Keys in nested dict that represents the raw configuration.
1249 value (str):
1250 String value in raw configuration that is supposed to be a
1251 comma separated list.
1252
1253 Return (list):
1254 Processed value as a list.
1255
1256 Examples:
1257 >>> BroadcastConfigValidator.strip_and_unquote_list(
1258 ... None, '["1, 2", 3]'
1259 ... )
1260 ['1, 2', '3']
1261 """
1262 if value.startswith('[') and value.endswith(']'):
1263 value = value.lstrip('[').rstrip(']')
1264 return ParsecValidator.strip_and_unquote_list(keys, value)
1265
1266 # BACK COMPAT: BroadcastConfigValidator.coerce_interval
1267 # The DB at 8.0.x stores Interval values as neither ISO8601 duration
1268 # string or DurationFloat. This has been fixed at 8.1.0, and
1269 # the following method acts as a bridge between fixed and broken.
1270 # url:
1271 # https://github.com/cylc/cylc-flow/pull/5138
1272 # from:
1273 # 8.0.x
1274 # to:
1275 # 8.1.x
1276 # remove at:
1277 # 8.x
1278 @classmethod
1279 def coerce_interval(cls, value, keys):
1280 """Coerce an ISO 8601 interval into seconds.
1281
1282 Examples:
1283 >>> BroadcastConfigValidator.coerce_interval('PT1H', None)
1284 3600.0
1285 >>> x = BroadcastConfigValidator.coerce_interval('62', None)
1286 >>> x
1287 62.0
1288 >>> str(x)
1289 'PT1M2S'
1290
1291 """
1292 value = cls.strip_and_unquote(keys, value)
1293 if not value:
1294 # Allow explicit empty values.
1295 return None
1296 try:
1297 interval = DurationParser().parse(value)
1298 except IsodatetimeError:
1299 try:
1300 interval = DurationParser().parse(str(DurationFloat(value)))
1301 except IsodatetimeError as exc:
1302 raise IllegalValueError(
1303 "ISO 8601 interval", keys, value, exc=exc
1304 ) from None
1305 return DurationFloat(interval.get_seconds())
1306
1307
1308 def cylc_config_validate(cfg_root, spec_root):
1309 """Short for "CylcConfigValidator().validate(...)"."""
1310 return CylcConfigValidator().validate(cfg_root, spec_root)