Debian Codegraph @

tests/u/test_platforms.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 # Tests for the platform lookup.
18
19 from typing import (
20 Any,
21 Dict,
22 List,
23 Optional,
24 )
25
26 import pytest
27
28 from cylc.flow.exceptions import (
29 GlobalConfigError,
30 PlatformLookupError,
31 )
32 from cylc.flow.parsec.OrderedDict import OrderedDictWithDefaults
33 from cylc.flow.platforms import (
34 _platform_name_from_job_info,
35 _validate_single_host,
36 generic_items_match,
37 get_install_target_from_platform,
38 get_install_target_to_platforms_map,
39 get_platform,
40 get_platform_deprecated_settings,
41 is_platform_definition_subshell,
42 platform_from_name,
43 )
44 from cylc.flow.run_modes import JOBLESS_MODES
45
46
47 PLATFORMS = {
48 'desktop[0-9]{2}|laptop[0-9]{2}': {
49 'job runner': 'background'
50 },
51 'sugar': {
52 'hosts': 'localhost',
53 'job runner': 'slurm',
54 },
55 'hpc-no-logs': {
56 'hosts': ['hpc1', 'hpc2'],
57 'job runner': 'pbs',
58 'retrieve job logs': False
59 },
60 'hpc-logs': {
61 'hosts': ['hpc1', 'hpc2'],
62 'job runner': 'pbs',
63 'retrieve job logs': True
64 },
65 'hpc1-bg': {
66 'hosts': 'hpc1',
67 'job runner': 'background',
68 },
69 'hpc2-bg': {
70 'hosts': 'hpc2',
71 'job runner': 'background'
72 },
73 'localhost': {
74 'hosts': 'localhost',
75 'job runner': 'background'
76 }
77 }
78
79 PLATFORMS_NO_UNIQUE = {
80 'sugar': {
81 'hosts': 'localhost',
82 'job runner': 'slurm'
83 },
84 'pepper': {
85 'hosts': ['hpc1', 'hpc2'],
86 'job runner': 'slurm'
87 },
88
89 }
90
91 PLATFORMS_WITH_RE = {
92 'hpc.*': {'hosts': 'hpc1', 'job runner': 'background'},
93 'h.*': {'hosts': 'hpc3'},
94 r'vld\d{2,3}, anselm\d{4}': {},
95 'nu.*': {
96 'job runner': 'slurm',
97 'hosts': ['localhost']
98 },
99 'localhost': {
100 'hosts': 'localhost',
101 'job runner': 'background'
102 }
103 }
104
105 PLATFORMS_TREK = {
106 'enterprise': {
107 'hosts': ['kirk', 'picard'],
108 'install target': 'picard',
109 'name': 'enterprise'
110 },
111 'voyager': {
112 'hosts': ['janeway'],
113 'install target': 'janeway',
114 'name': 'voyager'
115 },
116 'stargazer': {
117 'hosts': ['picard'],
118 'install target': 'picard',
119 'name': 'stargazer'
120 }
121 }
122
123
124 PLATFORMS_INVALID = {
125 'enterprise': {
126 'hosts': ['kirk', 'picard'],
127 'install target': 'picard',
128 'job runner': 'background' # requires one host
129 },
130 'voyager': {
131 'hosts': ['janeway', 'seven-of-nine'],
132 'install target': 'janeway',
133 'job runner': 'at' # requires one host
134 }
135 }
136
137
138 # ----------------------------------------------------------------------------
139 # Tests of platform_from_name
140 # ----------------------------------------------------------------------------
141 @pytest.mark.parametrize(
142 "PLATFORMS, platform, expected",
143 [
144 (PLATFORMS_WITH_RE, "nutmeg", {
145 "job runner": "slurm",
146 "name": "nutmeg",
147 "hosts": ['localhost']
148 }),
149 (PLATFORMS_WITH_RE, "vld798", ["vld798"]),
150 (PLATFORMS_WITH_RE, "vld56", ["vld56"]),
151 (
152 PLATFORMS_NO_UNIQUE,
153 "sugar",
154 {
155 "hosts": "localhost",
156 "job runner": "slurm",
157 "name": "sugar"
158 },
159 ),
160 (
161 PLATFORMS,
162 None,
163 {
164 "hosts": "localhost",
165 "name": "localhost",
166 "job runner": "background"
167 },
168 ),
169 (PLATFORMS, "laptop22", {
170 "job runner": "background",
171 "name": "laptop22",
172 "hosts": ["laptop22"]
173 }),
174 (
175 PLATFORMS,
176 "hpc1-bg",
177 {
178 "hosts": "hpc1",
179 "job runner": "background",
180 "name": "hpc1-bg"
181 },
182 ),
183 (PLATFORMS_WITH_RE, "hpc2", {"hosts": "hpc3", "name": "hpc2"}),
184 ],
185 )
186 def test_basic(PLATFORMS, platform, expected):
187 # n.b. The name field of the platform is set in the Globalconfig object
188 # if the name is 'localhost', so we don't test for it here.
189 platform = platform_from_name(platform_name=platform, platforms=PLATFORMS)
190 if isinstance(expected, dict):
191 assert platform == expected
192 else:
193 assert platform["hosts"] == expected
194
195
196 def test_platform_not_there():
197 with pytest.raises(PlatformLookupError):
198 platform_from_name('moooo', PLATFORMS)
199
200
201 @pytest.mark.parametrize(
202 'platform',
203 [
204 {i: j} for i, j in PLATFORMS_INVALID.items()
205 ]
206 )
207 def test_invalid_platforms(platform):
208 with pytest.raises(GlobalConfigError):
209 _validate_single_host(platform)
210
211
212 def test_similar_but_not_exact_match():
213 with pytest.raises(PlatformLookupError):
214 platform_from_name('vld1', PLATFORMS_WITH_RE)
215
216
217 # ----------------------------------------------------------------------------
218 # Tests of platform_name_from_job_info
219 # ----------------------------------------------------------------------------
220 # Basic tests that we can select sensible platforms
221 @pytest.mark.parametrize(
222 'job, remote, returns',
223 [
224 # Can we return a sensible platform for desktop 42
225 (
226 {},
227 {'host': 'desktop42'},
228 'desktop42'
229 ),
230
231 # Basic test where the user hasn't submitted anything and the task
232 # returns to default, i.e. localhost.
233 (
234 {'batch system': 'background'},
235 {'retrieve job logs retry delays': None},
236 'localhost'
237 ),
238 # Check that when the user asks for batch system = slurm alone
239 # they get system = sugar
240 (
241 {'batch system': 'slurm'},
242 {'host': ''},
243 'sugar'
244 ),
245 # Check that when users asks for hpc1 and pbs they get a platform
246 # with hpc1 in its list of hosts
247 (
248 {'batch system': 'pbs'},
249 {'host': 'hpc1'},
250 'hpc-logs'
251 ),
252 # When the user asks for hpc1 without specifying pbs user gets platform
253 # hpc bg1
254 (
255 {'batch system': 'background'},
256 {'host': 'hpc1'},
257 'hpc1-bg'
258 ),
259 # Check that None as a value is handled correctly
260 (
261 {'batch system': None},
262 {'host': 'hpc1-bg'},
263 'hpc1-bg'
264 ),
265 (
266 # Check that failure to set any items will return localhost
267 {'batch system': None},
268 {'host': None},
269 'localhost'
270 ),
271 (
272 # Check that all generic items are matched
273 {'batch system': 'pbs'},
274 {'host': 'hpc1', 'retrieve job logs': False},
275 'hpc-no-logs'
276 ),
277 ]
278 )
279 def test_platform_name_from_job_info_basic(job, remote, returns):
280 assert _platform_name_from_job_info(PLATFORMS, job, remote) == returns
281
282
283 def test_platform_name_from_job_info_evaluated_hostname():
284 result = _platform_name_from_job_info(
285 PLATFORMS,
286 {'batch system': 'background'},
287 {'host': '$(cat tiddles)'},
288 evaluated_host='hpc2',
289 )
290 assert result == 'hpc2-bg'
291
292
293 def test_platform_name_from_job_info_ordered_dict_comparison():
294 """Check that we are only comparing set items in OrderedDictWithDefaults.
295 """
296 job = {'batch system': 'background', 'Made up key': 'Zaphod'}
297 remote = {'host': 'hpc1', 'Made up key': 'Arthur'}
298 # Set up a fake OrderedDictWith a fake unset default.
299 platform = OrderedDictWithDefaults()
300 platform.defaults_ = {k: None for k in PLATFORMS['hpc1-bg'].keys()}
301 platform.defaults_['Made up key'] = {}
302 platform.update(PLATFORMS['hpc1-bg'])
303 platforms = {'hpc1-bg': platform, 'dobbie': PLATFORMS['sugar']}
304 assert _platform_name_from_job_info(platforms, job, remote) == 'hpc1-bg'
305
306
307 # Cases where the error ought to be raised because no matching platform should
308 # be found.
309 @pytest.mark.parametrize(
310 'job, remote',
311 [
312 # Check for error when the user asks for slurm on host desktop01
313 (
314 {'batch system': 'slurm'},
315 {'host': 'desktop01'},
316 ),
317 # ('hpc1', 'slurm', 'error'),
318 (
319 {'batch system': 'slurm'},
320 {'host': 'hpc1'},
321 ),
322 # Localhost doesn't support pbs
323 (
324 {'batch system': 'pbs'},
325 {},
326 ),
327 ]
328 )
329 def test_reverse_PlatformLookupError(job, remote):
330 with pytest.raises(PlatformLookupError):
331 _platform_name_from_job_info(PLATFORMS, job, remote)
332
333
334 # An example of a global config with two Spice systems available
335 @pytest.mark.parametrize(
336 'job, remote, returns',
337 [
338 (
339 {'batch system': 'slurm'},
340 {'host': 'sugar'},
341 'sugar'
342 ),
343 (
344 {'batch system': 'slurm'},
345 {},
346 'sugar'
347 ),
348 (
349 {'batch system': 'slurm'},
350 {'host': 'pepper'},
351 'pepper'
352 )
353 ]
354 )
355 def test_platform_name_from_job_info_two_spices(
356 job, remote, returns
357 ):
358 platforms = {
359 'sugar': {
360 'hosts': ['sugar', 'localhost'],
361 'job runner': 'slurm',
362 },
363 'pepper': {
364 'job runner': 'slurm',
365 'hosts': 'pepper'
366 },
367
368 }
369 assert _platform_name_from_job_info(platforms, job, remote) == returns
370
371
372 # An example of two platforms with the same hosts and job runner settings
373 # but some other setting different
374 @pytest.mark.parametrize(
375 'job, remote, returns',
376 [
377 (
378 {
379 'job runner': 'background',
380 'job runner command template': '',
381 'shell': '/bin/fish'
382 },
383 {
384 'host': 'desktop01',
385 'owner': '',
386 'workflow definition directory': '',
387 'retrieve job logs': '',
388 'retrieve job logs max size': '',
389 'retrieve job logs retry delays': 'None'
390 },
391 'my-platform-with-fish'
392 ),
393 ]
394 )
395 def test_platform_name_from_job_info_similar_platforms(
396 job, remote, returns
397 ):
398 platforms = {
399 'my-platform-with-bash': {
400 'hosts': 'desktop01',
401 'shell': '/bin/bash',
402 'job runner': 'background'
403 },
404 # An extra platform to check that we only pick up the first match
405 'my-platform-with-fish-not-this-one': {
406 'hosts': 'desktop01',
407 'shell': '/bin/fish',
408 'job runner': 'background'
409 },
410 'my-platform-with-fish': {
411 'hosts': 'desktop01',
412 'shell': '/bin/fish',
413 'job runner': 'background'
414 },
415 }
416 assert _platform_name_from_job_info(platforms, job, remote) == returns
417
418
419 # -----------------------------------------------------------------------------
420 # Tests for getting install target info
421
422 @pytest.mark.parametrize(
423 'platform, expected',
424 [
425 ({'name': 'rick', 'install target': 'desktop'}, 'desktop'),
426 ({'name': 'morty', 'install target': ''}, 'morty')
427 ]
428 )
429 def test_get_install_target_from_platform(platform, expected):
430 """Test that get_install_target_from_platform works as expected."""
431 assert get_install_target_from_platform(platform) == expected
432
433
434 @pytest.mark.parametrize(
435 'platform_names, expected_map',
436 [
437 (
438 ['enterprise', 'stargazer'],
439 {
440 'picard': [
441 PLATFORMS_TREK['enterprise'],
442 PLATFORMS_TREK['stargazer']
443 ]
444 },
445 ),
446 (
447 ['enterprise', 'voyager', 'enterprise'],
448 {
449 'picard': [
450 PLATFORMS_TREK['enterprise']
451 ],
452 'janeway': [
453 PLATFORMS_TREK['voyager']
454 ]
455 },
456 ),
457 (
458 ['enterprise', 'starkiller'], # ignores non-existent platform
459 {
460 'picard': [
461 PLATFORMS_TREK['enterprise']
462 ],
463 },
464 ),
465 ]
466 )
467 def test_get_install_target_to_platforms_map(
468 platform_names: list[str],
469 expected_map: dict[str, Any],
470 monkeypatch: pytest.MonkeyPatch,
471 ):
472 """Test that get_install_target_to_platforms_map works as expected."""
473 monkeypatch.setattr('cylc.flow.platforms.platform_from_name',
474 lambda x: platform_from_name(x, PLATFORMS_TREK))
475
476 result = get_install_target_to_platforms_map(platform_names)
477 # Sort the maps:
478 for _map in (result, expected_map):
479 for install_target in _map:
480 _map[install_target] = sorted(
481 _map[install_target], key=lambda k: k['name']
482 )
483 assert result == expected_map
484
485
486 @pytest.mark.parametrize('mode', sorted(JOBLESS_MODES))
487 def test_platform_from_name__jobless_modes(mode):
488 result = platform_from_name(mode)
489 assert result['name'] == 'localhost'
490
491
492 @pytest.mark.parametrize('mode', sorted(JOBLESS_MODES))
493 def test_get_install_target_to_platforms_map__jobless_modes(mode):
494 result = get_install_target_to_platforms_map([mode])
495 assert list(result) == ['localhost']
496 assert len(result['localhost']) == 1
497 assert result['localhost'][0]['hosts'] == ['localhost']
498 assert result['localhost'][0]['install target'] == 'localhost'
499
500
501 @pytest.mark.parametrize(
502 'platform, job, remote, expect',
503 [
504 (
505 # Default, no old settings.
506 {'ship': 'Enterprise'}, {}, {}, True
507 ),
508 (
509 {'captain': 'Kirk'},
510 {'captain': 'Picard'},
511 {},
512 False
513 ),
514 (
515 {'captain': 'Sisko'},
516 {},
517 {'captain': 'Janeway'},
518 False
519 ),
520 (
521 {'captain': 'Picard', 'ship': 'Enterprise'},
522 {'captain': 'Picard'},
523 {'ship': 'Enterprise'},
524 True
525 ),
526 (
527 {'captain': 'Picard', 'ship': 'Enterprise'},
528 {'captain': 'Picard'},
529 {'ship': 'Defiant'},
530 False
531 ),
532 (
533 {'captain': 'Picard', 'ship': 'Enterprise'},
534 {'captain': 'Picard'},
535 {},
536 True
537 )
538 ]
539 )
540 def test_generic_items_match(platform, job, remote, expect):
541 assert generic_items_match(platform, job, remote) == expect
542
543
544 @pytest.mark.parametrize(
545 'task_conf, expected',
546 [
547 pytest.param(
548 {
549 'remote': {
550 'host': 'cylcdevbox',
551 'retrieve job logs': True
552 },
553 'job': {
554 'batch system': 'pbs',
555 'batch submit command template': 'meow'
556 }
557 },
558 [
559 '[runtime][task][job]batch submit command template = meow',
560 '[runtime][task][remote]retrieve job logs = True',
561 '[runtime][task][remote]host = cylcdevbox',
562 '[runtime][task][job]batch system = pbs'
563 ],
564 id="All are deprecated settings"
565 ),
566 pytest.param(
567 {
568 'remote': {'host': 'localhost'},
569 'job': {
570 'batch system': 'pbs',
571 'batch submit command template': None
572 }
573 },
574 ['[runtime][task][job]batch system = pbs'],
575 id="Exclusions are excluded"
576 ),
577 pytest.param(
578 {
579 'environment filter': {
580 'include': ['frodo', 'sam']
581 }
582 },
583 [],
584 id="No deprecated settings"
585 )
586 ]
587 )
588 def test_get_platform_deprecated_settings(
589 task_conf: Dict[str, Any], expected: List[str]
590 ):
591 output = get_platform_deprecated_settings(task_conf, task_name='task')
592 assert set(output) == set(expected)
593
594
595 @pytest.mark.parametrize(
596 'plat_val, expected, err_msg',
597 [('normal', False, None),
598 ('$(yes)', True, None),
599 ('`echo ${chamber}`', None, "backticks are not supported")]
600 )
601 def test_is_platform_definition_subshell(
602 plat_val: str, expected: Optional[bool], err_msg: Optional[str]):
603 if err_msg:
604 with pytest.raises(PlatformLookupError) as exc:
605 is_platform_definition_subshell(plat_val)
606 assert err_msg in str(exc.value)
607 else:
608 assert is_platform_definition_subshell(plat_val) is expected
609
610
611 def test_get_platform_from_OrderedDictWithDefaults(mock_glbl_cfg):
612 """Get platform works with OrderedDictWithDefaults.
613
614 Most tests use dictionaries to check platforms functionality.
615 This one was added to catch an issue where the behaviour of
616 dict.get != OrderedDictWithDefaults.get.
617 See - https://github.com/cylc/cylc-flow/issues/4979
618 """
619 mock_glbl_cfg(
620 'cylc.flow.platforms.glbl_cfg',
621 '''
622 [platforms]
623 [[skarloey]]
624 hosts = foo, bar
625 job runner = slurm
626 '''
627 )
628 task_conf = OrderedDictWithDefaults()
629 task_conf.defaults_ = OrderedDictWithDefaults([
630 ('job', OrderedDictWithDefaults([
631 ('batch system', 'slurm')
632 ])),
633 ('remote', OrderedDictWithDefaults([
634 ('host', 'foo')
635 ])),
636 ])
637 result = get_platform(task_conf)['name']
638 assert result == 'skarloey'