Debian Codegraph @

tests/integration/test_workflow_events.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 asyncio
18 from types import MethodType
19
20 import pytest
21
22 from cylc.flow.scheduler import SchedulerError
23 from cylc.flow.workflow_events import WorkflowEventHandler
24
25
26 EVENTS = (
27 'startup',
28 'shutdown',
29 'abort',
30 'workflow timeout',
31 'stall',
32 'stall timeout',
33 'inactivity timeout',
34 'restart timeout',
35 )
36
37
38 @pytest.fixture
39 async def test_scheduler(flow, scheduler, capcall):
40 events = capcall(
41 'cylc.flow.scheduler.Scheduler.run_event_handlers',
42 )
43
44 def get_events():
45 return {e[0][1] for e in events}
46
47 def _schd(event_config=None, config=None, **opts):
48 assert not (event_config and config)
49 if not config:
50 config = {
51 'scheduler': {
52 'events': {
53 'mail events': ', '.join(EVENTS),
54 **(event_config or {}),
55 },
56 },
57 'scheduling': {
58 'graph': {
59 'R1': 'a'
60 }
61 },
62 }
63 id_ = flow(config)
64 schd = scheduler(id_, **opts)
65 schd.get_events = get_events
66 return schd
67
68 return _schd
69
70
71 async def test_startup_and_shutdown(test_scheduler, run):
72 """Test the startup and shutdown events.
73
74 * "startup" should fire every time a scheduler is started.
75 * "shutdown" should fire every time a scheduler does a controlled exit.
76 (i.e. excluding aborts on unexpected internal errors).
77 """
78 schd = test_scheduler()
79 async with run(schd):
80 # NOTE: the "startup" event is only yielded with "run" not "start"
81 pass
82 assert schd.get_events() == {'startup', 'shutdown'}
83
84
85 async def test_workflow_timeout(test_scheduler, run):
86 """Test the workflow timeout.
87
88 This counts down from scheduler start.
89 """
90 schd = test_scheduler({'workflow timeout': 'PT0S'})
91 async with asyncio.timeout(4):
92 async with run(schd):
93 await asyncio.sleep(0.1)
94 assert schd.get_events() == {'startup', 'workflow timeout', 'shutdown'}
95
96
97 async def test_inactivity_timeout(test_scheduler, start):
98 """Test the inactivity timeout.
99
100 This counts down from things like state changes.
101 """
102 schd = test_scheduler({
103 'inactivity timeout': 'PT0S',
104 'abort on inactivity timeout': 'True',
105 })
106 async with asyncio.timeout(4):
107 with pytest.raises(SchedulerError):
108 async with start(schd):
109 await asyncio.sleep(0)
110 await schd._main_loop()
111 assert schd.get_events() == {'inactivity timeout', 'shutdown'}
112
113
114 async def test_abort(test_scheduler, run):
115 """Test abort.
116
117 This should fire when uncaught internal exceptions are raised.
118
119 Note, this is orthogonal to shutdown (i.e. a scheduler either shuts down or
120 aborts, not both).
121
122 Note, this is orthogonal to the "abort on <event>" configurations.
123 """
124 schd = test_scheduler()
125
126 # get the main-loop to raise an exception
127 def killer():
128 raise Exception(':(')
129
130 schd._main_loop = killer
131
132 # start the scheduler and wait for it to hit the exception
133 with pytest.raises(Exception):
134 async with run(schd):
135 for _ in range(10):
136 # allow initialisation to complete
137 await asyncio.sleep(0.1)
138
139 # the abort event should be called
140 # note, "abort" and "shutdown" are orthogonal
141 assert schd.get_events() == {'startup', 'abort'}
142
143
144 async def test_stall(test_scheduler, start):
145 """Test the stall event.
146
147 This should fire when the scheduler enters the stalled state.
148 """
149 schd = test_scheduler()
150 async with start(schd):
151 # set the failed output
152 schd.pool.spawn_on_output(
153 schd.pool.get_tasks()[0],
154 'failed'
155 )
156
157 # set the failed status
158 schd.pool.get_tasks()[0].state_reset('failed')
159
160 # check for workflow stall condition
161 schd.is_paused = False
162 schd.check_workflow_stalled()
163
164 assert schd.get_events() == {'shutdown', 'stall'}
165
166
167 async def test_restart_timeout_workflow_completion(
168 test_scheduler,
169 scheduler,
170 run,
171 complete,
172 ):
173 """Test restart timeout for completed workflows.
174
175 This should fire when a completed workflow is restarted.
176 """
177 schd = test_scheduler({'restart timeout': 'PT0S'}, paused_start=False)
178
179 # run to completion
180 async with run(schd):
181 await complete(schd)
182 assert schd.get_events() == {'startup', 'shutdown'}
183
184 # restart
185 schd2 = scheduler(schd.workflow)
186 schd2.get_events = schd.get_events
187 async with run(schd2):
188 await asyncio.sleep(0.1)
189 assert schd2.get_events() == {'startup', 'restart timeout', 'shutdown'}
190
191
192 async def test_restart_timeout_workflow_stop_after_cycle_point(
193 test_scheduler,
194 scheduler,
195 run,
196 complete,
197 ):
198 """Test restart timeout with the "stop after cycle point" config.
199
200 This should fire when a completed workflow is restarted.
201 """
202 schd = test_scheduler(
203 config={
204 'scheduler': {
205 'cycle point format': 'CCYY',
206 'events': {'restart timeout': 'PT0S'},
207 },
208 'scheduling': {
209 'initial cycle point': '2000',
210 'stop after cycle point': '2000',
211 'graph': {
212 'P1Y': 'foo[-P1Y] => foo',
213 },
214 },
215 },
216 paused_start=False,
217 )
218
219 # run to completion
220 async with run(schd):
221 await complete(schd)
222 assert schd.get_events() == {'startup', 'shutdown'}
223
224 # restart
225 schd2 = scheduler(schd.workflow)
226 schd2.get_events = schd.get_events
227 async with run(schd2):
228 await asyncio.sleep(0.1)
229 assert schd2.get_events() == {'startup', 'restart timeout', 'shutdown'}
230
231
232 async def test_shutdown_handler_timeout_kill(
233 test_scheduler, run, monkeypatch, mock_glbl_cfg, caplog
234 ):
235 """Test shutdown handlers get killed on the process pool timeout.
236
237 Has to be done differently as the process pool is closed during shutdown.
238 See GitHub #6639
239
240 """
241 def mock_run_event_handlers(self, event, reason=""):
242 """To replace scheduler.run_event_handlers(...).
243
244 Run workflow event handlers even in simulation mode.
245
246 """
247 self.workflow_event_handler.handle(self, event, str(reason))
248
249 # Configure a long-running shutdown handler.
250 schd = test_scheduler({
251 'shutdown handlers': 'sleep 10; echo',
252 'mail events': '',
253 })
254
255 # Set a low process pool timeout value.
256 mock_glbl_cfg(
257 'cylc.flow.subprocpool.glbl_cfg',
258 '''
259 [scheduler]
260 process pool timeout = PT1S
261 '''
262 )
263
264 async with asyncio.timeout(30):
265 async with run(schd):
266 # Replace a scheduler method, to call handlers in simulation mode.
267 monkeypatch.setattr(
268 schd,
269 'run_event_handlers',
270 MethodType(mock_run_event_handlers, schd),
271 )
272 await asyncio.sleep(0.1)
273
274 assert (
275 "[('workflow-event-handler-00', 'shutdown') err] killed on "
276 "timeout (PT1S)"
277 ) in caplog.text
278
279
280 TEMPLATES = [
281 # perfectly valid
282 pytest.param('%(workflow)s', id='good'),
283 # no template variable of that name
284 pytest.param('%(no_such_variable)s', id='bad'),
285 # missing the 's'
286 pytest.param('%(broken_syntax)', id='ugly'),
287 ]
288
289
290 @pytest.mark.parametrize('template', TEMPLATES)
291 async def test_mail_footer_template(
292 mod_one, # use the same scheduler for each test
293 start,
294 mock_glbl_cfg,
295 log_filter,
296 capcall,
297 template,
298 ):
299 """It should handle templating issues with the mail footer."""
300 # prevent emails from being sent
301 mail_calls = capcall(
302 'cylc.flow.workflow_events.WorkflowEventHandler._send_mail'
303 )
304
305 # configure Cylc to send an email on startup with the configured footer
306 mock_glbl_cfg(
307 'cylc.flow.workflow_events.glbl_cfg',
308 f'''
309 [scheduler]
310 [[mail]]
311 footer = 'footer={template}'
312 [[events]]
313 mail events = startup
314 ''',
315 )
316
317 # start the workflow and get it to send an email
318 async with start(mod_one) as one_log:
319 one_log.clear() # clear previous log messages
320 mod_one.workflow_event_handler.handle(
321 mod_one,
322 WorkflowEventHandler.EVENT_STARTUP,
323 'event message'
324 )
325
326 # warnings should appear only when the template is invalid
327 should_log = 'workflow' not in template
328
329 # check that template issues are handled correctly
330 assert bool(log_filter(
331 contains='Ignoring bad mail footer template',
332 )) == should_log
333 assert bool(log_filter(
334 contains=template,
335 )) == should_log
336
337 # check that the mail is sent even if there are issues with the footer
338 assert len(mail_calls) == 1
339
340
341 @pytest.mark.parametrize('template', TEMPLATES)
342 async def test_custom_event_handler_template(
343 mod_one, # use the same scheduler for each test
344 start,
345 mock_glbl_cfg,
346 log_filter,
347 template,
348 ):
349 """It should handle templating issues with custom event handlers."""
350 # configure Cylc to send an email on startup with the configured footer
351 mock_glbl_cfg(
352 'cylc.flow.workflow_events.glbl_cfg',
353 f'''
354 [scheduler]
355 [[events]]
356 startup handlers = echo "{template}"
357 '''
358 )
359
360 # start the workflow and get it to send an email
361 async with start(mod_one) as one_log:
362 one_log.clear() # clear previous log messages
363 mod_one.workflow_event_handler.handle(
364 mod_one,
365 WorkflowEventHandler.EVENT_STARTUP,
366 'event message'
367 )
368
369 # warnings should appear only when the template is invalid
370 should_log = 'workflow' not in template
371
372 # check that template issues are handled correctly
373 assert bool(log_filter(
374 contains='bad template',
375 )) == should_log
376 assert bool(log_filter(
377 contains=template,
378 )) == should_log