Debian Codegraph @

tests/i/utils/flow_tools.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 """Wrappers for creating and launching flows.
17
18 These utilities are not intended for direct use by tests
19 (hence the underscore function names).
20 Use the fixtures provided in the conftest instead.
21
22 """
23
24 import asyncio
25 from contextlib import (
26 asynccontextmanager,
27 contextmanager,
28 )
29 import logging
30 from pathlib import Path
31 from secrets import token_hex
32 from typing import (
33 Any,
34 Optional,
35 Union,
36 )
37
38 import pytest
39
40 from cylc.flow import CYLC_LOG
41 from cylc.flow.scheduler import (
42 Scheduler,
43 SchedulerStop,
44 )
45 from cylc.flow.scheduler_cli import RunOptions
46 from cylc.flow.workflow_files import WorkflowFiles
47 from cylc.flow.workflow_status import StopMode
48
49 from .flow_writer import flow_config_str
50
51
52 def _make_src_flow(src_path, conf, filename=WorkflowFiles.FLOW_FILE):
53 """Construct a workflow on the filesystem"""
54 flow_src_dir = (src_path / token_hex(4))
55 flow_src_dir.mkdir(parents=True, exist_ok=True)
56 if isinstance(conf, dict):
57 conf = flow_config_str(conf)
58 with open((flow_src_dir / filename), 'w+') as flow_file:
59 flow_file.write(conf)
60 return flow_src_dir
61
62
63 def _make_flow(
64 cylc_run_dir: Union[Path, str],
65 test_dir: Path,
66 conf: Union[dict, str],
67 name: Optional[str] = None,
68 workflow_id: Optional[str] = None,
69 defaults: Optional[bool] = True,
70 filename: str = WorkflowFiles.FLOW_FILE,
71 ) -> str:
72 """Construct a workflow on the filesystem.
73
74 Args:
75 conf: Either a workflow config dictionary, or a graph string to be
76 used as the R1 graph in the workflow config.
77 defaults: Set up a common defaults.
78 * [scheduling]allow implicit tasks = true
79
80 Set false for Cylc 7 upgrader tests.
81 """
82 if workflow_id:
83 flow_run_dir = (cylc_run_dir / workflow_id)
84 else:
85 if name is None:
86 name = token_hex(4)
87 flow_run_dir = (test_dir / name)
88 flow_run_dir.mkdir(parents=True, exist_ok=True)
89 workflow_id = str(flow_run_dir.relative_to(cylc_run_dir))
90 if isinstance(conf, str):
91 conf = {
92 'scheduling': {
93 'graph': {
94 'R1': conf
95 }
96 }
97 }
98 if defaults:
99 # set the default simulation runtime to zero (can be overridden)
100 (
101 conf.setdefault('runtime', {})
102 .setdefault('root', {})
103 .setdefault('simulation', {})
104 .setdefault('default run length', 'PT0S')
105 )
106 # allow implicit tasks by default:
107 conf.setdefault('scheduler', {}).setdefault(
108 'allow implicit tasks', 'True')
109
110 with open((flow_run_dir / filename), 'w+') as flow_file:
111 flow_file.write(flow_config_str(conf))
112 return workflow_id
113
114
115 @contextmanager
116 def _make_scheduler():
117 """Return a scheduler object for a flow registration."""
118 schd: Scheduler = None # type: ignore[assignment]
119
120 def __make_scheduler(id_: str, **opts: Any) -> Scheduler:
121 opts = {
122 # safe n sane defaults for integration tests
123 'paused_start': True,
124 'run_mode': 'simulation',
125 **opts,
126 }
127 options = RunOptions(**opts)
128 # create workflow
129 nonlocal schd
130 schd = Scheduler(id_, options)
131 return schd
132
133 yield __make_scheduler
134 # Teardown
135 if hasattr(schd, 'workflow_db_mgr'):
136 schd.workflow_db_mgr.on_workflow_shutdown()
137
138
139 @asynccontextmanager
140 async def _start_flow(
141 caplog: Optional[pytest.LogCaptureFixture],
142 schd: Scheduler,
143 level: int = logging.INFO
144 ):
145 """Start a scheduler but don't set the main loop running."""
146 if caplog:
147 caplog.set_level(level, CYLC_LOG)
148
149 await schd.install()
150
151 # Speed up main loop
152 schd.INTERVAL_MAIN_LOOP = schd.INTERVAL_MAIN_LOOP_QUICK = 1e-4
153
154 try:
155 # Nested `try...finally` to ensure caplog always yielded even if
156 # exception occurs in Scheduler
157 try:
158 await schd.start()
159 finally:
160 # After this `yield`, the `with` block of the context manager
161 # is executed:
162 yield caplog
163 finally:
164 # Cleanup - this always runs after the `with` block of the
165 # context manager.
166 # Need to shut down Scheduler, but time out in case something
167 # goes wrong:
168 async with asyncio.timeout(5):
169 await schd.shutdown(SchedulerStop("integration test teardown"))
170
171
172 @asynccontextmanager
173 async def _run_flow(
174 caplog: Optional[pytest.LogCaptureFixture],
175 schd: Scheduler,
176 level: int = logging.INFO
177 ):
178 """Start a scheduler and set the main loop running."""
179 if caplog:
180 caplog.set_level(level, CYLC_LOG)
181
182 await schd.install()
183
184 # Speed up main loop
185 schd.INTERVAL_MAIN_LOOP = schd.INTERVAL_MAIN_LOOP_QUICK = 1e-4
186
187 task: Optional[asyncio.Task] = None
188 try:
189 # Nested `try...finally` to ensure caplog always yielded even if
190 # exception occurs in Scheduler
191 try:
192 await schd.start()
193 # Do not await as we need to yield control to the main loop:
194 task = asyncio.create_task(schd.run_scheduler())
195 finally:
196 # After this `yield`, the `with` block of the context manager
197 # is executed:
198 yield caplog
199 finally:
200 # Cleanup - this always runs after the `with` block of the
201 # context manager.
202 # Need to shut down Scheduler, but time out in case something
203 # goes wrong:
204 async with asyncio.timeout(5):
205 if task:
206 # ask the scheduler to shut down nicely,
207 # let main loop handle it:
208 schd._set_stop(StopMode.REQUEST_NOW_NOW)
209 await task
210 if schd.contact_data:
211 async with asyncio.timeout(5):
212 # Scheduler still running... try more forceful tear down:
213 await schd.shutdown(SchedulerStop("integration test teardown"))
214 if task:
215 # Brute force cleanup if something went wrong:
216 task.cancel()