Debian Codegraph @

tests/integration/test_workflow_files.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 itertools import product
18 import logging
19 from os import unlink
20 from pathlib import Path
21 from textwrap import dedent
22 from uuid import uuid4
23
24 import pytest
25
26 from cylc.flow import CYLC_LOG
27 from cylc.flow.exceptions import (
28 SchedulerAlive,
29 CylcError,
30 )
31 from cylc.flow.workflow_files import (
32 ContactFileFields as CFF,
33 WorkflowFiles,
34 _is_process_running,
35 detect_old_contact_file,
36 dump_contact_file,
37 load_contact_file,
38 load_contact_file_async,
39 )
40
41
42 @pytest.fixture(scope='module')
43 async def myflow(mod_flow, mod_scheduler, mod_run, mod_one_conf):
44 id_ = mod_flow(mod_one_conf)
45 schd = mod_scheduler(id_)
46 async with mod_run(schd):
47 yield schd
48
49
50 def test_load_contact_file(myflow):
51 cont = load_contact_file(myflow.workflow)
52 assert cont[CFF.HOST] == myflow.host
53
54
55 async def test_load_contact_file_async(myflow):
56 cont = await load_contact_file_async(myflow.workflow)
57 assert cont[CFF.HOST] == myflow.host
58
59 # compare the async interface to the sync interface
60 cont2 = load_contact_file(myflow.workflow)
61 assert cont == cont2
62
63
64 @pytest.fixture
65 async def workflow(flow, scheduler, one_conf, run_dir):
66 id_ = flow(one_conf)
67 schd = scheduler(id_)
68 await schd.install()
69
70 from collections import namedtuple
71 Server = namedtuple('Server', ['port', 'pub_port'])
72 schd.server = Server(1234, pub_port=2345)
73 schd.uuid_str = str(uuid4())
74
75 contact_data = schd.get_contact_data()
76 contact_file = Path(
77 run_dir,
78 id_,
79 WorkflowFiles.Service.DIRNAME,
80 WorkflowFiles.Service.CONTACT
81 )
82
83 def dump_contact(**kwargs):
84 dump_contact_file(
85 id_,
86 {
87 **contact_data,
88 **kwargs
89 }
90 )
91 assert contact_file.exists()
92
93 dump_contact()
94
95 Fixture = namedtuple(
96 'TextFixture',
97 [
98 'id_',
99 'contact_file',
100 'contact_data',
101 'dump_contact',
102 ]
103 )
104 return Fixture(id_, contact_file, contact_data, dump_contact)
105
106
107 def test_detect_old_contact_file_running(workflow):
108 """It should raise an error if the workflow is running."""
109 # the workflow is running so we should get a ServiceFileError
110 with pytest.raises(SchedulerAlive):
111 detect_old_contact_file(workflow.id_)
112 # the contact file is valid so should be left alone
113 assert workflow.contact_file.exists()
114
115
116 def test_detect_old_contact_file_network_issue(workflow):
117 """It should raise an error if there are network issues."""
118 # modify the contact file to make it look like the PID has changed
119 workflow.dump_contact(
120 **{
121 # set the HOST to a non existent host
122 CFF.HOST: 'not-a-host.no-such.domain'
123 }
124 )
125 # detect_old_contact_file should report that it can't tell if the workflow
126 # is running or not
127 with pytest.raises(CylcError) as exc_ctx:
128 detect_old_contact_file(workflow.id_)
129 assert (
130 'Cannot determine whether workflow is running'
131 in str(exc_ctx.value)
132 )
133 # the contact file should be left alone
134 assert workflow.contact_file.exists()
135
136
137 def test_detect_old_contact_file_old_run(workflow, caplog, log_filter):
138 """It should remove the contact file from an old run."""
139 # modify the contact file to make it look like the COMMAND has changed
140 workflow.dump_contact(
141 **{
142 CFF.COMMAND: 'foo bar baz'
143 }
144 )
145 caplog.set_level(logging.INFO, logger=CYLC_LOG)
146
147 # the workflow should not appear to be running (according to the contact
148 # data) so detect_old_contact_file should not raise any errors
149 detect_old_contact_file(workflow.id_)
150
151 # as a side effect the contact file should have been removed
152 assert not workflow.contact_file.exists()
153 assert log_filter(contains='Removed contact file')
154
155
156 def test_detect_old_contact_file_none(workflow):
157 """It should do nothing if there is no contact file."""
158 # remove the contact file
159 workflow.contact_file.unlink()
160 assert not workflow.contact_file.exists()
161 # detect_old_contact_file should return
162
163 detect_old_contact_file(workflow.id_)
164
165 # it should not recreate the contact file
166 assert not workflow.contact_file.exists()
167
168
169 @pytest.mark.parametrize(
170 'process_running,contact_present_after,raises_error',
171 filter(
172 lambda x: x != (False, False, True), # logically impossible
173 product([True, False], repeat=3),
174 )
175 )
176 def test_detect_old_contact_file_removal_errors(
177 workflow,
178 monkeypatch,
179 caplog,
180 log_filter,
181 process_running,
182 contact_present_after,
183 raises_error,
184 ):
185 """Test issues with removing the contact file are handled correctly.
186
187 Args:
188 process_running:
189 If True we will make it look like the workflow process is still
190 running (i.e. the workflow is still running). In this case
191 detect_old_contact_file should *not* attempt to remove the contact
192 file.
193 contact_present_after:
194 If False we will make the contact file disappear midway through
195 the operation. This can happen because:
196
197 * detect_old_contact_file in another client.
198 * cylc clean.
199 * Aliens.
200
201 This is fine, nothing should be logged.
202 raises_error:
203 If True we will make it look like removing the contact file
204 resulted in an OS error (not a FileNotFoundError). This error
205 should be logged.
206
207 """
208 # patch the is_process_running method
209 def mocked_is_process_running(*args):
210 if not contact_present_after:
211 # remove the contact file midway through detect_old_contact_file
212 unlink(workflow.contact_file)
213
214 return process_running
215
216 monkeypatch.setattr(
217 'cylc.flow.workflow_files._is_process_running',
218 mocked_is_process_running,
219 )
220
221 # patch the contact file removal
222 def _unlink(*args):
223 raise OSError('mocked-os-error')
224
225 if raises_error:
226 # force os.unlink to raise an arbitrary error
227 monkeypatch.setattr(
228 'cylc.flow.workflow_files.os.unlink',
229 _unlink,
230 )
231
232 caplog.set_level(logging.INFO, logger=CYLC_LOG)
233
234 # try to remove the contact file
235 if process_running:
236 # this should error if the process is running
237 with pytest.raises(SchedulerAlive):
238 detect_old_contact_file(workflow.id_)
239 else:
240 detect_old_contact_file(workflow.id_)
241
242 # decide which log messages we should expect to see
243 if process_running:
244 remove_succeeded = False
245 remove_failed = False
246 else:
247 if contact_present_after:
248 if raises_error:
249 remove_succeeded = False
250 remove_failed = True
251 else:
252 remove_succeeded = True
253 remove_failed = False
254 else:
255 remove_succeeded = False
256 remove_failed = False
257
258 # check the appropriate messages were logged
259 assert bool(log_filter(
260 contains='Removed contact file',
261 )) is remove_succeeded
262 assert bool(log_filter(
263 contains=(
264 f'Failed to remove contact file for {workflow.id_}:'
265 '\nmocked-os-error'
266 ),
267 )) is remove_failed
268
269
270 def test_is_process_running_dirty_output(monkeypatch, caplog):
271 """Ensure _is_process_running can handle polluted output.
272
273 E.G. this can happen if there is an echo statement in the `.bashrc`.
274 """
275
276 stdout = None
277
278 class Popen():
279
280 def __init__(self, *args, **kwargs):
281 self.returncode = 0
282
283 def communicate(self, *args, **kwargs):
284 return (stdout, '')
285
286 monkeypatch.setattr(
287 'cylc.flow.workflow_files.Popen',
288 Popen,
289 )
290
291 # respond with something Cylc should be able to make sense of
292 stdout = dedent('''
293 % simulated stdout pollution %
294 [["expected", "command"]]
295 ''')
296
297 caplog.set_level(logging.WARN, logger=CYLC_LOG)
298 assert _is_process_running('localhost', 1, 'expected command')
299 assert not caplog.record_tuples
300 assert not _is_process_running('localhost', 1, 'slartibartfast')
301 assert not caplog.record_tuples
302
303 # respond with something totally non-sensical
304 stdout = 'sir henry'
305 with pytest.raises(CylcError):
306 _is_process_running('localhost', 1, 'expected command')
307
308 # the command output should be in the debug message
309 assert 'sir henry' in caplog.records[0].message