Debian Codegraph @

cylc/flow/dbstatecheck.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
17 import errno
18 import json
19 import os
20 import sqlite3
21 import sys
22 from contextlib import suppress
23 from typing import Dict, Iterable, Optional, List, Union
24
25 from cylc.flow.exceptions import InputError
26 from cylc.flow.cycling.util import add_offset
27 from cylc.flow.cycling.integer import (
28 IntegerPoint,
29 IntegerInterval
30 )
31 from cylc.flow.flow_mgr import repr_flow_nums
32 from cylc.flow.pathutil import expand_path
33 from cylc.flow.rundb import CylcWorkflowDAO
34 from cylc.flow.task_outputs import (
35 TASK_OUTPUT_SUCCEEDED,
36 TASK_OUTPUT_FAILED,
37 TASK_OUTPUT_FINISHED,
38 )
39 from cylc.flow.task_state import (
40 TASK_STATE_MAP,
41 TASK_STATUSES_FINAL,
42 )
43 from cylc.flow.util import deserialise_set
44 from metomi.isodatetime.parsers import TimePointParser
45 from metomi.isodatetime.exceptions import ISO8601SyntaxError
46
47
48 output_fallback_msg = (
49 "Unable to filter by task output label for tasks run in Cylc versions "
50 "between 8.0.0-8.3.0. Falling back to filtering by task message instead."
51 )
52
53
54 class CylcWorkflowDBChecker:
55 """Object for querying task status or outputs from a workflow database.
56
57 Back-compat and task outputs:
58 # Cylc 7 stored {trigger: message} for custom outputs only.
59 1|foo|{"x": "the quick brown"}
60
61 # Cylc 8 (pre-8.3.0) stored [message] only, for all outputs.
62 1|foo|[1]|["submitted", "started", "succeeded", "the quick brown"]
63
64 # Cylc 8 (8.3.0+) stores {trigger: message} for all ouputs.
65 1|foo|[1]|{"submitted": "submitted", "started": "started",
66 "succeeded": "succeeded", "x": "the quick brown"}
67 """
68
69 def __init__(self, rund, workflow, db_path=None):
70 # (Explicit dp_path arg is to make testing easier).
71 if db_path is None:
72 # Infer DB path from workflow name and run dir.
73 db_path = expand_path(
74 rund, workflow, "log", CylcWorkflowDAO.DB_FILE_BASE_NAME
75 )
76 if not os.path.exists(db_path):
77 raise OSError(errno.ENOENT, os.strerror(errno.ENOENT), db_path)
78
79 self.conn: sqlite3.Connection = sqlite3.connect(db_path, timeout=10.0)
80
81 # Get workflow point format.
82 try:
83 self.db_point_fmt = self._get_db_point_format()
84 self.c7_back_compat_mode = False
85 except sqlite3.OperationalError as exc:
86 # BACK COMPAT: Cylc 7 DB (see method below).
87 try:
88 self.db_point_fmt = self._get_db_point_format_compat()
89 self.c7_back_compat_mode = True
90 except sqlite3.OperationalError:
91 with suppress(Exception):
92 self.conn.close()
93 raise exc from None # original error
94
95 def __enter__(self):
96 return self
97
98 def __exit__(self, exc_type, exc_value, traceback):
99 """Close DB connection when leaving context manager."""
100 self.conn.close()
101
102 def adjust_point_to_db(self, cycle, offset):
103 """Adjust a cycle point (with offset) to the DB point format.
104
105 Cycle point queries have to match in the DB as string literals,
106 so we convert given cycle points (e.g., from the command line)
107 to the DB point format before making the query.
108
109 """
110 if cycle is None or "*" in cycle:
111 if offset is not None:
112 raise InputError(
113 f'Cycle point "{cycle}" is not compatible with an offset.'
114 )
115 # Nothing to do
116 return cycle
117
118 if offset is not None:
119 if self.db_point_fmt is None:
120 # integer cycling
121 cycle = str(
122 IntegerPoint(cycle) +
123 IntegerInterval(offset)
124 )
125 else:
126 cycle = str(
127 add_offset(cycle, offset)
128 )
129
130 if self.db_point_fmt is None:
131 return cycle
132
133 # Convert cycle point to DB format.
134 try:
135 cycle = str(
136 TimePointParser().parse(
137 cycle, dump_format=self.db_point_fmt
138 )
139 )
140 except ISO8601SyntaxError:
141 raise InputError(
142 f'Cycle point "{cycle}" is not compatible'
143 f' with DB point format "{self.db_point_fmt}"'
144 ) from None
145 return cycle
146
147 @staticmethod
148 def display_maps(res, old_format=False, pretty_print=False):
149 if not res:
150 sys.stderr.write("INFO: No results to display.\n")
151 else:
152 for row in res:
153 if old_format:
154 sys.stdout.write(', '.join(row) + '\n')
155 else:
156 out = f"{row[1]}/{row[0]}:" # cycle/task:
157 status_or_outputs = row[2]
158 if pretty_print:
159 with suppress(json.decoder.JSONDecodeError):
160 status_or_outputs = (
161 json.dumps(
162 json.loads(
163 status_or_outputs.replace("'", '"')
164 ),
165 indent=4
166 )
167 )
168 out += status_or_outputs
169 if len(row) == 4:
170 out += row[3] # flow
171 sys.stdout.write(out + "\n")
172
173 def _get_db_point_format(self):
174 """Query a workflow database for a 'cycle point format' entry"""
175 for row in self.conn.execute(
176 rf'''
177 SELECT
178 value
179 FROM
180 {CylcWorkflowDAO.TABLE_WORKFLOW_PARAMS}
181 WHERE
182 key==?
183 ''', # nosec (table name is code constant)
184 ['cycle_point_format']
185 ):
186 return row[0]
187
188 def _get_db_point_format_compat(self):
189 """Query a Cylc 7 suite database for 'cycle point format'."""
190 # BACK COMPAT: Cylc 7 DB
191 # Workflows parameters table name change.
192 # from:
193 # 8.0.x
194 # to:
195 # 8.1.x
196 # remove at:
197 # 8.x
198 for row in self.conn.execute(
199 rf'''
200 SELECT
201 value
202 FROM
203 {CylcWorkflowDAO.TABLE_SUITE_PARAMS}
204 WHERE
205 key==?
206 ''', # nosec (table name is code constant)
207 ['cycle_point_format']
208 ):
209 return row[0]
210
211 def workflow_state_query(
212 self,
213 task: Optional[str] = None,
214 cycle: Optional[str] = None,
215 selector: Optional[str] = None,
216 is_trigger: Optional[bool] = False,
217 is_message: Optional[bool] = False,
218 flow_num: Optional[int] = None,
219 print_outputs: bool = False
220 ) -> List[List[str]]:
221 """Query task status or outputs (by trigger or message) in a database.
222
223 Args:
224 task:
225 task name
226 cycle:
227 cycle point
228 selector:
229 task status, trigger name, or message
230 is_trigger:
231 intpret the selector as a trigger
232 is_message:
233 interpret the selector as a task message
234
235 Return:
236 A list of results for all tasks that match the query.
237 [
238 [name, cycle, result, [flow]],
239 ...
240 ]
241
242 "result" is single string:
243 - for status queries: the task status
244 - for output queries: a serialized dict of completed outputs
245 {trigger: message}
246
247 """
248 stmt_args = []
249 stmt_wheres = []
250
251 check_polling_config(selector, is_trigger, is_message)
252
253 if is_trigger or is_message:
254 target_table = CylcWorkflowDAO.TABLE_TASK_OUTPUTS
255 mask = "name, cycle, outputs"
256 else:
257 target_table = CylcWorkflowDAO.TABLE_TASK_STATES
258 mask = "name, cycle, status"
259
260 if not self.c7_back_compat_mode:
261 # Cylc 8 DBs only
262 mask += ", flow_nums"
263
264 stmt = rf'''
265 SELECT
266 {mask}
267 FROM
268 {target_table}
269 ''' # nosec
270 # * mask is hardcoded
271 # * target_table is a code constant
272
273 # Select from DB by name, cycle, status.
274 # (Outputs and flow_nums are serialised).
275 if task:
276 if '*' in task:
277 # Replace Cylc ID wildcard with Sqlite query wildcard.
278 task = task.replace('*', '%')
279 stmt_wheres.append("name like ?")
280 else:
281 stmt_wheres.append("name==?")
282 stmt_args.append(task)
283
284 if cycle:
285 if '*' in cycle:
286 # Replace Cylc ID wildcard with Sqlite query wildcard.
287 cycle = cycle.replace('*', '%')
288 stmt_wheres.append("cycle like ?")
289 else:
290 stmt_wheres.append("cycle==?")
291 stmt_args.append(cycle)
292
293 if (
294 selector is not None
295 and target_table == CylcWorkflowDAO.TABLE_TASK_STATES
296 ):
297 # Can select by status in the DB but not outputs.
298 stmt_wheres.append("status==?")
299 stmt_args.append(selector)
300
301 if stmt_wheres:
302 stmt += "WHERE\n " + (" AND ").join(stmt_wheres)
303
304 if target_table == CylcWorkflowDAO.TABLE_TASK_STATES:
305 # (outputs table doesn't record submit number)
306 stmt += r"ORDER BY submit_num"
307
308 # Query the DB and drop incompatible rows.
309 db_res = []
310 for row in self.conn.execute(stmt, stmt_args):
311 # name, cycle, status_or_outputs, [flow_nums]
312 res = list(row[:3])
313 if row[2] is None:
314 # status can be None in Cylc 7 DBs
315 continue
316 if not self.c7_back_compat_mode:
317 flow_nums = deserialise_set(row[3])
318 if flow_num is not None and flow_num not in flow_nums:
319 # skip result, wrong flow
320 continue
321 fstr = repr_flow_nums(flow_nums)
322 if fstr:
323 res.append(fstr)
324 db_res.append(res)
325
326 if target_table == CylcWorkflowDAO.TABLE_TASK_STATES:
327 return db_res
328
329 warn_output_fallback = is_trigger
330 results = []
331 for row in db_res:
332 outputs: Union[Dict[str, str], List[str]] = json.loads(row[2])
333 if isinstance(outputs, dict):
334 messages: Iterable[str] = outputs.values()
335 else:
336 # Cylc 8 pre 8.3.0 back-compat: list of output messages
337 messages = outputs
338 if warn_output_fallback:
339 print(f"WARNING - {output_fallback_msg}", file=sys.stderr)
340 warn_output_fallback = False
341 if (
342 selector is None or
343 (is_message and selector in messages) or
344 (is_trigger and self._selector_in_outputs(selector, outputs))
345 ):
346 results.append(row[:2] + [str(outputs)] + row[3:])
347
348 return results
349
350 @staticmethod
351 def _selector_in_outputs(selector: str, outputs: Iterable[str]) -> bool:
352 """Check if a selector, including "finished", is in the outputs.
353
354 Examples:
355 >>> this = CylcWorkflowDBChecker._selector_in_outputs
356 >>> this('moop', ['started', 'moop'])
357 True
358 >>> this('moop', ['started'])
359 False
360 >>> this('finished', ['succeeded'])
361 True
362 >>> this('finish', ['failed'])
363 True
364 """
365 return selector in outputs or (
366 selector in (TASK_OUTPUT_FINISHED, "finish")
367 and (
368 TASK_OUTPUT_SUCCEEDED in outputs
369 or TASK_OUTPUT_FAILED in outputs
370 )
371 )
372
373
374 def check_polling_config(selector, is_trigger, is_message):
375 """Check for invalid or unreliable polling configurations."""
376 if selector and not (is_trigger or is_message):
377 # we are using task status polling
378 try:
379 trigger = TASK_STATE_MAP[selector]
380 except KeyError:
381 raise InputError(f'No such task state "{selector}"') from None
382 else:
383 if trigger is None:
384 raise InputError(
385 f'Cannot poll for the "{selector}" task state'
386 )
387
388 if selector not in TASK_STATUSES_FINAL:
389 raise InputError(
390 f'Polling for the "{selector}" task status is not'
391 ' reliable as it is a transient state.'
392 f'\nPoll for the "{trigger}" trigger instead.'
393 )