Debian Codegraph @

tests/integration/test_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
17 from datetime import datetime, timedelta
18 import pytest
19 import sqlite3
20 from typing import TYPE_CHECKING
21
22 from cylc.flow import commands
23
24 if TYPE_CHECKING:
25 from cylc.flow.scheduler import Scheduler
26
27
28 async def test_restart_number(
29 flow, one_conf, start, scheduler, log_filter, db_select
30 ):
31 """The restart number should increment correctly."""
32 id_ = flow(one_conf)
33
34 async def test(expected_restart_num: int, do_reload: bool = False):
35 """(Re)start the workflow and check the restart number is as expected.
36 """
37 schd: 'Scheduler' = scheduler(id_, paused_start=True)
38 async with start(schd):
39 if do_reload:
40 await commands.run_cmd(commands.reload_workflow(schd))
41 assert schd.workflow_db_mgr.n_restart == expected_restart_num
42 assert log_filter(
43 contains=f"(re)start number={expected_restart_num + 1}"
44 # (In the log, it's 1 higher than backend value)
45 )
46 assert ('n_restart', f'{expected_restart_num}') in db_select(
47 schd, False, 'workflow_params'
48 )
49
50 # First start
51 await test(expected_restart_num=0)
52 # Restart
53 await test(expected_restart_num=1)
54 # Restart + reload - https://github.com/cylc/cylc-flow/issues/4918
55 await test(expected_restart_num=2, do_reload=True)
56 # Final restart
57 await test(expected_restart_num=3)
58
59
60 def db_remove_column(schd: 'Scheduler', table: str, column: str) -> None:
61 """Remove a column from a scheduler DB table.
62
63 ALTER TABLE DROP COLUMN is not supported by sqlite yet, so we have to copy
64 the table (without the column) and rename it back to the original.
65 """
66 with schd.workflow_db_mgr.get_pri_dao() as pri_dao:
67 conn = pri_dao.connect()
68 # Get current column names, minus column
69 cursor = conn.execute(f'PRAGMA table_info({table})')
70 desc = cursor.fetchall()
71 c_names = ','.join(
72 [fields[1] for fields in desc if fields[1] != column]
73 )
74 # Copy table data to a temporary table, and rename it back.
75 conn.execute(rf"CREATE TABLE 'tmp'({c_names})")
76 conn.execute(
77 rf"INSERT INTO 'tmp'({c_names}) SELECT {c_names} FROM {table}")
78 conn.execute(rf"DROP TABLE '{table}'")
79 conn.execute(rf"ALTER TABLE 'tmp' RENAME TO '{table}'")
80 conn.commit()
81
82
83 async def test_db_upgrade_pre_803(
84 flow, one_conf, start, scheduler, log_filter, db_select
85 ):
86 """Test scheduler restart with upgrade of pre-8.0.3 DB."""
87 id_ = flow(one_conf)
88
89 # Run a scheduler to create a DB.
90 schd: 'Scheduler' = scheduler(id_, paused_start=True)
91 async with start(schd):
92 assert ('n_restart', '0') in db_select(schd, False, 'workflow_params')
93
94 # Remove task_states:is_manual_submit to fake a pre-8.0.3 DB.
95 db_remove_column(schd, "task_states", "is_manual_submit")
96 db_remove_column(schd, "task_jobs", "flow_nums")
97
98 schd: 'Scheduler' = scheduler(id_, paused_start=True)
99
100 # Restart should fail due to the missing column.
101 with pytest.raises(sqlite3.OperationalError):
102 async with start(schd):
103 pass
104 assert ('n_restart', '1') in db_select(schd, False, 'workflow_params')
105
106 schd: 'Scheduler' = scheduler(id_, paused_start=True)
107
108 # Run the DB upgrader for version 8.0.2
109 # (8.0.2 requires upgrade)
110 with schd.workflow_db_mgr.get_pri_dao() as pri_dao:
111 schd.workflow_db_mgr.upgrade_pre_803(pri_dao)
112 # Restart should now succeed.
113 async with start(schd):
114 assert ('n_restart', '2') in db_select(schd, False, 'workflow_params')
115
116
117 async def test_workflow_param_rapid_toggle(
118 one_conf, flow, scheduler, run
119 ):
120 """Check that queuing a workflow param toggle operation twice before
121 processing does not cause any problems.
122
123 https://github.com/cylc/cylc-flow/issues/5593
124 """
125 schd: 'Scheduler' = scheduler(flow(one_conf), paused_start=False)
126 async with run(schd):
127 assert schd.is_paused is False
128 schd.pause_workflow()
129 schd.resume_workflow()
130 schd.process_workflow_db_queue()
131 assert schd.is_paused is False
132
133 w_params = dict(schd.workflow_db_mgr.pri_dao.select_workflow_params())
134 assert w_params['is_paused'] == '0'
135
136
137 async def test_record_only_non_clock_triggers(
138 flow, run, scheduler, complete, db_select
139 ):
140 """Database does not record wall_clock xtriggers.
141
142 https://github.com/cylc/cylc-flow/issues/5911
143
144 Includes:
145 - Not in DB: A normal wall clock xtrigger (wall_clock).
146 - In DB: An xrandom mis-labelled as wall_clock trigger DB).
147 - Not in DB: An execution retry xtrigger.
148
149 @TODO: Refactor to use simulation mode to speedup after Simulation
150 mode upgrade bugfixes: This should speed this test up considerably.
151 """
152 rawpoint = '1348'
153 id_ = flow({
154 "scheduler": {
155 'cycle point format': '%Y',
156 'allow implicit tasks': True
157 },
158 "scheduling": {
159 "initial cycle point": rawpoint,
160 "xtriggers": {
161 "another": "xrandom(100)",
162 "wall_clock": "xrandom(100, _=Not a real wall clock trigger)",
163 "real_wall_clock": "wall_clock()"
164 },
165 "graph": {
166 "R1": """
167 @another & @wall_clock & @real_wall_clock => foo
168 @real_wall_clock => bar
169 """
170 }
171 },
172 })
173 schd = scheduler(id_, paused_start=False, run_mode='simulation')
174
175 async with run(schd):
176 await complete(schd, timeout=20)
177
178 # Assert that (only) the real clock trigger is not in the db:
179 assert db_select(schd, False, 'xtriggers', 'signature') == [
180 ('xrandom(100)',),
181 ('xrandom(100, _=Not a real wall clock trigger)',)]
182
183
184 async def test_time_zone_writing(
185 one_conf,
186 flow,
187 scheduler,
188 start,
189 db_select,
190 set_timezone
191 ):
192 """Don't store scheduler startup timezone forever.
193
194 https://github.com/cylc/cylc-flow/issues/6701
195 """
196 set_timezone('XXX-19:00')
197 schd = scheduler(flow(one_conf), paused_start=False, run_mode='live')
198 async with start(schd):
199 itask = schd.pool.get_tasks()[0]
200 now = datetime.now().astimezone()
201 set_timezone('XXX-19:17')
202 schd.submit_task_jobs([itask])
203
204 # Check the db time_submit:
205 (time_submit,) = db_select(schd, False, 'task_jobs', 'time_submit')[0]
206 time_submit = datetime.strptime(time_submit, '%Y-%m-%dT%H:%M:%S%z')
207 # The submit time should be approx correct:
208 assert (
209 abs(time_submit - now) < timedelta(seconds=10)
210 ), f"{time_submit} ~= {now}"