Debian Codegraph @

cylc/flow/workflow_db_mgr.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 """Manage the workflow runtime private and public databases.
17
18 This module provides the logic to:
19 * Create or initialise database file on start up.
20 * Queue database operations.
21 * Hide logic that is relevant for database operations.
22 * Recover public run database file lock.
23 * Manage existing run database files on restart.
24 """
25
26 from collections import defaultdict
27 import json
28 import os
29 from shutil import (
30 copy,
31 rmtree,
32 )
33 from sqlite3 import OperationalError
34 from tempfile import mkstemp
35 from typing import (
36 TYPE_CHECKING,
37 Any,
38 AnyStr,
39 DefaultDict,
40 Dict,
41 List,
42 Optional,
43 Set,
44 Tuple,
45 Union,
46 )
47
48 from packaging.version import parse as parse_version
49
50 from cylc.flow import (
51 LOG,
52 __version__ as CYLC_VERSION,
53 )
54 from cylc.flow.broadcast_report import get_broadcast_change_iter
55 from cylc.flow.exceptions import (
56 CylcError,
57 ServiceFileError,
58 )
59 from cylc.flow.rundb import CylcWorkflowDAO
60 from cylc.flow.task_outputs import TASK_OUTPUT_SUCCEEDED
61 from cylc.flow.util import (
62 deserialise_set,
63 serialise_set,
64 )
65 from cylc.flow.wallclock import (
66 get_current_time_string,
67 get_utc_mode,
68 )
69 from cylc.flow.scripts.set import XTRIGGER_PREREQ_PREFIX
70
71 if TYPE_CHECKING:
72 from pathlib import Path
73
74 from packaging.version import Version
75
76 from cylc.flow.cycling import PointBase
77 from cylc.flow.flow_mgr import FlowNums
78 from cylc.flow.rundb import (
79 DbArgDict,
80 DbUpdateTuple,
81 )
82 from cylc.flow.scheduler import Scheduler
83 from cylc.flow.task_events_mgr import EventKey
84 from cylc.flow.task_pool import TaskPool
85 from cylc.flow.task_proxy import TaskProxy
86
87
88 PERM_PRIVATE = 0o600 # -rw-------
89
90
91 INCOMPAT_MSG = f"Workflow database is incompatible with Cylc {CYLC_VERSION}"
92
93
94 class WorkflowDatabaseManager:
95 """Manage the workflow runtime private and public databases."""
96
97 KEY_INITIAL_CYCLE_POINT = 'icp'
98 KEY_START_CYCLE_POINT = 'startcp'
99 KEY_FINAL_CYCLE_POINT = 'fcp'
100 KEY_STOP_CYCLE_POINT = 'stopcp'
101 KEY_UUID_STR = 'uuid_str'
102 KEY_CYLC_VERSION = 'cylc_version'
103 KEY_UTC_MODE = 'UTC_mode'
104 KEY_PAUSED = 'is_paused'
105 KEY_HOLD_CYCLE_POINT = 'holdcp'
106 KEY_RUN_MODE = 'run_mode'
107 KEY_STOP_CLOCK_TIME = 'stop_clock_time'
108 KEY_STOP_TASK = 'stop_task'
109 KEY_CYCLE_POINT_FORMAT = 'cycle_point_format'
110 KEY_CYCLE_POINT_TIME_ZONE = 'cycle_point_tz'
111 KEY_RESTART_COUNT = 'n_restart'
112
113 TABLE_BROADCAST_EVENTS = CylcWorkflowDAO.TABLE_BROADCAST_EVENTS
114 TABLE_BROADCAST_STATES = CylcWorkflowDAO.TABLE_BROADCAST_STATES
115 TABLE_INHERITANCE = CylcWorkflowDAO.TABLE_INHERITANCE
116 TABLE_WORKFLOW_PARAMS = CylcWorkflowDAO.TABLE_WORKFLOW_PARAMS
117 TABLE_WORKFLOW_FLOWS = CylcWorkflowDAO.TABLE_WORKFLOW_FLOWS
118 TABLE_WORKFLOW_TEMPLATE_VARS = CylcWorkflowDAO.TABLE_WORKFLOW_TEMPLATE_VARS
119 TABLE_TASK_ACTION_TIMERS = CylcWorkflowDAO.TABLE_TASK_ACTION_TIMERS
120 TABLE_TASK_POOL = CylcWorkflowDAO.TABLE_TASK_POOL
121 TABLE_TASK_OUTPUTS = CylcWorkflowDAO.TABLE_TASK_OUTPUTS
122 TABLE_TASK_STATES = CylcWorkflowDAO.TABLE_TASK_STATES
123 TABLE_TASK_PREREQUISITES = CylcWorkflowDAO.TABLE_TASK_PREREQUISITES
124 TABLE_TASK_TIMEOUT_TIMERS = CylcWorkflowDAO.TABLE_TASK_TIMEOUT_TIMERS
125 TABLE_TASKS_TO_HOLD = CylcWorkflowDAO.TABLE_TASKS_TO_HOLD
126 TABLE_XTRIGGERS = CylcWorkflowDAO.TABLE_XTRIGGERS
127 TABLE_ABS_OUTPUTS = CylcWorkflowDAO.TABLE_ABS_OUTPUTS
128
129 def __init__(self, pri_d=None, pub_d=None):
130 self.pri_path = None
131 if pri_d:
132 self.pri_path = os.path.join(
133 pri_d, CylcWorkflowDAO.DB_FILE_BASE_NAME)
134 self.pub_path = None
135 if pub_d:
136 self.pub_path = os.path.join(
137 pub_d, CylcWorkflowDAO.DB_FILE_BASE_NAME)
138 self.pri_dao = None
139 self.pub_dao = None
140 self.n_restart = 0
141
142 self.db_deletes_map: Dict[str, List[DbArgDict]] = {
143 self.TABLE_BROADCAST_STATES: [],
144 self.TABLE_WORKFLOW_PARAMS: [],
145 self.TABLE_TASK_POOL: [],
146 self.TABLE_TASK_ACTION_TIMERS: [],
147 self.TABLE_TASK_OUTPUTS: [],
148 self.TABLE_TASK_PREREQUISITES: [],
149 self.TABLE_TASK_TIMEOUT_TIMERS: [],
150 self.TABLE_TASKS_TO_HOLD: [],
151 self.TABLE_XTRIGGERS: []}
152 self.db_inserts_map: Dict[str, List[DbArgDict]] = {
153 self.TABLE_BROADCAST_EVENTS: [],
154 self.TABLE_BROADCAST_STATES: [],
155 self.TABLE_INHERITANCE: [],
156 self.TABLE_WORKFLOW_PARAMS: [],
157 self.TABLE_WORKFLOW_FLOWS: [],
158 self.TABLE_WORKFLOW_TEMPLATE_VARS: [],
159 self.TABLE_TASK_POOL: [],
160 self.TABLE_TASK_ACTION_TIMERS: [],
161 self.TABLE_TASK_OUTPUTS: [],
162 self.TABLE_TASK_PREREQUISITES: [],
163 self.TABLE_TASK_TIMEOUT_TIMERS: [],
164 self.TABLE_TASKS_TO_HOLD: [],
165 self.TABLE_XTRIGGERS: [],
166 self.TABLE_ABS_OUTPUTS: []}
167 self.db_updates_map: DefaultDict[
168 str, List[DbUpdateTuple]
169 ] = defaultdict(list)
170
171 def copy_pri_to_pub(self) -> None:
172 """Copy content of primary database file to public database file."""
173 self.pub_dao.close()
174 # Use temporary file to ensure that we do not end up with a
175 # partial file.
176 # If an external connection is locking the old public db, it will
177 # still be connected to its inode, but should no longer affect future
178 # accesses (hopefully that process will soon recover to give up
179 # the lock).
180 temp_pub_db_fd, temp_pub_db_file_name = mkstemp(
181 prefix=self.pub_dao.DB_FILE_BASE_NAME,
182 dir=os.path.dirname(self.pub_dao.db_file_name)
183 )
184 os.close(temp_pub_db_fd)
185 try:
186 # Create the file if it didn't exist; this is done in the hope of
187 # addressing potential NFS file lag, we think
188 open(self.pub_dao.db_file_name, "a").close() # noqa: SIM115
189 # Get default permissions level for public db:
190 st_mode = os.stat(self.pub_dao.db_file_name).st_mode
191
192 copy(self.pri_dao.db_file_name, temp_pub_db_file_name)
193 os.rename(temp_pub_db_file_name, self.pub_dao.db_file_name)
194 os.chmod(self.pub_dao.db_file_name, st_mode)
195 except OSError:
196 if os.path.exists(temp_pub_db_file_name):
197 os.remove(temp_pub_db_file_name)
198 raise
199
200 def get_pri_dao(self) -> CylcWorkflowDAO:
201 """Return the primary DAO.
202
203 NOTE: the DAO should be closed after use. You can use this function as
204 a context manager, which handles this for you.
205 """
206 return CylcWorkflowDAO(self.pri_path, create_tables=True)
207
208 @staticmethod
209 def _namedtuple2json(obj):
210 """Convert nametuple obj to a JSON string.
211
212 Arguments:
213 obj (namedtuple): input object to serialize to JSON.
214
215 Return (str):
216 Serialized JSON string of input object in the form "[type, list]".
217 """
218 if obj is None:
219 return json.dumps(None)
220 else:
221 return json.dumps([type(obj).__name__, obj.__getnewargs__()])
222
223 def on_workflow_start(self, is_restart: bool) -> None:
224 """Initialise data access objects.
225
226 Ensure that:
227 * private database file is private
228 * public database is in sync with private database
229 """
230 if not is_restart:
231 try:
232 # Note: it should no longer be possible to have DB as we now
233 # detect restart based on whether DB exists...
234 os.unlink(self.pri_path)
235 except OSError:
236 # ... however, in case there is a directory at the path for
237 # some bizarre reason:
238 rmtree(self.pri_path, ignore_errors=True)
239 self.pri_dao = self.get_pri_dao()
240 os.chmod(self.pri_path, PERM_PRIVATE)
241 self.pub_dao = CylcWorkflowDAO(self.pub_path, is_public=True)
242 self.copy_pri_to_pub()
243
244 def on_workflow_shutdown(self):
245 """Close data access objects."""
246 if self.pri_dao:
247 self.pri_dao.close()
248 self.pri_dao = None
249 if self.pub_dao:
250 self.pub_dao.close()
251 self.pub_dao = None
252
253 def process_queued_ops(self) -> None:
254 """Handle queued db operations for each task proxy."""
255 if self.pri_dao is None or self.pub_dao is None:
256 return
257 # Record workflow parameters and tasks in pool
258 # Record any broadcast settings to be dumped out
259 if any(self.db_deletes_map.values()):
260 for table_name, db_deletes in sorted(self.db_deletes_map.items()):
261 while db_deletes:
262 where_args = db_deletes.pop(0)
263 self.pri_dao.add_delete_item(table_name, where_args)
264 self.pub_dao.add_delete_item(table_name, where_args)
265 if any(self.db_inserts_map.values()):
266 for table_name, db_inserts in sorted(self.db_inserts_map.items()):
267 while db_inserts:
268 db_insert = db_inserts.pop(0)
269 self.pri_dao.add_insert_item(table_name, db_insert)
270 self.pub_dao.add_insert_item(table_name, db_insert)
271 if any(self.db_updates_map.values()):
272 for table_name, db_updates in sorted(self.db_updates_map.items()):
273 while db_updates:
274 db_update = db_updates.pop(0)
275 self.pri_dao.add_update_item(table_name, db_update)
276 self.pub_dao.add_update_item(table_name, db_update)
277
278 # Previously, we used a separate thread for database writes. This has
279 # now been removed. For the private database, there is no real
280 # advantage in using a separate thread as it needs to be always in sync
281 # with what is current. For the public database, which does not need to
282 # be fully in sync, there is some advantage of using a separate
283 # thread/process, if writing to it becomes a bottleneck. At the moment,
284 # there is no evidence that this is a bottleneck, so it is better to
285 # keep the logic simple.
286 self.pri_dao.execute_queued_items()
287 self.pub_dao.execute_queued_items()
288
289 def put_broadcast(self, modified_settings, is_cancel=False):
290 """Put or clear broadcasts in runtime database."""
291 now = get_current_time_string(display_sub_seconds=True)
292 for broadcast_change in (
293 get_broadcast_change_iter(modified_settings, is_cancel)):
294 broadcast_change["time"] = now
295 self.db_inserts_map[self.TABLE_BROADCAST_EVENTS].append(
296 broadcast_change)
297 if is_cancel:
298 self.db_deletes_map[self.TABLE_BROADCAST_STATES].append({
299 "point": broadcast_change["point"],
300 "namespace": broadcast_change["namespace"],
301 "key": broadcast_change["key"]})
302 # Delete statements are currently executed before insert
303 # statements, so we should clear out any insert statements that
304 # are deleted here.
305 # (Not the most efficient logic here, but unless we have a
306 # large number of inserts, then this should not be a big
307 # concern.)
308 inserts = []
309 for insert in self.db_inserts_map[self.TABLE_BROADCAST_STATES]:
310 if any(insert[key] != broadcast_change[key]
311 for key in ["point", "namespace", "key"]):
312 inserts.append(insert)
313 self.db_inserts_map[self.TABLE_BROADCAST_STATES] = inserts
314 else:
315 self.db_inserts_map[self.TABLE_BROADCAST_STATES].append({
316 "point": broadcast_change["point"],
317 "namespace": broadcast_change["namespace"],
318 "key": broadcast_change["key"],
319 "value": broadcast_change["value"]})
320
321 def put_runtime_inheritance(self, config):
322 """Put task/family inheritance in runtime database."""
323 for namespace in config.cfg['runtime']:
324 value = config.runtime['linearized ancestors'][namespace]
325 self.db_inserts_map[self.TABLE_INHERITANCE].append({
326 "namespace": namespace,
327 "inheritance": json.dumps(value)})
328
329 def put_workflow_params(self, schd: 'Scheduler') -> None:
330 """Put various workflow parameters from schd in runtime database.
331
332 This method queues the relevant insert statements.
333
334 Arguments:
335 schd: scheduler object.
336 """
337 self.db_deletes_map[self.TABLE_WORKFLOW_PARAMS].append({})
338 self.db_inserts_map[self.TABLE_WORKFLOW_PARAMS].extend([
339 {"key": self.KEY_UUID_STR, "value": schd.uuid_str},
340 {"key": self.KEY_CYLC_VERSION, "value": CYLC_VERSION},
341 {"key": self.KEY_UTC_MODE, "value": get_utc_mode()},
342 {"key": self.KEY_RESTART_COUNT, "value": self.n_restart},
343 {"key": self.KEY_CYCLE_POINT_FORMAT,
344 "value": schd.config.cycle_point_dump_format},
345 {"key": self.KEY_PAUSED, "value": int(schd.is_paused)},
346 {"key": self.KEY_STOP_CLOCK_TIME, "value": schd.stop_clock_time},
347 {"key": self.KEY_STOP_TASK, "value": schd.stop_task},
348 ])
349
350 # Store raw initial cycle point in the DB.
351 self.put_workflow_params_1(
352 self.KEY_INITIAL_CYCLE_POINT, str(schd.config.initial_point)
353 )
354
355 for key in (
356 self.KEY_FINAL_CYCLE_POINT,
357 self.KEY_START_CYCLE_POINT,
358 self.KEY_STOP_CYCLE_POINT
359 ):
360 value = getattr(schd.options, key, None)
361 value = None if value == 'reload' else value
362 self.put_workflow_params_1(key, value)
363
364 self.put_workflow_params_1(
365 self.KEY_CYCLE_POINT_TIME_ZONE,
366 getattr(schd.options, self.KEY_CYCLE_POINT_TIME_ZONE, None),
367 )
368 self.put_workflow_params_1(
369 self.KEY_RUN_MODE,
370 schd.get_run_mode().value,
371 )
372
373 def put_workflow_params_1(
374 self, key: str, value: Union[AnyStr, float, None]
375 ) -> None:
376 """Queue insertion of 1 key=value pair to the workflow_params table."""
377 self.db_inserts_map[self.TABLE_WORKFLOW_PARAMS].append(
378 {"key": key, "value": value}
379 )
380
381 def put_workflow_paused(self, value: bool) -> None:
382 """Put workflow paused flag to workflow_params table."""
383 self.put_workflow_params_1(self.KEY_PAUSED, int(value))
384
385 def put_workflow_hold_cycle_point(
386 self, value: Optional['PointBase']
387 ) -> None:
388 """Put workflow hold cycle point to workflow_params table."""
389 self.put_workflow_params_1(
390 self.KEY_HOLD_CYCLE_POINT,
391 str(value) if value is not None else None
392 )
393
394 def put_workflow_stop_clock_time(self, value: Optional[str]) -> None:
395 """Put workflow stop clock time to workflow_params table."""
396 self.put_workflow_params_1(self.KEY_STOP_CLOCK_TIME, value)
397
398 def put_workflow_stop_cycle_point(self, value: Optional[str]) -> None:
399 """Put workflow stop cycle point to workflow_params table."""
400 self.put_workflow_params_1(self.KEY_STOP_CYCLE_POINT, value)
401
402 def put_workflow_stop_task(self, value: Optional[str]) -> None:
403 """Put workflow stop task to workflow_params table."""
404 self.put_workflow_params_1(self.KEY_STOP_TASK, value)
405
406 def put_workflow_template_vars(
407 self, template_vars: Dict[str, Any]
408 ) -> None:
409 """Put template_vars in runtime database.
410
411 This method queues the relevant insert statements.
412 """
413 self.db_inserts_map[self.TABLE_WORKFLOW_TEMPLATE_VARS].extend(
414 {"key": key, "value": repr(value)}
415 for key, value in template_vars.items()
416 )
417
418 def put_task_event_timers(self, task_events_mgr) -> None:
419 """Put statements to update the task_action_timers table."""
420 if task_events_mgr.event_timers_updated:
421 self.db_deletes_map[self.TABLE_TASK_ACTION_TIMERS].append({})
422 id_key: 'EventKey'
423 for id_key, timer in task_events_mgr._event_timers.items():
424 key1 = (id_key.handler, id_key.event)
425 self.db_inserts_map[self.TABLE_TASK_ACTION_TIMERS].append({
426 "name": id_key.tokens['task'],
427 "cycle": id_key.tokens['cycle'],
428 "ctx_key": json.dumps((key1, int(id_key.tokens['job']),)),
429 "ctx": self._namedtuple2json(timer.ctx),
430 "delays": json.dumps(timer.delays),
431 "num": timer.num,
432 "delay": timer.delay,
433 "timeout": timer.timeout
434 })
435 task_events_mgr.event_timers_updated = False
436
437 def put_xtriggers(self, sat_xtrig):
438 """Put statements to update xtriggers table."""
439 for sig, res in sat_xtrig.items():
440 if not sig.startswith('wall_clock('):
441 self.db_inserts_map[self.TABLE_XTRIGGERS].append({
442 "signature": sig,
443 "results": json.dumps(res)})
444
445 def put_update_task_state(self, itask: 'TaskProxy') -> None:
446 """Update task_states table for current state of itask.
447
448 NOTE the task_states table is normally updated along with the task pool
449 table. This method is only needed as a final update for finished tasks,
450 when they get removed from the task_pool.
451 """
452 set_args = {
453 "time_updated": itask.state.time_updated,
454 "status": itask.state.status,
455 "flow_wait": itask.flow_wait,
456 "is_manual_submit": itask.is_manual_submit,
457 }
458 if not itask.transient:
459 set_args['submit_num'] = itask.submit_num
460 # Note tasks_states table rows are for latest submit_num only
461 # (not one row per submit).
462 where_args = {
463 "cycle": str(itask.point),
464 "name": itask.tdef.name,
465 "flow_nums": serialise_set(itask.flow_nums),
466 }
467 self.db_updates_map[self.TABLE_TASK_STATES].append(
468 (set_args, where_args)
469 )
470
471 def put_update_task_flow_wait(self, itask):
472 """Update flow_wait status of a task, in the task_states table.
473
474 NOTE the task_states table is normally updated along with the task pool
475 table. This method is only needed as a final update for a non-pool task
476 that just spawned its children after a flow wait.
477 """
478 set_args = {
479 "time_updated": itask.state.time_updated,
480 "flow_wait": itask.flow_wait,
481 }
482 where_args = {
483 "cycle": str(itask.point),
484 "name": itask.tdef.name,
485 "flow_nums": serialise_set(itask.flow_nums),
486 }
487 self.db_updates_map[self.TABLE_TASK_STATES].append(
488 (set_args, where_args))
489
490 def put_task_pool(self, pool: 'TaskPool') -> None:
491 """Delete task pool table content and recreate from current task pool.
492
493 Also recreate:
494 - prerequisites table
495 - timeout timers table
496 - action timers table
497
498 And update:
499 - task states table
500 """
501 self.db_deletes_map[self.TABLE_TASK_POOL].append({})
502 # Comment this out to retain the trigger-time prereq status of past
503 # tasks (but then the prerequisite table will grow indefinitely):
504 self.db_deletes_map[self.TABLE_TASK_PREREQUISITES].append({})
505 # This should already be done by self.put_task_event_timers above:
506 # self.db_deletes_map[self.TABLE_TASK_ACTION_TIMERS].append({})
507 self.db_deletes_map[self.TABLE_TASK_TIMEOUT_TIMERS].append({})
508 for itask in pool.get_tasks():
509 for prereq in itask.state.prerequisites:
510 for (p_cycle, p_name, p_output), satisfied_state in (
511 prereq.items()
512 ):
513 self.put_insert_task_prerequisites(itask, {
514 "prereq_name": p_name,
515 "prereq_cycle": p_cycle,
516 "prereq_output": p_output,
517 "satisfied": satisfied_state
518 })
519 for x_label, x_satisfied in itask.state.xtriggers.items():
520 if x_satisfied:
521 self.put_insert_task_prerequisites(itask, {
522 "prereq_name": x_label,
523 "prereq_cycle": XTRIGGER_PREREQ_PREFIX,
524 "prereq_output": TASK_OUTPUT_SUCCEEDED,
525 "satisfied": True
526 })
527
528 self.db_inserts_map[self.TABLE_TASK_POOL].append({
529 "name": itask.tdef.name,
530 "cycle": str(itask.point),
531 "flow_nums": serialise_set(itask.flow_nums),
532 "status": itask.state.status,
533 "is_held": itask.state.is_held
534 })
535 if itask.timeout is not None:
536 self.db_inserts_map[self.TABLE_TASK_TIMEOUT_TIMERS].append({
537 "name": itask.tdef.name,
538 "cycle": str(itask.point),
539 "timeout": itask.timeout
540 })
541 if itask.poll_timer is not None:
542 self.db_inserts_map[self.TABLE_TASK_ACTION_TIMERS].append({
543 "name": itask.tdef.name,
544 "cycle": str(itask.point),
545 "ctx_key": json.dumps("poll_timer"),
546 "ctx": self._namedtuple2json(itask.poll_timer.ctx),
547 "delays": json.dumps(itask.poll_timer.delays),
548 "num": itask.poll_timer.num,
549 "delay": itask.poll_timer.delay,
550 "timeout": itask.poll_timer.timeout
551 })
552 for ctx_key_1, timer in itask.try_timers.items():
553 if timer is None:
554 continue
555 self.db_inserts_map[self.TABLE_TASK_ACTION_TIMERS].append({
556 "name": itask.tdef.name,
557 "cycle": str(itask.point),
558 "ctx_key": json.dumps(("try_timers", ctx_key_1)),
559 "ctx": self._namedtuple2json(timer.ctx),
560 "delays": json.dumps(timer.delays),
561 "num": timer.num,
562 "delay": timer.delay,
563 "timeout": timer.timeout
564 })
565 if itask.state.time_updated:
566 set_args = {
567 "time_updated": itask.state.time_updated,
568 "submit_num": itask.submit_num,
569 "try_num": itask.get_try_num(),
570 "status": itask.state.status,
571 "is_manual_submit": itask.is_manual_submit,
572 }
573 where_args = {
574 "cycle": str(itask.point),
575 "name": itask.tdef.name,
576 "flow_nums": serialise_set(itask.flow_nums)
577 }
578 self.db_updates_map[self.TABLE_TASK_STATES].append(
579 (set_args, where_args)
580 )
581 itask.state.time_updated = None
582
583 def put_tasks_to_hold(
584 self, tasks: Set[Tuple[str, 'PointBase']]
585 ) -> None:
586 """Replace the tasks in the tasks_to_hold table."""
587 # There isn't that much cost in calling this multiple times between
588 # processing of the db queue (when the db queue is eventually
589 # processed, the SQL commands only get run once). Still, replacing the
590 # whole table each time the queue is processed is a bit inefficient.
591 self.db_deletes_map[self.TABLE_TASKS_TO_HOLD] = [{}]
592 self.db_inserts_map[self.TABLE_TASKS_TO_HOLD] = [
593 {"name": name, "cycle": str(point)}
594 for name, point in tasks
595 ]
596
597 def put_insert_task_events(self, itask, args):
598 """Put INSERT statement for task_events table."""
599 self._put_insert_task_x(CylcWorkflowDAO.TABLE_TASK_EVENTS, itask, args)
600
601 def put_insert_task_late_flags(self, itask):
602 """If itask is late, put INSERT statement to task_late_flags table."""
603 if itask.is_late:
604 self._put_insert_task_x(
605 CylcWorkflowDAO.TABLE_TASK_LATE_FLAGS, itask, {"value": True})
606
607 def put_insert_task_jobs(self, itask, args):
608 """Put INSERT statement for task_jobs table."""
609 self._put_insert_task_x(CylcWorkflowDAO.TABLE_TASK_JOBS, itask, args)
610
611 def put_insert_task_states(self, itask: 'TaskProxy') -> None:
612 """Put INSERT statement for task_states table."""
613 now = get_current_time_string()
614 self._put_insert_task_x(
615 CylcWorkflowDAO.TABLE_TASK_STATES,
616 itask,
617 {
618 "time_created": now,
619 "time_updated": now,
620 "status": itask.state.status,
621 "flow_nums": serialise_set(itask.flow_nums),
622 "flow_wait": itask.flow_wait,
623 "is_manual_submit": itask.is_manual_submit,
624 },
625 )
626
627 def put_insert_task_prerequisites(self, itask, args):
628 """Put INSERT statement for task_prerequisites table."""
629 args.setdefault("flow_nums", serialise_set(itask.flow_nums))
630 self._put_insert_task_x(self.TABLE_TASK_PREREQUISITES, itask, args)
631
632 def put_insert_task_outputs(self, itask):
633 """Reset outputs for a task."""
634 self._put_insert_task_x(
635 CylcWorkflowDAO.TABLE_TASK_OUTPUTS,
636 itask,
637 {
638 "flow_nums": serialise_set(itask.flow_nums),
639 "outputs": json.dumps({})
640 }
641 )
642
643 def put_insert_abs_output(self, cycle, name, output):
644 """Put INSERT statement for a new abs output."""
645 args = {
646 "cycle": str(cycle),
647 "name": name,
648 "output": output
649 }
650 self.db_inserts_map.setdefault(CylcWorkflowDAO.TABLE_ABS_OUTPUTS, [])
651 self.db_inserts_map[CylcWorkflowDAO.TABLE_ABS_OUTPUTS].append(args)
652
653 def put_insert_workflow_flows(self, flow_num, flow_metadata):
654 """Put INSERT statement for a new flow."""
655 self.db_inserts_map.setdefault(
656 CylcWorkflowDAO.TABLE_WORKFLOW_FLOWS, []
657 )
658 self.db_inserts_map[CylcWorkflowDAO.TABLE_WORKFLOW_FLOWS].append(
659 {
660 "flow_num": flow_num,
661 "start_time": flow_metadata["start_time"],
662 "description": flow_metadata["description"],
663 }
664 )
665
666 def _put_insert_task_x(
667 self, table_name: str, itask: 'TaskProxy', args: 'DbArgDict'
668 ) -> None:
669 """Put INSERT statement for a task_* table."""
670 args.update({
671 "name": itask.tdef.name,
672 "cycle": str(itask.point),
673 })
674 args.setdefault("submit_num", itask.submit_num)
675 self.db_inserts_map.setdefault(table_name, []).append(args)
676
677 def put_update_task_jobs(self, itask: 'TaskProxy', set_args: dict) -> None:
678 """Put UPDATE statement for task_jobs table."""
679 set_args.setdefault('flow_nums', serialise_set(itask.flow_nums))
680 self._put_update_task_x(
681 CylcWorkflowDAO.TABLE_TASK_JOBS, itask, set_args
682 )
683
684 def put_update_task_outputs(self, itask: 'TaskProxy') -> None:
685 """Put UPDATE statement for task_outputs table."""
686 set_args = {
687 "outputs": json.dumps(
688 itask.state.outputs.get_completed_outputs()
689 )
690 }
691 where_args = {
692 "cycle": str(itask.point),
693 "name": itask.tdef.name,
694 "flow_nums": serialise_set(itask.flow_nums),
695 }
696 self.db_updates_map[self.TABLE_TASK_OUTPUTS].append(
697 (set_args, where_args)
698 )
699
700 def _put_update_task_x(
701 self, table_name: str, itask: 'TaskProxy', set_args: 'DbArgDict'
702 ) -> None:
703 """Put UPDATE statement for a task_* table."""
704 where_args: Dict[str, Any] = {
705 "cycle": str(itask.point),
706 "name": itask.tdef.name,
707 }
708 if "submit_num" not in set_args:
709 where_args["submit_num"] = itask.submit_num
710 if "flow_nums" not in set_args:
711 where_args["flow_nums"] = serialise_set(itask.flow_nums)
712 self.db_updates_map[table_name].append((set_args, where_args))
713
714 def remove_task_from_flows(
715 self, point: str, name: str, flow_nums: 'FlowNums'
716 ) -> 'FlowNums':
717 """Remove flow numbers for a task in the task_states and task_outputs
718 tables.
719
720 Args:
721 point: Cycle point of the task.
722 name: Name of the task.
723 flow_nums: Flow numbers to remove. If empty, remove all
724 flow numbers.
725
726 Returns the flow numbers that were removed, if any.
727
728 N.B. the task_prerequisites table is automatically updated separately
729 during the main loop.
730 """
731 removed_flow_nums: FlowNums = set()
732 for table in (
733 self.TABLE_TASK_STATES,
734 self.TABLE_TASK_OUTPUTS,
735 ):
736 fnums_select_stmt = rf'''
737 SELECT
738 flow_nums
739 FROM
740 {table}
741 WHERE
742 cycle = ?
743 AND name = ?
744 ''' # nosec B608 (table name is a code constant)
745 fnums_select_cursor = self.pri_dao.connect().execute(
746 fnums_select_stmt, (point, name)
747 )
748
749 if not flow_nums:
750 for db_fnums_str, *_ in fnums_select_cursor:
751 removed_flow_nums.update(deserialise_set(db_fnums_str))
752
753 stmt = rf'''
754 UPDATE OR REPLACE
755 {table}
756 SET
757 flow_nums = ?
758 WHERE
759 cycle = ?
760 AND name = ?
761 ''' # nosec B608 (table name is a code constant)
762 params: List[tuple] = [(serialise_set(), point, name)]
763 else:
764 # Mapping of existing flow nums to what should be left after
765 # removing the specified flow nums:
766 flow_nums_map: Dict[str, FlowNums] = {}
767 for db_fnums_str, *_ in fnums_select_cursor:
768 db_fnums: FlowNums = deserialise_set(db_fnums_str)
769 fnums_to_remove = db_fnums.intersection(flow_nums)
770 if fnums_to_remove:
771 flow_nums_map[db_fnums_str] = db_fnums.difference(
772 flow_nums
773 )
774 removed_flow_nums.update(fnums_to_remove)
775
776 stmt = rf'''
777 UPDATE OR REPLACE
778 {table}
779 SET
780 flow_nums = ?
781 WHERE
782 cycle = ?
783 AND name = ?
784 AND flow_nums = ?
785 ''' # nosec B608 (table name is a code constant)
786 params = [
787 (serialise_set(new), point, name, old)
788 for old, new in flow_nums_map.items()
789 ]
790
791 self.db_updates_map[table].append(
792 (stmt, params)
793 )
794
795 return removed_flow_nums
796
797 def recover_pub_from_pri(self):
798 """Recover public database from private database."""
799 if self.pub_dao.n_tries >= self.pub_dao.MAX_TRIES:
800 self.copy_pri_to_pub()
801 LOG.warning(
802 f"{self.pub_dao.db_file_name}: recovered from "
803 f"{self.pri_dao.db_file_name}")
804 self.pub_dao.n_tries = 0
805
806 def restart_check(self) -> None:
807 """Check & vacuum the runtime DB for a restart.
808
809 Increments the restart number in the DB. Sets self.n_restart.
810 """
811 if self.n_restart != 0:
812 # This will not raise unless the method is mistakenly called twice
813 raise RuntimeError("restart check must only happen once")
814 with self.get_pri_dao() as pri_dao:
815 pri_dao.vacuum()
816 self.n_restart = pri_dao.select_workflow_params_restart_count() + 1
817 self.put_workflow_params_1(self.KEY_RESTART_COUNT, self.n_restart)
818 self.process_queued_ops()
819
820 @classmethod
821 def _get_last_run_version(cls, pri_dao: CylcWorkflowDAO) -> 'Version':
822 """Return the version of Cylc this DB was last run with.
823
824 Args:
825 pri_dao: Open private database connection object.
826
827 """
828 try:
829 last_run_ver = pri_dao.connect().execute(
830 rf'''
831 SELECT
832 value
833 FROM
834 {cls.TABLE_WORKFLOW_PARAMS}
835 WHERE
836 key == ?
837 ''', # nosec B608 (table name is a code constant)
838 [cls.KEY_CYLC_VERSION]
839 ).fetchone()[0]
840 except (TypeError, OperationalError) as exc:
841 raise ServiceFileError(
842 f"{INCOMPAT_MSG}, or is corrupted."
843 ) from exc
844 return parse_version(last_run_ver)
845
846 @classmethod
847 def upgrade_pre_803(cls, pri_dao: CylcWorkflowDAO) -> None:
848 """Upgrade on restart from a pre-8.0.3 database.
849
850 Add "is_manual_submit" column to the task states table.
851 See GitHub cylc/cylc-flow#5023 and #5187.
852 """
853 conn = pri_dao.connect()
854 c_name = "is_manual_submit"
855 LOG.info(
856 f"DB upgrade (pre-8.0.3): "
857 f"add {c_name} column to {cls.TABLE_TASK_STATES}"
858 )
859 conn.execute(
860 rf"ALTER TABLE {cls.TABLE_TASK_STATES} "
861 rf"ADD COLUMN {c_name} INTEGER "
862 r"DEFAULT 0 NOT NULL"
863 )
864 conn.commit()
865
866 @staticmethod
867 def upgrade_pre_810(pri_dao: CylcWorkflowDAO) -> None:
868 """Upgrade on restart from a pre-8.1.0 database.
869
870 Add "flow_nums" column to the "task_jobs".
871 See GitHub cylc/cylc-flow#5252.
872
873 This is only possible if we have single item in the list
874 represented by flow_nums, else we have to raise an error
875 """
876 conn = pri_dao.connect()
877 c_name = "flow_nums"
878 LOG.info(
879 f"DB upgrade (pre-8.1.0): "
880 f"add {c_name} column to {CylcWorkflowDAO.TABLE_TASK_JOBS}"
881 )
882
883 # We can't upgrade if the flow_nums in task_states are not
884 # distinct.
885 flow_nums = deserialise_set(conn.execute(
886 'SELECT DISTINCT flow_nums FROM task_states;').fetchall()[0][0])
887 if len(flow_nums) != 1:
888 raise CylcError(
889 'Cannot upgrade-restart from 8.0.x to 8.1.0 IF'
890 ' multiple flows have been used.'
891 )
892
893 conn.execute(
894 rf"ALTER TABLE {CylcWorkflowDAO.TABLE_TASK_JOBS} "
895 rf"ADD COLUMN {c_name} "
896 r"DEFAULT '[1]'"
897 )
898 conn.commit()
899
900 @classmethod
901 def upgrade(cls, db_file: Union['Path', str]) -> None:
902 """Upgrade this database to this Cylc version.
903 """
904 with CylcWorkflowDAO(db_file, create_tables=True) as pri_dao:
905 last_run_ver = cls._get_last_run_version(pri_dao)
906 if last_run_ver < parse_version("8.0.3.dev"):
907 cls.upgrade_pre_803(pri_dao)
908 if last_run_ver < parse_version("8.1.0.dev"):
909 cls.upgrade_pre_810(pri_dao)
910
911 @classmethod
912 def check_db_compatibility(cls, db_file: Union['Path', str]) -> 'Version':
913 """Check this DB is compatible with this Cylc version.
914
915 Raises:
916 ServiceFileError:
917 If the existing workflow database is incompatible with the
918 current version of Cylc.
919
920 """
921 if not os.path.isfile(db_file):
922 raise FileNotFoundError(db_file)
923
924 with CylcWorkflowDAO(db_file) as dao:
925 last_run_ver = cls._get_last_run_version(dao)
926 # WARNING: Do no upgrade the DB here
927
928 restart_incompat_ver = parse_version(
929 CylcWorkflowDAO.RESTART_INCOMPAT_VERSION
930 )
931 if last_run_ver <= restart_incompat_ver:
932 raise ServiceFileError(
933 f"{INCOMPAT_MSG} (workflow last run with Cylc {last_run_ver})."
934 )
935 return last_run_ver