Debian Codegraph @

cylc/flow/scripts/workflow_state.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 r"""cylc workflow-state [OPTIONS] ARGS
20
21 Check or poll a workflow database for task statuses or completed outputs.
22
23 The ID argument can target a workflow, or a cycle point, or a specific task,
24 with an optional selector on cycle or task to match final task statuses,
25 output trigger (with --triggers), or output message (with --messages).
26 You cannot poll for transient states such as "submitted" and "running";
27 poll for the corresponding output triggers instead ("submitted", "started").
28
29 All matching results will be printed.
30
31 If no results match, the command will repeatedly check (poll) until a match
32 is found or polling is exhausted (see --max-polls and --interval). For a
33 one-off check set --max-polls=1.
34
35 If the database does not exist at first, polls are consumed waiting for it
36 so you can start checking before the target workflow is started.
37
38 Legacy (pre-8.3.0) options are supported, but deprecated, for existing scripts:
39 cylc workflow-state --task=NAME --point=CYCLE --status=STATUS
40 --output=MESSAGE --message=MESSAGE --task-point WORKFLOW
41 (Note from 8.0 until 8.3.0 --output and --message both matched task messages).
42
43 In "cycle/task:selector" the selector will match task statuses, unless:
44 - with --triggers, it will only match task output triggers.
45 - with --messages, it will only match task output messages. It is recommended
46 to use triggers instead - they match both naturally & manually set outputs.
47
48 Selector does not default to "succeeded". If omitted, any status will match.
49
50 The "finished" pseudo-output is an alias for "succeeded or failed".
51
52 In the ID, both cycle and task can include "*" to match any sequence of zero
53 or more characters. Quote the pattern to protect it from shell expansion.
54
55 Note tasks get recorded in the DB once they enter the active window (n=0).
56
57 Flow numbers are only printed for flow numbers > 1.
58
59 Use in task scripting:
60 - To poll a task at the same cycle point in another workflow, just use
61 $CYLC_TASK_CYCLE_POINT in the ID.
62 - To poll a task at an offset cycle point, use the --offset option to
63 have Cylc do the datetime arithmetic for you.
64 - However, see also the workflow_state xtrigger for this use case.
65
66 Warnings:
67 - Typos in the workflow or task ID will result in fruitless polling.
68 - Cycle points are auto-converted to the DB point format (and UTC mode).
69 - Task outputs manually completed by "cylc set" have "(force-completed)"
70 recorded as the task message in the DB, so it is best to query trigger
71 names, not messages, unless specifically interested in forced outputs.
72
73 Examples:
74 # Print the status of all tasks in WORKFLOW:
75 $ cylc workflow-state WORKFLOW
76
77 # Print the status of all tasks in cycle point 2033:
78 $ cylc workflow-state WORKFLOW//2033
79
80 # Print the status of all tasks named foo:
81 $ cylc workflow-state "WORKFLOW//*/foo"
82
83 # Print all succeeded tasks:
84 $ cylc workflow-state "WORKFLOW//*/*:succeeded"
85
86 # Print all tasks foo that completed output (trigger name) file1:
87 $ cylc workflow-state "WORKFLOW//*/foo:file1"
88
89 # Print if task 2033/foo completed output (trigger name) file1:
90 $ cylc workflow-state WORKFLOW//2033/foo:file1
91
92 See also:
93 - the workflow_state xtrigger, for state polling within workflows
94 - "cylc dump -t", to query a scheduler for current statuses
95 - "cylc show", to query a scheduler for task prerequisites and outputs
96 """
97
98 import asyncio
99 import os
100 import sqlite3
101 import sys
102 from typing import TYPE_CHECKING, List, Optional
103
104 from cylc.flow.pathutil import get_cylc_run_dir
105 from cylc.flow.id import Tokens
106 from cylc.flow.exceptions import InputError
107 from cylc.flow.option_parsers import (
108 ID_SEL_ARG_DOC,
109 CylcOptionParser as COP,
110 )
111 from cylc.flow import LOG
112 from cylc.flow.command_polling import Poller
113 from cylc.flow.dbstatecheck import CylcWorkflowDBChecker
114 from cylc.flow.terminal import cli_function
115 from cylc.flow.workflow_files import infer_latest_run_from_id
116 from cylc.flow.task_state import (
117 TASK_STATUSES_FINAL,
118 TASK_STATUSES_ALL,
119 )
120
121 if TYPE_CHECKING:
122 from optparse import Values
123
124
125 WILDCARD = "*"
126
127 # polling defaults
128 MAX_POLLS = 12
129 INTERVAL = 5
130
131 OPT_DEPR_MSG = "DEPRECATED, use ID"
132 OPT_DEPR_MSG1 = 'DEPRECATED, use "ID:STATUS"'
133 OPT_DEPR_MSG2 = 'DEPRECATED, use "ID:MSG"'
134
135
136 def unquote(s: str) -> str:
137 """Remove leading & trailing quotes from a string.
138
139 Examples:
140 >>> unquote('"foo"')
141 'foo'
142 >>> unquote("'foo'")
143 'foo'
144 >>> unquote('foo')
145 'foo'
146 >>> unquote("'tis a fine morning")
147 "'tis a fine morning"
148 """
149 if (
150 s.startswith('"') and s.endswith('"')
151 or s.startswith("'") and s.endswith("'")
152 ):
153 return s[1:-1]
154 return s
155
156
157 class WorkflowPoller(Poller):
158 """An object that polls for task states or outputs in a workflow DB."""
159
160 def __init__(
161 self,
162 id_: str,
163 offset: Optional[str],
164 flow_num: Optional[int],
165 alt_cylc_run_dir: Optional[str],
166 default_status: Optional[str],
167 is_trigger: bool,
168 is_message: bool,
169 old_format: bool = False,
170 pretty_print: bool = False,
171 **kwargs
172 ):
173 self.id_ = id_
174 self.offset = offset
175 self.flow_num = flow_num
176 self.alt_cylc_run_dir = alt_cylc_run_dir
177 self.old_format = old_format
178 self.pretty_print = pretty_print
179 self.is_message = is_message
180 self.is_trigger = is_trigger
181
182 try:
183 tokens = Tokens(self.id_)
184 except ValueError as exc:
185 raise InputError(exc) from None
186
187 self.workflow_id_raw = tokens.workflow_id
188 self.selector = (
189 tokens["cycle_sel"] or
190 tokens["task_sel"] or
191 default_status
192 )
193 if self.selector:
194 self.selector = unquote(self.selector)
195 self.cycle_raw = tokens["cycle"]
196 self.task = tokens["task"]
197
198 self.workflow_id: Optional[str] = None
199 self.cycle: Optional[str] = None
200 self.result: Optional[List[List[str]]] = None
201 self._db_checker: Optional[CylcWorkflowDBChecker] = None
202
203 super().__init__(**kwargs)
204
205 def _find_workflow(self) -> bool:
206 """Find workflow and infer run directory, return True if found."""
207 try:
208 self.workflow_id = infer_latest_run_from_id(
209 self.workflow_id_raw,
210 self.alt_cylc_run_dir
211 )
212 except InputError:
213 LOG.debug("Workflow not found")
214 return False
215
216 if self.workflow_id != self.workflow_id_raw:
217 # Print inferred ID.
218 sys.stderr.write(f"Inferred workflow ID: {self.workflow_id}\n")
219 return True
220
221 @property
222 def db_checker(self) -> Optional[CylcWorkflowDBChecker]:
223 """Connect to workflow DB if not already connected.
224
225 Returns DB checker if connected.
226 """
227 if not self._db_checker:
228 try:
229 self._db_checker = CylcWorkflowDBChecker(
230 get_cylc_run_dir(self.alt_cylc_run_dir),
231 self.workflow_id
232 )
233 except (OSError, sqlite3.Error):
234 LOG.debug("DB not connected")
235 return None
236
237 return self._db_checker
238
239 async def check(self) -> bool:
240 """Return True if requested state achieved, else False.
241
242 Called once per poll by super() so only find and connect once.
243
244 Store self.result for external access.
245
246 """
247 if self.workflow_id is None and not self._find_workflow():
248 return False
249
250 if self.db_checker is None:
251 return False
252
253 if self.cycle is None:
254 # Adjust target cycle point to the DB format.
255 self.cycle = self.db_checker.adjust_point_to_db(
256 self.cycle_raw, self.offset)
257
258 self.result = self.db_checker.workflow_state_query(
259 self.task, self.cycle, self.selector, self.is_trigger,
260 self.is_message, self.flow_num
261 )
262 if self.result:
263 # End the polling dot stream and print inferred runN workflow ID.
264 self.db_checker.display_maps(
265 self.result, self.old_format, self.pretty_print)
266
267 return bool(self.result)
268
269
270 def get_option_parser() -> COP:
271 parser = COP(
272 __doc__,
273 argdoc=[ID_SEL_ARG_DOC]
274 )
275
276 # --run-dir for pre-8.3.0 back-compat
277 parser.add_option(
278 "-d", "--alt-cylc-run-dir", "--run-dir",
279 help="Alternate cylc-run directory, e.g. for other users' workflows.",
280 metavar="DIR", action="store", dest="alt_cylc_run_dir", default=None)
281
282 parser.add_option(
283 "-s", "--offset",
284 help="Offset from ID cycle point as an ISO8601 duration for datetime"
285 " cycling (e.g. 'PT30M' for 30 minutes) or an integer interval for"
286 " integer cycling (e.g. 'P2'). This can be used in task job scripts"
287 " to poll offset cycle points without doing the cycle arithmetic"
288 " yourself - but see also the workflow_state xtrigger.",
289 action="store", dest="offset", metavar="DURATION", default=None)
290
291 parser.add_option(
292 "--flow",
293 help="Flow number, for target tasks. By default, any flow.",
294 action="store", type="int", dest="flow_num", default=None)
295
296 parser.add_option(
297 "--triggers",
298 help="Task selector should match output trigger names rather than "
299 "status.",
300 action="store_true", dest="is_trigger", default=False)
301
302 parser.add_option(
303 "--messages",
304 help="Task selector should match output messages rather than status.",
305 action="store_true", dest="is_message", default=False)
306
307 parser.add_option(
308 "--pretty",
309 help="Pretty-print outputs (the default is single-line output).",
310 action="store_true", dest="pretty_print", default=False)
311
312 parser.add_option(
313 "--old-format",
314 help="Print results in legacy comma-separated format.",
315 action="store_true", dest="old_format", default=False)
316
317 # Back-compat support for pre-8.3.0 command line options.
318 parser.add_option(
319 "-t", "--task", help=f"Task name. {OPT_DEPR_MSG}.",
320 metavar="NAME",
321 action="store", dest="depr_task", default=None)
322
323 parser.add_option(
324 "-p", "--point", metavar="CYCLE",
325 help=f"Cycle point. {OPT_DEPR_MSG}.",
326 action="store", dest="depr_point", default=None)
327
328 parser.add_option(
329 "-T", "--task-point",
330 help="Get cycle point from the environment variable"
331 " $CYLC_TASK_CYCLE_POINT (e.g. in task job scripts)",
332 action="store_true", dest="depr_env_point", default=False)
333
334 parser.add_option(
335 "-S", "--status",
336 metavar="STATUS",
337 help=f"Task status. {OPT_DEPR_MSG1}.",
338 action="store", dest="depr_status", default=None)
339
340 # Prior to 8.3.0 --output was just an alias for --message
341 parser.add_option(
342 "-O", "--output", "-m", "--message",
343 metavar="MSG",
344 help=f"Task output message. {OPT_DEPR_MSG2}.",
345 action="store", dest="depr_msg", default=None)
346
347 WorkflowPoller.add_to_cmd_options(
348 parser,
349 d_interval=INTERVAL,
350 d_max_polls=MAX_POLLS
351 )
352
353 return parser
354
355
356 @cli_function(get_option_parser, remove_opts=["--db"])
357 def main(parser: COP, options: 'Values', *ids: str) -> None:
358 # Note it would be cleaner to use 'id_cli.parse_ids()' here to get the
359 # workflow ID and tokens, but that function infers run number and fails
360 # if the workflow is not installed yet. We want to be able to start polling
361 # before the workflow is installed, which makes it easier to get a set of
362 # interdependent workflows up and running, so runN inference is done inside
363 # the poller. TODO: consider using id_cli.parse_ids inside the poller.
364 # (Note this applies to polling tasks, which use the CLI, not xtriggers).
365
366 id_ = ids[0].rstrip('/') # might get 'id/' due to autcomplete
367
368 if any(
369 [
370 options.depr_task,
371 options.depr_status,
372 options.depr_msg,
373 options.depr_point,
374 options.depr_env_point
375 ]
376 ):
377 depr_opts = (
378 "--task, --status, --message, --output, --point, --task-point"
379 )
380
381 if id_ != Tokens(id_)["workflow"]:
382 raise InputError(
383 f"with deprecated {depr_opts}, the argument must be a"
384 " plain workflow ID (i.e. no cycle, task, or :selector)."
385 )
386
387 if options.depr_status and options.depr_msg:
388 raise InputError("set --status or --message, not both.")
389
390 if options.depr_env_point:
391 if options.depr_point:
392 raise InputError(
393 "set --task-point or --point=CYCLE, not both.")
394 try:
395 options.depr_point = os.environ["CYLC_TASK_CYCLE_POINT"]
396 except KeyError:
397 raise InputError(
398 "--task-point: $CYLC_TASK_CYCLE_POINT is not defined"
399 ) from None
400
401 if options.depr_point is not None:
402 id_ += f"//{options.depr_point}"
403 elif (
404 options.depr_task is not None or
405 options.depr_status is not None or
406 options.depr_msg is not None
407 ):
408 id_ += "//*"
409 if options.depr_task is not None:
410 id_ += f"/{options.depr_task}"
411 if options.depr_status is not None:
412 id_ += f":{options.depr_status}"
413 elif options.depr_msg is not None:
414 id_ += f":{options.depr_msg}"
415 options.is_message = True
416
417 msg = f"{depr_opts} are deprecated. Please use an ID: "
418 if not options.depr_env_point:
419 msg += id_
420 else:
421 msg += id_.replace(options.depr_point, "$CYLC_TASK_CYCLE_POINT")
422
423 if (
424 options.depr_status
425 and options.depr_status in TASK_STATUSES_ALL
426 and options.depr_status not in TASK_STATUSES_FINAL
427 ):
428 # polling for non-final task statuses is flaky
429 msg += ' and the --triggers option'
430
431 LOG.warning(msg)
432
433 poller = WorkflowPoller(
434 id_,
435 options.offset,
436 options.flow_num,
437 options.alt_cylc_run_dir,
438 default_status=None,
439 is_trigger=options.is_trigger,
440 is_message=options.is_message,
441 old_format=options.old_format,
442 pretty_print=options.pretty_print,
443 condition=id_,
444 interval=options.interval,
445 max_polls=options.max_polls,
446 args=None
447 )
448
449 if not asyncio.run(
450 poller.poll()
451 ):
452 sys.exit(1)