Debian Codegraph @

tests/unit/test_task_remote_mgr.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 from contextlib import suppress
18 from pathlib import Path
19 from time import sleep
20 import pytest
21 from typing import (Any, Optional)
22 from unittest.mock import MagicMock, Mock
23
24 from cylc.flow.exceptions import PlatformError
25 from cylc.flow.network.client_factory import CommsMeth
26 from cylc.flow.task_remote_mgr import (
27 REMOTE_FILE_INSTALL_DONE, REMOTE_INIT_IN_PROGRESS, TaskRemoteMgr)
28 from cylc.flow.workflow_files import WorkflowFiles, get_workflow_srv_dir
29
30
31 Fixture = Any
32
33
34 @pytest.mark.parametrize(
35 'comms_meth, expected',
36 [
37 (CommsMeth.SSH, True),
38 (CommsMeth.ZMQ, True),
39 (CommsMeth.POLL, False)
40 ]
41 )
42 def test__remote_init_items(comms_meth: CommsMeth, expected: bool):
43 """Test _remote_init_items().
44
45 Should only includes files under .service/
46 """
47 id_ = 'barclay'
48 mock_mgr = Mock(workflow=id_)
49 srv_dir = get_workflow_srv_dir(id_)
50 items = TaskRemoteMgr._remote_init_items(mock_mgr, comms_meth)
51 if expected:
52 assert items
53 for src_path, dst_path in items:
54 Path(src_path).relative_to(srv_dir)
55 Path(dst_path).relative_to(WorkflowFiles.Service.DIRNAME)
56 else:
57 assert not items
58
59
60 @pytest.mark.parametrize(
61 'install_target, skip_expected, expected_status',
62 [('localhost', True, REMOTE_FILE_INSTALL_DONE),
63 ('something_else', False, REMOTE_INIT_IN_PROGRESS)]
64 )
65 def test_remote_init_skip(
66 install_target: str, skip_expected: bool, expected_status: str,
67 monkeypatch: Fixture):
68 """Test the TaskRemoteMgr.remote_init() skips localhost install target.
69
70 Params:
71 install_target: The platform's install target.
72 skip_expected: Whether remote init is expected to be skipped.
73 expected_status: The expected value of
74 TaskRemoteMgr.remote_init_map[install_target].
75 """
76 platform = {
77 'install target': install_target,
78 'communication method': CommsMeth.POLL,
79 'hosts': ['localhost'],
80 'selection': {'method': 'random'},
81 'name': 'foo'
82 }
83 mock_task_remote_mgr = MagicMock(remote_init_map={}, bad_hosts=[])
84 mock_construct_ssh_cmd = Mock()
85 monkeypatch.setattr('cylc.flow.task_remote_mgr.construct_ssh_cmd',
86 mock_construct_ssh_cmd)
87 for item in (
88 'tarfile',
89 'get_remote_workflow_run_dir',
90 'get_dirs_to_symlink'):
91 monkeypatch.setattr(f'cylc.flow.task_remote_mgr.{item}', MagicMock())
92
93 TaskRemoteMgr.remote_init(mock_task_remote_mgr, platform)
94 call_expected = not skip_expected
95 assert mock_task_remote_mgr._remote_init_items.called is call_expected
96 assert mock_construct_ssh_cmd.called is call_expected
97 assert mock_task_remote_mgr.proc_pool.put_command.called is call_expected
98 status = mock_task_remote_mgr.remote_init_map[install_target]
99 assert status == expected_status
100
101
102 @pytest.mark.parametrize(
103 'install_target, load_type, expected',
104 [
105 ('install_target', None, '03-start-install_target.log'),
106 ('some_install_target',
107 'restart',
108 '03-restart-some_install_target.log'),
109 ('another_install_target',
110 'reload',
111 '03-reload-another_install_target.log')
112 ]
113 )
114 def test_get_log_file_name(tmp_path: Path,
115 install_target: str,
116 load_type: Optional[str],
117 expected: str):
118 task_remote_mgr = TaskRemoteMgr('some_workflow', None, None, None, None)
119 if load_type == 'restart':
120 task_remote_mgr.is_restart = True
121 elif load_type == 'reload':
122 task_remote_mgr.is_reload = True
123 # else load type is start (no flag required)
124 run_dir = tmp_path
125 log_dir = run_dir / 'some_workflow' / 'log' / 'remote-install'
126 log_dir.mkdir(parents=True)
127 for log_num in range(1, 3):
128 Path(f"{log_dir}/{log_num:02d}-start-{install_target}.log").touch()
129 sleep(0.1)
130 log_name = task_remote_mgr.get_log_file_name(
131 install_target, install_log_dir=log_dir)
132 assert log_name == expected
133
134
135 @pytest.mark.parametrize(
136 'platform_names, install_targets, glblcfg, expect',
137 [
138 pytest.param(
139 # Two platforms share an install target. Both are reachable.
140 ['sir_handel', 'peter_sam'],
141 ['mountain_railway'],
142 '''
143 [platforms]
144 [[peter_sam, sir_handel]]
145 install target = mountain_railway
146 ''',
147 {
148 'targets': {'mountain_railway': ['peter_sam', 'sir_handel']},
149 'unreachable': set()
150 },
151 id='basic'
152 ),
153 pytest.param(
154 # Two platforms share an install target. Both are unreachable.
155 set(),
156 ['mountain_railway'],
157 '''
158 [platforms]
159 [[peter_sam, sir_handel]]
160 install target = mountain_railway
161 ''',
162 {
163 'targets': {'mountain_railway': []},
164 'unreachable': {'mountain_railway'}
165 },
166 id='platform_unreachable'
167 ),
168 pytest.param(
169 # One of our install targets matches one of our platforms,
170 # but only implicitly; i.e. the platform name is the same as the
171 # install target name.
172 ['sir_handel'],
173 ['sir_handel'],
174 '''
175 [platforms]
176 [[sir_handel]]
177 ''',
178 {
179 'targets': {'sir_handel': ['sir_handel']},
180 'unreachable': set()
181 },
182 id='implicit-target'
183 ),
184 pytest.param(
185 # One of our install targets matches one of our platforms,
186 # but only implicitly, and the platform name is defined using a
187 # regex.
188 ['sir_handel42'],
189 ['sir_handel42'],
190 '''
191 [platforms]
192 [[sir_handel..]]
193 ''',
194 {
195 'targets': {'sir_handel42': ['sir_handel42']},
196 'unreachable': set()
197 },
198 id='implicit-target-regex'
199 ),
200 pytest.param(
201 # One of our install targets (rusty) has no defined platforms
202 # causing a PlatformLookupError.
203 ['duncan', 'rusty'],
204 ['mountain_railway', 'rusty'],
205 '''
206 [platforms]
207 [[duncan]]
208 install target = mountain_railway
209 ''',
210 {
211 'targets': {'mountain_railway': ['duncan']},
212 'unreachable': {'rusty'}
213 },
214 id='PlatformLookupError'
215 )
216 ]
217 )
218 def test_map_platforms_used_for_install_targets(
219 mock_glbl_cfg,
220 platform_names, install_targets, glblcfg, expect, caplog
221 ):
222 def flatten_install_targets_map(itm):
223 result = {}
224 for target, platforms in itm.items():
225 result[target] = sorted([p['name'] for p in platforms])
226 return result
227
228 mock_glbl_cfg('cylc.flow.platforms.glbl_cfg', glblcfg)
229
230 install_targets_map = TaskRemoteMgr._get_remote_tidy_targets(
231 set(platform_names), set(install_targets))
232
233 with suppress(KeyError):
234 install_targets_map.pop('localhost')
235
236 assert (
237 expect['targets'] == flatten_install_targets_map(install_targets_map))
238
239 if expect['unreachable']:
240 for unreachable in expect["unreachable"]:
241 assert (
242 unreachable in caplog.records[0].msg)
243 else:
244 assert not caplog.records
245
246
247 shared_eval_params = [
248 pytest.param(
249 'localhost', {}, 'localhost', id="localhost"
250 ),
251 pytest.param(
252 '$(some-cmd)', {}, None, id="subshell_1st_eval"
253 ),
254 pytest.param(
255 '$(some-cmd)', {'some-cmd': None}, None,
256 id="subshell_awaiting_eval"
257 ),
258 pytest.param(
259 '$(some-cmd)', {'some-cmd': 'isaac clarke'}, 'isaac clarke',
260 id="subshell_finished_eval"
261 ),
262 pytest.param(
263 '$SOME_ENV', {}, 'nolan stross', id="env_var"
264 ),
265 pytest.param(
266 '$(env-cmd)', {'env-cmd': '$SOME_ENV'}, 'nolan stross',
267 id="subshell_env_var"
268 ),
269 pytest.param(
270 'titan_station', {}, 'titan_station', id="verbatim_name"
271 ),
272 pytest.param(
273 '', {}, 'localhost', id="empty"
274 ),
275 ]
276
277
278 @pytest.fixture
279 def task_remote_mgr_eval(monkeypatch: pytest.MonkeyPatch):
280 """Fixture providing a task remote manager for eval_platform() &
281 eval_host() tests."""
282 def _task_remote_mgr_eval(remote_cmd_map: dict) -> TaskRemoteMgr:
283 monkeypatch.setenv('SOME_ENV', 'nolan stross')
284 task_remote_mgr = TaskRemoteMgr(
285 workflow='usg_ishimura',
286 proc_pool=Mock(),
287 bad_hosts=[],
288 db_mgr=None,
289 server=None
290 )
291 task_remote_mgr.remote_command_map = remote_cmd_map
292 return task_remote_mgr
293
294 return _task_remote_mgr_eval
295
296
297 @pytest.mark.parametrize(
298 'eval_str, remote_cmd_map, expected',
299 [
300 *shared_eval_params,
301 pytest.param(
302 'localhost_tau_volantis', {}, 'localhost_tau_volantis',
303 id="name_begin_w_localhost"
304 )
305 ]
306 )
307 def test_eval_platform(
308 eval_str: str, remote_cmd_map: dict, expected: Optional[str],
309 task_remote_mgr_eval,
310 ):
311 task_remote_mgr: TaskRemoteMgr = task_remote_mgr_eval(remote_cmd_map)
312 assert task_remote_mgr.eval_platform(eval_str) == expected
313
314
315 def test_eval_platform_bad(task_remote_mgr_eval):
316 exc_msg = "foreign contaminant detected"
317 task_remote_mgr: TaskRemoteMgr = task_remote_mgr_eval(
318 {'cmd': PlatformError(exc_msg, 'aegis_vii')}
319 )
320 with pytest.raises(PlatformError, match=exc_msg):
321 task_remote_mgr.eval_platform('$(cmd)')
322
323
324 @pytest.mark.parametrize(
325 'eval_str, remote_cmd_map, expected',
326 [
327 *shared_eval_params,
328 pytest.param(
329 'localhost4.localdomain4', {}, 'localhost', id="localhost_variant"
330 ),
331 pytest.param(
332 '`other cmd`', {'other cmd': 'nicole brennan'}, 'nicole brennan',
333 id="backticks"
334 ),
335 ]
336 )
337 def test_eval_host(
338 eval_str: str, remote_cmd_map: dict, expected: Optional[str],
339 task_remote_mgr_eval,
340 ):
341 task_remote_mgr: TaskRemoteMgr = task_remote_mgr_eval(remote_cmd_map)
342 assert task_remote_mgr.eval_host(eval_str) == expected