Debian Codegraph @

tests/integration/test_scheduler.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 import logging
19 from pathlib import Path
20 import re
21 from signal import (
22 SIGHUP,
23 SIGINT,
24 SIGTERM,
25 )
26 from typing import (
27 Any,
28 Callable,
29 )
30 from unittest.mock import Mock
31
32 import pytest
33
34 from cylc.flow import commands
35 from cylc.flow.exceptions import CylcError
36 from cylc.flow.parsec.exceptions import ParsecError
37 from cylc.flow.scheduler import (
38 Scheduler,
39 SchedulerStop,
40 )
41 from cylc.flow.task_remote_mgr import (
42 REMOTE_FILE_INSTALL_255,
43 REMOTE_FILE_INSTALL_DONE,
44 REMOTE_FILE_INSTALL_FAILED,
45 REMOTE_INIT_255,
46 REMOTE_INIT_DONE,
47 REMOTE_INIT_FAILED,
48 )
49 from cylc.flow.task_state import (
50 TASK_STATUS_FAILED,
51 TASK_STATUS_RUNNING,
52 TASK_STATUS_SUBMIT_FAILED,
53 TASK_STATUS_SUBMITTED,
54 TASK_STATUS_SUCCEEDED,
55 TASK_STATUS_WAITING,
56 )
57 from cylc.flow.workflow_status import (
58 AutoRestartMode,
59 StopMode,
60 )
61
62
63 from cylc.flow.network.resolvers import TaskMsg
64 from cylc.flow.id import Tokens
65
66 Fixture = Any
67
68
69 TRACEBACK_MSG = "Traceback (most recent call last):"
70
71
72 async def test_is_paused_after_stop(
73 one_conf: Fixture, flow: Fixture, scheduler: Fixture, run: Fixture,
74 db_select: Fixture):
75 """Test the paused status is unset on normal shutdown."""
76 id_: str = flow(one_conf)
77 schd: 'Scheduler' = scheduler(id_, paused_start=True)
78 # Run
79 async with run(schd):
80 assert not schd.is_restart
81 assert schd.is_paused
82 # Stopped
83 assert ('is_paused', '1') not in db_select(schd, False, 'workflow_params')
84 # Restart
85 schd = scheduler(id_, paused_start=None)
86 async with run(schd):
87 assert schd.is_restart
88 assert not schd.is_paused
89
90
91 async def test_is_paused_after_crash(
92 one_conf: Fixture, flow: Fixture, scheduler: Fixture, run: Fixture,
93 db_select: Fixture):
94 """Test the paused status is not unset for an interrupted workflow."""
95 id_: str = flow(one_conf)
96 schd: 'Scheduler' = scheduler(id_, paused_start=True)
97
98 def ctrl_c():
99 raise asyncio.CancelledError("Mock keyboard interrupt")
100 # Patch this part of the main loop
101 _schd_workflow_shutdown = schd.workflow_shutdown
102 setattr(schd, 'workflow_shutdown', ctrl_c)
103
104 # Run
105 with pytest.raises(asyncio.CancelledError):
106 async with run(schd):
107 assert not schd.is_restart
108 assert schd.is_paused
109 # Stopped
110 assert ('is_paused', '1') in db_select(schd, False, 'workflow_params')
111 # Reset patched method
112 setattr(schd, 'workflow_shutdown', _schd_workflow_shutdown)
113 # Restart
114 schd = scheduler(id_, paused_start=None)
115 async with run(schd):
116 assert schd.is_restart
117 assert schd.is_paused
118
119
120 async def test_shutdown_CylcError_log(one: Scheduler, run: Callable):
121 """Test that if a CylcError occurs during shutdown, it is
122 logged in one line."""
123 schd = one
124
125 # patch the shutdown to raise an error
126 async def mock_shutdown(*a, **k):
127 raise CylcError("Error on shutdown")
128 setattr(schd, '_shutdown', mock_shutdown)
129
130 # run the workflow
131 log: pytest.LogCaptureFixture
132 with pytest.raises(CylcError) as exc:
133 async with run(schd) as log:
134 pass
135
136 # check the log records after attempted shutdown
137 assert str(exc.value) == "Error on shutdown"
138 last_record = log.records[-1]
139 assert last_record.message == "CylcError: Error on shutdown"
140 assert last_record.levelno == logging.ERROR
141
142 # shut down the scheduler properly
143 await Scheduler._shutdown(schd, SchedulerStop('because I said so'))
144
145
146 async def test_shutdown_general_exception_log(one: Scheduler, run: Callable):
147 """Test that if a non-CylcError occurs during shutdown, it is
148 logged with traceback (but not excessive)."""
149 schd = one
150
151 # patch the shutdown to raise an error
152 async def mock_shutdown(*a, **k):
153 raise ValueError("Error on shutdown")
154 setattr(schd, '_shutdown', mock_shutdown)
155
156 # run the workflow
157 log: pytest.LogCaptureFixture
158 with pytest.raises(ValueError) as exc:
159 async with run(schd) as log:
160 pass
161
162 # check the log records after attempted shutdown
163 assert str(exc.value) == "Error on shutdown"
164 last_record = log.records[-1]
165 assert last_record.message == "Error on shutdown"
166 assert last_record.levelno == logging.ERROR
167 assert last_record.exc_text is not None
168 assert last_record.exc_text.startswith(TRACEBACK_MSG)
169 assert ("During handling of the above exception, "
170 "another exception occurred") not in last_record.exc_text
171
172 # shut down the scheduler properly
173 await Scheduler._shutdown(schd, SchedulerStop('because I said so'))
174
175
176 async def test_holding_tasks_whilst_scheduler_paused(
177 capture_submission,
178 flow,
179 one_conf,
180 start,
181 scheduler,
182 ):
183 """It should hold tasks irrespective of workflow state.
184
185 See https://github.com/cylc/cylc-flow/issues/4278
186 """
187 id_ = flow(one_conf)
188 one = scheduler(id_, paused_start=True)
189
190 # run the workflow
191 async with start(one):
192 # capture any job submissions
193 submitted_tasks = capture_submission(one)
194 assert submitted_tasks == set()
195
196 # release runahead/queued tasks
197 # (nothing should happen because the scheduler is paused)
198 one.pool.release_runahead_tasks()
199 one.release_tasks_to_run()
200 assert submitted_tasks == set()
201
202 # hold all tasks & resume the workflow
203 await commands.run_cmd(commands.hold(one, ['*/*']))
204 one.resume_workflow()
205
206 # release queued tasks
207 # (there should be no change because the task is still held)
208 one.release_tasks_to_run()
209 assert submitted_tasks == set()
210
211 # release all tasks
212 await commands.run_cmd(commands.release(one, ['*/*']))
213
214 # release queued tasks
215 # (the task should be submitted)
216 one.release_tasks_to_run()
217 assert len(submitted_tasks) == 1
218
219
220 async def test_no_poll_waiting_tasks(
221 capture_polling,
222 flow,
223 one_conf,
224 start,
225 scheduler,
226 ):
227 """Waiting tasks shouldn't be polled.
228
229 If a waiting task previously it will have the submit number of its previous
230 job, and polling would erroneously return the state of that job.
231
232 See https://github.com/cylc/cylc-flow/issues/4658
233 """
234 id_: str = flow(one_conf)
235 # start the scheduler in live mode in order to activate regular polling
236 # logic
237 one: Scheduler = scheduler(id_, run_mode='live')
238
239 log: pytest.LogCaptureFixture
240 async with start(one) as log:
241 # Test assumes start up with a waiting task.
242 task = (one.pool.get_tasks())[0]
243 assert task.state.status == TASK_STATUS_WAITING
244
245 polled_tasks = capture_polling(one)
246
247 # Waiting tasks should not be polled.
248 await commands.run_cmd(commands.poll_tasks(one, ['*/*']))
249 assert polled_tasks == set()
250
251 # Even if they have a submit number.
252 task.submit_num = 1
253 await commands.run_cmd(commands.poll_tasks(one, ['*/*']))
254 assert len(polled_tasks) == 0
255
256 # But these states should be:
257 for state in [
258 TASK_STATUS_SUBMIT_FAILED,
259 TASK_STATUS_FAILED,
260 TASK_STATUS_SUBMITTED,
261 TASK_STATUS_RUNNING
262 ]:
263 task.state.status = state
264 await commands.run_cmd(commands.poll_tasks(one, ['*/*']))
265 assert len(polled_tasks) == 1
266 polled_tasks.clear()
267
268 # Shut down with a running task.
269 task.state.status = TASK_STATUS_RUNNING
270
271 # For good measure, check the faked running task is reported at shutdown.
272 assert "Orphaned tasks:\n* 1/one (running)" in log.messages
273
274
275 async def test_unexpected_ParsecError(
276 one: Scheduler,
277 start: Callable,
278 log_filter: Callable,
279 monkeypatch: pytest.MonkeyPatch
280 ):
281 """Test that ParsecErrors - that occur at any time other than config load
282 when running a workflow - are displayed with traceback, because they are
283 not expected."""
284 log: pytest.LogCaptureFixture
285
286 def raise_ParsecError(*a, **k):
287 raise ParsecError("Mock error")
288
289 monkeypatch.setattr(one, '_configure_contact', raise_ParsecError)
290
291 with pytest.raises(ParsecError):
292 async with start(one) as log:
293 pass
294
295 assert log_filter(
296 logging.CRITICAL,
297 exact_match="Workflow shutting down - Mock error"
298 )
299 assert TRACEBACK_MSG in log.text
300
301
302 async def test_error_during_auto_restart(
303 one: Scheduler,
304 run: Callable,
305 log_filter: Callable,
306 monkeypatch: pytest.MonkeyPatch,
307 ):
308 """Test that an error during auto-restart does not get swallowed"""
309 log: pytest.LogCaptureFixture
310 err_msg = "Mock error: sugar in water"
311
312 def mock_auto_restart(*a, **k):
313 raise RuntimeError(err_msg)
314
315 monkeypatch.setattr(one, 'workflow_auto_restart', mock_auto_restart)
316 monkeypatch.setattr(
317 one, 'auto_restart_mode', AutoRestartMode.RESTART_NORMAL
318 )
319
320 with pytest.raises(RuntimeError, match=err_msg):
321 async with run(one) as log:
322 pass
323
324 assert log_filter(logging.ERROR, err_msg)
325 assert TRACEBACK_MSG in log.text
326
327
328 async def test_uuid_unchanged_on_restart(
329 one: Scheduler,
330 scheduler: Callable,
331 start: Callable,
332 ):
333 """Restart gets UUID from Database:
334
335 See https://github.com/cylc/cylc-flow/issues/5615
336
337 Process:
338 * Create a scheduler then shut it down.
339 * Create a new scheduler for the same workflow and check that it has
340 retrieved the UUID from the Daatabase.
341 """
342 uuid_re = re.compile('CYLC_WORKFLOW_UUID=(.*)')
343 contact_file = Path(one.workflow_run_dir) / '.service/contact'
344
345 async with start(one):
346 pass
347
348 schd = scheduler(one.workflow_name, paused_start=True)
349 async with start(schd):
350 # UUID in contact file should be the same as that set in the database
351 # and the scheduler.
352 cf_uuid = uuid_re.findall(contact_file.read_text())
353 assert cf_uuid == [schd.uuid_str]
354
355
356 async def test_restart_timeout(
357 flow,
358 one_conf,
359 scheduler,
360 run,
361 log_filter,
362 complete,
363 capture_submission,
364 ):
365 """It should wait for user input if there are no tasks in the pool.
366
367 When restarting a completed workflow there are no tasks in the pool so
368 the scheduler is inclined to shutdown before the user has had the chance
369 to trigger tasks in order to allow the workflow to continue.
370
371 In order to make this easier, the scheduler should enter the paused state
372 and wait around for a configured period before shutting itself down.
373
374 See: https://github.com/cylc/cylc-flow/issues/5078
375 """
376 id_ = flow(one_conf)
377
378 # run the workflow to completion
379 schd: Scheduler = scheduler(id_, paused_start=False)
380 async with run(schd):
381 await complete(schd)
382
383 # restart the completed workflow
384 schd = scheduler(id_, paused_start=False)
385 async with run(schd):
386 # it should detect that the workflow has completed and alert the user
387 assert log_filter(
388 logging.WARNING,
389 contains='This workflow already ran to completion.'
390 )
391
392 # it should activate a timeout
393 assert log_filter(logging.WARNING, contains='restart timer starts NOW')
394
395 capture_submission(schd)
396 # when we trigger tasks the timeout should be cleared
397 await commands.run_cmd(
398 commands.force_trigger_tasks(schd, ['1/one'], []))
399
400 await asyncio.sleep(0) # yield control to the main loop
401 assert log_filter(logging.INFO, contains='restart timer stopped')
402
403
404 @pytest.mark.parametrize("signal", ((SIGHUP), (SIGINT), (SIGTERM)))
405 async def test_signal_escallation(one, start, signal, log_filter):
406 """Double signal should escalate shutdown.
407
408 If a term-like signal is received whilst the workflow is already stopping
409 in NOW mode, then the shutdown should be escalated to NOW_NOW
410 mode.
411
412 See https://github.com/cylc/cylc-flow/pull/6444
413 """
414 async with start(one):
415 # put the workflow in the stopping state
416 one._set_stop(StopMode.REQUEST_CLEAN)
417 assert one.stop_mode.name == 'REQUEST_CLEAN'
418
419 # one signal should escalate this from CLEAN to NOW
420 one._handle_signal(signal, None)
421 assert log_filter(contains=signal.name)
422 assert one.stop_mode.name == 'REQUEST_NOW'
423
424 # two signals should escalate this from NOW to NOW_NOW
425 one._handle_signal(signal, None)
426 assert one.stop_mode.name == 'REQUEST_NOW_NOW'
427
428
429 async def test_set_stall_interaction(flow, scheduler, start):
430 """Test the interaction between manual set and workflow stall.
431
432 A set operation can put a scheduler into the stalled state and can also get
433 a scheduler out of the stalled state.
434 """
435 id_ = flow({
436 'scheduling': {
437 'xtriggers': {'never': 'xrandom(0)'},
438 'graph': {
439 'R1': '''
440 # add a pending xtrigger so that when we un-stall the
441 # workflow (via "cylc set") there are no downstream impacts
442 # See https://github.com/cylc/cylc-flow/issues/7157
443 @never => b
444 a => b
445 '''
446 },
447 },
448 })
449 schd: 'Scheduler' = scheduler(id_, paused_start=False)
450 async with start(schd):
451 # set 1/a to failed
452 await commands.run_cmd(
453 commands.set_prereqs_and_outputs(
454 schd, ['^/a'], [], [TASK_STATUS_FAILED]
455 )
456 )
457
458 # the scheduler should be stalled
459 await schd._main_loop()
460 await schd._main_loop()
461 assert schd.is_stalled is True
462 assert (
463 schd.data_store_mgr.data[schd.tokens.id]['workflow'].status_msg
464 == 'stalled'
465 )
466
467 # set 1/a to succeeded
468 await commands.run_cmd(
469 commands.set_prereqs_and_outputs(
470 schd, ['^/a'], [], [TASK_STATUS_SUCCEEDED]
471 )
472 )
473
474 # the scheduler should NOT be stalled
475 await schd._main_loop()
476 await schd._main_loop()
477 assert schd.is_stalled is False
478 assert (
479 schd.data_store_mgr.data[schd.tokens.id]['workflow'].status_msg
480 != 'stalled'
481 )
482
483
484 async def test_cylc_message(one, start, log_filter, caplog):
485 message = (
486 "20000101T0000Z", # event_time
487 "INFO", # severity
488 'some-message', # message
489 )
490
491 async with start(one):
492 # send a message for an invalid task (task names cannot contain spaces)
493 one.message_queue.put(
494 TaskMsg(
495 Tokens("1/Invalid task", relative=True),
496 *message,
497 )
498 )
499 one.process_queued_task_messages()
500 assert log_filter(contains="Illegal task name: Invalid task")
501
502 # send a message for a valid task
503 caplog.clear()
504 one.message_queue.put(
505 TaskMsg(
506 Tokens("1/one", relative=True),
507 *message,
508 )
509 )
510 one.process_queued_task_messages()
511 assert not log_filter(contains="Illegal task name")
512 assert log_filter(contains='(received)some-message')
513
514
515 async def test_manage_remote_init_retry_on_255(
516 flow, scheduler, start, monkeypatch: pytest.MonkeyPatch
517 ):
518 """Test that manage_remote_init retries remote init/file install on 255.
519
520 See https://github.com/cylc/cylc-flow/issues/7286
521
522 On restart, if remote-init fails with exit code 255 (SSH connection
523 failure), manage_remote_init should retry rather than silently dropping
524 the install target.
525 """
526 missing_target = 'Alderaan'
527 fake_platform = {'install target': missing_target, 'name': 'test_plat'}
528
529 schd: Scheduler = scheduler(flow('one'), run_mode='live')
530 async with start(schd):
531 remote_mgr = schd.task_job_mgr.task_remote_mgr
532 mock_remote_init = Mock()
533 monkeypatch.setattr(remote_mgr, 'remote_init', mock_remote_init)
534 mock_file_install = Mock()
535 monkeypatch.setattr(remote_mgr, 'file_install', mock_file_install)
536
537 # Simulate restart remote-init has been kicked off and is being
538 # tracked via incomplete_ri_map:
539 schd.incomplete_ri_map[missing_target] = fake_platform
540
541 # REMOTE_INIT_255: retry remote_init (not file_install)
542 remote_mgr.remote_init_map[missing_target] = REMOTE_INIT_255
543 schd.manage_remote_init()
544 mock_remote_init.assert_called_once_with(fake_platform)
545 mock_file_install.assert_not_called()
546 assert missing_target in schd.incomplete_ri_map, (
547 "Install target should remain in incomplete_ri_map for tracking"
548 )
549 mock_remote_init.reset_mock()
550
551 # REMOTE_INIT_DONE: should trigger file_install (not remote_init)
552 remote_mgr.remote_init_map[missing_target] = REMOTE_INIT_DONE
553 schd.manage_remote_init()
554 mock_file_install.assert_called_once_with(fake_platform)
555 mock_remote_init.assert_not_called()
556 assert missing_target in schd.incomplete_ri_map
557 mock_file_install.reset_mock()
558
559 # REMOTE_FILE_INSTALL_255: should retry file_install (not remote_init)
560 remote_mgr.remote_init_map[missing_target] = REMOTE_FILE_INSTALL_255
561 schd.manage_remote_init()
562 mock_file_install.assert_called_once_with(fake_platform)
563 mock_remote_init.assert_not_called()
564 assert missing_target in schd.incomplete_ri_map
565 mock_file_install.reset_mock()
566
567 # REMOTE_FILE_INSTALL_DONE: should remove from ri map
568 remote_mgr.remote_init_map[missing_target] = REMOTE_FILE_INSTALL_DONE
569 schd.manage_remote_init()
570 mock_remote_init.assert_not_called()
571 mock_file_install.assert_not_called()
572 assert missing_target not in schd.incomplete_ri_map
573
574 # REMOTE_INIT_FAILED: should remove from ri map
575 schd.incomplete_ri_map[missing_target] = fake_platform
576 remote_mgr.remote_init_map[missing_target] = REMOTE_INIT_FAILED
577 schd.manage_remote_init()
578 mock_remote_init.assert_not_called()
579 mock_file_install.assert_not_called()
580 assert missing_target not in schd.incomplete_ri_map
581
582 # REMOTE_FILE_INSTALL_FAILED: should remove from ri map
583 schd.incomplete_ri_map[missing_target] = fake_platform
584 remote_mgr.remote_init_map[missing_target] = REMOTE_FILE_INSTALL_FAILED
585 schd.manage_remote_init()
586 mock_remote_init.assert_not_called()
587 mock_file_install.assert_not_called()
588 assert missing_target not in schd.incomplete_ri_map