Debian Codegraph @

tests/u/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 """Tests for Cylc scheduler server."""
17
18 import logging
19 from secrets import token_hex
20 from time import time
21 from types import SimpleNamespace
22 from typing import List
23 from unittest.mock import (
24 MagicMock,
25 Mock,
26 )
27
28 import pytest
29
30 from cylc.flow import CYLC_LOG
31 from cylc.flow.exceptions import InputError
32 from cylc.flow.scheduler import Scheduler
33 from cylc.flow.scheduler_cli import RunOptions
34 from cylc.flow.task_pool import TaskPool
35 from cylc.flow.task_proxy import TaskProxy
36 from cylc.flow.workflow_status import AutoRestartMode
37
38
39 @pytest.mark.parametrize(
40 'opts_to_test, is_restart, err_msg',
41 [
42 pytest.param(
43 ['icp', 'startcp', 'starttask'],
44 True,
45 "option --{} is not valid for restart",
46 id="start opts on restart"
47 ),
48 pytest.param(
49 ['icp', 'startcp', 'starttask'],
50 False,
51 "option --{}=reload is not valid",
52 id="start opts =reload"
53 ),
54 pytest.param(
55 ['fcp', 'stopcp'],
56 False,
57 "option --{}=reload is only valid for restart",
58 id="end opts =reload when not restart"
59 ),
60 ]
61 )
62 def test_check_startup_opts(
63 opts_to_test: List[str],
64 is_restart: bool,
65 err_msg: str
66 ) -> None:
67 """Test Scheduler._check_startup_opts()"""
68 for opt in opts_to_test:
69 mocked_scheduler = Mock(is_restart=is_restart)
70 mocked_scheduler.options = SimpleNamespace(**{opt: 'reload'})
71 with pytest.raises(InputError) as excinfo:
72 Scheduler._check_startup_opts(mocked_scheduler)
73 assert err_msg.format(opt) in str(excinfo)
74
75
76 @pytest.mark.parametrize(
77 'auto_restart_time, expected',
78 [
79 (-1, True),
80 (0, True),
81 (1, False),
82 (None, False),
83 ]
84 )
85 def test_should_auto_restart_now(
86 auto_restart_time, expected, monkeypatch: pytest.MonkeyPatch
87 ):
88 """Test Scheduler.should_auto_restart_now()."""
89 time_now = time()
90 monkeypatch.setattr('cylc.flow.scheduler.time', lambda: time_now)
91 if auto_restart_time is not None:
92 auto_restart_time += time_now
93 mock_schd = Mock(spec=Scheduler, auto_restart_time=auto_restart_time)
94 assert Scheduler.should_auto_restart_now(mock_schd) == expected
95
96
97 def test_release_tasks_to_run__auto_restart():
98 """Test that Scheduler.release_tasks_to_run() works as expected
99 during auto restart."""
100 mock_schd = MagicMock(
101 auto_restart_time=(time() - 100),
102 auto_restart_mode=AutoRestartMode.RESTART_NORMAL,
103 is_paused=False,
104 stop_mode=None,
105 pool=Mock(
106 spec=TaskPool,
107 get_tasks=lambda: [Mock(spec=TaskProxy)]
108 ),
109 workflow='parachutes',
110 options=RunOptions(),
111 task_job_mgr=MagicMock()
112 )
113 Scheduler.release_tasks_to_run(mock_schd)
114 # Should not actually release any more tasks, just submit the
115 # preparing ones
116 mock_schd.pool.release_queued_tasks.assert_not_called()
117
118 Scheduler.start_job_submission(mock_schd, mock_schd.pool.get_tasks())
119 mock_schd.submit_task_jobs.assert_called()
120
121
122 def test_auto_restart_DNS_error(mock_glbl_cfg, caplog, log_filter):
123 """Ensure that DNS errors in host selection are caught."""
124 # fake a "get address info" error
125 # this error can occur due to an unknown host resulting from broken
126 # DNS or an invalid host name in the global config
127 hostname = f'elephant_{token_hex(4)}'
128 mock_glbl_cfg(
129 'cylc.flow.host_select.glbl_cfg',
130 f'''
131 [scheduler]
132 [[run hosts]]
133 available = {hostname}
134 '''
135 )
136 schd = Mock(
137 workflow='myworkflow',
138 options=RunOptions(abort_if_any_task_fails=False),
139 INTERVAL_AUTO_RESTART_ERROR=0,
140 )
141 caplog.set_level(logging.ERROR, CYLC_LOG)
142 assert not Scheduler.workflow_auto_restart(schd, max_retries=2)
143 assert log_filter(contains=hostname)
144
145
146 def test_auto_restart_popen_error(monkeypatch, caplog, log_filter):
147 """Ensure that subprocess errors are handled."""
148 def _select_workflow_host(cached=False):
149 # mock a host-select return value
150 return ('foo', 'foo')
151
152 monkeypatch.setattr(
153 'cylc.flow.scheduler.select_workflow_host',
154 _select_workflow_host,
155 )
156
157 def _popen(*args, **kwargs):
158 # mock an auto-restart command failure
159 return Mock(
160 wait=lambda: 1,
161 communicate=lambda: ('mystdout', 'mystderr'),
162 )
163
164 monkeypatch.setattr(
165 'cylc.flow.scheduler.Popen',
166 _popen,
167 )
168
169 schd = Mock(
170 workflow='myworkflow',
171 options=RunOptions(abort_if_any_task_fails=False),
172 INTERVAL_AUTO_RESTART_ERROR=0,
173 )
174 caplog.set_level(logging.ERROR, CYLC_LOG)
175 assert not Scheduler.workflow_auto_restart(schd, max_retries=2)
176 assert log_filter(contains='mystderr')