Debian Codegraph @

tests/i/network/test_scan.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 """Test file-system interaction aspects of scan functionality."""
17
18 from contextlib import suppress
19 from pathlib import Path
20 import re
21 from shutil import rmtree
22 from tempfile import TemporaryDirectory
23 from typing import List
24
25 import pytest
26
27 from cylc.flow.network.scan import (
28 filter_name,
29 graphql_query,
30 is_active,
31 scan,
32 scan_multi,
33 workflow_params,
34 )
35 from cylc.flow.workflow_db_mgr import WorkflowDatabaseManager
36 from cylc.flow.workflow_files import WorkflowFiles
37
38
39 SRV_DIR = Path(WorkflowFiles.Service.DIRNAME)
40 CONTACT = Path(WorkflowFiles.Service.CONTACT)
41 RUN_N = Path(WorkflowFiles.RUN_N)
42 INSTALL = Path(WorkflowFiles.Install.DIRNAME)
43
44
45 def init_flows(tmp_run_path=None, running=None, registered=None,
46 un_registered=None, tmp_src_path=None, src=None):
47 """Create some dummy workflows for scan to discover.
48
49 Assume "run1, run2, ..., runN" structure if flow name constains "run".
50 Optionally create workflow source dirs in a give location too.
51
52 """
53 def make_registered(name, running=False):
54 run_d = Path(tmp_run_path, name)
55 run_d.mkdir(parents=True, exist_ok=True)
56 (run_d / "flow.cylc").touch()
57 if "run" in name:
58 root = Path(tmp_run_path, name).parent
59 with suppress(FileExistsError):
60 (root / "runN").symlink_to(run_d, target_is_directory=True)
61 else:
62 root = run_d
63 (root / INSTALL).mkdir(parents=True, exist_ok=True)
64 srv_d = (run_d / SRV_DIR)
65 srv_d.mkdir(parents=True, exist_ok=True)
66 if running:
67 (srv_d / CONTACT).touch()
68
69 def make_src(name):
70 src_d = Path(tmp_src_path, name)
71 src_d.mkdir(parents=True, exist_ok=True)
72 (src_d / "flow.cylc").touch()
73
74 for name in (running or []):
75 make_registered(name, running=True)
76 for name in (registered or []):
77 make_registered(name)
78 for name in (un_registered or []):
79 Path(tmp_run_path, name).mkdir(parents=True, exist_ok=True)
80 for name in (src or []):
81 make_src(name)
82
83
84 @pytest.fixture(scope='session')
85 def sample_run_dir():
86 tmp_path = Path(TemporaryDirectory().name)
87 tmp_path.mkdir()
88 init_flows(
89 tmp_path,
90 running=('foo', 'bar/pub', 'cheese/run2'),
91 registered=('baz', 'cheese/run1'),
92 un_registered=('qux',)
93 )
94 yield tmp_path
95 rmtree(tmp_path)
96
97
98 @pytest.fixture
99 def badly_messed_up_cylc_run_dir(
100 tmp_path: Path,
101 monkeypatch: pytest.MonkeyPatch
102 ) -> Path:
103 monkeypatch.setattr('cylc.flow.pathutil._CYLC_RUN_DIR', tmp_path)
104 # one regular workflow
105 init_flows(
106 tmp_path,
107 running=('foo',)
108 )
109 # and an erroneous service dir at the top level for no reason
110 Path(tmp_path, SRV_DIR).mkdir()
111 return tmp_path
112
113
114 @pytest.fixture(scope='session')
115 def run_dir_with_symlinks():
116 tmp_path = Path(TemporaryDirectory().name)
117 tmp_path.mkdir()
118 # one regular workflow
119 init_flows(
120 tmp_path,
121 running=('foo',)
122 )
123 # one symlinked workflow
124 tmp_path2 = Path(TemporaryDirectory().name)
125 tmp_path2.mkdir()
126 init_flows(
127 tmp_path2,
128 # make it nested to prove that the link is followed
129 running=('bar/baz',)
130 )
131 Path(tmp_path, 'bar').symlink_to(Path(tmp_path2, 'bar'))
132 yield tmp_path
133 rmtree(tmp_path)
134
135
136 @pytest.fixture(scope='session')
137 def run_dir_with_nasty_symlinks():
138 tmp_path = Path(TemporaryDirectory().name)
139 tmp_path.mkdir()
140 # one regular workflow
141 init_flows(
142 tmp_path,
143 running=('foo',)
144 )
145 # and a symlink pointing back at it in the same dir
146 Path(tmp_path, 'bar').symlink_to(Path(tmp_path, 'foo'))
147 yield tmp_path
148 rmtree(tmp_path)
149
150
151 @pytest.fixture(scope='session')
152 def nested_dir():
153 tmp_path = Path(TemporaryDirectory().name)
154 tmp_path.mkdir()
155 init_flows(
156 tmp_path,
157 running=('a', 'b/c', 'd/e/f', 'g/h/i/j'),
158 )
159 yield tmp_path
160 rmtree(tmp_path)
161
162
163 @pytest.fixture
164 def source_dirs(mock_glbl_cfg):
165 src = Path(TemporaryDirectory().name)
166 src.mkdir()
167 src1 = src / '1'
168 src1.mkdir()
169 init_flows(
170 tmp_src_path=src1,
171 src=('a', 'b/c')
172 )
173 src2 = src / '2'
174 src2.mkdir()
175 init_flows(
176 tmp_src_path=src2,
177 src=('d', 'e/f')
178 )
179 mock_glbl_cfg(
180 'cylc.flow.scripts.scan.glbl_cfg',
181 f'''
182 [install]
183 source dirs = {src1}, {src2}
184 '''
185 )
186 yield [src1, src2]
187 rmtree(src)
188
189
190 async def listify(async_gen, field='name'):
191 """Convert an async generator into a list."""
192 ret = []
193 async for item in async_gen:
194 ret.append(item[field])
195 ret.sort()
196 return ret
197
198
199 async def test_scan(sample_run_dir):
200 """It should list all flows."""
201 assert await listify(
202 scan(sample_run_dir)
203 ) == [
204 'bar/pub',
205 'baz',
206 'cheese/run1',
207 'cheese/run2',
208 'foo'
209 ]
210
211
212 async def test_scan_with_files(sample_run_dir):
213 """It shouldn't be perturbed by arbitrary files."""
214 Path(sample_run_dir, 'abc').touch()
215 Path(sample_run_dir, 'def').touch()
216 assert await listify(
217 scan(sample_run_dir)
218 ) == [
219 'bar/pub',
220 'baz',
221 'cheese/run1',
222 'cheese/run2',
223 'foo',
224 ]
225
226
227 async def test_scan_horrible_mess(badly_messed_up_cylc_run_dir):
228 """It shouldn't be affected by erroneous cylc files/dirs.
229
230 How could you end up with a .service dir in ~/cylc-run? Well misuse of
231 Cylc7 can result in this situation so this test ensures Cylc7 workflows
232 can't mess up a Cylc8 scan.
233
234 """
235 assert await listify(
236 scan(badly_messed_up_cylc_run_dir)
237 ) == [
238 'foo'
239 ]
240
241
242 async def test_scan_symlinks(run_dir_with_symlinks):
243 """It should follow symlinks to flows in other dirs."""
244 assert await listify(
245 scan(run_dir_with_symlinks)
246 ) == [
247 'bar/baz',
248 'foo'
249 ]
250
251
252 async def test_scan_nasty_symlinks(run_dir_with_nasty_symlinks):
253 """It should handle strange symlinks because users can be nasty."""
254 assert await listify(
255 scan(run_dir_with_nasty_symlinks)
256
257 ) == [
258 'bar', # well you got what you asked for
259 'foo'
260 ]
261
262
263 async def test_scan_non_exist(tmp_path: Path):
264 """Calling scan() on a scan_dir that doesn't exist should not raise."""
265 assert await listify(
266 scan(scan_dir=(tmp_path / 'HORSE'))
267 ) == []
268
269
270 async def test_is_active(sample_run_dir):
271 """It should filter flows by presence of a contact file."""
272 # running flows
273 assert await is_active.func(
274 {'path': sample_run_dir / 'foo'},
275 True
276 )
277 assert await is_active.func(
278 {'path': sample_run_dir / 'bar/pub'},
279 True
280 )
281 # registered flows
282 assert not await is_active.func(
283 {'path': sample_run_dir / 'baz'},
284 True
285 )
286 # unregistered flows
287 assert not await is_active.func(
288 {'path': sample_run_dir / 'qux'},
289 True
290 )
291 # non-existent flows
292 assert not await is_active.func(
293 {'path': sample_run_dir / 'elephant'},
294 True
295 )
296
297
298 @pytest.mark.parametrize(
299 'depth, expected',
300 [
301 (1, ['a']),
302 (3, ['a', 'b/c', 'd/e/f'])
303 ]
304 )
305 async def test_max_depth(nested_dir, depth: int, expected: List[str]):
306 """It should descend only as far as permitted."""
307 assert await listify(
308 scan(nested_dir, max_depth=depth)
309 ) == expected
310
311
312 async def test_max_depth_configurable(nested_dir, mock_glbl_cfg):
313 """Default scan depth should be configurable in global.cylc."""
314 mock_glbl_cfg(
315 'cylc.flow.network.scan.glbl_cfg',
316 '''
317 [install]
318 max depth = 2
319 '''
320 )
321 assert await listify(
322 scan(nested_dir)
323 ) == [
324 'a',
325 'b/c',
326 ]
327
328
329 async def test_scan_one(one, start, test_dir):
330 """Ensure that a running workflow appears in the scan results."""
331 async with start(one):
332 pipe = (
333 # scan just this workflow
334 scan(scan_dir=test_dir)
335 | filter_name(rf'^{re.escape(one.workflow)}$')
336 | is_active(True)
337 | workflow_params
338 )
339 async for flow in pipe:
340 assert flow['name'] == one.workflow
341 break
342 else:
343 raise Exception('Expected one scan result')
344
345
346 async def test_workflow_params(
347 one,
348 start,
349 one_conf,
350 run_dir,
351 mod_test_dir
352 ):
353 """It should extract workflow params from the workflow database.
354
355 Note:
356 For this test we ensure that the workflow UUID is present in the params
357 table.
358 """
359 async with start(one):
360 pipe = (
361 # scan just this workflow
362 scan(scan_dir=mod_test_dir)
363 | filter_name(rf'^{re.escape(one.workflow)}$')
364 | is_active(True)
365 | workflow_params
366 )
367 async for flow in pipe:
368 # check the workflow_params field has been provided
369 assert 'workflow_params' in flow
370 # check the workflow uuid key has been read from the DB
371 uuid_key = WorkflowDatabaseManager.KEY_UUID_STR
372 assert uuid_key in flow['workflow_params']
373 # check the workflow uuid key matches the scheduler value
374 assert flow['workflow_params'][uuid_key] == one.uuid_str
375 break
376 else:
377 raise Exception('Expected one scan result')
378
379
380 async def test_source_dirs(source_dirs):
381 """It should list uninstalled workflows from configured source dirs."""
382 src1, src2 = source_dirs
383 assert await listify(
384 scan_multi(source_dirs, max_depth=3)
385 ) == [
386 # NOTE: flow names from scan_multi are full paths
387 (src1 / 'a'),
388 (src1 / 'b/c'),
389 (src2 / 'd'),
390 (src2 / 'e/f'),
391 ]
392
393
394 async def test_scan_sigstop(
395 flow,
396 scheduler,
397 start,
398 one_conf,
399 test_dir,
400 caplog,
401 ):
402 """It should log warnings if workflows are un-contactable.
403
404 Note:
405 This replaces tests/functional/cylc-scan/02-sigstop.t
406 last found in Cylc Flow 8.0a2 which used sigstop to make the flow
407 unresponsive.
408
409 """
410 # run a workflow
411 id_ = flow(one_conf)
412 schd = scheduler(id_)
413 async with start(schd):
414 # stop the server to make the flow un-responsive
415 await schd.server.stop('make-unresponsive')
416 # try scanning the workflow
417 pipe = scan(test_dir) | graphql_query(['status'])
418 caplog.clear()
419 async for flow in pipe:
420 raise Exception("There shouldn't be any scan results")
421 # there should, however, be a warning
422 name = Path(id_).name
423 assert (
424 (30, f'Workflow not running: {name}')
425 in [(level, msg) for _, level, msg in caplog.record_tuples]
426 )
427
428
429 @pytest.fixture
430 def cylc7_run_dir(tmp_path):
431 """A run directory containing three Cylc 7 workflows."""
432 # a workflow that has not yet been run
433 # (could be run by either cylc 7 or 8 so should appear in scan results)
434 either = tmp_path / 'either'
435 either.mkdir()
436 (either / WorkflowFiles.SUITE_RC).touch()
437
438 # a Cylc 7 workflow that has been / is being run by Cylc 7
439 # (should not appear in scan results)
440 cylc7 = tmp_path / 'cylc7'
441 cylc7.mkdir()
442 (cylc7 / WorkflowFiles.SUITE_RC).touch()
443 Path(cylc7, WorkflowFiles.LogDir.DIRNAME, 'suite').mkdir(parents=True)
444 Path(cylc7, WorkflowFiles.LogDir.DIRNAME, 'suite', 'log').touch()
445
446 # a Cylc 7 workflow running under Cylc 8 in compatibility mode
447 # (should appear in scan results)
448 cylc8 = tmp_path / 'cylc8'
449 cylc8.mkdir()
450 (cylc8 / WorkflowFiles.SUITE_RC).touch()
451 Path(cylc8, WorkflowFiles.LogDir.DIRNAME, 'scheduler').mkdir(parents=True)
452 Path(cylc8, WorkflowFiles.LogDir.DIRNAME, 'scheduler', 'log').touch()
453
454 # a Cylc 7 workflow installed by Cylc 8 but not run yet.
455 # (should appear in scan results)
456 cylc8a = tmp_path / 'cylc8a'
457 cylc8a.mkdir()
458 (cylc8a / WorkflowFiles.SUITE_RC).touch()
459 Path(cylc8a, WorkflowFiles.LogDir.DIRNAME, 'install').mkdir(parents=True)
460
461 # crazy niche case of a Cylc 7 workflow that has had its DB removed
462 # and re-run under Cylc 8
463 # (should appear in scan results)
464 cylc8 = tmp_path / 'cylc78'
465 cylc8.mkdir()
466 (cylc8 / WorkflowFiles.SUITE_RC).touch()
467 Path(cylc8, WorkflowFiles.LogDir.DIRNAME, 'suite').mkdir(parents=True)
468 Path(cylc8, WorkflowFiles.LogDir.DIRNAME, 'suite', 'log').touch()
469 Path(cylc8, WorkflowFiles.LogDir.DIRNAME, 'scheduler').mkdir(parents=True)
470 Path(cylc8, WorkflowFiles.LogDir.DIRNAME, 'scheduler', 'log').touch()
471
472 return tmp_path
473
474
475 async def test_scan_cylc7(cylc7_run_dir):
476 """It should exclude Cylc 7 workflows from scan results.
477
478 Unless they are running under Cylc 8 in Cylc 7 compatibility mode.
479 """
480 assert await listify(
481 scan(cylc7_run_dir)
482 ) == [
483 'cylc78', 'cylc8', 'cylc8a', 'either'
484 ]