Debian Codegraph @

tests/integration/test_task_events_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 import logging
18 from types import SimpleNamespace
19 from typing import Any as Fixture
20
21 import pytest
22
23 from cylc.flow.data_store_mgr import (
24 JOBS,
25 TASK_STATUS_WAITING,
26 )
27 from cylc.flow.id import Tokens
28 from cylc.flow.run_modes import RunMode
29 from cylc.flow.scheduler import Scheduler
30 from cylc.flow.task_events_mgr import (
31 EventKey,
32 TaskJobLogsRetrieveContext,
33 )
34 from cylc.flow.task_state import (
35 TASK_STATUS_PREPARING,
36 TASK_STATUS_SUBMIT_FAILED,
37 )
38
39 from cylc.flow.network.resolvers import TaskMsg
40
41 from .test_workflow_events import TEMPLATES
42
43
44 # NOTE: we do not test custom event handlers here because these are tested
45 # as a part of workflow validation (now also performed by cylc play)
46
47
48 async def test_process_job_logs_retrieval_warns_no_platform(
49 one_conf: Fixture, flow: Fixture, scheduler: Fixture, run: Fixture,
50 db_select: Fixture, caplog: Fixture
51 ):
52 """Job log retrieval handles `NoHostsError`"""
53
54 ctx = TaskJobLogsRetrieveContext(
55 platform_name='skarloey',
56 max_size=256,
57 key='skarloey'
58 )
59 id_: str = flow(one_conf)
60 schd: 'Scheduler' = scheduler(id_, paused_start=True)
61 # Run
62 async with run(schd):
63 schd.task_events_mgr._process_job_logs_retrieval(
64 schd, ctx, 'foo'
65 )
66 warning = caplog.records[-1]
67 assert warning.levelname == 'WARNING'
68 assert 'Unable to retrieve' in warning.msg
69
70
71 async def test__reset_job_timers(
72 one_conf: Fixture, flow: Fixture, scheduler: Fixture,
73 start: Fixture, caplog: Fixture, mock_glbl_cfg: Fixture,
74 ):
75 """Integration test of pathway leading to
76 process_execution_polling_intervals.
77 """
78 schd = scheduler(flow(one_conf))
79 async with start(schd, level=logging.DEBUG):
80 itask = schd.pool.get_tasks()[0]
81 itask.state.status = 'running'
82 itask.platform['execution polling intervals'] = [25]
83 itask.platform['execution time limit polling intervals'] = [10]
84 itask.summary['execution_time_limit'] = 30
85 caplog.records.clear()
86 schd.task_events_mgr._reset_job_timers(itask)
87
88 assert (
89 'polling intervals=PT25S,PT15S,PT10S,...'
90 in caplog.records[0].msg
91 )
92
93
94 async def test__insert_task_job(flow, one_conf, scheduler, start, validate):
95 """Simulation mode tasks are inserted into the Data Store,
96 with correct submit number.
97 """
98 conf = {
99 'scheduling': {'graph': {'R1': 'rhenas'}},
100 'runtime': {
101 'rhenas': {
102 'simulation': {
103 'fail cycle points': '1',
104 'fail try 1 only': False,
105 }
106 }
107 },
108 }
109 id_ = flow(conf)
110 schd = scheduler(id_)
111 async with start(schd):
112 # Set task to running:
113 itask = schd.pool.get_tasks()[0]
114 itask.state.status = 'running'
115 itask.submit_num += 1
116 itask.run_mode = RunMode.SIMULATION
117
118 # Not run _insert_task_job yet:
119 assert not schd.data_store_mgr.added['jobs'].keys()
120
121 # Insert task (twice):
122 schd.task_events_mgr._insert_task_job(itask, 'now', 1)
123 itask.submit_num += 1
124 schd.task_events_mgr._insert_task_job(itask, 'now', 1)
125
126 # Check that there are two entries with correct submit
127 # numbers waiting for data-store insertion:
128 assert [
129 i.submit_num for i
130 in schd.data_store_mgr.added['jobs'].values()
131 ] == [1, 2]
132
133
134 async def test__always_insert_task_job(
135 flow, scheduler, mock_glbl_cfg, start
136 ):
137 """Insert Task Job _Always_ inserts a task into the data store.
138
139 Bug https://github.com/cylc/cylc-flow/issues/6172 was caused
140 by passing task state to data_store_mgr.insert_job: Where
141 a submission retry was in progress the task state would be
142 "waiting" which caused the data_store_mgr.insert_job
143 to return without adding the task to the data store.
144 This is testing two different cases:
145
146 * Could not select host from platform
147 * Could not select host from platform group
148 """
149 global_config = """
150 [platforms]
151 [[broken1]]
152 hosts = no-such-host-1
153 job runner = abc
154 [[broken2]]
155 hosts = no-such-host-2
156 job runner = def
157 [platform groups]
158 [[broken_group]]
159 platforms = broken1
160 """
161 mock_glbl_cfg('cylc.flow.platforms.glbl_cfg', global_config)
162
163 id_ = flow({
164 'scheduling': {'graph': {'R1': 'foo & bar'}},
165 'runtime': {
166 'root': {'submission retry delays': 'PT10M'},
167 'foo': {'platform': 'broken_group'},
168 'bar': {'platform': 'broken2'}
169 }
170 })
171
172 schd: Scheduler = scheduler(id_, run_mode='live')
173 schd.bad_hosts.update({'no-such-host-1', 'no-such-host-2'})
174 async with start(schd):
175 schd.submit_task_jobs(schd.pool.get_tasks())
176 await schd.update_data_structure()
177
178 # Both tasks are in a waiting state:
179 assert all(
180 i.state.status == TASK_STATUS_WAITING
181 for i in schd.pool.get_tasks()
182 )
183
184 # Both jobs are in the data store with submit-failed state:
185 ds_jobs = schd.data_store_mgr.data[schd.id][JOBS]
186 updates = {
187 id_.split('//')[-1]: (job.state, job.platform, job.job_runner_name)
188 for id_, job in ds_jobs.items()
189 }
190 assert updates == {
191 '1/foo/01': ('submit-failed', 'broken_group', ''),
192 '1/bar/01': ('submit-failed', 'broken2', 'def'),
193 }
194 for job in ds_jobs.values():
195 assert job.submitted_time
196
197
198 async def test__submit_failed_job_id(flow, scheduler, start, db_select):
199 """If a job is killed in the submitted state, the job ID should still be
200 in the DB/data store.
201
202 See https://github.com/cylc/cylc-flow/pull/6926
203 """
204 async def get_ds_job_id(schd: Scheduler):
205 await schd.update_data_structure()
206 return list(schd.data_store_mgr.data[schd.id][JOBS].values())[0].job_id
207
208 id_ = flow('foo')
209 schd: Scheduler = scheduler(id_)
210 job_id = '1234'
211 async with start(schd):
212 itask = schd.pool.get_tasks()[0]
213 itask.state_reset(TASK_STATUS_PREPARING)
214 itask.submit_num = 1
215 itask.summary['submit_method_id'] = job_id
216 schd.workflow_db_mgr.put_insert_task_jobs(itask, {})
217 schd.task_events_mgr.process_message(
218 itask, 'INFO', schd.task_events_mgr.EVENT_SUBMITTED
219 )
220 assert await get_ds_job_id(schd) == job_id
221
222 schd.task_events_mgr.process_message(
223 itask, 'CRITICAL', schd.task_events_mgr.EVENT_SUBMIT_FAILED
224 )
225 assert itask.state(TASK_STATUS_SUBMIT_FAILED)
226 assert await get_ds_job_id(schd) == job_id
227
228 assert db_select(schd, False, 'task_jobs', 'job_id', 'submit_status') == [
229 (job_id, 1)
230 ]
231
232 # Restart and check data store again:
233 schd = scheduler(id_)
234 async with start(schd):
235 assert await get_ds_job_id(schd) == job_id
236
237
238 async def test__process_message_failed_with_retry(
239 one: Scheduler, start, log_filter
240 ):
241 """Log job failure, even if a retry is scheduled.
242
243 See: https://github.com/cylc/cylc-flow/pull/6169
244
245 """
246
247 async with start(one) as LOG:
248 fail_once = one.pool.get_tasks()[0]
249 # Add retry timers:
250 one.task_job_mgr._set_retry_timers(
251 fail_once, {
252 'execution retry delays': [1],
253 'submission retry delays': [1]
254 })
255
256 # Process submit failed message with and without retries:
257 one.task_events_mgr._process_message_submit_failed(fail_once, None)
258 record = log_filter(contains='1/one:waiting(queued)] retrying in')
259 assert record[0][0] == logging.WARNING
260
261 one.task_events_mgr._process_message_submit_failed(fail_once, None)
262 failed_record = log_filter(level=logging.ERROR)[-1]
263 assert 'submission failed' in failed_record[1]
264
265 # Process failed message with and without retries:
266 one.task_events_mgr._process_message_failed(
267 fail_once, None, 'failed', False, 'failed/OOK')
268 last_record = LOG.records[-1]
269 assert last_record.levelno == logging.WARNING
270 assert 'retrying in' in last_record.message
271
272 one.task_events_mgr._process_message_failed(
273 fail_once, None, 'failed', False, 'failed/OOK')
274 failed_record = log_filter(level=logging.ERROR)[-1]
275 assert 'failed/OOK' in failed_record[1]
276
277
278 @pytest.mark.parametrize('id_', ['1/no_such_task/01', '1/no_job'])
279 async def test__unhandled_message(id_, one: Scheduler, start, log_filter):
280 """It should log unhandled messages."""
281
282 async with start(one):
283 one.message_queue.put(
284 TaskMsg(
285 Tokens(id_, relative=True), "time", 'INFO', "the quick brown"
286 )
287 )
288 one.process_queued_task_messages()
289
290 _, warning_msg = log_filter(level=logging.WARNING)[-1]
291 assert (
292 'Undeliverable task messages received and ignored:' in warning_msg
293 )
294 assert f'{id_}: INFO - "the quick brown"' in warning_msg
295
296
297 @pytest.mark.parametrize('template', TEMPLATES)
298 async def test_mail_footer_template(
299 mod_one, # use the same scheduler for each test
300 start,
301 mock_glbl_cfg,
302 log_filter,
303 capcall,
304 template,
305 ):
306 """It should handle templating issues with the mail footer."""
307 # prevent emails from being sent
308 mail_calls = capcall(
309 'cylc.flow.task_events_mgr.TaskEventsManager._send_mail'
310 )
311
312 # configure mail footer
313 mock_glbl_cfg(
314 'cylc.flow.workflow_events.glbl_cfg',
315 f'''
316 [scheduler]
317 [[mail]]
318 footer = 'footer={template}'
319 ''',
320 )
321
322 # start the workflow and get it to send an email
323 ctx = SimpleNamespace(mail_to=None, mail_from=None)
324 id_keys = [EventKey('none', 'failed', 'failed', Tokens('//1/a'))]
325 async with start(mod_one):
326 mod_one.task_events_mgr._process_event_email(mod_one, ctx, id_keys)
327
328 # warnings should appear only when the template is invalid
329 should_log = 'workflow' not in template
330
331 # check that template issues are handled correctly
332 assert bool(log_filter(
333 contains='Ignoring bad mail footer template',
334 )) == should_log
335 assert bool(log_filter(
336 contains=template,
337 )) == should_log
338
339 # check that the mail is sent even if there are issues with the footer
340 assert len(mail_calls) == 1
341
342
343 async def test_event_email_body(
344 mod_one,
345 start,
346 capcall,
347 ):
348 """It should send an email with the event context."""
349 mail_calls = capcall(
350 'cylc.flow.task_events_mgr.TaskEventsManager._send_mail'
351 )
352
353 # start the workflow and get it to send an email
354 ctx = SimpleNamespace(mail_to=None, mail_from=None)
355 async with start(mod_one):
356 # send a custom task message with the warning severity level
357 id_keys = [
358 EventKey('none', 'warning', 'warning message', Tokens('//1/a/01'))
359 ]
360 mod_one.task_events_mgr._process_event_email(mod_one, ctx, id_keys)
361
362 # test the email which would have been sent for this message
363 email_body = mail_calls[0][0][3]
364 assert 'event: warning'
365 assert 'job: 1/a/01' in email_body
366 assert 'message: warning message' in email_body
367 assert f'workflow: {mod_one.tokens["workflow"]}' in email_body
368 assert f'host: {mod_one.host}' in email_body
369 assert f'port: {mod_one.server.port}' in email_body
370 assert f'owner: {mod_one.owner}' in email_body