Debian Codegraph @

tests/integration/scripts/test_broadcast.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 import logging
18
19 from ansimarkup import strip as cstrip
20 import pytest
21
22 from cylc.flow.network.client import WorkflowRuntimeClient
23 from cylc.flow.option_parsers import Options
24 from cylc.flow.rundb import CylcWorkflowDAO
25 from cylc.flow.scheduler import Scheduler
26 from cylc.flow.scripts.broadcast import (
27 _main,
28 get_option_parser,
29 )
30 from cylc.flow.util import sstrip
31
32
33 BroadcastOptions = Options(get_option_parser())
34
35
36 async def test_broadcast_multi_workflow(
37 one_conf,
38 flow,
39 scheduler,
40 start,
41 run_dir,
42 test_dir,
43 capsys,
44 ):
45 """Test a multi-workflow broadcast command."""
46 # create three workflows
47 one = scheduler(flow(one_conf))
48 two = scheduler(flow(one_conf))
49 thr = scheduler(flow(one_conf))
50
51 # the ID under which all three are installed
52 id_base = test_dir.relative_to(run_dir)
53
54 async with start(one):
55 async with start(two):
56 async with start(thr):
57 capsys.readouterr()
58
59 # test a successful broadcast command
60 rets = await _main(
61 BroadcastOptions(settings=['script=true']), f'{id_base}*'
62 )
63
64 # all three broadcasts should have succeeded
65 assert list(rets.values()) == [True, True, True]
66
67 out, err = capsys.readouterr()
68 assert '[*/root] script=true' in out
69 assert err == ''
70
71 # test an unsuccessful broadcast command
72 rets = await _main(
73 BroadcastOptions(
74 namespaces=['*'],
75 settings=['script=true'],
76 ),
77 f'{id_base}*',
78 )
79
80 # all three broadcasts should have failed
81 assert list(rets.values()) == [False, False, False]
82
83 out, err = capsys.readouterr()
84 assert '[*/root] script=true' not in out
85 assert (
86 # NOTE: for historical reasons this message goes to stdout
87 # not stderr
88 'Rejected broadcast:'
89 ' settings are not compatible with the workflow'
90 ) in out
91 assert err == ''
92
93
94 async def test_broadcast_multi_namespace(
95 flow,
96 scheduler,
97 start,
98 db_select,
99 ):
100 """Test a multi-namespace broadcast command.
101
102 See https://github.com/cylc/cylc-flow/issues/6334
103 """
104 id_ = flow(
105 {
106 'scheduling': {
107 'graph': {'R1': 'a & b & c & fin'},
108 },
109 'runtime': {
110 'root': {'execution time limit': 'PT1S'},
111 'VOWELS': {'execution time limit': 'PT2S'},
112 'CONSONANTS': {'execution time limit': 'PT3S'},
113 'a': {'inherit': 'VOWELS'},
114 'b': {'inherit': 'CONSONANTS'},
115 'c': {'inherit': 'CONSONANTS'},
116 },
117 }
118 )
119 schd = scheduler(id_)
120
121 async with start(schd):
122 # issue a broadcast to multiple namespaces
123 rets = await _main(
124 BroadcastOptions(
125 settings=['execution time limit = PT5S'],
126 namespaces=['root', 'VOWELS', 'CONSONANTS'],
127 ),
128 schd.workflow,
129 )
130
131 # the broadcast should succeed
132 assert list(rets.values()) == [True]
133
134 # the broadcast manager should store the "coerced" setting
135 for task in ['a', 'b', 'c', 'fin']:
136 assert schd.broadcast_mgr.get_broadcast(
137 schd.tokens.duplicate(cycle='1', task=task)
138 ) == {'execution time limit': 5.0}
139
140 # the database should store the "raw" setting
141 assert sorted(
142 db_select(schd, True, CylcWorkflowDAO.TABLE_BROADCAST_STATES)
143 ) == [
144 ('*', 'CONSONANTS', 'execution time limit', 'PT5S'),
145 ('*', 'VOWELS', 'execution time limit', 'PT5S'),
146 ('*', 'root', 'execution time limit', 'PT5S'),
147 ]
148
149
150 async def test_broadcast_truncated_datetime(flow, scheduler, start, capsys):
151 """It should reject truncated datetime cycle points.
152
153 See https://github.com/cylc/cylc-flow/issues/6407
154 """
155 id_ = flow({
156 'scheduling': {
157 'initial cycle point': '2000',
158 'graph': {
159 'R1': 'foo',
160 },
161 }
162 })
163 schd = scheduler(id_)
164 async with start(schd):
165 # attempt an invalid broadcast
166 rets = await _main(
167 BroadcastOptions(
168 settings=['[environment]FOO=bar'],
169 point_strings=['050101T0000Z'], # <== truncated
170 ),
171 schd.workflow,
172 )
173
174 # the broadcast should fail
175 assert list(rets.values()) == [False]
176
177 # an error should be recorded
178 _out, err = capsys.readouterr()
179 assert (
180 'Rejected broadcast:'
181 ' settings are not compatible with the workflow'
182 ) in err
183
184
185 async def test_invalid(one, start, capsys, monkeypatch):
186 """It should reject invalid broadcasts.
187
188 * Broadcast operations may contain a mix of valid and invalid
189 cycles/namespaces/settings.
190 * Valid settings are applied and reported.
191 * Invalid settings are rejected and reported.
192 """
193 # disable client side config validation so that we can see invalid
194 # broadcast settings in the CLI output
195 monkeypatch.setattr(
196 'cylc.flow.scripts.broadcast.cylc_config_validate',
197 lambda *args, **kwargs: True,
198 )
199
200 # 1) disable CLI colour output
201 monkeypatch.setattr('cylc.flow.scripts.broadcast.cparse', cstrip)
202
203 async with start(one):
204 # test the GraphQL API
205 client = WorkflowRuntimeClient(one.workflow)
206 response = await client.async_request(
207 'graphql',
208 {
209 'request_string': '''
210 mutation(
211 $workflows: [WorkflowID]!,
212 $cycles: [BroadcastCyclePoint],
213 $namespaces: [NamespaceName],
214 $settings: [BroadcastSetting]
215 ) {
216 broadcast(
217 mode: Set
218 workflows: $workflows
219 cyclePoints: $cycles
220 namespaces: $namespaces
221 settings: $settings
222 ) {
223 result
224 }
225 }
226 ''',
227 'variables': {
228 'workflows': [one.workflow],
229 # valid, invalid
230 'cycles': ['*', 'invalid'],
231 'namespaces': ['root', 'invalid'],
232 'settings': [{'script': 'true'}, {'invalid': 'false'}],
233 }
234 }
235 )
236 modified, rejected = response['broadcast']['result'][0]['response']
237
238 assert modified == [
239 [
240 # cycle
241 '*',
242 # namespace
243 'root',
244 # settings
245 {'script': 'true'},
246 ]
247 ]
248 assert rejected == {
249 'point_strings': ['invalid'],
250 'namespaces': ['invalid'],
251 'settings': [{'invalid': 'false'}],
252 }
253
254 # 2) test the CLI
255 capsys.readouterr() # flush out any stdout/err
256 await _main(
257 BroadcastOptions(
258 point_strings=['*', 'invalid'],
259 namespaces=['root', 'invalid'],
260 settings=['script=true', 'invalid=false'],
261 ),
262 one.workflow,
263 )
264 out, err = capsys.readouterr()
265 assert out == 'Broadcast set:\n+ [*/root] script=true\n'
266 assert err == sstrip('''
267 ERROR: Rejected broadcast: settings are not compatible with the workflow
268 --namespace=invalid
269 --point=invalid
270 --set=invalid=false
271 ''') + '\n'
272
273
274 async def test_internal_error(one, start, capsys, monkeypatch, log_filter):
275 """It should handle internal code errors elegantly."""
276
277 # simulate an internal error
278 # Note: The broadcast "lock" mechanism is an example of how such an error
279 # could arise
280 def put_broadcast(*args, **kwargs):
281 raise Exception('FooBar')
282
283 async with start(one):
284 # issue a broadcast
285 one.broadcast_mgr.put_broadcast = put_broadcast
286 client = WorkflowRuntimeClient(one.workflow)
287 response = await client.async_request(
288 'graphql',
289 {
290 'request_string': '''
291 mutation(
292 $workflows: [WorkflowID]!,
293 $cycles: [BroadcastCyclePoint],
294 $namespaces: [NamespaceName],
295 $settings: [BroadcastSetting]
296 ) {
297 broadcast(
298 mode: Set
299 workflows: $workflows
300 cyclePoints: $cycles
301 namespaces: $namespaces
302 settings: $settings
303 ) {
304 result
305 }
306 }
307 ''',
308 'variables': {
309 'workflows': [one.workflow],
310 'cycles': ['*'],
311 'namespaces': ['root'],
312 'settings': [{'script': 'true'}],
313 }
314 }
315 )
316
317 # check it comes back with an error code
318 assert (
319 response['broadcast']['result'][0]
320 )['response']['error']['message'] == 'FooBar'
321
322 # the error should be logged server-side too
323 assert log_filter(contains='FooBar')
324
325
326 async def test_broadcast_auto_upgraded_settings(
327 one: Scheduler,
328 start,
329 log_filter,
330 caplog: pytest.LogCaptureFixture,
331 capsys: pytest.CaptureFixture,
332 ):
333 """Test broadcast of deprecated/obsolete settings."""
334 opts = {
335 'point_strings': ['1'],
336 'namespaces': ['root'],
337 }
338 async with start(one):
339 # Test deprecated setting that is moved to a different section by
340 # the auto-upgrader should still work.
341 rets = await _main(
342 BroadcastOptions(
343 settings=['[job]execution time limit=PT1H'], **opts
344 ),
345 one.workflow,
346 )
347 assert set(rets.values()) == {True}
348 assert log_filter(
349 logging.WARNING, regex=r"Deprecated config.* upgraded.* broadcast"
350 )
351
352 stdout, stderr = capsys.readouterr()
353 assert "Traceback" not in stdout + stderr
354 caplog.clear()
355
356 # Test obsolete setting that is removed by the auto-upgrader should
357 # be rejected.
358 rets = await _main(
359 BroadcastOptions(
360 settings=['extra log files=whatever'], **opts
361 ),
362 one.workflow,
363 )
364 assert set(rets.values()) == {False}
365 assert log_filter(
366 logging.WARNING,
367 regex=r"Obsolete config.* rejected by the broadcast",
368 )
369 stdout, stderr = capsys.readouterr()
370 assert "InputError: No valid settings to broadcast" in stderr
371 assert "Traceback" not in stdout + stderr