Debian Codegraph @

tests/u/main_loop/test_auto_restart.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 logging
18 from socket import gaierror
19 from unittest.mock import Mock
20
21 import pytest
22
23 from cylc.flow import CYLC_LOG
24 from cylc.flow.exceptions import (
25 CylcConfigError, CylcError, HostSelectException
26 )
27 from cylc.flow.main_loop.auto_restart import (
28 _can_auto_restart,
29 _set_auto_restart,
30 _should_auto_restart,
31 auto_restart,
32 )
33 from cylc.flow.parsec.exceptions import ParsecError
34 from cylc.flow.scheduler import Scheduler
35 from cylc.flow.workflow_status import (
36 AutoRestartMode,
37 StopMode
38 )
39
40
41 def test_can_auto_restart_pass(monkeypatch, caplog):
42 """Test can_auto_restart for successful host selection."""
43 def select_workflow_host(**_):
44 return ('localhost', 'localhost')
45 monkeypatch.setattr(
46 'cylc.flow.main_loop.auto_restart.select_workflow_host',
47 select_workflow_host
48 )
49 assert _can_auto_restart()
50 assert caplog.record_tuples == []
51
52
53 def test_can_auto_restart_fail(monkeypatch, caplog):
54 """Test can_auto_restart for unsuccessful host selection."""
55 def select_workflow_host(**_):
56 raise HostSelectException({})
57 monkeypatch.setattr(
58 'cylc.flow.main_loop.auto_restart.select_workflow_host',
59 select_workflow_host
60 )
61 with caplog.at_level(level=logging.DEBUG, logger=CYLC_LOG):
62 assert not _can_auto_restart()
63 [(_, level, msg)] = caplog.record_tuples
64 assert level == logging.CRITICAL
65 assert 'No alternative host to restart workflow on' in msg
66
67
68 def test_can_auto_restart_fail_horribly(
69 monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
70 ):
71 """Test can_auto_restart for really unsuccessful host selection."""
72 def select_workflow_host(**_):
73 raise Exception('Unexpected error in host selection')
74 monkeypatch.setattr(
75 'cylc.flow.main_loop.auto_restart.select_workflow_host',
76 select_workflow_host
77 )
78 with caplog.at_level(level=logging.ERROR, logger=CYLC_LOG):
79 assert not _can_auto_restart()
80 assert 'Error in host selection' in caplog.text
81 assert "Traceback (most recent call last):" in caplog.text
82
83
84 @pytest.mark.parametrize(
85 'host, stop_mode, condemned_hosts,'
86 ' auto_restart_time, should_auto_restart',
87 [
88 ( # no reason to restart, no reason not to
89 'localhost',
90 None,
91 [],
92 None,
93 False
94 ),
95 ( # should restart but already stopping
96 'localhost',
97 StopMode.AUTO,
98 ['localhost'],
99 None,
100 False
101 ),
102 ( # stop restart but already auto-restarting
103 'localhost',
104 StopMode.AUTO,
105 ['localhost'],
106 12345,
107 False
108 ),
109 ( # should restart
110 'localhost',
111 None,
112 ['localhost'],
113 None,
114 AutoRestartMode.RESTART_NORMAL
115 ),
116 ( # should force stop
117 'localhost',
118 None,
119 ['localhost!'],
120 None,
121 AutoRestartMode.FORCE_STOP
122 )
123 ]
124 )
125 def test_should_auto_restart(
126 host,
127 stop_mode,
128 condemned_hosts,
129 auto_restart_time,
130 should_auto_restart,
131 monkeypatch
132 ):
133 """Ensure the workflow only auto-restarts when appropriate."""
134 # factor out networking and FQDNs for testing purposes
135 monkeypatch.setattr(
136 'cylc.flow.main_loop.auto_restart.get_fqdn_by_host',
137 lambda x: x
138 )
139 # mock a scheduler object
140 scheduler = Mock(
141 host=host,
142 stop_mode=stop_mode,
143 auto_restart_time=auto_restart_time
144 )
145 # mock a workflow configuration object
146 cfg = Mock()
147 cfg.get = lambda x: condemned_hosts
148 # test
149 assert _should_auto_restart(scheduler, cfg) == should_auto_restart
150
151
152 def test_should_auto_restart__condemned_host_down(
153 monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
154 ):
155 """Check we don't get any spurious error messages if a condemned host is
156 unavailable.
157
158 A condemned host being unavailable is expected!
159 """
160 monkeypatch.setattr(
161 'cylc.flow.main_loop.auto_restart.get_fqdn_by_host',
162 Mock(side_effect=gaierror('oopsie'))
163 )
164 scheduler = Mock(
165 spec=Scheduler,
166 host='localhost',
167 stop_mode=None,
168 auto_restart_time=None,
169 )
170 cfg = Mock(get=lambda x: ['condemned-host'])
171
172 assert _should_auto_restart(scheduler, cfg) is False
173 assert not caplog.records
174
175
176 def test_set_auto_restart_already_stopping(caplog):
177 """Ensure restart isn't attempted if already stopping."""
178 scheduler = Mock(
179 stop_mode=StopMode.AUTO
180 )
181 with caplog.at_level(level=logging.DEBUG, logger=CYLC_LOG):
182 assert _set_auto_restart(scheduler)
183 assert caplog.record_tuples == []
184
185
186 def test_set_auto_restart_force_oveeride(caplog):
187 """Ensure scheduled restart is cancelled for a force stop."""
188 scheduler = Mock(
189 stop_mode=None,
190 auto_restart_time=1234
191 )
192 with caplog.at_level(level=logging.DEBUG, logger=CYLC_LOG):
193 assert _set_auto_restart(
194 scheduler,
195 mode=AutoRestartMode.FORCE_STOP,
196 )
197 assert len(caplog.record_tuples) == 2
198 [
199 (*_, msg1),
200 (*_, msg2)
201 ] = caplog.record_tuples
202 assert 'This workflow will be shutdown' in msg1
203 assert 'Scheduled automatic restart canceled' in msg2
204
205
206 def test_set_auto_restart_already_restarting(caplog):
207 """Ensure restart isn't re-scheduled."""
208 scheduler = Mock(
209 stop_mode=None,
210 auto_restart_time=1234
211 )
212 with caplog.at_level(level=logging.DEBUG, logger=CYLC_LOG):
213 assert _set_auto_restart(scheduler)
214 assert caplog.record_tuples == []
215
216
217 def test_set_auto_restart_no_detach(caplog: pytest.LogCaptureFixture):
218 """Ensure raises a CylcError (or subclass) if running in no-detach mode."""
219 scheduler = Mock(
220 spec=Scheduler,
221 stop_mode=None,
222 auto_restart_time=None,
223 options=Mock(no_detach=True)
224 )
225 with caplog.at_level(level=logging.DEBUG, logger=CYLC_LOG):
226 with pytest.raises(CylcError):
227 _set_auto_restart(scheduler)
228 assert caplog.record_tuples == []
229
230
231 def test_set_auto_restart_unable_to_restart(monkeypatch):
232 """Ensure returns False if workflow is unable to restart"""
233 called = False
234
235 def workflow_select_fail(**_):
236 nonlocal called
237 called = True # prevent this becoming a placebo
238 return False
239
240 monkeypatch.setattr(
241 'cylc.flow.main_loop.auto_restart._can_auto_restart',
242 workflow_select_fail
243 )
244 scheduler = Mock(
245 stop_mode=None,
246 auto_restart_time=None,
247 options=Mock(no_detach=False)
248 )
249 assert not _set_auto_restart(
250 scheduler
251 )
252 assert called
253
254
255 def test_set_auto_restart_with_delay(monkeypatch, caplog):
256 """Ensure workflows wait for a period before auto-restarting."""
257 called = False
258
259 def workflow_select_pass(**_):
260 nonlocal called
261 called = True # prevent this becoming a placebo
262 return True
263
264 monkeypatch.setattr(
265 'cylc.flow.main_loop.auto_restart._can_auto_restart',
266 workflow_select_pass
267 )
268 monkeypatch.setattr(
269 # remove the random element of the restart delay
270 'cylc.flow.main_loop.auto_restart.random',
271 lambda: 1
272 )
273 scheduler = Mock(
274 stop_mode=None,
275 auto_restart_time=None,
276 options=Mock(no_detach=False)
277 )
278 with caplog.at_level(level=logging.DEBUG, logger=CYLC_LOG):
279 assert _set_auto_restart(
280 scheduler,
281 restart_delay=1
282 )
283 [(*_, msg1), (*_, msg2)] = caplog.record_tuples
284 assert 'will automatically restart' in msg1
285 assert 'will restart in 1s' in msg2
286 assert called
287
288
289 def test_set_auto_restart_without_delay(monkeypatch, caplog):
290 """Ensure workflows auto-restart when no delay is provided."""
291 called = False
292
293 def workflow_select_pass(**_):
294 nonlocal called
295 called = True # prevent this becoming a placebo
296 return True
297
298 monkeypatch.setattr(
299 'cylc.flow.main_loop.auto_restart._can_auto_restart',
300 workflow_select_pass
301 )
302 scheduler = Mock(
303 stop_mode=None,
304 auto_restart_time=None,
305 options=Mock(no_detach=False)
306 )
307 with caplog.at_level(level=logging.DEBUG, logger=CYLC_LOG):
308 assert _set_auto_restart(
309 scheduler
310 )
311 [(*_, msg)] = caplog.record_tuples
312 assert 'will automatically restart' in msg
313 assert called
314
315
316 @pytest.mark.parametrize('exc_class', [ParsecError, CylcConfigError])
317 async def test_log_config_error(caplog, log_filter, monkeypatch, exc_class):
318 """It should log errors in the global config.
319
320 When errors are present in the global config they should be caught and
321 logged nicely rather than left to spill over as traceback in the log.
322 """
323 # make the global config raise an error
324 def global_config_load_error(*args, **kwargs):
325 raise exc_class('something even more bizarrely inexplicable')
326
327 monkeypatch.setattr(
328 'cylc.flow.main_loop.auto_restart.glbl_cfg',
329 global_config_load_error,
330 )
331
332 # call the auto_restart plugin, the error should be caught
333 caplog.clear()
334 assert await auto_restart(None, None) is False
335
336 # the error should have been logged
337 assert len(caplog.messages) == 1
338 assert 'an error in the global config' in caplog.messages[0]
339 assert 'something even more bizarrely inexplicable' in caplog.messages[0]