| 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 |
"""Manage submission, poll and kill of a job to the job runners. |
| 18 |
|
| 19 |
The job runner interface is documented in |
| 20 |
cylc.flow.job_runner_handlers.documentation. |
| 21 |
|
| 22 |
Please update this file as the interface changes. |
| 23 |
|
| 24 |
""" |
| 25 |
|
| 26 |
from contextlib import suppress |
| 27 |
import json |
| 28 |
import os |
| 29 |
from pathlib import Path |
| 30 |
import shlex |
| 31 |
import stat |
| 32 |
import sys |
| 33 |
import traceback |
| 34 |
from shutil import rmtree |
| 35 |
from signal import SIGKILL |
| 36 |
from subprocess import DEVNULL # nosec |
| 37 |
|
| 38 |
from cylc.flow.task_message import ( |
| 39 |
CYLC_JOB_PID, CYLC_JOB_INIT_TIME, CYLC_JOB_EXIT_TIME, CYLC_JOB_EXIT, |
| 40 |
CYLC_MESSAGE) |
| 41 |
from cylc.flow.cylc_subproc import procopen |
| 42 |
from cylc.flow.task_job_logs import ( |
| 43 |
JOB_LOG_ERR, JOB_LOG_JOB, JOB_LOG_OUT, JOB_LOG_STATUS) |
| 44 |
from cylc.flow.task_outputs import TASK_OUTPUT_SUCCEEDED |
| 45 |
from cylc.flow.wallclock import get_current_time_string |
| 46 |
from cylc.flow.parsec.OrderedDict import OrderedDict |
| 47 |
|
| 48 |
|
| 49 |
JOB_FILES_REMOVED_MESSAGE = 'ERR_JOB_FILES_REMOVED' |
| 50 |
|
| 51 |
|
| 52 |
class JobPollContext(): |
| 53 |
"""Context object for a job poll.""" |
| 54 |
CONTEXT_ATTRIBUTES = ( |
| 55 |
'job_log_dir', # cycle/task/submit_num |
| 56 |
'job_runner_name', |
| 57 |
'job_id', # job id in job runner |
| 58 |
'job_runner_exit_polled', # 0 for false, 1 for true |
| 59 |
'run_status', # 0 for success, 1 for failure |
| 60 |
'run_signal', # signal received on run failure |
| 61 |
'time_submit_exit', # submit (exit) time |
| 62 |
'time_run', # run start time |
| 63 |
'time_run_exit', # run exit time |
| 64 |
'job_runner_call_no_lines', # line count in job runner call stdout |
| 65 |
) |
| 66 |
|
| 67 |
__slots__ = CONTEXT_ATTRIBUTES + ( |
| 68 |
'pid', |
| 69 |
'messages' |
| 70 |
) |
| 71 |
|
| 72 |
def __init__(self, job_log_dir, **attrs): |
| 73 |
self.job_log_dir = job_log_dir |
| 74 |
self.job_runner_name = None |
| 75 |
self.job_id = None |
| 76 |
self.job_runner_exit_polled = None |
| 77 |
self.pid = None |
| 78 |
self.run_status = None |
| 79 |
self.run_signal = None |
| 80 |
self.time_submit_exit = None |
| 81 |
self.time_run = None |
| 82 |
self.time_run_exit = None |
| 83 |
self.job_runner_call_no_lines = None |
| 84 |
self.messages = [] |
| 85 |
|
| 86 |
if attrs: |
| 87 |
for key, value in attrs.items(): |
| 88 |
if key not in self.CONTEXT_ATTRIBUTES: |
| 89 |
raise ValueError('Invalid kwarg "%s"' % key) |
| 90 |
setattr(self, key, value) |
| 91 |
|
| 92 |
def update(self, other): |
| 93 |
"""Update my data from given file context.""" |
| 94 |
for i in self.__slots__: |
| 95 |
setattr(self, i, getattr(other, i)) |
| 96 |
|
| 97 |
def get_summary_str(self): |
| 98 |
"""Return the poll context as a summary string delimited by "|".""" |
| 99 |
ret = OrderedDict() |
| 100 |
for key in self.CONTEXT_ATTRIBUTES: |
| 101 |
value = getattr(self, key) |
| 102 |
if key == 'job_log_dir' or value is None: |
| 103 |
continue |
| 104 |
ret[key] = value |
| 105 |
return '%s|%s' % (self.job_log_dir, json.dumps(ret)) |
| 106 |
|
| 107 |
|
| 108 |
class JobRunnerManager(): |
| 109 |
"""Job submission, poll and kill. |
| 110 |
|
| 111 |
Manage the importing of job submission method modules. |
| 112 |
|
| 113 |
""" |
| 114 |
|
| 115 |
CYLC_JOB_RUNNER_NAME = "CYLC_JOB_RUNNER_NAME" |
| 116 |
CYLC_JOB_ID = "CYLC_JOB_ID" |
| 117 |
CYLC_JOB_RUNNER_SUBMIT_TIME = "CYLC_JOB_RUNNER_SUBMIT_TIME" |
| 118 |
CYLC_JOB_RUNNER_EXIT_POLLED = "CYLC_JOB_RUNNER_EXIT_POLLED" |
| 119 |
FAIL_SIGNALS = ("EXIT", "ERR", "TERM", "XCPU") |
| 120 |
LINE_PREFIX_JOB_RUNNER_NAME = "# Job runner: " |
| 121 |
LINE_PREFIX_JOB_RUNNER_CMD_TMPL = "# Job runner command template: " |
| 122 |
LINE_PREFIX_EXECUTION_TIME_LIMIT = "# Execution time limit: " |
| 123 |
LINE_PREFIX_EOF = "#EOF: " |
| 124 |
LINE_PREFIX_JOB_LOG_DIR = "# Job log directory: " |
| 125 |
OUT_PREFIX_COMMAND = "[TASK JOB COMMAND]" |
| 126 |
OUT_PREFIX_MESSAGE = "[TASK JOB MESSAGE]" |
| 127 |
OUT_PREFIX_SUMMARY = "[TASK JOB SUMMARY]" |
| 128 |
OUT_PREFIX_CMD_ERR = "[TASK JOB ERROR]" |
| 129 |
_INSTANCES: dict = {} |
| 130 |
|
| 131 |
@classmethod |
| 132 |
def configure_workflow_run_dir(cls, workflow_run_dir): |
| 133 |
"""Add local python module paths if not already done.""" |
| 134 |
for sub_dir in ["python", os.path.join("lib", "python")]: |
| 135 |
# TODO - eventually drop the deprecated "python" sub-dir. |
| 136 |
workflow_py = os.path.join(workflow_run_dir, sub_dir) |
| 137 |
if os.path.isdir(workflow_py) and workflow_py not in sys.path: |
| 138 |
sys.path.append(workflow_py) |
| 139 |
|
| 140 |
def __init__(self, clean_env=False, env=None, path=None): |
| 141 |
"""Initialise JobRunnerManager.""" |
| 142 |
# Job submission environment. |
| 143 |
self.clean_env = clean_env |
| 144 |
self.path = path |
| 145 |
self.env = env |
| 146 |
|
| 147 |
def _get_sys(self, job_runner_name): |
| 148 |
"""Return an instance of the class for "job_runner_name".""" |
| 149 |
if job_runner_name in self._INSTANCES: |
| 150 |
return self._INSTANCES[job_runner_name] |
| 151 |
for key in [f"cylc.flow.job_runner_handlers.{job_runner_name}", |
| 152 |
job_runner_name]: |
| 153 |
|
| 154 |
try: |
| 155 |
mod_of_name = __import__(key, fromlist=[key]) |
| 156 |
self._INSTANCES[job_runner_name] = getattr( |
| 157 |
mod_of_name, "JOB_RUNNER_HANDLER", None) |
| 158 |
return self._INSTANCES[job_runner_name] |
| 159 |
except ImportError: |
| 160 |
if key == job_runner_name: |
| 161 |
raise |
| 162 |
|
| 163 |
def format_directives(self, job_conf): |
| 164 |
"""Format the job directives for a job file, if relevant.""" |
| 165 |
job_runner = self._get_sys(job_conf['platform']['job runner']) |
| 166 |
if hasattr(job_runner, "format_directives"): |
| 167 |
job_conf = { |
| 168 |
# strip $HOME from the job file path |
| 169 |
# paths in directives should be interpreted relative to $HOME |
| 170 |
# https://github.com/cylc/cylc-flow/issues/4247 |
| 171 |
**job_conf, |
| 172 |
'job_file_path': ( |
| 173 |
job_conf["job_file_path"].replace(r"$HOME/", "") |
| 174 |
) |
| 175 |
} |
| 176 |
return job_runner.format_directives(job_conf) |
| 177 |
|
| 178 |
def get_fail_signals(self, job_conf): |
| 179 |
"""Return a list of failure signal names to trap in the job file.""" |
| 180 |
job_runner = self._get_sys(job_conf['platform']['job runner']) |
| 181 |
return getattr(job_runner, "FAIL_SIGNALS", self.FAIL_SIGNALS) |
| 182 |
|
| 183 |
def get_vacation_signal(self, job_conf): |
| 184 |
"""Return the vacation signal name for a job file.""" |
| 185 |
job_runner = self._get_sys(job_conf['platform']['job runner']) |
| 186 |
if hasattr(job_runner, "get_vacation_signal"): |
| 187 |
return job_runner.get_vacation_signal(job_conf) |
| 188 |
|
| 189 |
def is_job_local_to_host(self, job_runner_name): |
| 190 |
"""Return True if job runner runs jobs local to the submit host.""" |
| 191 |
return getattr( |
| 192 |
self._get_sys(job_runner_name), "SHOULD_KILL_PROC_GROUP", False) |
| 193 |
|
| 194 |
def jobs_kill(self, job_log_root, job_log_dirs): |
| 195 |
"""Kill multiple jobs. |
| 196 |
|
| 197 |
job_log_root -- The log/job/ sub-directory of the workflow. |
| 198 |
job_log_dirs -- A list containing point/name/submit_num for jobs. |
| 199 |
|
| 200 |
""" |
| 201 |
# Note: The more efficient way to do this is to group the jobs by their |
| 202 |
# job runners, and call the kill command for each job runner once. |
| 203 |
# However, this will make it more difficult to determine if the kill |
| 204 |
# command for a particular job is successful or not. |
| 205 |
if "$" in job_log_root: |
| 206 |
job_log_root = os.path.expandvars(job_log_root) |
| 207 |
self.configure_workflow_run_dir(job_log_root.rsplit(os.sep, 2)[0]) |
| 208 |
now = get_current_time_string() |
| 209 |
for job_log_dir in job_log_dirs: |
| 210 |
ret_code, err = self.job_kill( |
| 211 |
os.path.join(job_log_root, job_log_dir, JOB_LOG_STATUS)) |
| 212 |
sys.stdout.write("%s%s|%s|%d\n" % ( |
| 213 |
self.OUT_PREFIX_SUMMARY, now, job_log_dir, ret_code)) |
| 214 |
# Note: Print STDERR to STDOUT may look a bit strange, but it |
| 215 |
# requires less logic for the workflow to parse the output. |
| 216 |
for line in err.strip().splitlines(): |
| 217 |
sys.stdout.write( |
| 218 |
f"{self.OUT_PREFIX_CMD_ERR}{now}|{job_log_dir}|{line}\n" |
| 219 |
) |
| 220 |
|
| 221 |
def jobs_poll(self, job_log_root, job_log_dirs): |
| 222 |
"""Poll multiple jobs. |
| 223 |
|
| 224 |
job_log_root -- The log/job/ sub-directory of the workflow. |
| 225 |
job_log_dirs -- A list containing point/name/submit_num for jobs. |
| 226 |
|
| 227 |
""" |
| 228 |
if "$" in job_log_root: |
| 229 |
job_log_root = os.path.expandvars(job_log_root) |
| 230 |
self.configure_workflow_run_dir(job_log_root.rsplit(os.sep, 2)[0]) |
| 231 |
|
| 232 |
ctx_list = [] # Contexts for all relevant jobs |
| 233 |
ctx_list_by_job_runner = {} # {job_runner_name1: [ctx1, ...], ...} |
| 234 |
|
| 235 |
for job_log_dir in job_log_dirs: |
| 236 |
ctx = self._jobs_poll_status_files(job_log_root, job_log_dir) |
| 237 |
if ctx is None: |
| 238 |
continue |
| 239 |
ctx_list.append(ctx) |
| 240 |
|
| 241 |
if not ctx.job_runner_name or not ctx.job_id: |
| 242 |
# Lost job runner information for some reason. |
| 243 |
# Mark the job as if it is no longer in the job runner. |
| 244 |
ctx.job_runner_exit_polled = 1 |
| 245 |
sys.stderr.write( |
| 246 |
"%s/%s: incomplete job runner info\n" % ( |
| 247 |
ctx.job_log_dir, JOB_LOG_STATUS)) |
| 248 |
|
| 249 |
# We can trust: |
| 250 |
# * Jobs previously polled to have exited the job runner. |
| 251 |
# * Jobs succeeded or failed with ERR/EXIT. |
| 252 |
if (ctx.job_runner_exit_polled or ctx.run_status == 0 or |
| 253 |
ctx.run_signal in ["ERR", "EXIT"]): |
| 254 |
continue |
| 255 |
|
| 256 |
if ctx.job_runner_name not in ctx_list_by_job_runner: |
| 257 |
ctx_list_by_job_runner[ctx.job_runner_name] = [] |
| 258 |
ctx_list_by_job_runner[ctx.job_runner_name].append(ctx) |
| 259 |
|
| 260 |
for job_runner_name, my_ctx_list in ctx_list_by_job_runner.items(): |
| 261 |
self._jobs_poll_runner( |
| 262 |
job_log_root, job_runner_name, my_ctx_list) |
| 263 |
|
| 264 |
cur_time_str = get_current_time_string() |
| 265 |
for ctx in ctx_list: |
| 266 |
for message in ctx.messages: |
| 267 |
sys.stdout.write("%s%s|%s|%s\n" % ( |
| 268 |
self.OUT_PREFIX_MESSAGE, |
| 269 |
cur_time_str, |
| 270 |
ctx.job_log_dir, |
| 271 |
message)) |
| 272 |
sys.stdout.write("%s%s|%s\n" % ( |
| 273 |
self.OUT_PREFIX_SUMMARY, |
| 274 |
cur_time_str, |
| 275 |
ctx.get_summary_str())) |
| 276 |
|
| 277 |
def jobs_submit(self, job_log_root, job_log_dirs, remote_mode=False, |
| 278 |
utc_mode=False): |
| 279 |
"""Submit multiple jobs. |
| 280 |
|
| 281 |
job_log_root -- The log/job/ sub-directory of the workflow. |
| 282 |
job_log_dirs -- A list containing point/name/submit_num for jobs. |
| 283 |
remote_mode -- am I running on the remote job host? |
| 284 |
utc_mode -- is the workflow running in UTC mode? |
| 285 |
|
| 286 |
""" |
| 287 |
if "$" in job_log_root: |
| 288 |
job_log_root = os.path.expandvars(job_log_root) |
| 289 |
self.configure_workflow_run_dir(job_log_root.rsplit(os.sep, 2)[0]) |
| 290 |
if remote_mode: |
| 291 |
items = self._jobs_submit_prep_by_stdin(job_log_root, job_log_dirs) |
| 292 |
else: |
| 293 |
items = self._jobs_submit_prep_by_args(job_log_root, job_log_dirs) |
| 294 |
now = get_current_time_string(override_use_utc=utc_mode) |
| 295 |
for job_log_dir, job_runner_name, submit_opts in items: |
| 296 |
job_file_path = os.path.join( |
| 297 |
job_log_root, job_log_dir, JOB_LOG_JOB) |
| 298 |
if not job_runner_name: |
| 299 |
sys.stdout.write("%s%s|%s|1|\n" % ( |
| 300 |
self.OUT_PREFIX_SUMMARY, now, job_log_dir)) |
| 301 |
continue |
| 302 |
ret_code, out, err, job_id = self._job_submit_impl( |
| 303 |
job_file_path, job_runner_name, submit_opts) |
| 304 |
sys.stdout.write("%s%s|%s|%d|%s\n" % ( |
| 305 |
self.OUT_PREFIX_SUMMARY, now, job_log_dir, ret_code, job_id)) |
| 306 |
for key, value in [("STDERR", err), ("STDOUT", out)]: |
| 307 |
if value is None: |
| 308 |
continue |
| 309 |
for line in value.strip().splitlines(): |
| 310 |
sys.stdout.write( |
| 311 |
f"{self.OUT_PREFIX_COMMAND}{now}" |
| 312 |
f"|{job_log_dir}|[{key}] {line}\n" |
| 313 |
) |
| 314 |
|
| 315 |
def job_kill(self, st_file_path): |
| 316 |
"""Ask job runner to terminate the job specified in "st_file_path". |
| 317 |
|
| 318 |
Return 0 on success, non-zero integer on failure. |
| 319 |
|
| 320 |
""" |
| 321 |
# WORKFLOW_RUN_DIR/log/job/CYCLE/TASK/SUBMIT/job.status |
| 322 |
self.configure_workflow_run_dir(st_file_path.rsplit(os.sep, 6)[0]) |
| 323 |
try: |
| 324 |
with open(st_file_path) as st_file: |
| 325 |
for line in st_file: |
| 326 |
if line.startswith(f"{self.CYLC_JOB_RUNNER_NAME}="): |
| 327 |
job_runner = self._get_sys( |
| 328 |
line.strip().split("=", 1)[1] |
| 329 |
) |
| 330 |
break |
| 331 |
else: |
| 332 |
return ( |
| 333 |
1, |
| 334 |
"Cannot determine job runner from " |
| 335 |
f"{JOB_LOG_STATUS} file" |
| 336 |
) |
| 337 |
st_file.seek(0, 0) # rewind |
| 338 |
if getattr(job_runner, "SHOULD_KILL_PROC_GROUP", False): |
| 339 |
for line in st_file: |
| 340 |
if line.startswith(CYLC_JOB_PID + "="): |
| 341 |
pid = line.strip().split("=", 1)[1] |
| 342 |
try: |
| 343 |
os.killpg(os.getpgid(int(pid)), SIGKILL) |
| 344 |
except (OSError, ValueError) as exc: |
| 345 |
traceback.print_exc() |
| 346 |
return (1, str(exc)) |
| 347 |
else: |
| 348 |
return (0, "") |
| 349 |
st_file.seek(0, 0) # rewind |
| 350 |
if hasattr(job_runner, "KILL_CMD_TMPL"): |
| 351 |
for line in st_file: |
| 352 |
if not line.startswith(f"{self.CYLC_JOB_ID}="): |
| 353 |
continue |
| 354 |
job_id = line.strip().split("=", 1)[1] |
| 355 |
command = shlex.split( |
| 356 |
job_runner.KILL_CMD_TMPL % {"job_id": job_id}) |
| 357 |
try: |
| 358 |
proc = procopen(command, stdindevnull=True, |
| 359 |
stderrpipe=True) |
| 360 |
except OSError as exc: |
| 361 |
# subprocess.Popen has a bad habit of not setting |
| 362 |
# the filename of the executable when it raises an |
| 363 |
# OSError. |
| 364 |
if not exc.filename: |
| 365 |
exc.filename = command[0] |
| 366 |
traceback.print_exc() |
| 367 |
return (1, str(exc)) |
| 368 |
else: |
| 369 |
return ( |
| 370 |
proc.wait(), |
| 371 |
proc.communicate()[1].decode() |
| 372 |
) |
| 373 |
return (1, f"Cannot determine job ID from {JOB_LOG_STATUS} file") |
| 374 |
except IOError as exc: |
| 375 |
return (1, str(exc)) |
| 376 |
|
| 377 |
@classmethod |
| 378 |
def _create_nn(cls, job_file_path): |
| 379 |
"""Create NN symbolic link if necessary, and remove any old job logs. |
| 380 |
|
| 381 |
If NN => 01, remove numbered dirs with submit numbers greater than 01. |
| 382 |
|
| 383 |
Helper for "self._job_submit_impl". |
| 384 |
|
| 385 |
""" |
| 386 |
job_file_dir = os.path.dirname(job_file_path) |
| 387 |
|
| 388 |
source = os.path.basename(job_file_dir) |
| 389 |
task_log_dir = os.path.dirname(job_file_dir) |
| 390 |
nn_path = os.path.join(task_log_dir, "NN") |
| 391 |
try: |
| 392 |
old_source = os.readlink(nn_path) |
| 393 |
except OSError: |
| 394 |
old_source = None |
| 395 |
if old_source is not None and old_source != source: |
| 396 |
os.unlink(nn_path) |
| 397 |
old_source = None |
| 398 |
if old_source is None: |
| 399 |
os.symlink(source, nn_path) |
| 400 |
|
| 401 |
# On submit 1, remove any left over digit directories from prev runs |
| 402 |
if source == "01": |
| 403 |
for name in os.listdir(task_log_dir): |
| 404 |
if name != source and name.isdigit(): |
| 405 |
# Ignore errors, not disastrous if rmtree fails |
| 406 |
rmtree( |
| 407 |
os.path.join(task_log_dir, name), ignore_errors=True) |
| 408 |
|
| 409 |
# Delete old job logs if necessary |
| 410 |
for name in JOB_LOG_ERR, JOB_LOG_OUT: |
| 411 |
with suppress(FileNotFoundError): |
| 412 |
os.unlink(os.path.join(job_file_dir, name)) |
| 413 |
|
| 414 |
@classmethod |
| 415 |
def _filter_submit_output(cls, st_file_path, job_runner, out, err): |
| 416 |
"""Filter submit command output, if relevant.""" |
| 417 |
job_id = None |
| 418 |
if hasattr(job_runner, "REC_ID_FROM_SUBMIT_ERR"): |
| 419 |
text = err |
| 420 |
rec_id = job_runner.REC_ID_FROM_SUBMIT_ERR |
| 421 |
elif hasattr(job_runner, "REC_ID_FROM_SUBMIT_OUT"): |
| 422 |
text = out |
| 423 |
rec_id = job_runner.REC_ID_FROM_SUBMIT_OUT |
| 424 |
if rec_id: |
| 425 |
for line in str(text).splitlines(): |
| 426 |
match = rec_id.match(line) |
| 427 |
if match: |
| 428 |
job_id = match.group("id") |
| 429 |
if hasattr(job_runner, "manip_job_id"): |
| 430 |
job_id = job_runner.manip_job_id(job_id) |
| 431 |
with open(st_file_path, "a") as job_status_file: |
| 432 |
job_status_file.write("{0}={1}\n".format( |
| 433 |
cls.CYLC_JOB_ID, job_id)) |
| 434 |
job_status_file.write("{0}={1}\n".format( |
| 435 |
cls.CYLC_JOB_RUNNER_SUBMIT_TIME, |
| 436 |
get_current_time_string())) |
| 437 |
break |
| 438 |
if hasattr(job_runner, "filter_submit_output"): |
| 439 |
out, err = job_runner.filter_submit_output(out, err) |
| 440 |
return out, err, job_id |
| 441 |
|
| 442 |
def _jobs_poll_status_files(self, job_log_root, job_log_dir): |
| 443 |
"""Helper 1 for self.jobs_poll(job_log_root, job_log_dirs).""" |
| 444 |
ctx = JobPollContext(job_log_dir) |
| 445 |
# If the log directory has been deleted prematurely, return a task |
| 446 |
# failure and an explanation: |
| 447 |
if not os.path.exists(os.path.join(job_log_root, ctx.job_log_dir)): |
| 448 |
# The job may still be in the job runner and may yet succeed, |
| 449 |
# but we assume it failed & exited because it's the best we |
| 450 |
# can do as it is no longer possible to poll it. |
| 451 |
ctx.run_status = 1 |
| 452 |
ctx.job_runner_exit_polled = 1 |
| 453 |
ctx.run_signal = JOB_FILES_REMOVED_MESSAGE |
| 454 |
return ctx |
| 455 |
try: |
| 456 |
with open( |
| 457 |
os.path.join(job_log_root, ctx.job_log_dir, JOB_LOG_STATUS) |
| 458 |
) as handle: |
| 459 |
for line in handle: |
| 460 |
if "=" not in line: |
| 461 |
continue |
| 462 |
key, value = line.strip().split("=", 1) |
| 463 |
if key == self.CYLC_JOB_RUNNER_NAME: |
| 464 |
ctx.job_runner_name = value |
| 465 |
elif key == self.CYLC_JOB_ID: |
| 466 |
ctx.job_id = value |
| 467 |
elif key == self.CYLC_JOB_RUNNER_EXIT_POLLED: |
| 468 |
ctx.job_runner_exit_polled = 1 |
| 469 |
elif key == CYLC_JOB_PID: |
| 470 |
ctx.pid = value |
| 471 |
elif key == self.CYLC_JOB_RUNNER_SUBMIT_TIME: |
| 472 |
ctx.time_submit_exit = value |
| 473 |
elif key == CYLC_JOB_INIT_TIME: |
| 474 |
ctx.time_run = value |
| 475 |
elif key == CYLC_JOB_EXIT_TIME: |
| 476 |
ctx.time_run_exit = value |
| 477 |
elif key == CYLC_JOB_EXIT: |
| 478 |
if value == TASK_OUTPUT_SUCCEEDED.upper(): |
| 479 |
ctx.run_status = 0 |
| 480 |
else: |
| 481 |
ctx.run_status = 1 |
| 482 |
ctx.run_signal = value |
| 483 |
elif key == CYLC_MESSAGE: |
| 484 |
ctx.messages.append(value) |
| 485 |
except IOError as exc: |
| 486 |
sys.stderr.write(f"{exc}\n") |
| 487 |
return |
| 488 |
|
| 489 |
return ctx |
| 490 |
|
| 491 |
def _jobs_poll_runner(self, job_log_root, job_runner_name, my_ctx_list): |
| 492 |
"""Helper 2 for self.jobs_poll(job_log_root, job_log_dirs).""" |
| 493 |
exp_job_ids = [ctx.job_id for ctx in my_ctx_list] |
| 494 |
bad_job_ids = list(exp_job_ids) |
| 495 |
exp_pids = [] |
| 496 |
bad_pids = [] |
| 497 |
items = [[self._get_sys(job_runner_name), exp_job_ids, bad_job_ids]] |
| 498 |
if getattr(items[0][0], "SHOULD_POLL_PROC_GROUP", False): |
| 499 |
exp_pids = [ctx.pid for ctx in my_ctx_list if ctx.pid is not None] |
| 500 |
bad_pids.extend(exp_pids) |
| 501 |
items.append([self._get_sys("background"), exp_pids, bad_pids]) |
| 502 |
debug_messages = [] |
| 503 |
for job_runner, exp_ids, bad_ids in items: |
| 504 |
if hasattr(job_runner, "get_poll_many_cmd"): |
| 505 |
# Some poll commands may not be as simple |
| 506 |
cmd = job_runner.get_poll_many_cmd(exp_ids) |
| 507 |
else: # if hasattr(job_runner, "POLL_CMD"): |
| 508 |
# Simple poll command that takes a list of job IDs |
| 509 |
cmd = [job_runner.POLL_CMD, *exp_ids] |
| 510 |
try: |
| 511 |
proc = procopen(cmd, stdindevnull=True, |
| 512 |
stderrpipe=True, stdoutpipe=True) |
| 513 |
except OSError as exc: |
| 514 |
# subprocess.Popen has a bad habit of not setting the |
| 515 |
# filename of the executable when it raises an OSError. |
| 516 |
if not exc.filename: |
| 517 |
exc.filename = cmd[0] |
| 518 |
sys.stderr.write(f"{exc}\n") |
| 519 |
return |
| 520 |
ret_code = proc.wait() |
| 521 |
out, err = (f.decode() for f in proc.communicate()) |
| 522 |
debug_messages.append('{0} - {1}'.format( |
| 523 |
job_runner, len(out.split('\n'))) |
| 524 |
) |
| 525 |
sys.stderr.write(err) |
| 526 |
if (ret_code and hasattr(job_runner, "POLL_CANT_CONNECT_ERR") and |
| 527 |
job_runner.POLL_CANT_CONNECT_ERR in err): |
| 528 |
# Poll command failed because it cannot connect to job runner |
| 529 |
# Assume jobs are still healthy until the job runner is back. |
| 530 |
bad_ids[:] = [] |
| 531 |
elif hasattr(job_runner, "filter_poll_many_output"): |
| 532 |
# Allow custom filter |
| 533 |
for id_ in job_runner.filter_poll_many_output(out): |
| 534 |
with suppress(ValueError): |
| 535 |
bad_ids.remove(id_) |
| 536 |
else: |
| 537 |
# Just about all poll commands return a table, with column 1 |
| 538 |
# being the job ID. The logic here should be sufficient to |
| 539 |
# ensure that any table header is ignored. |
| 540 |
for line in out.splitlines(): |
| 541 |
try: |
| 542 |
head = line.split(None, 1)[0] |
| 543 |
except IndexError: |
| 544 |
continue |
| 545 |
if head in exp_ids: |
| 546 |
with suppress(ValueError): |
| 547 |
bad_ids.remove(head) |
| 548 |
|
| 549 |
debug_flag = False |
| 550 |
for ctx in my_ctx_list: |
| 551 |
ctx.job_runner_exit_polled = int( |
| 552 |
ctx.job_id in bad_job_ids) |
| 553 |
# Exited job runner, but process still running |
| 554 |
# This can happen to jobs in some "at" implementation |
| 555 |
if ctx.job_runner_exit_polled and ctx.pid in exp_pids: |
| 556 |
if ctx.pid not in bad_pids: |
| 557 |
ctx.job_runner_exit_polled = 0 |
| 558 |
else: |
| 559 |
debug_flag = True |
| 560 |
# Add information to "job.status" |
| 561 |
if ctx.job_runner_exit_polled: |
| 562 |
try: |
| 563 |
with open(os.path.join( |
| 564 |
job_log_root, ctx.job_log_dir, JOB_LOG_STATUS), "a" |
| 565 |
) as handle: |
| 566 |
handle.write("{0}={1}\n".format( |
| 567 |
self.CYLC_JOB_RUNNER_EXIT_POLLED, |
| 568 |
get_current_time_string()) |
| 569 |
) |
| 570 |
except IOError as exc: |
| 571 |
sys.stderr.write(f"{exc}\n") |
| 572 |
|
| 573 |
# Re-read the status file in case the job started and exited |
| 574 |
# between the file and batch system checks, which would be |
| 575 |
# interpreted as submit-failed (job exited without starting). |
| 576 |
# Possible if polling many jobs and/or system heavily loaded. |
| 577 |
file_ctx = self._jobs_poll_status_files( |
| 578 |
job_log_root, ctx.job_log_dir) |
| 579 |
ctx.update(file_ctx) |
| 580 |
|
| 581 |
if debug_flag: |
| 582 |
ctx.job_runner_call_no_lines = ', '.join(debug_messages) |
| 583 |
|
| 584 |
def _job_submit_impl( |
| 585 |
self, job_file_path, job_runner_name, submit_opts): |
| 586 |
"""Helper for self.jobs_submit() and self.job_submit().""" |
| 587 |
|
| 588 |
# Create NN symbolic link, if necessary |
| 589 |
self._create_nn(job_file_path) |
| 590 |
|
| 591 |
# Start new status file |
| 592 |
with open(f"{job_file_path}.status", "w") as job_status_file: |
| 593 |
job_status_file.write( |
| 594 |
"{0}={1}\n".format( |
| 595 |
self.CYLC_JOB_RUNNER_NAME, |
| 596 |
job_runner_name |
| 597 |
) |
| 598 |
) |
| 599 |
|
| 600 |
# Submit job |
| 601 |
job_runner = self._get_sys(job_runner_name) |
| 602 |
if not self.clean_env: |
| 603 |
# Pass the whole environment to the job submit subprocess. |
| 604 |
# (Note this runs on the job host). |
| 605 |
# NOTE:: We modify this below so use a copy! |
| 606 |
# See: https://github.com/cylc/cylc-flow/issues/7333 |
| 607 |
env = dict(os.environ) |
| 608 |
else: |
| 609 |
# $HOME is required by job.sh on the job host. |
| 610 |
env = {'HOME': os.environ.get('HOME', '')} |
| 611 |
# Pass selected extra variables to the job submit subprocess. |
| 612 |
for var in self.env: |
| 613 |
env[var] = os.environ.get(var, '') |
| 614 |
if self.path is not None: |
| 615 |
# Append to avoid overriding an inherited PATH (e.g. in a venv) |
| 616 |
env['PATH'] = env.get('PATH', '') + ':' + ':'.join(self.path) |
| 617 |
if hasattr(job_runner, "submit"): |
| 618 |
submit_opts['env'] = env |
| 619 |
# job_runner.submit should handle OSError, if relevant. |
| 620 |
ret_code, out, err = job_runner.submit(job_file_path, submit_opts) |
| 621 |
else: |
| 622 |
proc_stdin_arg = None |
| 623 |
# Set command STDIN to DEVNULL by default to prevent leakage of |
| 624 |
# STDIN from current environment. |
| 625 |
proc_stdin_value = DEVNULL # nosec |
| 626 |
if hasattr(job_runner, "get_submit_stdin"): |
| 627 |
proc_stdin_arg, proc_stdin_value = job_runner.get_submit_stdin( |
| 628 |
job_file_path, submit_opts) |
| 629 |
if isinstance(proc_stdin_value, str): |
| 630 |
proc_stdin_value = proc_stdin_value.encode() |
| 631 |
if hasattr(job_runner, "SUBMIT_CMD_ENV"): |
| 632 |
env.update(job_runner.SUBMIT_CMD_ENV) |
| 633 |
job_runner_cmd_tmpl = submit_opts.get("job_runner_cmd_tmpl") |
| 634 |
if job_runner_cmd_tmpl: |
| 635 |
# No need to catch OSError when using shell. It is unlikely |
| 636 |
# that we do not have a shell, and still manage to get as far |
| 637 |
# as here. |
| 638 |
job_runner_cmd = job_runner_cmd_tmpl % {"job": job_file_path} |
| 639 |
proc = procopen(job_runner_cmd, stdin=proc_stdin_arg, |
| 640 |
stdoutpipe=True, stderrpipe=True, usesh=True, |
| 641 |
env=env) |
| 642 |
# calls to open a shell are aggregated in |
| 643 |
# cylc_subproc.procopen() |
| 644 |
else: |
| 645 |
command = shlex.split( |
| 646 |
job_runner.SUBMIT_CMD_TMPL % {"job": job_file_path}) |
| 647 |
try: |
| 648 |
proc = procopen( |
| 649 |
command, |
| 650 |
stdin=proc_stdin_arg, |
| 651 |
stdoutpipe=True, |
| 652 |
stderrpipe=True, |
| 653 |
env=env, |
| 654 |
# paths in directives should be interpreted relative to |
| 655 |
# $HOME |
| 656 |
# https://github.com/cylc/cylc-flow/issues/4247 |
| 657 |
cwd=Path('~').expanduser() |
| 658 |
) |
| 659 |
except OSError as exc: |
| 660 |
# subprocess.Popen has a bad habit of not setting the |
| 661 |
# filename of the executable when it raises an OSError. |
| 662 |
if not exc.filename: |
| 663 |
exc.filename = command[0] |
| 664 |
return 1, "", str(exc), "" |
| 665 |
out, err = (f.decode() for f in proc.communicate(proc_stdin_value)) |
| 666 |
ret_code = proc.wait() |
| 667 |
with suppress(AttributeError, IOError): |
| 668 |
proc_stdin_arg.close() |
| 669 |
|
| 670 |
# Filter submit command output, if relevant |
| 671 |
# Get job ID, if possible |
| 672 |
job_id = None |
| 673 |
if out or err: |
| 674 |
try: |
| 675 |
out, err, job_id = self._filter_submit_output( |
| 676 |
f"{job_file_path}.status", job_runner, out, err) |
| 677 |
except OSError: |
| 678 |
ret_code = 1 |
| 679 |
self.job_kill(f"{job_file_path}.status") |
| 680 |
|
| 681 |
return ret_code, out, err, job_id |
| 682 |
|
| 683 |
def _jobs_submit_prep_by_args(self, job_log_root, job_log_dirs): |
| 684 |
"""Prepare job files for submit by reading files in arguments. |
| 685 |
|
| 686 |
Job files are specified in the arguments in local mode. Extract job |
| 687 |
submission methods and job submission command templates from each job |
| 688 |
file. |
| 689 |
|
| 690 |
Return a list, where each element contains something like: |
| 691 |
(job_log_dir, job_runner_name, submit_opts) |
| 692 |
|
| 693 |
""" |
| 694 |
items = [] |
| 695 |
for job_log_dir in job_log_dirs: |
| 696 |
job_file_path = os.path.join(job_log_root, job_log_dir, "job") |
| 697 |
job_runner_name = None |
| 698 |
submit_opts = {} |
| 699 |
with open(job_file_path, 'r') as job_file: |
| 700 |
for line in job_file: |
| 701 |
if line.startswith(self.LINE_PREFIX_JOB_RUNNER_NAME): |
| 702 |
job_runner_name = line.replace( |
| 703 |
self.LINE_PREFIX_JOB_RUNNER_NAME, "").strip() |
| 704 |
elif line.startswith(self.LINE_PREFIX_JOB_RUNNER_CMD_TMPL): |
| 705 |
submit_opts["job_runner_cmd_tmpl"] = line.replace( |
| 706 |
self.LINE_PREFIX_JOB_RUNNER_CMD_TMPL, "").strip() |
| 707 |
elif line.startswith( |
| 708 |
self.LINE_PREFIX_EXECUTION_TIME_LIMIT |
| 709 |
): |
| 710 |
submit_opts["execution_time_limit"] = float( |
| 711 |
line.replace( |
| 712 |
self.LINE_PREFIX_EXECUTION_TIME_LIMIT, "" |
| 713 |
).strip() |
| 714 |
) |
| 715 |
items.append((job_log_dir, job_runner_name, submit_opts)) |
| 716 |
return items |
| 717 |
|
| 718 |
def _jobs_submit_prep_by_stdin(self, job_log_root, job_log_dirs): |
| 719 |
"""Prepare job files for submit by reading from STDIN. |
| 720 |
|
| 721 |
Job files are uploaded via STDIN in remote mode. Extract job submission |
| 722 |
methods and job submission command templates from each job file. |
| 723 |
|
| 724 |
Return a list, where each element contains something like: |
| 725 |
(job_log_dir, job_runner_name, submit_opts) |
| 726 |
|
| 727 |
""" |
| 728 |
items = [[job_log_dir, None, {}] for job_log_dir in job_log_dirs] |
| 729 |
items_map = {} |
| 730 |
for item in items: |
| 731 |
items_map[item[0]] = item |
| 732 |
handle = None |
| 733 |
job_runner_name = None |
| 734 |
submit_opts = {} |
| 735 |
job_log_dir = None |
| 736 |
lines = [] |
| 737 |
# Get job files from STDIN. |
| 738 |
# Get job runner name and job runner command template from each job |
| 739 |
# file. |
| 740 |
# Write job file in correct location. |
| 741 |
while True: # Note: "for cur_line in sys.stdin:" may hang |
| 742 |
cur_line = sys.stdin.readline() |
| 743 |
if not cur_line: |
| 744 |
if handle is not None: |
| 745 |
handle.close() |
| 746 |
break |
| 747 |
if cur_line.startswith(self.LINE_PREFIX_JOB_RUNNER_NAME): |
| 748 |
job_runner_name = cur_line.replace( |
| 749 |
self.LINE_PREFIX_JOB_RUNNER_NAME, "").strip() |
| 750 |
elif cur_line.startswith(self.LINE_PREFIX_JOB_RUNNER_CMD_TMPL): |
| 751 |
submit_opts["job_runner_cmd_tmpl"] = cur_line.replace( |
| 752 |
self.LINE_PREFIX_JOB_RUNNER_CMD_TMPL, "").strip() |
| 753 |
elif cur_line.startswith(self.LINE_PREFIX_EXECUTION_TIME_LIMIT): |
| 754 |
submit_opts["execution_time_limit"] = float(cur_line.replace( |
| 755 |
self.LINE_PREFIX_EXECUTION_TIME_LIMIT, "").strip()) |
| 756 |
elif cur_line.startswith(self.LINE_PREFIX_JOB_LOG_DIR): |
| 757 |
job_log_dir = cur_line.replace( |
| 758 |
self.LINE_PREFIX_JOB_LOG_DIR, "").strip() |
| 759 |
os.makedirs( |
| 760 |
os.path.join(job_log_root, job_log_dir), |
| 761 |
exist_ok=True) |
| 762 |
if handle is not None: |
| 763 |
handle.close() |
| 764 |
handle = open( # noqa: SIM115 (can't convert to with open) |
| 765 |
os.path.join(job_log_root, job_log_dir, "job.tmp"), "wb") |
| 766 |
|
| 767 |
if handle is None: |
| 768 |
lines.append(cur_line) |
| 769 |
else: |
| 770 |
for line in lines + [cur_line]: |
| 771 |
handle.write(line.encode()) |
| 772 |
lines = [] |
| 773 |
if cur_line.startswith(self.LINE_PREFIX_EOF + job_log_dir): |
| 774 |
handle.close() |
| 775 |
# Make it executable |
| 776 |
os.chmod(handle.name, ( |
| 777 |
os.stat(handle.name).st_mode | |
| 778 |
stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)) |
| 779 |
# Rename from "*/job.tmp" to "*/job" |
| 780 |
os.rename(handle.name, handle.name[:-4]) |
| 781 |
try: |
| 782 |
items_map[job_log_dir][1] = job_runner_name |
| 783 |
items_map[job_log_dir][2] = submit_opts |
| 784 |
except KeyError: |
| 785 |
pass |
| 786 |
handle = None |
| 787 |
job_log_dir = None |
| 788 |
job_runner_name = None |
| 789 |
submit_opts = {} |
| 790 |
return items |