Debian Codegraph @

cylc/flow/job_file.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 """Write job files."""
17
18 from contextlib import suppress
19 import os
20 import re
21 import stat
22 from subprocess import Popen, PIPE, DEVNULL
23 from textwrap import dedent
24
25 from cylc.flow import __version__ as CYLC_VERSION
26 from cylc.flow.job_runner_mgr import JobRunnerManager
27 import cylc.flow.flags
28 from cylc.flow.log_level import verbosity_to_env
29 from cylc.flow.config import interpolate_template, ParamExpandError
30
31
32 class JobFileWriter:
33
34 """Write job files."""
35
36 def __init__(self):
37 self.workflow_env = {}
38 self.job_runner_mgr = JobRunnerManager()
39
40 def set_workflow_env(self, workflow_env):
41 """Configure workflow environment for all job files."""
42 self.workflow_env.clear()
43 self.workflow_env.update(workflow_env)
44
45 def write(self, local_job_file_path, job_conf, check_syntax=True):
46 """Write each job script section in turn."""
47
48 # ########### !!!!!!!! WARNING !!!!!!!!!!! #####################
49 # BE EXTREMELY WARY OF CHANGING THE ORDER OF JOB SCRIPT SECTIONS
50 # Users may be relying on the existing order (see for example
51 # the comment below on workflow bin path being required before
52 # task runtime environment setup).
53 # ##############################################################
54
55 # Access to cylc must be configured before user environment so
56 # that cylc commands can be used in defining user environment
57 # variables: NEXT_CYCLE=$( cylc cycle-point --offset-hours=6 )
58 tmp_name = os.path.expandvars(local_job_file_path + '.tmp')
59 try:
60 with open(tmp_name, 'w') as handle:
61 self._write_header(handle, job_conf)
62 self._write_directives(handle, job_conf)
63 self._write_reinvocation(handle)
64 self._write_prelude(handle, job_conf)
65 self._write_workflow_environment(handle, job_conf)
66 self._write_task_environment(handle, job_conf)
67 # workflow bin access must be before runtime environment
68 # because workflow bin commands may be used in variable
69 # assignment expressions: FOO=$(command args).
70 self._write_runtime_environment(handle, job_conf)
71 self._write_script(handle, job_conf)
72 self._write_global_init_script(handle, job_conf)
73 self._write_epilogue(handle, job_conf)
74 except IOError as exc:
75 # Remove temporary file
76 with suppress(OSError):
77 os.unlink(tmp_name)
78 raise exc
79 # check syntax
80 if check_syntax:
81 try:
82 with Popen( # nosec
83 ['/usr/bin/env', 'bash', '-n', tmp_name],
84 stderr=PIPE,
85 stdin=DEVNULL,
86 text=True
87 # * the purpose of this is to evaluate user defined code
88 # prior to it being executed
89 ) as proc:
90 if proc.wait():
91 # This will leave behind the temporary file,
92 # which is useful for debugging syntax errors, etc.
93 raise RuntimeError(proc.communicate()[1])
94 except OSError as exc:
95 # Popen has a bad habit of not telling you anything if it fails
96 # to run the executable.
97 if exc.filename is None:
98 exc.filename = 'bash'
99 # Remove temporary file
100 with suppress(OSError):
101 os.unlink(tmp_name)
102 raise exc
103 # Make job file executable
104 mode = (
105 os.stat(tmp_name).st_mode |
106 stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
107 os.chmod(tmp_name, mode)
108 os.rename(tmp_name, os.path.expandvars(local_job_file_path))
109
110 @staticmethod
111 def _check_script_value(value):
112 """Return True if script has any executable statements."""
113 if value:
114 for line in value.splitlines():
115 line = line.strip()
116 if line and not line.startswith("#"):
117 return True
118 return False
119
120 @staticmethod
121 def _write_header(handle, job_conf):
122 """Write job script header."""
123 handle.write("#!/bin/bash -l\n")
124 handle.write("#\n# ++++ THIS IS A CYLC JOB SCRIPT ++++")
125 for prefix, value in [
126 ("# Workflow: ", job_conf['workflow_name']),
127 ("# Task: ", job_conf['task_id']),
128 (JobRunnerManager.LINE_PREFIX_JOB_LOG_DIR, job_conf['job_d']),
129 (JobRunnerManager.LINE_PREFIX_JOB_RUNNER_NAME,
130 job_conf['platform']['job runner']),
131 (JobRunnerManager.LINE_PREFIX_JOB_RUNNER_CMD_TMPL,
132 job_conf['platform']['job runner command template']),
133 (JobRunnerManager.LINE_PREFIX_EXECUTION_TIME_LIMIT,
134 job_conf['execution_time_limit'])]:
135 if value:
136 handle.write("\n%s%s" % (prefix, value))
137
138 def _write_directives(self, handle, job_conf):
139 """Job directives."""
140 lines = self.job_runner_mgr.format_directives(job_conf)
141 if lines:
142 handle.write('\n\n# DIRECTIVES:')
143 for line in lines:
144 handle.write('\n' + line)
145
146 def _write_reinvocation(self, handle):
147 """Re-invoke using user determined bash interpreter."""
148 # NOTE this must be done after the directives are written out
149 # due to the way slurm reads directives
150 # NOTE we cannot do /usr/bin/env bash because we need to use the -l
151 # option and GNU env doesn't support additional arguments (recent
152 # versions permit this with the -S option similar to BSD env but we
153 # cannot make the jump to this until is it more widely adopted)
154 handle.write(dedent('''
155 if [[ $1 == 'noreinvoke' ]]; then
156 shift
157 else
158 exec bash -l "$0" noreinvoke "$@"
159 fi
160 '''))
161
162 def _write_prelude(self, handle, job_conf):
163 """Job script prelude."""
164 # Variables for traps
165 handle.write("\nCYLC_FAIL_SIGNALS='%s'" % " ".join(
166 self.job_runner_mgr.get_fail_signals(job_conf)))
167 vacation_signals_str = self.job_runner_mgr.get_vacation_signal(
168 job_conf)
169 if vacation_signals_str:
170 handle.write("\nCYLC_VACATION_SIGNALS='%s'" % vacation_signals_str)
171 # Path to the `cylc` executable, if defined.
172 cylc_path = job_conf['platform']['cylc path']
173 if cylc_path:
174 handle.write(f"\nexport PATH={cylc_path}:$PATH")
175 # Environment variables for prelude
176 for key, value in verbosity_to_env(cylc.flow.flags.verbosity).items():
177 handle.write(f'\nexport {key}={value}')
178 handle.write("\nexport CYLC_VERSION='%s'" % CYLC_VERSION)
179 try:
180 CYLC_ENV_NAME = os.environ['CYLC_ENV_NAME']
181 except KeyError:
182 pass
183 else:
184 handle.write(
185 "\nexport CYLC_ENV_NAME='%s'" % CYLC_ENV_NAME)
186 handle.write(
187 '\nexport CYLC_WORKFLOW_ID='
188 f'"{job_conf["workflow_name"]}"'
189 )
190 env_vars = (
191 (job_conf['platform']['copyable environment variables'] or [])
192 # pass CYLC_COVERAGE into the job execution environment
193 + ['CYLC_COVERAGE']
194 )
195 for key in env_vars:
196 if key in os.environ:
197 handle.write("\nexport %s='%s'" % (key, os.environ[key]))
198
199 def _write_workflow_environment(self, handle, job_conf):
200 """Workflow and task environment."""
201 handle.write("\n\ncylc__job__inst__cylc_env() {")
202 handle.write("\n # CYLC WORKFLOW ENVIRONMENT:")
203 # write the static workflow variables
204 for var, val in sorted(self.workflow_env.items()):
205 if var not in ('CYLC_DEBUG', 'CYLC_VERBOSE', 'CYLC_WORKFLOW_ID'):
206 handle.write('\n export %s="%s"' % (var, val))
207
208 if str(self.workflow_env.get('CYLC_UTC')) == 'True':
209 handle.write('\n export TZ="UTC"')
210
211 handle.write(
212 '\n export CYLC_WORKFLOW_UUID="%s"' % job_conf['uuid_str'])
213
214 def _write_task_environment(self, handle, job_conf):
215 comm_meth = job_conf['platform']['communication method']
216
217 handle.write("\n\n # CYLC TASK ENVIRONMENT:")
218 handle.write(f"\n export CYLC_TASK_COMMS_METHOD={comm_meth}")
219 handle.write('\n export CYLC_TASK_JOB="%s"' % job_conf['job_d'])
220 handle.write(
221 '\n export CYLC_TASK_NAMESPACE_HIERARCHY="%s"' %
222 ' '.join(job_conf['namespace_hierarchy']))
223 handle.write(
224 '\n export CYLC_TASK_TRY_NUMBER=%s' % job_conf['try_num'])
225 handle.write(
226 "\n export CYLC_TASK_FLOW_NUMBERS="
227 f"{','.join(str(f) for f in job_conf['flow_nums'])}"
228 )
229 # Standard parameter environment variables
230 for var, val in job_conf['param_var'].items():
231 handle.write('\n export CYLC_TASK_PARAM_%s="%s"' % (var, val))
232 if job_conf['work_d']:
233 # Note: not an environment variable, but used by job.sh
234 handle.write(
235 "\n CYLC_TASK_WORK_DIR_BASE='%s'" % job_conf['work_d'])
236 handle.write("\n}")
237
238 @staticmethod
239 def _write_runtime_environment(handle, job_conf):
240 if job_conf['environment']:
241 handle.write("\n\ncylc__job__inst__user_env() {")
242 # Generate variable assignment expressions
243 handle.write("\n # TASK RUNTIME ENVIRONMENT:")
244
245 # NOTE: the reason for separate export of user-specified
246 # variables is this: inline export does not activate the
247 # error trap if sub-expressions fail, e.g. (note typo in
248 # 'echo' command name):
249 # export FOO=$( ecko foo ) # error not trapped!
250 # FOO=$( ecko foo ) # error trapped
251 # The export is done before variable definition to enable
252 # use of already defined variables by command substitutions
253 # in later definitions:
254 # FOO='foo'
255 # BAR=$(script_using_FOO)
256 handle.write("\n export")
257 for var in job_conf['environment']:
258 handle.write(f' {var}')
259 for var, val in job_conf['environment'].items():
260 value = JobFileWriter._get_variable_value_definition(
261 str(val), job_conf.get('param_var', {})
262 )
263 handle.write(f'\n {var}={value}')
264 handle.write("\n}")
265
266 @staticmethod
267 def _get_variable_value_definition(value, param_vars):
268 """Return a properly-quoted command which handles parameter environment
269 templates and the '~' character.
270
271 Args:
272 value (str): value to assign to a variable
273 param_vars (dict): parameter variables ( job_conf['param_vars'] )
274 """
275 # Interpolate any parameter environment template variables:
276 if param_vars:
277 with suppress(ParamExpandError):
278 value = interpolate_template(value, param_vars)
279 # ParamExpandError: Already logged warnings in
280 # cylc.flow.config.WorkflowConfig.check_param_env_tmpls()
281
282 # Handle '~':
283 match = re.match(r"^(~[^/\s]*/)(.*)$", value)
284 if match:
285 # ~foo/bar or ~/bar
286 # write as ~foo/"bar" or ~/"bar"
287 head, tail = match.groups()
288 return '%s"%s"' % (head, tail)
289 elif re.match(r"^~[^\s]*$", value):
290 # plain ~foo or just ~
291 # just leave unquoted as subsequent spaces don't
292 # make sense in this case anyway
293 return value
294 else:
295 # Non tilde values - quote the lot.
296 # This gets values like "~one ~two" too, but these
297 # (in variable values) aren't expanded by the shell
298 # anyway so it doesn't matter.
299 return '"%s"' % value
300
301 # NOTE ON TILDE EXPANSION:
302 # The code above handles the following correctly:
303 # | ~foo/bar
304 # | ~/bar
305 # | ~/filename with spaces
306 # | ~foo
307 # | ~
308
309 @classmethod
310 def _write_global_init_script(cls, handle, job_conf):
311 """Global Init-script."""
312 global_init_script = job_conf['platform']['global init-script']
313 if cls._check_script_value(global_init_script):
314 handle.write("\n\n# GLOBAL INIT-SCRIPT:\n")
315 handle.write(global_init_script)
316
317 @classmethod
318 def _write_script(cls, handle, job_conf):
319 """Write (*-)script in functions.
320
321 init-script, env-script, err-script, pre-script, script, post-script,
322 exit-script
323 """
324 for prefix in ['init-', 'env-', 'err-', 'pre-', '', 'post-', 'exit-']:
325 value = job_conf[prefix + 'script']
326 if cls._check_script_value(value):
327 handle.write("\n\ncylc__job__inst__%sscript() {" % (
328 prefix.replace("-", "_")))
329 handle.write("\n# %sSCRIPT:\n%s" % (
330 prefix.upper(), value))
331 handle.write("\n}")
332
333 @staticmethod
334 def _write_epilogue(handle, job_conf):
335 """Write epilogue."""
336 handle.write('\n\nCYLC_RUN_DIR="${CYLC_RUN_DIR:-$HOME/cylc-run}"')
337 handle.write(
338 '\n. '
339 '"${CYLC_RUN_DIR}/${CYLC_WORKFLOW_ID}/.service/etc/job.sh"'
340 '\ncylc__job__main'
341 )
342 handle.write("\n\n%s%s\n" % (
343 JobRunnerManager.LINE_PREFIX_EOF, job_conf['job_d']))