Debian Codegraph @

cylc/flow/job_runner_handlers/slurm.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 """Submits job scripts to Simple Linux Utility for Resource Management.
17
18 .. cylc-scope:: flow.cylc[runtime][<namespace>]
19
20 Uses the ``sbatch`` command. SLURM directives can be provided in the flow.cylc
21 file:
22
23 .. code-block:: cylc
24 :caption: global.cylc
25
26 [platforms]
27 [[slurm_platform]]
28 job runner = slurm
29
30 .. code-block:: cylc
31 :caption: flow.cylc
32
33 [runtime]
34 [[my_task]]
35 platform = slurm_platform
36 execution time limit = PT1H
37 [[[directives]]]
38 --nodes = 5
39 --account = QXZ5W2
40
41 .. note::
42
43 * Cylc requires long form directives (e.g. ``--begin`` not ``-b``).
44 * Cylc requires an ``=`` even if the directive does not have a value
45 (e.g. ``--hold=`` not ``--hold``).
46 * If a directive does not have a value you may use the short form
47 (e.g. ``-H=``). But the directive must still be suffixed with an ``=``.
48
49 These are written to the top of the job script like this:
50
51 .. code-block:: bash
52
53 #!/bin/bash
54 #SBATCH --nodes=5
55 #SBATCH --time=60:00
56 #SBATCH --account=QXZ5W2
57
58 If :cylc:conf:`execution time limit` is specified, it is used to generate the
59 ``--time`` directive. Do not specify the ``--time`` directive explicitly if
60 :cylc:conf:`execution time limit` is specified. Otherwise, the execution time
61 limit known by the workflow may be out of sync with what is submitted to the
62 job runner.
63
64 Cylc supports heterogeneous Slurm jobs via special numbered directive prefixes
65 that distinguish repeated directives from one another:
66
67 .. code-block:: cylc
68
69 [runtime]
70 # run two heterogenous job components:
71 script = srun sleep 10 : sleep 30
72 [[my_task]]
73 execution time limit = PT1H
74 platform = slurm_platform
75 [[[directives]]]
76 --account = QXZ5W2
77 hetjob_0_--mem = 1G # first prefix must be "0"
78 hetjob_0_--nodes = 3
79 hetjob_1_--mem = 2G
80 hetjob_1_--nodes = 6
81
82 The resulting formatted directives are:
83
84 .. code-block:: bash
85
86 #!/bin/bash
87 #SBATCH --time=60:00
88 #SBATCH --account=QXZ5W2
89 #SBATCH --mem=1G
90 #SBATCH --nodes=3
91 #SBATCH hetjob
92 #SBATCH --mem=2G
93 #SBATCH --nodes=6
94
95 .. note::
96
97 For older Slurm versions with *packjob* instead of *hetjob*, use
98 :cylc:conf:`global.cylc[platforms][<platform name>]job runner =
99 slurm_packjob` and directive prefixes ``packjob_0_`` etc.
100
101 .. cylc-scope::
102
103 """
104
105 import re
106 import shlex
107
108 from cylc.flow.id import Tokens
109
110
111 class SLURMHandler():
112 """SLURM job submission and manipulation."""
113
114 DIRECTIVE_PREFIX = "#SBATCH "
115 # SLURM tries to kill the parent script directly with SIGTERM rather than
116 # the process group as a whole. In these circumstances it is the jobscript
117 # that handles the signal propagation to children (fixed in #3440).
118 # This does not apply to jobs with proper 'steps'
119 # (e.g. using srun within an sbatch script), which are properly
120 # signalled.
121 # XCPU isn't used by SLURM at the moment, but it's a valid way
122 # to manually signal jobs using scancel or sbatch --signal.
123 KILL_CMD_TMPL = "scancel '%(job_id)s'"
124 # N.B. The "squeue -j JOB_ID" command returns 1 if JOB_ID is no longer in
125 # the system, so there is no need to filter its output.
126 POLL_CMD = "squeue -h"
127 REC_ID_FROM_SUBMIT_OUT = re.compile(
128 r"\ASubmitted\sbatch\sjob\s(?P<id>\d+)")
129 REC_ID_FROM_POLL_OUT = re.compile(r"^ *(?P<id>\d+)")
130 SUBMIT_CMD_TMPL = "sbatch '%(job)s'"
131
132 # Heterogeneous job support
133 # Match artificial directive prefix
134 REC_HETJOB = re.compile(r"^hetjob_(\d+)_")
135 # Separator between het job directive sections
136 SEP_HETJOB = "#SBATCH hetjob"
137
138 TIME_LIMIT_DIRECTIVE = "--time"
139
140 @classmethod
141 def filter_poll_many_output(cls, out):
142 """Return list of job IDs extracted from job poll stdout.
143
144 Needed to avoid the extension for heterogenous jobs ("+0", "+1" etc.)
145
146 """
147 job_ids = set()
148 for line in out.splitlines():
149 m = cls.REC_ID_FROM_POLL_OUT.match(line)
150 if m:
151 job_ids.add(m.group("id"))
152 return list(job_ids)
153
154 @classmethod
155 def format_directives(cls, job_conf):
156 """Format the job directives for a job file."""
157 job_file_path = job_conf['job_file_path']
158 directives = job_conf['directives'].__class__()
159 tokens = Tokens(job_conf['task_id'], relative=True)
160 directives['--job-name'] = (
161 f'{tokens["task"]}.{tokens["cycle"]}.{job_conf["workflow_name"]}'
162 )
163 directives['--output'] = job_file_path.replace('%', '%%') + ".out"
164 directives['--error'] = job_file_path.replace('%', '%%') + ".err"
165 if (job_conf["execution_time_limit"] and
166 directives.get(cls.TIME_LIMIT_DIRECTIVE) is None):
167 directives[cls.TIME_LIMIT_DIRECTIVE] = "%d:%02d" % (
168 job_conf["execution_time_limit"] / 60,
169 job_conf["execution_time_limit"] % 60)
170 for key, value in list(job_conf['directives'].items()):
171 directives[key] = value
172 lines = []
173 seen = set()
174 for key, value in directives.items():
175 m = cls.REC_HETJOB.match(key)
176 if m:
177 n = m.groups()[0]
178 if n != "0" and n not in seen:
179 lines.append(cls.SEP_HETJOB)
180 seen.add(n)
181 newkey = cls.REC_HETJOB.sub('', key)
182 else:
183 newkey = key
184 if value:
185 lines.append("%s%s=%s" % (cls.DIRECTIVE_PREFIX, newkey, value))
186 else:
187 lines.append("%s%s" % (cls.DIRECTIVE_PREFIX, newkey))
188 return lines
189
190 @classmethod
191 def get_poll_many_cmd(cls, job_ids):
192 """Return the poll command for a list of job IDs."""
193 return shlex.split(cls.POLL_CMD) + ["-j", ",".join(job_ids)]
194
195
196 JOB_RUNNER_HANDLER = SLURMHandler()