Debian Codegraph @

cylc/flow/workflow_events.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 """Workflow event handler."""
17
18 from enum import Enum
19 import os
20 from shlex import quote
21 from typing import Any, Dict, List, Union, TYPE_CHECKING
22
23 from cylc.flow import LOG
24 from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
25 from cylc.flow.hostuserutil import get_host, get_user
26 from cylc.flow.log_diagnosis import run_reftest
27 from cylc.flow.parsec.config import DefaultList
28 from cylc.flow.subprocctx import SubProcContext
29
30 if TYPE_CHECKING:
31 from cylc.flow.config import WorkflowConfig
32 from cylc.flow.scheduler import Scheduler
33
34
35 class EventData(Enum):
36 """The following variables are available to workflow event handlers.
37
38 They can be templated into event handlers with Python percent style string
39 formatting e.g:
40
41 .. code-block:: none
42
43 %(workflow)s is running on %(host)s
44
45 .. note::
46
47 Substitution patterns should not be quoted in the template strings.
48 This is done automatically where required.
49
50 For an explanation of the substitution syntax, see
51 `String Formatting Operations in the Python documentation
52 <https://docs.python.org/3/library/stdtypes.html
53 #printf-style-string-formatting>`_.
54
55 """
56
57 Event = 'event'
58 """The type of workflow event that has occurred e.g. ``stall``."""
59
60 Message = 'message'
61 """Additional information about the event."""
62
63 Workflow = 'workflow'
64 """The workflow ID"""
65
66 Host = 'host'
67 """The host where the workflow is running."""
68
69 Port = 'port'
70 """The port where the workflow is running."""
71
72 Owner = 'owner'
73 """The user account under which the workflow is running."""
74
75 UUID = 'uuid'
76 """The unique identification string for this workflow run.
77
78 This string is preserved for the lifetime of the scheduler and is restored
79 from the database on restart.
80 """
81
82 WorkflowURL = 'workflow_url'
83 """The URL defined in :cylc:conf:`flow.cylc[meta]URL`."""
84
85 # BACK COMPAT: "suite" deprecated
86 # url:
87 # https://github.com/cylc/cylc-flow/pull/4724 (& 4714)
88 # from:
89 # Cylc 8
90 # remove at:
91 # Cylc 8.x
92 Suite = 'suite'
93 """The workflow ID
94
95 .. deprecated:: 8.0.0
96
97 Use "workflow".
98 """
99
100 # BACK COMPAT: "suite_uuid" deprecated
101 # url:
102 # https://github.com/cylc/cylc-flow/pull/4724 (& 4714)
103 # from:
104 # Cylc 8
105 # remove at:
106 # Cylc 8.x
107 Suite_UUID = 'suite_uuid'
108 """The unique identification string for this workflow run.
109
110 .. deprecated:: 8.0.0
111
112 Use "uuid".
113 """
114
115 # BACK COMPAT: "suite_url" deprecated
116 # url:
117 # https://github.com/cylc/cylc-flow/pull/4724 (& 4714)
118 # from:
119 # Cylc 8
120 # remove at:
121 # Cylc 8.x
122 SuiteURL = 'suite_url'
123 """The URL defined in :cylc:conf:`flow.cylc[meta]URL`.
124
125 .. deprecated:: 8.0.0
126
127 Use "workflow_url".
128 """
129
130
131 def construct_mail_cmd(
132 subject: str, from_address: str, to_address: str
133 ) -> List[str]:
134 """Construct a mail command."""
135 return [
136 'mail',
137 '-s', subject,
138 '-r', from_address,
139 to_address
140 ]
141
142
143 def get_template_variables(
144 schd: 'Scheduler',
145 event: str,
146 reason: str
147 ) -> Dict[str, Union[str, int]]:
148 """Return a dictionary of template varaibles for a workflow event."""
149 workflow_url: str = schd.config.cfg['meta'].get('URL', '')
150 return {
151 # scheduler properties
152 EventData.Event.value:
153 event,
154 EventData.Message.value:
155 reason,
156 EventData.Workflow.value:
157 schd.workflow,
158 EventData.Host.value:
159 schd.host,
160 EventData.Port.value:
161 (schd.server.port if schd.server else -1),
162 EventData.Owner.value:
163 schd.owner,
164 EventData.UUID.value:
165 schd.uuid_str,
166 EventData.WorkflowURL.value:
167 workflow_url,
168
169 # BACK COMPAT: "suite", "suite_uuid", "suite_url"
170 # url:
171 # https://github.com/cylc/cylc-flow/pull/4724 (&4714)
172 # from:
173 # Cylc 8
174 # remove at:
175 # Cylc 8.x
176 EventData.Suite.value:
177 schd.workflow,
178 EventData.Suite_UUID.value:
179 schd.uuid_str,
180 EventData.SuiteURL.value:
181 workflow_url,
182
183 # workflow metadata
184 **{
185 key: quote(value)
186 for key, value in schd.config.cfg['meta'].items()
187 if key != 'URL'
188 }, # noqa: E122
189 }
190
191
192 def process_mail_footer(
193 mail_footer_tmpl: str,
194 template_vars,
195 ) -> str:
196 """Process mail footer for workflow or task events.
197
198 Returns an empty string if issues occur in processing.
199 """
200 try:
201 return (mail_footer_tmpl + '\n') % template_vars
202 except (KeyError, TypeError, ValueError):
203 LOG.warning(
204 f'Ignoring bad mail footer template: {mail_footer_tmpl}'
205 )
206 return ''
207
208
209 class WorkflowEventHandler():
210 """Workflow event handler."""
211
212 EVENT_STARTUP = 'startup'
213 EVENT_SHUTDOWN = 'shutdown'
214 EVENT_ABORTED = 'abort'
215 EVENT_STALL = 'stall'
216 EVENT_STALL_TIMEOUT = 'stall timeout'
217 EVENT_WORKFLOW_TIMEOUT = 'workflow timeout'
218 EVENT_INACTIVITY_TIMEOUT = 'inactivity timeout'
219 EVENT_RESTART_TIMEOUT = 'restart timeout'
220
221 EVENTS = [
222 EVENT_STARTUP,
223 EVENT_SHUTDOWN,
224 EVENT_ABORTED,
225 EVENT_STALL,
226 EVENT_STALL_TIMEOUT,
227 EVENT_WORKFLOW_TIMEOUT,
228 EVENT_INACTIVITY_TIMEOUT,
229 EVENT_RESTART_TIMEOUT,
230 ]
231 EVENTS_DEPRECATED = {
232 'aborted': EVENT_ABORTED,
233 'inactivity': EVENT_INACTIVITY_TIMEOUT,
234 'stalled': EVENT_STALL,
235 'timeout': EVENT_STALL_TIMEOUT,
236 }
237
238 WORKFLOW_EVENT_HANDLER = 'workflow-event-handler'
239 WORKFLOW_EVENT_MAIL = 'workflow-event-mail'
240
241 def __init__(self, proc_pool):
242 self.proc_pool = proc_pool
243
244 @staticmethod
245 def get_events_conf(
246 config: 'WorkflowConfig', key: str, default: Any = None
247 ) -> Any:
248 """Return a named [scheduler][[events]] configuration."""
249 for getter in (
250 config.cfg['scheduler']['events'],
251 config.cfg['scheduler'].get('mail', {}),
252 glbl_cfg().get(['scheduler', 'events']),
253 glbl_cfg().get(['scheduler', 'mail'])
254 ):
255 value = getter.get(key)
256 if value is not None and not isinstance(value, DefaultList):
257 return value
258 return default
259
260 def handle(self, schd: 'Scheduler', event: str, reason: str) -> None:
261 """Handle a workflow event."""
262 template_variables = get_template_variables(schd, event, reason)
263 self._run_event_mail(schd, template_variables, event)
264 self._run_event_custom_handlers(schd, template_variables, event)
265 if schd.config.options.reftest and event == self.EVENT_SHUTDOWN:
266 run_reftest(schd)
267
268 def _run_event_mail(self, schd, template_variables, event):
269 """Helper for "run_event_handlers", do mail notification."""
270 if event in self.get_events_conf(schd.config, 'mail events', []):
271 # SMTP server
272 env = dict(os.environ)
273 mail_smtp = self.get_events_conf(schd.config, 'smtp')
274 if mail_smtp:
275 env['smtp'] = mail_smtp
276 subject = (
277 f'[workflow %({EventData.Event.value})s]'
278 f' %({EventData.Workflow.value})s' % (
279 template_variables
280 )
281 )
282 stdin_str = ''
283 for key in (
284 EventData.Event.value,
285 EventData.Message.value,
286 EventData.Workflow.value,
287 EventData.Host.value,
288 EventData.Port.value,
289 EventData.Owner.value,
290 ):
291 value = template_variables.get(key, None)
292 if value:
293 stdin_str += '%s: %s\n' % (key, value)
294 mail_footer_tmpl = self.get_events_conf(schd.config, 'footer')
295 if mail_footer_tmpl:
296 stdin_str += process_mail_footer(
297 mail_footer_tmpl,
298 template_variables,
299 )
300 self._send_mail(event, subject, stdin_str, schd, env)
301
302 def _send_mail(
303 self,
304 event: str,
305 subject: str,
306 message: str,
307 schd: 'Scheduler',
308 env: Dict[str, str]
309 ) -> None:
310 proc_ctx = SubProcContext(
311 (self.WORKFLOW_EVENT_HANDLER, event),
312 construct_mail_cmd(
313 subject,
314 from_address=self.get_events_conf(
315 schd.config, 'from', f'notifications@{get_host()}'
316 ),
317 to_address=self.get_events_conf(schd.config, 'to', get_user())
318 ),
319 env=env,
320 stdin_str=message
321 )
322 self._run_cmd(proc_ctx, callback=self._run_event_mail_callback)
323
324 def _run_cmd(self, ctx, callback):
325 """Queue or directly run a command and its callback.
326
327 Queue the command to the subprocess pool if possible, or else run it
328 in the foreground (but still subject to the subprocess pool timeout).
329
330 """
331 if not self.proc_pool.closed:
332 # Queue it to the subprocess pool.
333 self.proc_pool.put_command(ctx, callback=callback)
334 else:
335 # Run it in the foreground.
336 self.proc_pool.run_command(ctx, callback=callback)
337
338 def _run_event_custom_handlers(self, schd, template_variables, event):
339 """Helper for "run_event_handlers", custom event handlers."""
340 # Look for event handlers
341 # 1. Handlers for specific event
342 # 2. General handlers
343 config = schd.config
344 handlers = self.get_events_conf(config, '%s handlers' % event)
345 if not handlers and (
346 event in
347 self.get_events_conf(config, 'handler events', [])
348 ):
349 handlers = self.get_events_conf(config, 'handlers')
350 if not handlers:
351 return
352 for i, handler in enumerate(handlers):
353 cmd_key = ('%s-%02d' % (self.WORKFLOW_EVENT_HANDLER, i), event)
354 try:
355 cmd = handler % (template_variables)
356 except (KeyError, TypeError, ValueError) as exc:
357 message = f'{cmd_key} bad template: {handler}\n{exc}'
358 LOG.error(message)
359 continue
360 if cmd == handler:
361 # Nothing substituted, assume classic interface
362 cmd = (
363 f"%(handler)s"
364 f" '%({EventData.Event.value})s'"
365 f" '%({EventData.Workflow.value})s'"
366 f" '%({EventData.Message.value})s'"
367 ) % (
368 {'handler': handler, **template_variables}
369 )
370 proc_ctx = SubProcContext(
371 cmd_key,
372 cmd,
373 env=dict(os.environ),
374 shell=True # nosec (designed to run user defined code)
375 )
376 self._run_cmd(proc_ctx, self._run_event_handlers_callback)
377
378 @staticmethod
379 def _run_event_handlers_callback(proc_ctx):
380 """Callback on completion of a workflow event handler."""
381 if proc_ctx.ret_code:
382 LOG.error(str(proc_ctx))
383 LOG.error(f'{proc_ctx.cmd_key[1]} EVENT HANDLER FAILED')
384 else:
385 LOG.info(str(proc_ctx))
386
387 @staticmethod
388 def _run_event_mail_callback(proc_ctx):
389 """Callback the mail command for notification of a workflow event."""
390 if proc_ctx.ret_code:
391 LOG.warning(str(proc_ctx))
392 else:
393 LOG.info(str(proc_ctx))