Debian Codegraph @

cylc/flow/scripts/validate.py

raw
1 #!/usr/bin/env python3
2
3 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
4 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 """cylc validate [OPTIONS] ARGS
20
21 Validate a workflow configuration.
22
23 If the workflow definition uses include-files, reported line numbers will
24 correspond to the inlined version seen by the parser;
25 use 'cylc view -i,--inline WORKFLOW' for comparison.
26 """
27
28 import asyncio
29 from ansimarkup import parse as cparse
30 from copy import deepcopy
31 from pathlib import Path
32 import sys
33 from typing import TYPE_CHECKING
34
35 from cylc.flow import LOG, __version__ as CYLC_VERSION
36 from cylc.flow.config import WorkflowConfig
37 from cylc.flow.exceptions import (
38 WorkflowConfigError,
39 TaskProxySequenceBoundsError,
40 TriggerExpressionError
41 )
42 import cylc.flow.flags
43 from cylc.flow.id import Tokens
44 from cylc.flow.id_cli import parse_id_async
45 from cylc.flow.loggingutil import set_timestamps
46 from cylc.flow.option_parsers import (
47 AGAINST_SOURCE_OPTION,
48 WORKFLOW_ID_OR_PATH_ARG_DOC,
49 CylcOptionParser as COP,
50 OptionSettings,
51 Options,
52 ICP_OPTION,
53 )
54 from cylc.flow.profiler import Profiler
55 from cylc.flow.scheduler_cli import RUN_MODE
56 from cylc.flow.task_proxy import TaskProxy
57 from cylc.flow.templatevars import get_template_vars
58 from cylc.flow.terminal import cli_function
59 from cylc.flow.run_modes import RunMode
60 from cylc.flow.workflow_files import get_workflow_run_dir
61
62 if TYPE_CHECKING:
63 from cylc.flow.option_parsers import Values
64
65
66 VALIDATE_RUN_MODE = deepcopy(RUN_MODE)
67 VALIDATE_RUN_MODE.sources = {'validate'}
68 VALIDATE_ICP_OPTION = deepcopy(ICP_OPTION)
69 VALIDATE_ICP_OPTION.sources = {'validate'}
70 VALIDATE_AGAINST_SOURCE_OPTION = deepcopy(AGAINST_SOURCE_OPTION)
71 VALIDATE_AGAINST_SOURCE_OPTION.sources = {'validate'}
72
73
74 VALIDATE_OPTIONS = [
75 OptionSettings(
76 ["--check-circular"],
77 help=(
78 "Check for circular dependencies in graphs when the number of"
79 " tasks is greater than 100 (smaller graphs are always"
80 " checked). This can be slow when the number of"
81 " tasks is high."),
82 action="store_true",
83 default=False,
84 dest="check_circular",
85 sources={'validate'}
86 ),
87 OptionSettings(
88 ["--output", "-o"],
89 help="Specify a file name to dump the processed flow.cylc.",
90 metavar="FILENAME",
91 action="store",
92 dest="output",
93 sources={'validate'}
94 ),
95 OptionSettings(
96 ["--profile"],
97 help="Output profiling (performance) information",
98 action="store_true",
99 default=False,
100 dest="profile_mode",
101 sources={'validate'}
102 ),
103 VALIDATE_RUN_MODE,
104 VALIDATE_ICP_OPTION,
105 ]
106
107
108 def get_option_parser():
109 parser = COP(
110 __doc__,
111 jset=True,
112 argdoc=[WORKFLOW_ID_OR_PATH_ARG_DOC],
113 )
114
115 for option in [
116 *parser.get_cylc_rose_options(),
117 *VALIDATE_OPTIONS,
118 VALIDATE_AGAINST_SOURCE_OPTION,
119 ]:
120 parser.add_option(*option.args, **option.kwargs)
121
122 parser.set_defaults(is_validate=True)
123
124 return parser
125
126
127 ValidateOptions = Options(
128 get_option_parser(),
129 # defaults
130 {
131 'check_circular': False,
132 'profile_mode': False,
133 'run_mode': RunMode.LIVE.value
134 }
135 )
136
137
138 @cli_function(get_option_parser)
139 def main(parser: COP, options: 'Values', workflow_id: str) -> None:
140 asyncio.run(run(parser, options, workflow_id))
141
142
143 async def run(
144 parser: COP, options: 'Values', workflow_id: str
145 ) -> None:
146 """cylc validate CLI."""
147 profiler = Profiler(None, options.profile_mode)
148 profiler.start()
149
150 if cylc.flow.flags.verbosity < 2:
151 set_timestamps(LOG, False)
152
153 workflow_id, _, flow_file = await parse_id_async(
154 workflow_id,
155 src=True,
156 constraint='workflows',
157 )
158
159 # Save the location of the existing workflow run dir in the
160 # against source option:
161 if getattr(options, 'against_source', False):
162 options.against_source = Path(get_workflow_run_dir(workflow_id))
163
164 cfg = WorkflowConfig(
165 workflow_id,
166 flow_file,
167 options,
168 get_template_vars(options),
169 output_fname=options.output,
170 mem_log_func=profiler.log_memory
171 )
172
173 # Instantiate tasks and force evaluation of trigger expressions.
174 # (Taken from config.py to avoid circular import problems.)
175 # TODO - This is not exhaustive, it only uses the initial cycle point.
176 if cylc.flow.flags.verbosity > 0:
177 print('Instantiating tasks to check trigger expressions')
178 for name, taskdef in cfg.taskdefs.items():
179 try:
180 itask = TaskProxy(
181 Tokens(workflow_id),
182 taskdef,
183 cfg.start_point,
184 )
185 except TaskProxySequenceBoundsError:
186 # Should already failed above
187 mesg = 'Task out of bounds for %s: %s\n' % (cfg.start_point, name)
188 if cylc.flow.flags.verbosity > 0:
189 sys.stderr.write(' + %s\n' % mesg)
190 continue
191 except Exception as exc:
192 raise WorkflowConfigError(
193 'failed to instantiate task %s: %s' % (name, exc)
194 ) from None
195
196 # force trigger evaluation now
197 try:
198 itask.state.prerequisites_eval_all()
199 except TriggerExpressionError:
200 raise WorkflowConfigError("ERROR: bad trigger") from None
201 except Exception as exc:
202 print(str(exc), file=sys.stderr)
203 raise WorkflowConfigError(
204 '%s: failed to evaluate triggers.' % name
205 ) from None
206 if cylc.flow.flags.verbosity > 0:
207 print(' + %s ok' % itask.identity)
208
209 print(cparse('<green>Valid for cylc-%s</green>' % CYLC_VERSION))
210 profiler.stop()