| 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 |
"""Provide data access object for the workflow runtime database.""" |
| 17 |
|
| 18 |
from collections import defaultdict |
| 19 |
from contextlib import suppress |
| 20 |
from dataclasses import dataclass |
| 21 |
from os.path import expandvars |
| 22 |
from pprint import pformat |
| 23 |
import sqlite3 |
| 24 |
import traceback |
| 25 |
from typing import ( |
| 26 |
TYPE_CHECKING, |
| 27 |
Any, |
| 28 |
DefaultDict, |
| 29 |
Dict, |
| 30 |
Iterable, |
| 31 |
List, |
| 32 |
Optional, |
| 33 |
Set, |
| 34 |
Tuple, |
| 35 |
Union, |
| 36 |
cast, |
| 37 |
) |
| 38 |
|
| 39 |
from cylc.flow import LOG |
| 40 |
from cylc.flow.exceptions import PlatformLookupError |
| 41 |
import cylc.flow.flags |
| 42 |
from cylc.flow.flow_mgr import stringify_flow_nums |
| 43 |
from cylc.flow.util import ( |
| 44 |
deserialise_set, |
| 45 |
serialise_set, |
| 46 |
) |
| 47 |
|
| 48 |
|
| 49 |
if TYPE_CHECKING: |
| 50 |
from pathlib import Path |
| 51 |
|
| 52 |
from cylc.flow.flow_mgr import FlowNums |
| 53 |
|
| 54 |
|
| 55 |
DbArgDict = Dict[str, Any] |
| 56 |
DbUpdateTuple = Union[ |
| 57 |
Tuple[DbArgDict, DbArgDict], |
| 58 |
Tuple[str, list] |
| 59 |
] |
| 60 |
|
| 61 |
|
| 62 |
@dataclass |
| 63 |
class CylcWorkflowDAOTableColumn: |
| 64 |
"""Represent a column in a table.""" |
| 65 |
|
| 66 |
name: str |
| 67 |
datatype: str |
| 68 |
is_primary_key: bool |
| 69 |
|
| 70 |
|
| 71 |
class CylcWorkflowDAOTable: |
| 72 |
"""Represent a table in the workflow runtime database.""" |
| 73 |
|
| 74 |
FMT_CREATE = "CREATE TABLE %(name)s(%(columns_str)s%(primary_keys_str)s)" |
| 75 |
FMT_DELETE = "DELETE FROM %(name)s%(where_str)s" |
| 76 |
FMT_INSERT = "INSERT OR REPLACE INTO %(name)s VALUES(%(values_str)s)" |
| 77 |
FMT_UPDATE = "UPDATE %(name)s SET %(set_str)s%(where_str)s" |
| 78 |
|
| 79 |
__slots__ = ('name', 'columns', 'delete_queues', 'insert_queue', |
| 80 |
'update_queues') |
| 81 |
|
| 82 |
def __init__(self, name, column_items): |
| 83 |
self.name = name |
| 84 |
self.columns: List[CylcWorkflowDAOTableColumn] = [] |
| 85 |
for column_item in column_items: |
| 86 |
name = column_item[0] |
| 87 |
attrs = {} |
| 88 |
if len(column_item) > 1: |
| 89 |
attrs = column_item[1] |
| 90 |
self.columns.append(CylcWorkflowDAOTableColumn( |
| 91 |
name, |
| 92 |
attrs.get("datatype", "TEXT"), |
| 93 |
attrs.get("is_primary_key", False))) |
| 94 |
self.delete_queues = {} |
| 95 |
self.insert_queue = [] |
| 96 |
self.update_queues: DefaultDict[str, list] = defaultdict(list) |
| 97 |
|
| 98 |
def get_create_stmt(self): |
| 99 |
"""Return an SQL statement to create this table.""" |
| 100 |
column_str_list = [] |
| 101 |
primary_keys = [] |
| 102 |
for column in self.columns: |
| 103 |
column_str_list.append(column.name + " " + column.datatype) |
| 104 |
if column.is_primary_key: |
| 105 |
primary_keys.append(column.name) |
| 106 |
primary_keys_str = "" |
| 107 |
if primary_keys: |
| 108 |
primary_keys_str = ", PRIMARY KEY(" + ", ".join(primary_keys) + ")" |
| 109 |
return self.FMT_CREATE % { |
| 110 |
"name": self.name, |
| 111 |
"columns_str": ", ".join(column_str_list), |
| 112 |
"primary_keys_str": primary_keys_str} |
| 113 |
|
| 114 |
def get_insert_stmt(self): |
| 115 |
"""Return an SQL statement to insert a row to this table.""" |
| 116 |
return self.FMT_INSERT % { |
| 117 |
"name": self.name, |
| 118 |
"values_str": ", ".join("?" * len(self.columns))} |
| 119 |
|
| 120 |
def add_delete_item(self, where_args): |
| 121 |
"""Queue a DELETE item. |
| 122 |
|
| 123 |
where_args should be a dict, delete will only apply to rows matching |
| 124 |
all these items. |
| 125 |
|
| 126 |
""" |
| 127 |
stmt_args = [] |
| 128 |
where_str = "" |
| 129 |
if where_args: |
| 130 |
where_strs = [] |
| 131 |
for column in self.columns: |
| 132 |
if column.name in where_args: |
| 133 |
where_strs.append(column.name + "==?") |
| 134 |
stmt_args.append(where_args[column.name]) |
| 135 |
if where_strs: |
| 136 |
where_str = " WHERE " + " AND ".join(where_strs) |
| 137 |
stmt = self.FMT_DELETE % {"name": self.name, "where_str": where_str} |
| 138 |
if stmt not in self.delete_queues: |
| 139 |
self.delete_queues[stmt] = [] |
| 140 |
self.delete_queues[stmt].append(stmt_args) |
| 141 |
|
| 142 |
def add_insert_item(self, args): |
| 143 |
"""Queue an INSERT args. |
| 144 |
|
| 145 |
If args is a list, its length will be adjusted to be the same as the |
| 146 |
number of columns. If args is a dict, will return a list with the same |
| 147 |
length as the number of columns, the elements of which are determined |
| 148 |
by matching the column names with the keys in the dict. |
| 149 |
|
| 150 |
Empty elements are padded with None. |
| 151 |
|
| 152 |
""" |
| 153 |
if isinstance(args, list): |
| 154 |
if len(args) == len(self.columns): |
| 155 |
stmt_args = list(args) |
| 156 |
elif len(args) < len(self.columns): |
| 157 |
stmt_args = args + [None] * (len(self.columns) - len(args)) |
| 158 |
else: # len(args) > len(self.columns) |
| 159 |
stmt_args = args[0:len(self.columns)] |
| 160 |
else: |
| 161 |
stmt_args = [ |
| 162 |
args.get(column.name, None) for column in self.columns] |
| 163 |
self.insert_queue.append(stmt_args) |
| 164 |
|
| 165 |
def add_update_item(self, item: DbUpdateTuple) -> None: |
| 166 |
"""Queue an UPDATE item. |
| 167 |
|
| 168 |
If stmt is not a string, it should be a tuple (set_args, where_args) - |
| 169 |
set_args should be a dict, with column keys and values to be set. |
| 170 |
where_args should be a dict, update will only apply to rows matching |
| 171 |
all these items. |
| 172 |
|
| 173 |
""" |
| 174 |
if isinstance(item[0], str): |
| 175 |
stmt = item[0] |
| 176 |
params = cast('list', item[1]) |
| 177 |
self.update_queues[stmt].extend(params) |
| 178 |
return |
| 179 |
|
| 180 |
set_args = item[0] |
| 181 |
where_args = cast('DbArgDict', item[1]) |
| 182 |
set_strs = [] |
| 183 |
stmt_args = [] |
| 184 |
for column in self.columns: |
| 185 |
if column.name in set_args: |
| 186 |
set_strs.append(column.name + "=?") |
| 187 |
stmt_args.append(set_args[column.name]) |
| 188 |
set_str = ", ".join(set_strs) |
| 189 |
where_str = "" |
| 190 |
if where_args: |
| 191 |
where_strs = [] |
| 192 |
for column in self.columns: |
| 193 |
if column.name in where_args: |
| 194 |
where_strs.append(column.name + "==?") |
| 195 |
stmt_args.append(where_args[column.name]) |
| 196 |
if where_strs: |
| 197 |
where_str = " WHERE " + " AND ".join(where_strs) |
| 198 |
stmt = self.FMT_UPDATE % { |
| 199 |
"name": self.name, |
| 200 |
"set_str": set_str, |
| 201 |
"where_str": where_str |
| 202 |
} |
| 203 |
self.update_queues[stmt].append(stmt_args) |
| 204 |
|
| 205 |
|
| 206 |
class CylcWorkflowDAO: |
| 207 |
"""Data access object for the workflow runtime database.""" |
| 208 |
|
| 209 |
CONN_TIMEOUT = 0.2 |
| 210 |
DB_FILE_BASE_NAME = "db" |
| 211 |
MAX_TRIES = 100 |
| 212 |
RESTART_INCOMPAT_VERSION = "8.0rc2" # Can't restart if <= this version |
| 213 |
TABLE_BROADCAST_EVENTS = "broadcast_events" |
| 214 |
TABLE_BROADCAST_STATES = "broadcast_states" |
| 215 |
TABLE_INHERITANCE = "inheritance" |
| 216 |
TABLE_WORKFLOW_PARAMS = "workflow_params" |
| 217 |
# BACK COMPAT: suite_params |
| 218 |
# This Cylc 7 DB table is needed to allow workflow-state |
| 219 |
# xtriggers (and the `cylc workflow-state` command) to |
| 220 |
# work with Cylc 7 workflows. |
| 221 |
# url: https://github.com/cylc/cylc-flow/issues/5236 |
| 222 |
# remove at: 8.x |
| 223 |
TABLE_SUITE_PARAMS = "suite_params" |
| 224 |
TABLE_WORKFLOW_FLOWS = "workflow_flows" |
| 225 |
TABLE_WORKFLOW_TEMPLATE_VARS = "workflow_template_vars" |
| 226 |
TABLE_TASK_JOBS = "task_jobs" |
| 227 |
TABLE_TASK_EVENTS = "task_events" |
| 228 |
TABLE_TASK_ACTION_TIMERS = "task_action_timers" |
| 229 |
TABLE_TASK_LATE_FLAGS = "task_late_flags" |
| 230 |
TABLE_TASK_OUTPUTS = "task_outputs" |
| 231 |
TABLE_TASK_POOL = "task_pool" |
| 232 |
TABLE_TASK_PREREQUISITES = "task_prerequisites" |
| 233 |
TABLE_TASK_STATES = "task_states" |
| 234 |
TABLE_TASK_TIMEOUT_TIMERS = "task_timeout_timers" |
| 235 |
TABLE_TASKS_TO_HOLD = "tasks_to_hold" |
| 236 |
TABLE_XTRIGGERS = "xtriggers" |
| 237 |
TABLE_ABS_OUTPUTS = "absolute_outputs" |
| 238 |
|
| 239 |
TABLES_ATTRS = { |
| 240 |
TABLE_BROADCAST_EVENTS: [ |
| 241 |
["time"], |
| 242 |
["change"], |
| 243 |
["point"], |
| 244 |
["namespace"], |
| 245 |
["key"], |
| 246 |
["value"], |
| 247 |
], |
| 248 |
TABLE_BROADCAST_STATES: [ |
| 249 |
["point", {"is_primary_key": True}], |
| 250 |
["namespace", {"is_primary_key": True}], |
| 251 |
["key", {"is_primary_key": True}], |
| 252 |
["value"], |
| 253 |
], |
| 254 |
TABLE_INHERITANCE: [ |
| 255 |
["namespace", {"is_primary_key": True}], |
| 256 |
["inheritance"], |
| 257 |
], |
| 258 |
TABLE_WORKFLOW_PARAMS: [ |
| 259 |
["key", {"is_primary_key": True}], |
| 260 |
["value"], |
| 261 |
], |
| 262 |
TABLE_WORKFLOW_FLOWS: [ |
| 263 |
["flow_num", {"datatype": "INTEGER", "is_primary_key": True}], |
| 264 |
["start_time"], |
| 265 |
["description"], |
| 266 |
], |
| 267 |
TABLE_WORKFLOW_TEMPLATE_VARS: [ |
| 268 |
["key", {"is_primary_key": True}], |
| 269 |
["value"], |
| 270 |
], |
| 271 |
TABLE_TASK_ACTION_TIMERS: [ |
| 272 |
["cycle", {"is_primary_key": True}], |
| 273 |
["name", {"is_primary_key": True}], |
| 274 |
["ctx_key", {"is_primary_key": True}], |
| 275 |
["ctx"], |
| 276 |
["delays"], |
| 277 |
["num", {"datatype": "INTEGER"}], |
| 278 |
["delay"], |
| 279 |
["timeout"], |
| 280 |
], |
| 281 |
# NOTE: this table is used by `cylc clean`, don't rename me! |
| 282 |
TABLE_TASK_JOBS: [ |
| 283 |
["cycle", {"is_primary_key": True}], |
| 284 |
["name", {"is_primary_key": True}], |
| 285 |
["submit_num", {"datatype": "INTEGER", "is_primary_key": True}], |
| 286 |
["flow_nums"], |
| 287 |
["is_manual_submit", {"datatype": "INTEGER"}], |
| 288 |
["try_num", {"datatype": "INTEGER"}], |
| 289 |
# This is used to store simulation task start time across restarts. |
| 290 |
["time_submit"], |
| 291 |
["time_submit_exit"], |
| 292 |
["submit_status", {"datatype": "INTEGER"}], |
| 293 |
["time_run"], |
| 294 |
["time_run_exit"], |
| 295 |
["run_signal"], |
| 296 |
["run_status", {"datatype": "INTEGER"}], |
| 297 |
# NOTE: this field is used by `cylc clean` don't rename me! |
| 298 |
["platform_name"], |
| 299 |
["job_runner_name"], |
| 300 |
["job_id"], |
| 301 |
], |
| 302 |
TABLE_TASK_EVENTS: [ |
| 303 |
["name"], |
| 304 |
["cycle"], |
| 305 |
["time"], |
| 306 |
["submit_num", {"datatype": "INTEGER"}], |
| 307 |
["event"], |
| 308 |
["message"], |
| 309 |
], |
| 310 |
TABLE_TASK_LATE_FLAGS: [ |
| 311 |
["cycle", {"is_primary_key": True}], |
| 312 |
["name", {"is_primary_key": True}], |
| 313 |
["value", {"datatype": "INTEGER"}], |
| 314 |
], |
| 315 |
TABLE_TASK_OUTPUTS: [ |
| 316 |
["cycle", {"is_primary_key": True}], |
| 317 |
["name", {"is_primary_key": True}], |
| 318 |
["flow_nums", {"is_primary_key": True}], |
| 319 |
["outputs"], |
| 320 |
], |
| 321 |
TABLE_TASK_POOL: [ |
| 322 |
["cycle", {"is_primary_key": True}], |
| 323 |
["name", {"is_primary_key": True}], |
| 324 |
["flow_nums", {"is_primary_key": True}], |
| 325 |
["status"], |
| 326 |
["is_held", {"datatype": "INTEGER"}], |
| 327 |
], |
| 328 |
TABLE_TASK_PREREQUISITES: [ |
| 329 |
["cycle", {"is_primary_key": True}], |
| 330 |
["name", {"is_primary_key": True}], |
| 331 |
["flow_nums", {"is_primary_key": True}], |
| 332 |
["prereq_name", {"is_primary_key": True}], |
| 333 |
["prereq_cycle", {"is_primary_key": True}], |
| 334 |
["prereq_output", {"is_primary_key": True}], |
| 335 |
["satisfied"], |
| 336 |
], |
| 337 |
# The xtriggers table holds the function signature and result of |
| 338 |
# already-satisfied (the scheduler no longer needs to call them). |
| 339 |
TABLE_XTRIGGERS: [ |
| 340 |
["signature", {"is_primary_key": True}], |
| 341 |
["results"], |
| 342 |
], |
| 343 |
TABLE_TASK_STATES: [ |
| 344 |
["name", {"is_primary_key": True}], |
| 345 |
["cycle", {"is_primary_key": True}], |
| 346 |
["flow_nums", {"is_primary_key": True}], |
| 347 |
["time_created"], |
| 348 |
["time_updated"], |
| 349 |
["submit_num", {"datatype": "INTEGER"}], |
| 350 |
["status"], |
| 351 |
["flow_wait", {"datatype": "INTEGER"}], |
| 352 |
["is_manual_submit", {"datatype": "INTEGER"}], |
| 353 |
], |
| 354 |
TABLE_TASK_TIMEOUT_TIMERS: [ |
| 355 |
["cycle", {"is_primary_key": True}], |
| 356 |
["name", {"is_primary_key": True}], |
| 357 |
["timeout", {"datatype": "REAL"}], |
| 358 |
], |
| 359 |
TABLE_ABS_OUTPUTS: [ |
| 360 |
["cycle"], |
| 361 |
["name"], |
| 362 |
["output"], |
| 363 |
], |
| 364 |
TABLE_TASKS_TO_HOLD: [ |
| 365 |
["name"], |
| 366 |
["cycle"], |
| 367 |
], |
| 368 |
} |
| 369 |
|
| 370 |
def __init__( |
| 371 |
self, |
| 372 |
db_file_name: Union['Path', str], |
| 373 |
is_public: bool = False, |
| 374 |
create_tables: bool = False |
| 375 |
): |
| 376 |
"""Initialise database access object. |
| 377 |
|
| 378 |
An instance of this class can also be opened as a context manager |
| 379 |
which will automatically close the DB connection. |
| 380 |
|
| 381 |
Args: |
| 382 |
db_file_name: Path to the database file. |
| 383 |
is_public: If True, allow retries. |
| 384 |
create_tables: If True, create the tables if they |
| 385 |
don't already exist. |
| 386 |
|
| 387 |
""" |
| 388 |
self.db_file_name = expandvars(db_file_name) |
| 389 |
self.is_public = is_public |
| 390 |
self.conn: Optional[sqlite3.Connection] = None |
| 391 |
self.n_tries = 0 |
| 392 |
|
| 393 |
self.tables = { |
| 394 |
name: CylcWorkflowDAOTable(name, attrs) |
| 395 |
for name, attrs in sorted(self.TABLES_ATTRS.items()) |
| 396 |
} |
| 397 |
|
| 398 |
if create_tables: |
| 399 |
self.create_tables() |
| 400 |
|
| 401 |
def __enter__(self): |
| 402 |
return self |
| 403 |
|
| 404 |
def __exit__(self, exc_type, exc_value, traceback): |
| 405 |
"""Close DB connection when leaving context manager.""" |
| 406 |
self.close() |
| 407 |
|
| 408 |
def add_delete_item(self, table_name, where_args=None): |
| 409 |
"""Queue a DELETE item for a given table. |
| 410 |
|
| 411 |
where_args should be a dict, update will only apply to rows matching |
| 412 |
all these items. |
| 413 |
|
| 414 |
""" |
| 415 |
self.tables[table_name].add_delete_item(where_args) |
| 416 |
|
| 417 |
def add_insert_item(self, table_name, args): |
| 418 |
"""Queue an INSERT args for a given table. |
| 419 |
|
| 420 |
If args is a list, its length will be adjusted to be the same as the |
| 421 |
number of columns. If args is a dict, will return a list with the same |
| 422 |
length as the number of columns, the elements of which are determined |
| 423 |
by matching the column names with the keys in the dict. |
| 424 |
|
| 425 |
Empty elements are padded with None. |
| 426 |
|
| 427 |
""" |
| 428 |
self.tables[table_name].add_insert_item(args) |
| 429 |
|
| 430 |
def add_update_item( |
| 431 |
self, table_name: str, item: DbUpdateTuple |
| 432 |
) -> None: |
| 433 |
"""Queue an UPDATE item for a given table. |
| 434 |
|
| 435 |
If stmt is not a string, it should be a tuple (set_args, where_args) - |
| 436 |
set_args should be a dict, with column keys and values to be set. |
| 437 |
where_args should be a dict, update will only apply to rows matching |
| 438 |
all these items. |
| 439 |
|
| 440 |
""" |
| 441 |
self.tables[table_name].add_update_item(item) |
| 442 |
|
| 443 |
def close(self) -> None: |
| 444 |
"""Explicitly close the connection.""" |
| 445 |
if self.conn is not None: |
| 446 |
try: |
| 447 |
self.conn.close() |
| 448 |
except sqlite3.Error as exc: |
| 449 |
LOG.debug(f"Error closing connection to DB: {exc}") |
| 450 |
self.conn = None |
| 451 |
|
| 452 |
def connect(self) -> sqlite3.Connection: |
| 453 |
"""Connect to the database.""" |
| 454 |
if self.conn is None: |
| 455 |
self.conn = sqlite3.connect(self.db_file_name, self.CONN_TIMEOUT) |
| 456 |
return self.conn |
| 457 |
|
| 458 |
def create_tables(self): |
| 459 |
"""Create tables.""" |
| 460 |
names = [] |
| 461 |
for row in self.connect().execute( |
| 462 |
"SELECT name FROM sqlite_master WHERE type==? ORDER BY name", |
| 463 |
["table"]): |
| 464 |
names.append(row[0]) |
| 465 |
cur = None |
| 466 |
for name, table in self.tables.items(): |
| 467 |
if name not in names: |
| 468 |
cur = self.conn.execute(table.get_create_stmt()) |
| 469 |
if cur is not None: |
| 470 |
self.conn.commit() |
| 471 |
|
| 472 |
def execute_queued_items(self): |
| 473 |
"""Execute queued items for each table.""" |
| 474 |
# determine the sql statements to execute |
| 475 |
sql_queue = [] # (sql_statement, values) |
| 476 |
for table in self.tables.values(): |
| 477 |
# DELETE statements may have varying number of WHERE args so we |
| 478 |
# can only executemany for each identical template statement. |
| 479 |
for stmt, stmt_args_list in table.delete_queues.items(): |
| 480 |
sql_queue.append((stmt, stmt_args_list)) |
| 481 |
|
| 482 |
# INSERT statements are uniform for each table, so all INSERT |
| 483 |
# statements can be executed using a single "executemany" call. |
| 484 |
if table.insert_queue: |
| 485 |
sql_queue.append(( |
| 486 |
table.get_insert_stmt(), |
| 487 |
table.insert_queue, |
| 488 |
)) |
| 489 |
|
| 490 |
# UPDATE statements can have varying number of SET and WHERE |
| 491 |
# args so we can only executemany for each identical template |
| 492 |
# statement. |
| 493 |
for stmt, stmt_args_list in table.update_queues.items(): |
| 494 |
sql_queue.append((stmt, stmt_args_list)) |
| 495 |
|
| 496 |
# execute the statements and commit the transaction |
| 497 |
try: |
| 498 |
for stmt, stmt_args in sql_queue: |
| 499 |
self._execute_stmt(stmt, stmt_args) |
| 500 |
# Connection should only be opened if we have executed something. |
| 501 |
if self.conn is None: |
| 502 |
return |
| 503 |
self.conn.commit() |
| 504 |
|
| 505 |
# something went wrong |
| 506 |
# (includes DB file not found, transaction processing issue, db locked) |
| 507 |
except sqlite3.Error as e: |
| 508 |
# Detailed error codes are only available for python >= 3.11 |
| 509 |
if hasattr(e, "sqlite_errorcode"): |
| 510 |
error_code = str(e.sqlite_errorcode) |
| 511 |
else: |
| 512 |
error_code = "Not available" |
| 513 |
|
| 514 |
if hasattr(e, "sqlite_errorname"): |
| 515 |
error_name = e.sqlite_errorname |
| 516 |
else: |
| 517 |
error_name = "Not available" |
| 518 |
|
| 519 |
if not self.is_public: |
| 520 |
# incase this isn't a filesystem issue, log the statements |
| 521 |
# which make up the transaction to assist debug |
| 522 |
LOG.error( |
| 523 |
'An error occurred when writing to the database %(file)s,' |
| 524 |
' this is probably a filesystem issue.' |
| 525 |
' The error was: %(error)s' |
| 526 |
' SQLite error code: %(error_code)s' |
| 527 |
' SQLite error name: %(error_name)s' |
| 528 |
' The attempted transaction was:\n %(transaction)s' % { |
| 529 |
"file": self.db_file_name, |
| 530 |
"error": str(e), |
| 531 |
"error_code": error_code, |
| 532 |
"error_name": error_name, |
| 533 |
"transaction": pformat(sql_queue) |
| 534 |
} |
| 535 |
) |
| 536 |
raise |
| 537 |
self.n_tries += 1 |
| 538 |
LOG.info( |
| 539 |
"%(file)s: write attempt (%(attempt)d)" |
| 540 |
" did not complete: %(error)s\n" |
| 541 |
" SQLite error code: %(error_code)s\n" |
| 542 |
" SQLite error name: %(error_name)s" % { |
| 543 |
"file": self.db_file_name, |
| 544 |
"attempt": self.n_tries, |
| 545 |
"error": str(e), |
| 546 |
"error_code": error_code, |
| 547 |
"error_name": error_name |
| 548 |
} |
| 549 |
) |
| 550 |
if self.conn is not None: |
| 551 |
with suppress(sqlite3.Error): |
| 552 |
self.conn.rollback() |
| 553 |
return |
| 554 |
|
| 555 |
else: |
| 556 |
# Clear the queues |
| 557 |
for table in self.tables.values(): |
| 558 |
table.delete_queues.clear() |
| 559 |
table.insert_queue.clear() |
| 560 |
table.update_queues.clear() |
| 561 |
# Report public database retry recovery if necessary |
| 562 |
if self.n_tries: |
| 563 |
LOG.info( |
| 564 |
"%(file)s: recovered after (%(attempt)d) attempt(s)\n" % { |
| 565 |
"file": self.db_file_name, "attempt": self.n_tries}) |
| 566 |
self.n_tries = 0 |
| 567 |
|
| 568 |
finally: |
| 569 |
# Note: This is not strictly necessary. But if the workflow run |
| 570 |
# directory is removed, a forced reconnection to the private |
| 571 |
# database will ensure that the workflow dies. |
| 572 |
self.close() |
| 573 |
|
| 574 |
def _execute_stmt(self, stmt, stmt_args_list): |
| 575 |
"""Helper for "self.execute_queued_items". |
| 576 |
|
| 577 |
Execute a statement. If this is the public database, return True on |
| 578 |
success and False on failure. If this is the private database, return |
| 579 |
True on success, and raise on failure. |
| 580 |
""" |
| 581 |
# Filter out CYLC_TEMPLATE_VARS which breaks executemany because it's: |
| 582 |
# - a dict |
| 583 |
# - recursive (contains itself!) |
| 584 |
if stmt_args_list and stmt_args_list[0]: |
| 585 |
stmt_args_list = [ |
| 586 |
i for i in stmt_args_list if i[0] != 'CYLC_TEMPLATE_VARS' |
| 587 |
] |
| 588 |
|
| 589 |
try: |
| 590 |
self.connect() |
| 591 |
self.conn.executemany(stmt, stmt_args_list) |
| 592 |
except sqlite3.Error as e: |
| 593 |
if not self.is_public: |
| 594 |
raise |
| 595 |
if cylc.flow.flags.verbosity > 1: |
| 596 |
traceback.print_exc() |
| 597 |
err_log = ( |
| 598 |
"cannot execute database statement:\n" |
| 599 |
"file=%(file)s:\nstmt=%(stmt)s\nerror=%(error)s" |
| 600 |
) % {"file": self.db_file_name, "stmt": stmt, "error": str(e)} |
| 601 |
for i, stmt_args in enumerate(stmt_args_list): |
| 602 |
err_log += ("\nstmt_args[%(i)d]=%(stmt_args)s" % { |
| 603 |
"i": i, "stmt_args": stmt_args}) |
| 604 |
if self.is_public: |
| 605 |
LOG.info(err_log) |
| 606 |
else: |
| 607 |
LOG.warning(err_log) |
| 608 |
raise |
| 609 |
|
| 610 |
def pre_select_broadcast_states(self, order=None): |
| 611 |
"""Query statement and args formation for select_broadcast_states.""" |
| 612 |
form_stmt = r"SELECT point,namespace,key,value FROM %s" |
| 613 |
if order == "ASC": |
| 614 |
ordering = " ORDER BY point ASC, namespace ASC, key ASC" |
| 615 |
form_stmt = form_stmt + ordering |
| 616 |
return form_stmt % self.TABLE_BROADCAST_STATES |
| 617 |
|
| 618 |
def select_broadcast_states(self, callback, sort=None): |
| 619 |
"""Select from broadcast_states. |
| 620 |
|
| 621 |
Invoke callback(row_idx, row) on each row, where each row contains: |
| 622 |
[point, namespace, key, value] |
| 623 |
""" |
| 624 |
stmt = self.pre_select_broadcast_states(order=sort) |
| 625 |
for row_idx, row in enumerate(self.connect().execute(stmt)): |
| 626 |
callback(row_idx, list(row)) |
| 627 |
|
| 628 |
def select_workflow_params(self) -> Iterable[Tuple[str, Optional[str]]]: |
| 629 |
"""Select all from workflow_params. |
| 630 |
|
| 631 |
E.g. a row might be ('UTC mode', '1') |
| 632 |
""" |
| 633 |
stmt = rf''' |
| 634 |
SELECT |
| 635 |
key, value |
| 636 |
FROM |
| 637 |
{self.TABLE_WORKFLOW_PARAMS} |
| 638 |
''' # nosec B608 (table name is code constant) |
| 639 |
return self.connect().execute(stmt) |
| 640 |
|
| 641 |
def select_workflow_flows(self, flow_nums: Iterable[int]): |
| 642 |
"""Return flow data for selected flows.""" |
| 643 |
stmt = rf''' |
| 644 |
SELECT |
| 645 |
flow_num, start_time, description |
| 646 |
FROM |
| 647 |
{self.TABLE_WORKFLOW_FLOWS} |
| 648 |
WHERE |
| 649 |
flow_num in ({stringify_flow_nums(flow_nums)}) |
| 650 |
''' # nosec B608 (table name is code constant, flow_nums just ints) |
| 651 |
flows = {} |
| 652 |
for flow_num, start_time, descr in self.connect().execute(stmt): |
| 653 |
flows[flow_num] = { |
| 654 |
"start_time": start_time, |
| 655 |
"description": descr |
| 656 |
} |
| 657 |
return flows |
| 658 |
|
| 659 |
def select_workflow_flows_max_flow_num(self): |
| 660 |
"""Return max flow number in the workflow_flows table.""" |
| 661 |
stmt = rf''' |
| 662 |
SELECT |
| 663 |
MAX(flow_num) |
| 664 |
FROM |
| 665 |
{self.TABLE_WORKFLOW_FLOWS} |
| 666 |
''' # nosec B608 (table name is code constant) |
| 667 |
return self.connect().execute(stmt).fetchone()[0] |
| 668 |
|
| 669 |
def select_workflow_params_restart_count(self): |
| 670 |
"""Return number of restarts in workflow_params table.""" |
| 671 |
stmt = rf""" |
| 672 |
SELECT |
| 673 |
value |
| 674 |
FROM |
| 675 |
{self.TABLE_WORKFLOW_PARAMS} |
| 676 |
WHERE |
| 677 |
key == 'n_restart' |
| 678 |
""" # nosec B608 (table name is code constant) |
| 679 |
result = self.connect().execute(stmt).fetchone() |
| 680 |
return int(result[0]) if result else 0 |
| 681 |
|
| 682 |
def select_workflow_template_vars(self, callback): |
| 683 |
"""Select from workflow_template_vars. |
| 684 |
|
| 685 |
Invoke callback(row_idx, row) on each row, where each row contains: |
| 686 |
[key,value] |
| 687 |
""" |
| 688 |
for row_idx, row in enumerate(self.connect().execute( |
| 689 |
rf''' |
| 690 |
SELECT |
| 691 |
key, value |
| 692 |
FROM |
| 693 |
{self.TABLE_WORKFLOW_TEMPLATE_VARS} |
| 694 |
''' # nosec B608 (table name is code constant) |
| 695 |
)): |
| 696 |
callback(row_idx, list(row)) |
| 697 |
|
| 698 |
def select_task_action_timers(self, callback): |
| 699 |
"""Select from task_action_timers for restart. |
| 700 |
|
| 701 |
Invoke callback(row_idx, row) on each row. |
| 702 |
""" |
| 703 |
attrs = [] |
| 704 |
for item in self.TABLES_ATTRS[self.TABLE_TASK_ACTION_TIMERS]: |
| 705 |
attrs.append(item[0]) |
| 706 |
stmt = rf''' |
| 707 |
SELECT |
| 708 |
{",".join(attrs)} |
| 709 |
FROM |
| 710 |
{self.TABLE_TASK_ACTION_TIMERS} |
| 711 |
''' # nosec B608 |
| 712 |
# * table name is code constant |
| 713 |
# * attrs are code constants |
| 714 |
for row_idx, row in enumerate(self.connect().execute(stmt)): |
| 715 |
callback(row_idx, list(row)) |
| 716 |
|
| 717 |
def select_task_job( |
| 718 |
self, cycle: str, name: str, submit_num: str | int | None = None |
| 719 |
) -> dict[str, Any] | None: |
| 720 |
"""Select items from task_jobs by (cycle, name, submit_num). |
| 721 |
|
| 722 |
:return: a dict for mapping keys to the column values |
| 723 |
""" |
| 724 |
keys = [] |
| 725 |
for column in self.tables[self.TABLE_TASK_JOBS].columns[3:]: |
| 726 |
keys.append(column.name) |
| 727 |
if submit_num in [None, "NN"]: |
| 728 |
stmt = rf''' |
| 729 |
SELECT |
| 730 |
{",".join(keys)} |
| 731 |
FROM |
| 732 |
{self.TABLE_TASK_JOBS} |
| 733 |
WHERE |
| 734 |
cycle==? |
| 735 |
AND name==? |
| 736 |
ORDER BY |
| 737 |
submit_num DESC LIMIT 1 |
| 738 |
''' # nosec B608 |
| 739 |
# * table name is code constant |
| 740 |
# * keys are code constants |
| 741 |
stmt_args: list[Any] = [cycle, name] |
| 742 |
else: |
| 743 |
stmt = rf''' |
| 744 |
SELECT |
| 745 |
{",".join(keys)} |
| 746 |
FROM |
| 747 |
{self.TABLE_TASK_JOBS} |
| 748 |
WHERE |
| 749 |
cycle==? |
| 750 |
AND name==? |
| 751 |
AND submit_num==? |
| 752 |
''' # nosec B608 |
| 753 |
# * table name is code constant |
| 754 |
# * keys are code constants |
| 755 |
stmt_args = [cycle, name, submit_num] |
| 756 |
with suppress(sqlite3.DatabaseError): |
| 757 |
for row in self.connect().execute(stmt, stmt_args): |
| 758 |
ret = {} |
| 759 |
for key, value in zip(keys, row): |
| 760 |
ret[key] = value |
| 761 |
return ret |
| 762 |
return None |
| 763 |
|
| 764 |
def select_jobs_for_restart(self, callback): |
| 765 |
"""Select from task_pool+task_states+task_jobs for restart. |
| 766 |
|
| 767 |
Invoke callback(row_idx, row) on each row of the result. |
| 768 |
""" |
| 769 |
form_stmt = r""" |
| 770 |
SELECT |
| 771 |
%(task_pool)s.cycle, |
| 772 |
%(task_pool)s.name, |
| 773 |
%(task_jobs)s.submit_num, |
| 774 |
%(task_jobs)s.time_submit, |
| 775 |
%(task_jobs)s.submit_status, |
| 776 |
%(task_jobs)s.time_run, |
| 777 |
%(task_jobs)s.time_run_exit, |
| 778 |
%(task_jobs)s.run_status, |
| 779 |
%(task_jobs)s.job_runner_name, |
| 780 |
%(task_jobs)s.job_id, |
| 781 |
%(task_jobs)s.platform_name |
| 782 |
FROM |
| 783 |
%(task_jobs)s |
| 784 |
JOIN |
| 785 |
%(task_pool)s |
| 786 |
ON %(task_jobs)s.cycle == %(task_pool)s.cycle AND |
| 787 |
%(task_jobs)s.name == %(task_pool)s.name |
| 788 |
""" |
| 789 |
form_data = { |
| 790 |
"task_pool": self.TABLE_TASK_POOL, |
| 791 |
"task_jobs": self.TABLE_TASK_JOBS, |
| 792 |
} |
| 793 |
stmt = form_stmt % form_data |
| 794 |
for row_idx, row in enumerate(self.connect().execute(stmt)): |
| 795 |
callback(row_idx, list(row)) |
| 796 |
|
| 797 |
def select_task_job_run_times(self, callback): |
| 798 |
"""Select run times of succeeded task jobs grouped by task names. |
| 799 |
|
| 800 |
Invoke callback(row_idx, row) on each row, where each row contains: |
| 801 |
[name, run_times_str] |
| 802 |
|
| 803 |
where run_times_str is a string containing comma separated list of |
| 804 |
integer run times. This method is used to re-populate elapsed run times |
| 805 |
of each task on restart. |
| 806 |
""" |
| 807 |
stmt = ( |
| 808 |
r"SELECT" |
| 809 |
r" name," |
| 810 |
r" GROUP_CONCAT(" |
| 811 |
r" CAST(strftime('%s', time_run_exit) AS NUMERIC) -" |
| 812 |
r" CAST(strftime('%s', time_run) AS NUMERIC))" |
| 813 |
r" FROM task_jobs" |
| 814 |
r" WHERE run_status==0 GROUP BY name ORDER BY time_run_exit") |
| 815 |
for row_idx, row in enumerate(self.connect().execute(stmt)): |
| 816 |
callback(row_idx, list(row)) |
| 817 |
|
| 818 |
def select_task_job_platforms(self): |
| 819 |
"""Return the set of platform names from task_jobs table. |
| 820 |
|
| 821 |
Warning: |
| 822 |
This interface is used by `cylc clean` which does not upgrade the |
| 823 |
DB first (it could, this would only extend backwards |
| 824 |
compatibility but would not help with forwards compatibility). |
| 825 |
Keep this query to the minimum of tables/fields to avoid |
| 826 |
breaking compatibility with older/newer versions of Cylc. |
| 827 |
|
| 828 |
""" |
| 829 |
stmt = rf''' |
| 830 |
SELECT DISTINCT |
| 831 |
platform_name |
| 832 |
FROM |
| 833 |
{self.TABLE_TASK_JOBS} |
| 834 |
''' # nosec B608 (table name is code constant) |
| 835 |
return {i[0] for i in self.connect().execute(stmt)} |
| 836 |
|
| 837 |
def select_prev_instances( |
| 838 |
self, name: str, point: str |
| 839 |
) -> List[Tuple[int, bool, Set[int], str]]: |
| 840 |
"""Select task_states table info about previous instances of a task. |
| 841 |
|
| 842 |
Flow merge results in multiple entries for the same submit number. |
| 843 |
""" |
| 844 |
# Ignore bandit false positive: B608: hardcoded_sql_expressions |
| 845 |
# Not an injection, simply putting the table name in the SQL query |
| 846 |
# expression as a string constant local to this module. |
| 847 |
stmt = ( # nosec B608 |
| 848 |
r"SELECT flow_nums,submit_num,flow_wait,status FROM %(name)s" |
| 849 |
r" WHERE name==? AND cycle==?" |
| 850 |
) % {"name": self.TABLE_TASK_STATES} |
| 851 |
return [ |
| 852 |
( |
| 853 |
submit_num, |
| 854 |
flow_wait == 1, |
| 855 |
deserialise_set(flow_nums_str), |
| 856 |
status |
| 857 |
) |
| 858 |
for flow_nums_str, submit_num, flow_wait, status in ( |
| 859 |
self.connect().execute(stmt, (name, point,)) |
| 860 |
) |
| 861 |
] |
| 862 |
|
| 863 |
def select_latest_flow_nums(self) -> Optional['FlowNums']: |
| 864 |
"""Return a list of the most recent previous flow numbers.""" |
| 865 |
stmt = rf''' |
| 866 |
SELECT |
| 867 |
flow_nums, MAX(time_created) |
| 868 |
FROM |
| 869 |
{self.TABLE_TASK_STATES} |
| 870 |
WHERE |
| 871 |
flow_nums != ? |
| 872 |
''' # nosec B608 (table name is code constant) |
| 873 |
# Exclude flow=none: |
| 874 |
params = [serialise_set()] |
| 875 |
flow_nums_str = self.connect().execute(stmt, params).fetchone()[0] |
| 876 |
if flow_nums_str: |
| 877 |
return deserialise_set(flow_nums_str) |
| 878 |
return None |
| 879 |
|
| 880 |
def select_task_outputs( |
| 881 |
self, name: str, point: str |
| 882 |
) -> 'Dict[str, FlowNums]': |
| 883 |
"""Select task outputs for each flow. |
| 884 |
|
| 885 |
Return: {outputs_dict_str: flow_nums_set} |
| 886 |
|
| 887 |
""" |
| 888 |
stmt = rf''' |
| 889 |
SELECT |
| 890 |
flow_nums,outputs |
| 891 |
FROM |
| 892 |
{self.TABLE_TASK_OUTPUTS} |
| 893 |
WHERE |
| 894 |
name==? AND cycle==? |
| 895 |
''' # nosec B608 (table name is code constant) |
| 896 |
return { |
| 897 |
outputs: deserialise_set(flow_nums) |
| 898 |
for flow_nums, outputs in self.connect().execute( |
| 899 |
stmt, (name, point,) |
| 900 |
) |
| 901 |
} |
| 902 |
|
| 903 |
def select_xtriggers_for_restart(self, callback): |
| 904 |
stmt = rf''' |
| 905 |
SELECT |
| 906 |
signature, results |
| 907 |
FROM |
| 908 |
{self.TABLE_XTRIGGERS} |
| 909 |
''' # nosec B608 (table name is code constant) |
| 910 |
for row_idx, row in enumerate(self.connect().execute(stmt, [])): |
| 911 |
callback(row_idx, list(row)) |
| 912 |
|
| 913 |
def select_abs_outputs_for_restart(self, callback): |
| 914 |
stmt = rf''' |
| 915 |
SELECT |
| 916 |
cycle, name, output |
| 917 |
FROM |
| 918 |
{self.TABLE_ABS_OUTPUTS} |
| 919 |
''' # nosec B608 (table name is code constant) |
| 920 |
for row_idx, row in enumerate(self.connect().execute(stmt, [])): |
| 921 |
callback(row_idx, list(row)) |
| 922 |
|
| 923 |
def select_task_pool(self, callback): |
| 924 |
"""Select from task_pool. |
| 925 |
|
| 926 |
Invoke callback(row_idx, row) on each row, where each row contains: |
| 927 |
[cycle, name, status] |
| 928 |
""" |
| 929 |
form_stmt = r"SELECT cycle,name,status,is_held FROM %s" |
| 930 |
stmt = form_stmt % self.TABLE_TASK_POOL |
| 931 |
for row_idx, row in enumerate(self.connect().execute(stmt)): |
| 932 |
callback(row_idx, list(row)) |
| 933 |
|
| 934 |
def select_task_pool_for_restart(self, callback): |
| 935 |
"""Select from task_pool+task_states+task_jobs for restart. |
| 936 |
|
| 937 |
Invoke callback(row_idx, row) on each row, where each row contains: |
| 938 |
the fields in the SELECT statement below. |
| 939 |
|
| 940 |
Raises: |
| 941 |
PlatformLookupError: Do not start up if platforms for running |
| 942 |
tasks cannot be found in global.cylc. This exception should |
| 943 |
not be caught. |
| 944 |
""" |
| 945 |
form_stmt = r""" |
| 946 |
SELECT |
| 947 |
%(task_pool)s.cycle, |
| 948 |
%(task_pool)s.name, |
| 949 |
%(task_pool)s.flow_nums, |
| 950 |
%(task_states)s.flow_wait, |
| 951 |
%(task_states)s.is_manual_submit, |
| 952 |
%(task_late_flags)s.value, |
| 953 |
%(task_pool)s.status, |
| 954 |
%(task_pool)s.is_held, |
| 955 |
%(task_states)s.submit_num, |
| 956 |
%(task_jobs)s.try_num, |
| 957 |
%(task_jobs)s.platform_name, |
| 958 |
%(task_jobs)s.time_submit, |
| 959 |
%(task_jobs)s.time_run, |
| 960 |
%(task_timeout_timers)s.timeout, |
| 961 |
%(task_outputs)s.outputs |
| 962 |
FROM |
| 963 |
%(task_pool)s |
| 964 |
JOIN |
| 965 |
%(task_states)s |
| 966 |
ON %(task_pool)s.cycle == %(task_states)s.cycle AND |
| 967 |
%(task_pool)s.name == %(task_states)s.name AND |
| 968 |
%(task_pool)s.flow_nums == %(task_states)s.flow_nums |
| 969 |
LEFT OUTER JOIN |
| 970 |
%(task_late_flags)s |
| 971 |
ON %(task_pool)s.cycle == %(task_late_flags)s.cycle AND |
| 972 |
%(task_pool)s.name == %(task_late_flags)s.name |
| 973 |
LEFT OUTER JOIN |
| 974 |
%(task_jobs)s |
| 975 |
ON %(task_pool)s.cycle == %(task_jobs)s.cycle AND |
| 976 |
%(task_pool)s.name == %(task_jobs)s.name AND |
| 977 |
%(task_states)s.submit_num == %(task_jobs)s.submit_num |
| 978 |
LEFT OUTER JOIN |
| 979 |
%(task_timeout_timers)s |
| 980 |
ON %(task_pool)s.cycle == %(task_timeout_timers)s.cycle AND |
| 981 |
%(task_pool)s.name == %(task_timeout_timers)s.name |
| 982 |
LEFT OUTER JOIN |
| 983 |
%(task_outputs)s |
| 984 |
ON %(task_pool)s.cycle == %(task_outputs)s.cycle AND |
| 985 |
%(task_pool)s.name == %(task_outputs)s.name AND |
| 986 |
%(task_pool)s.flow_nums == %(task_outputs)s.flow_nums |
| 987 |
""" |
| 988 |
form_data = { |
| 989 |
"task_pool": self.TABLE_TASK_POOL, |
| 990 |
"task_states": self.TABLE_TASK_STATES, |
| 991 |
"task_late_flags": self.TABLE_TASK_LATE_FLAGS, |
| 992 |
"task_timeout_timers": self.TABLE_TASK_TIMEOUT_TIMERS, |
| 993 |
"task_jobs": self.TABLE_TASK_JOBS, |
| 994 |
"task_outputs": self.TABLE_TASK_OUTPUTS, |
| 995 |
} |
| 996 |
stmt = form_stmt % form_data |
| 997 |
|
| 998 |
# Run the callback, collecting any platform errors to be handled later: |
| 999 |
platform_errors = [] |
| 1000 |
for row_idx, row in enumerate(self.connect().execute(stmt)): |
| 1001 |
platform_error = callback(row_idx, list(row)) |
| 1002 |
if platform_error: |
| 1003 |
platform_errors.append(platform_error) |
| 1004 |
|
| 1005 |
# If any of the platforms could not be found, raise an exception |
| 1006 |
# and stop trying to play this workflow: |
| 1007 |
if platform_errors: |
| 1008 |
msg = ( |
| 1009 |
"The following platforms are not defined in" |
| 1010 |
" the global.cylc file:" |
| 1011 |
) |
| 1012 |
for platform in platform_errors: |
| 1013 |
msg += f"\n * {platform}" |
| 1014 |
raise PlatformLookupError(msg) |
| 1015 |
|
| 1016 |
def select_task_prerequisites( |
| 1017 |
self, cycle: str, name: str, flow_nums: str |
| 1018 |
) -> List[Tuple[str, str, str, str]]: |
| 1019 |
"""Return prerequisites of a task of the given name & cycle point.""" |
| 1020 |
stmt = rf""" |
| 1021 |
SELECT |
| 1022 |
prereq_name, |
| 1023 |
prereq_cycle, |
| 1024 |
prereq_output, |
| 1025 |
satisfied |
| 1026 |
FROM |
| 1027 |
{self.TABLE_TASK_PREREQUISITES} |
| 1028 |
WHERE |
| 1029 |
cycle == ? AND |
| 1030 |
name == ? AND |
| 1031 |
flow_nums == ? |
| 1032 |
""" # nosec B608 (table name is code constant) |
| 1033 |
stmt_args = [cycle, name, flow_nums] |
| 1034 |
return list(self.connect().execute(stmt, stmt_args)) |
| 1035 |
|
| 1036 |
def select_tasks_to_hold(self) -> List[Tuple[str, str]]: |
| 1037 |
"""Return all tasks to hold stored in the DB.""" |
| 1038 |
stmt = rf''' |
| 1039 |
SELECT |
| 1040 |
name, cycle |
| 1041 |
FROM |
| 1042 |
{self.TABLE_TASKS_TO_HOLD} |
| 1043 |
''' # nosec B608 (table name is code constant) |
| 1044 |
return list(self.connect().execute(stmt)) |
| 1045 |
|
| 1046 |
def select_task_times(self): |
| 1047 |
"""Select submit/start/stop times to compute job timings. |
| 1048 |
|
| 1049 |
To make data interpretation easier, choose the most recent succeeded |
| 1050 |
task to sample timings from. |
| 1051 |
""" |
| 1052 |
stmt = rf""" |
| 1053 |
SELECT |
| 1054 |
name, |
| 1055 |
cycle, |
| 1056 |
platform_name, |
| 1057 |
job_runner_name, |
| 1058 |
time_submit, |
| 1059 |
time_run, |
| 1060 |
time_run_exit |
| 1061 |
FROM |
| 1062 |
{self.TABLE_TASK_JOBS} |
| 1063 |
WHERE |
| 1064 |
run_status = 0 |
| 1065 |
""" # nosec B608 (table name is code constant) |
| 1066 |
columns = ( |
| 1067 |
'name', 'cycle', 'host', 'job_runner', |
| 1068 |
'submit_time', 'start_time', 'succeed_time' |
| 1069 |
) |
| 1070 |
return columns, list(self.connect().execute(stmt)) |
| 1071 |
|
| 1072 |
def select_tasks_for_datastore( |
| 1073 |
self, task_ids |
| 1074 |
): |
| 1075 |
"""Select state and outputs of specified tasks.""" |
| 1076 |
if not task_ids: |
| 1077 |
return [] |
| 1078 |
form_stmt = r""" |
| 1079 |
SELECT |
| 1080 |
%(task_states)s.cycle, |
| 1081 |
%(task_states)s.name, |
| 1082 |
%(task_states)s.flow_nums, |
| 1083 |
%(task_states)s.status, |
| 1084 |
MAX(%(task_states)s.submit_num), |
| 1085 |
%(task_outputs)s.outputs |
| 1086 |
FROM |
| 1087 |
%(task_states)s |
| 1088 |
LEFT OUTER JOIN |
| 1089 |
%(task_outputs)s |
| 1090 |
ON %(task_states)s.cycle == %(task_outputs)s.cycle AND |
| 1091 |
%(task_states)s.name == %(task_outputs)s.name |
| 1092 |
WHERE |
| 1093 |
%(task_states)s.cycle || '/' || %(task_states)s.name IN ( |
| 1094 |
%(task_ids)s |
| 1095 |
) |
| 1096 |
GROUP BY |
| 1097 |
%(task_states)s.cycle, %(task_states)s.name |
| 1098 |
""" |
| 1099 |
form_data = { |
| 1100 |
"task_states": self.TABLE_TASK_STATES, |
| 1101 |
"task_outputs": self.TABLE_TASK_OUTPUTS, |
| 1102 |
"task_ids": ', '.join(f"'{val}'" for val in task_ids), |
| 1103 |
} |
| 1104 |
stmt = form_stmt % form_data |
| 1105 |
return list(self.connect().execute(stmt)) |
| 1106 |
|
| 1107 |
def select_prereqs_for_datastore( |
| 1108 |
self, prereq_ids |
| 1109 |
): |
| 1110 |
"""Select prerequisites of specified tasks.""" |
| 1111 |
if not prereq_ids: |
| 1112 |
return [] |
| 1113 |
form_stmt = r""" |
| 1114 |
SELECT |
| 1115 |
cycle, |
| 1116 |
name, |
| 1117 |
prereq_name, |
| 1118 |
prereq_cycle, |
| 1119 |
prereq_output, |
| 1120 |
satisfied |
| 1121 |
FROM |
| 1122 |
%(prerequisites)s |
| 1123 |
WHERE |
| 1124 |
cycle || '/' || name || '/' || flow_nums IN ( |
| 1125 |
%(prereq_tasks_args)s |
| 1126 |
) |
| 1127 |
""" |
| 1128 |
form_data = { |
| 1129 |
"prerequisites": self.TABLE_TASK_PREREQUISITES, |
| 1130 |
"prereq_tasks_args": ', '.join(f"'{val}'" for val in prereq_ids), |
| 1131 |
} |
| 1132 |
stmt = form_stmt % form_data |
| 1133 |
return list(self.connect().execute(stmt)) |
| 1134 |
|
| 1135 |
def select_jobs_for_datastore( |
| 1136 |
self, task_ids |
| 1137 |
): |
| 1138 |
"""Select jobs of of specified tasks.""" |
| 1139 |
if not task_ids: |
| 1140 |
return [] |
| 1141 |
form_stmt = r""" |
| 1142 |
SELECT |
| 1143 |
%(task_states)s.cycle, |
| 1144 |
%(task_states)s.name, |
| 1145 |
%(task_jobs)s.submit_num, |
| 1146 |
%(task_jobs)s.time_submit, |
| 1147 |
%(task_jobs)s.submit_status, |
| 1148 |
%(task_jobs)s.time_run, |
| 1149 |
%(task_jobs)s.time_run_exit, |
| 1150 |
%(task_jobs)s.run_status, |
| 1151 |
%(task_jobs)s.job_runner_name, |
| 1152 |
%(task_jobs)s.job_id, |
| 1153 |
%(task_jobs)s.platform_name |
| 1154 |
FROM |
| 1155 |
%(task_jobs)s |
| 1156 |
JOIN |
| 1157 |
%(task_states)s |
| 1158 |
ON %(task_jobs)s.cycle == %(task_states)s.cycle AND |
| 1159 |
%(task_jobs)s.name == %(task_states)s.name |
| 1160 |
WHERE |
| 1161 |
%(task_states)s.cycle || '/' || %(task_states)s.name IN ( |
| 1162 |
%(task_ids)s |
| 1163 |
) |
| 1164 |
ORDER BY |
| 1165 |
%(task_states)s.submit_num DESC |
| 1166 |
""" |
| 1167 |
form_data = { |
| 1168 |
"task_states": self.TABLE_TASK_STATES, |
| 1169 |
"task_jobs": self.TABLE_TASK_JOBS, |
| 1170 |
"task_ids": ', '.join(f"'{val}'" for val in task_ids), |
| 1171 |
} |
| 1172 |
stmt = form_stmt % form_data |
| 1173 |
return list(self.connect().execute(stmt)) |
| 1174 |
|
| 1175 |
def vacuum(self): |
| 1176 |
"""Vacuum to the database.""" |
| 1177 |
return self.connect().execute("VACUUM") |