Debian Codegraph @

cylc/flow/task_job_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 """Manage jobs.
17
18 This module provides logic to:
19 * Set up the directory structure on remote job hosts.
20 * Copy workflow service files to remote job hosts for communication clients.
21 * Clean up of service files on workflow shutdown.
22 * Prepare job files.
23 * Prepare jobs submission, and manage the callbacks.
24 * Prepare jobs poll/kill, and manage the callbacks.
25 """
26
27 from contextlib import suppress
28 import json
29 from logging import (
30 CRITICAL,
31 DEBUG,
32 INFO,
33 WARNING,
34 )
35 import os
36 from shutil import rmtree
37 from time import time
38 from typing import (
39 TYPE_CHECKING,
40 Any,
41 Dict,
42 Iterable,
43 List,
44 Literal,
45 Optional,
46 Set,
47 Tuple,
48 Union,
49 cast,
50 )
51
52 from cylc.flow import LOG
53 from cylc.flow.cfgspec.globalcfg import SYSPATH
54 from cylc.flow.exceptions import (
55 NoHostsError,
56 NoPlatformsError,
57 PlatformError,
58 PlatformLookupError,
59 )
60 from cylc.flow.hostuserutil import (
61 get_host,
62 is_remote_platform,
63 )
64 from cylc.flow.job_file import JobFileWriter
65 from cylc.flow.job_runner_mgr import (
66 JOB_FILES_REMOVED_MESSAGE,
67 JobPollContext,
68 )
69 from cylc.flow.pathutil import get_remote_workflow_run_job_dir
70 from cylc.flow.platforms import (
71 FORBIDDEN_WITH_PLATFORM,
72 fail_if_platform_and_host_conflict,
73 get_host_from_platform,
74 get_install_target_from_platform,
75 get_localhost_install_target,
76 get_platform,
77 )
78 from cylc.flow.remote import construct_ssh_cmd
79 from cylc.flow.run_modes import (
80 WORKFLOW_ONLY_MODES,
81 RunMode,
82 )
83 from cylc.flow.subprocctx import SubProcContext
84 from cylc.flow.subprocpool import SubProcPool
85 from cylc.flow.task_action_timer import (
86 TaskActionTimer,
87 TimerFlags,
88 )
89 from cylc.flow.task_events_mgr import (
90 TaskEventsManager,
91 log_task_job_activity,
92 )
93 from cylc.flow.task_job_logs import (
94 JOB_LOG_JOB,
95 NN,
96 get_task_job_activity_log,
97 get_task_job_job_log,
98 get_task_job_log,
99 )
100 from cylc.flow.task_message import FAIL_MESSAGE_PREFIX
101 from cylc.flow.task_outputs import (
102 TASK_OUTPUT_FAILED,
103 TASK_OUTPUT_STARTED,
104 TASK_OUTPUT_SUBMITTED,
105 TASK_OUTPUT_SUCCEEDED,
106 )
107 from cylc.flow.task_remote_mgr import (
108 REMOTE_FILE_INSTALL_255,
109 REMOTE_FILE_INSTALL_DONE,
110 REMOTE_FILE_INSTALL_FAILED,
111 REMOTE_FILE_INSTALL_IN_PROGRESS,
112 REMOTE_INIT_255,
113 REMOTE_INIT_DONE,
114 REMOTE_INIT_FAILED,
115 REMOTE_INIT_IN_PROGRESS,
116 TaskRemoteMgr,
117 )
118 from cylc.flow.task_state import (
119 TASK_STATUS_PREPARING,
120 TASK_STATUS_RUNNING,
121 TASK_STATUS_SUBMITTED,
122 TASK_STATUS_WAITING,
123 )
124 from cylc.flow.util import serialise_set
125 from cylc.flow.wallclock import (
126 get_current_time_string,
127 get_time_string_from_unix_time,
128 get_utc_mode,
129 )
130
131
132 if TYPE_CHECKING:
133 from cylc.flow.data_store_mgr import DataStoreMgr
134 from cylc.flow.task_proxy import TaskProxy
135 from cylc.flow.workflow_db_mgr import WorkflowDatabaseManager
136
137
138 class TaskJobManager:
139 """Manage task job submit, poll and kill.
140
141 This class provides logic to:
142 * Submit jobs.
143 * Poll jobs.
144 * Kill jobs.
145 * Set up the directory structure on job hosts.
146 * Install workflow communicate client files on job hosts.
147 * Remove workflow contact files on job hosts.
148 """
149
150 JOBS_KILL = 'jobs-kill'
151 JOBS_POLL = 'jobs-poll'
152 JOBS_SUBMIT = SubProcPool.JOBS_SUBMIT
153 POLL_FAIL = 'poll failed'
154 REMOTE_SELECT_MSG = 'waiting for remote host selection'
155 REMOTE_INIT_MSG = 'remote host initialising'
156 REMOTE_FILE_INSTALL_MSG = 'file installation in progress'
157 REMOTE_INIT_255_MSG = 'remote init failed with an unreachable host'
158 KEY_EXECUTE_TIME_LIMIT = TaskEventsManager.KEY_EXECUTE_TIME_LIMIT
159
160 IN_PROGRESS = {
161 REMOTE_FILE_INSTALL_IN_PROGRESS: REMOTE_FILE_INSTALL_MSG,
162 REMOTE_INIT_IN_PROGRESS: REMOTE_INIT_MSG
163 }
164
165 def __init__(
166 self,
167 workflow,
168 proc_pool,
169 workflow_db_mgr,
170 task_events_mgr,
171 data_store_mgr,
172 bad_hosts,
173 server,
174 ):
175 self.workflow: str = workflow
176 self.proc_pool = proc_pool
177 self.workflow_db_mgr: WorkflowDatabaseManager = workflow_db_mgr
178 self.task_events_mgr: TaskEventsManager = task_events_mgr
179 self.data_store_mgr: DataStoreMgr = data_store_mgr
180 self.job_file_writer = JobFileWriter()
181 self.job_runner_mgr = self.job_file_writer.job_runner_mgr
182 self.bad_hosts: Set[str] = bad_hosts
183 self.bad_hosts_to_clear: Set[str] = set()
184 self.task_remote_mgr = TaskRemoteMgr(
185 workflow, proc_pool, self.bad_hosts, self.workflow_db_mgr, server
186 )
187
188 def check_task_jobs(self, task_pool):
189 """Check submission and execution timeout and polling timers.
190
191 Poll tasks that have timed out and/or have reached next polling time.
192 """
193 now = time()
194 poll_tasks = set()
195 for itask in task_pool.get_tasks():
196 if self.task_events_mgr.check_job_time(itask, now):
197 poll_tasks.add(itask)
198 if itask.poll_timer.delay is not None:
199 LOG.info(
200 f"[{itask}] poll now, (next in "
201 f"{itask.poll_timer.delay_timeout_as_str()})"
202 )
203 if poll_tasks:
204 self.poll_task_jobs(poll_tasks)
205
206 def kill_task_jobs(
207 self, itasks: 'Iterable[TaskProxy]'
208 ) -> None:
209 """Issue the command to kill jobs of active tasks."""
210 self._run_job_cmd(
211 self.JOBS_KILL,
212 itasks,
213 self._kill_task_jobs_callback,
214 self._kill_task_jobs_callback_255,
215 )
216
217 def kill_prep_task(self, itask: 'TaskProxy') -> None:
218 """Kill a preparing task."""
219 itask.summary['platforms_used'][itask.submit_num] = ''
220 itask.waiting_on_job_prep = False
221 itask.local_job_file_path = None # reset for retry
222 self._set_retry_timers(itask)
223 self._prep_submit_task_job_error(itask, '(killed in job prep)', '')
224
225 def poll_task_jobs(
226 self, itasks: 'Iterable[TaskProxy]', msg: str | None = None
227 ):
228 """Poll jobs of specified tasks.
229
230 This method uses _poll_task_jobs_callback() and
231 _manip_task_jobs_callback() as help/callback methods.
232
233 _poll_task_job_callback() executes one specific job.
234 """
235 if itasks:
236 if msg is not None:
237 LOG.info(msg)
238 self._run_job_cmd(
239 self.JOBS_POLL,
240 [
241 # Don't poll waiting tasks. (This is not only pointless, it
242 # is dangerous because a task waiting to rerun has the
243 # submit number of its previous job, which can be polled).
244 itask for itask in itasks
245 if itask.state.status != TASK_STATUS_WAITING
246 ],
247 self._poll_task_jobs_callback,
248 self._poll_task_jobs_callback_255
249 )
250
251 def prep_submit_task_jobs(
252 self,
253 itasks: 'Iterable[TaskProxy]',
254 check_syntax: bool = True,
255 ) -> 'Tuple[List[TaskProxy], List[TaskProxy]]':
256 """Prepare task jobs for submit.
257
258 Prepare tasks where possible. Ignore tasks that are waiting for host
259 select command to complete. Bad host select command or error writing to
260 a job file will cause a bad task - leading to submission failure.
261
262 Return (good_tasks, bad_tasks)
263 """
264 prepared_tasks = []
265 bad_tasks = []
266 for itask in itasks:
267 if not itask.state(TASK_STATUS_PREPARING):
268 # bump the submit_num *before* resetting the state so that the
269 # state transition message reflects the correct submit_num
270 itask.submit_num += 1
271 itask.state_reset(TASK_STATUS_PREPARING)
272 self.data_store_mgr.delta_task_state(itask)
273 prep_task = self._prep_submit_task_job(
274 itask, check_syntax=check_syntax
275 )
276 if prep_task:
277 prepared_tasks.append(itask)
278 elif prep_task is False:
279 bad_tasks.append(itask)
280 return (prepared_tasks, bad_tasks)
281
282 def submit_task_jobs(
283 self,
284 itasks: 'Iterable[TaskProxy]',
285 run_mode: RunMode,
286 ) -> 'List[TaskProxy]':
287 """Prepare for job submission and submit task jobs.
288
289 Return: tasks that attempted submission.
290 """
291 # submit "simulation/skip" mode tasks, modify "dummy" task configs:
292 itasks, submitted_nonlive_tasks = self.submit_nonlive_task_jobs(
293 itasks, run_mode
294 )
295
296 # submit "live" mode tasks (and "dummy" mode tasks)
297 submitted_live_tasks = self.submit_livelike_task_jobs(itasks)
298
299 return submitted_nonlive_tasks + submitted_live_tasks
300
301 def submit_livelike_task_jobs(
302 self, itasks: 'Iterable[TaskProxy]'
303 ) -> 'List[TaskProxy]':
304 """Submission for live tasks and dummy tasks.
305
306 Preparation (host selection, remote host init, and remote install)
307 is done asynchronously. Newly released tasks may be sent here several
308 times until these init subprocesses have returned. Failure during
309 preparation is considered to be job submission failure.
310
311 Once preparation has completed or failed, reset .waiting_on_job_prep in
312 task instances so the scheduler knows to stop sending them back here.
313
314 This method uses prep_submit_task_jobs() as helper.
315
316 Return: tasks that attempted submission.
317 """
318 prepared_tasks, bad_tasks = self.prep_submit_task_jobs(itasks)
319
320 # Reset consumed host selection results
321 self.task_remote_mgr.subshell_eval_reset()
322
323 if not prepared_tasks:
324 return bad_tasks
325
326 ri_map = self.task_remote_mgr.remote_init_map
327 # Mapping of platform names to task proxies
328 # (resolved platforms, not platform groups):
329 platform_itasks: 'Dict[str, List[TaskProxy]]' = {}
330 for itask in prepared_tasks:
331 platform_itasks.setdefault(itask.platform['name'], []).append(
332 itask
333 )
334
335 # Submit task jobs for each platform
336 # Non-prepared tasks can be considered done for now:
337 done_tasks = bad_tasks
338
339 for _platform_name, itasks in sorted(platform_itasks.items()):
340 # All tasks in this iteration have the same platform
341 platform = itasks[0].platform
342
343 if self.bad_hosts.issuperset(platform['hosts']):
344 # Out of hosts for this platform.
345 for itask in itasks:
346 # Get another platform, if task config platform is a group
347 # (Note there may be tasks with different but intersecting
348 # platform groups)
349 if not self._select_new_platform(itask):
350 # else set task to submit failed.
351 self._platform_submit_failure(itask)
352 done_tasks.append(itask)
353 continue
354
355 install_target = get_install_target_from_platform(platform)
356
357 if ri_map.get(install_target) != REMOTE_FILE_INSTALL_DONE:
358 if install_target == get_localhost_install_target():
359 # Skip init and file install for localhost.
360 LOG.debug(f"REMOTE INIT NOT REQUIRED for {install_target}")
361 ri_map[install_target] = (REMOTE_FILE_INSTALL_DONE)
362
363 elif install_target not in ri_map:
364 # Remote init not in progress for target, so start it.
365 self.task_remote_mgr.remote_init(platform)
366 for itask in itasks:
367 self.data_store_mgr.delta_job_msg(
368 itask.job_tokens, self.REMOTE_INIT_MSG
369 )
370 continue
371
372 elif ri_map[install_target] == REMOTE_INIT_DONE:
373 # Already done remote init so move on to file install
374 self.task_remote_mgr.file_install(platform)
375 continue
376
377 elif ri_map[install_target] in self.IN_PROGRESS:
378 # Remote init or file install in progress.
379 for itask in itasks:
380 msg = self.IN_PROGRESS[ri_map[install_target]]
381 self.data_store_mgr.delta_job_msg(
382 itask.job_tokens, msg
383 )
384 continue
385 elif ri_map[install_target] == REMOTE_INIT_255:
386 # Remote init previously failed because a host was
387 # unreachable, so start it again.
388 del ri_map[install_target]
389 self.task_remote_mgr.remote_init(platform)
390 for itask in itasks:
391 self.data_store_mgr.delta_job_msg(
392 itask.job_tokens, self.REMOTE_INIT_MSG
393 )
394 continue
395
396 # Ensure that localhost background/at jobs are recorded as running
397 # on the host name of the current workflow host, rather than just
398 # "localhost". On restart on a different workflow host, this
399 # allows the restart logic to correctly poll the status of the
400 # background/at jobs that may still be running on the previous
401 # workflow host.
402 try:
403 host = get_host_from_platform(
404 platform, bad_hosts=self.bad_hosts
405 )
406 except NoHostsError:
407 del ri_map[install_target]
408 self.task_remote_mgr.remote_init(platform)
409 for itask in itasks:
410 self.data_store_mgr.delta_job_msg(
411 itask.job_tokens, self.REMOTE_INIT_MSG
412 )
413 continue
414
415 if self.job_runner_mgr.is_job_local_to_host(
416 itask.summary['job_runner_name']
417 ) and not is_remote_platform(platform):
418 host = get_host()
419
420 done_tasks.extend(itasks)
421 for itask in itasks:
422 # Log and persist
423 LOG.debug(f"[{itask}] host={host}")
424 self.workflow_db_mgr.put_insert_task_jobs(itask, {
425 'flow_nums': serialise_set(itask.flow_nums),
426 'is_manual_submit': itask.is_manual_submit,
427 'try_num': itask.get_try_num(),
428 'time_submit': get_current_time_string(),
429 'platform_name': itask.platform['name'],
430 'job_runner_name': itask.summary['job_runner_name'],
431 })
432 # reset the is_manual_submit flag in case of retries
433 itask.is_manual_submit = False
434
435 if ri_map[install_target] == REMOTE_FILE_INSTALL_255:
436 del ri_map[install_target]
437 self.task_remote_mgr.file_install(platform)
438 for itask in itasks:
439 self.data_store_mgr.delta_job_msg(
440 itask.job_tokens, REMOTE_FILE_INSTALL_IN_PROGRESS
441 )
442 continue
443
444 if ri_map[install_target] in {
445 REMOTE_INIT_FAILED, REMOTE_FILE_INSTALL_FAILED
446 }:
447 # Remote init or install failed. Set submit-failed for all
448 # affected tasks and remove target from remote init map
449 # - this enables new tasks to re-initialise that target
450 init_error = ri_map[install_target]
451 del ri_map[install_target]
452 for itask in itasks:
453 itask.waiting_on_job_prep = False
454 itask.local_job_file_path = None # reset for retry
455 log_task_job_activity(
456 SubProcContext(
457 self.JOBS_SUBMIT,
458 '(init %s)' % host,
459 err=init_error,
460 ret_code=1,
461 ),
462 self.workflow,
463 itask.point,
464 itask.tdef.name,
465 )
466 self._prep_submit_task_job_error(
467 itask, '(remote init)', ''
468 )
469 continue
470
471 # Build the "cylc jobs-submit" command
472 cmd = [self.JOBS_SUBMIT]
473 if LOG.isEnabledFor(DEBUG):
474 cmd.append('--debug')
475 if get_utc_mode():
476 cmd.append('--utc-mode')
477 if is_remote_platform(itask.platform):
478 remote_mode = True
479 cmd.append('--remote-mode')
480 else:
481 remote_mode = False
482 if itask.platform[
483 'clean job submission environment']:
484 cmd.append('--clean-env')
485 for var in itask.platform[
486 'job submission environment pass-through']:
487 cmd.append(f"--env={var}")
488 for path in itask.platform[
489 'job submission executable paths'] + SYSPATH:
490 cmd.append(f"--path={path}")
491 cmd.append('--')
492 cmd.append(get_remote_workflow_run_job_dir(self.workflow))
493 # Chop itasks into a series of shorter lists if it's very big
494 # to prevent overloading of stdout and stderr pipes.
495 itasks = sorted(itasks, key=lambda itask: itask.identity)
496 chunk_size = (
497 len(itasks) // (
498 (len(itasks) // platform['max batch submit size']) + 1
499 ) + 1
500 )
501 itasks_batches = [
502 itasks[i:i + chunk_size]
503 for i in range(0, len(itasks), chunk_size)
504 ]
505 LOG.debug(
506 '%s ... # will invoke in batches, sizes=%s',
507 cmd, [len(b) for b in itasks_batches])
508
509 if remote_mode:
510 cmd = construct_ssh_cmd(
511 cmd, platform, host
512 )
513 else:
514 cmd = ['cylc'] + cmd
515
516 for itasks_batch in itasks_batches:
517 stdin_files = []
518 job_log_dirs = []
519 for itask in itasks_batch:
520 if not itask.waiting_on_job_prep:
521 # Avoid duplicate job submissions when flushing
522 # preparing tasks before a reload. See
523 # https://github.com/cylc/cylc-flow/pull/6345
524 continue
525
526 if remote_mode:
527 stdin_files.append(
528 os.path.expandvars(
529 get_task_job_job_log(
530 self.workflow,
531 itask.point,
532 itask.tdef.name,
533 itask.submit_num,
534 )
535 )
536 )
537 job_log_dirs.append(
538 itask.job_tokens.relative_id
539 )
540 # The job file is now (about to be) used: reset the file
541 # write flag so that subsequent manual retrigger will
542 # generate a new job file.
543 itask.local_job_file_path = None
544 itask.waiting_on_job_prep = False
545
546 if not job_log_dirs:
547 continue
548
549 self.proc_pool.put_command(
550 SubProcContext(
551 self.JOBS_SUBMIT,
552 cmd + job_log_dirs,
553 stdin_files=stdin_files,
554 job_log_dirs=job_log_dirs,
555 host=host
556 ),
557 bad_hosts=self.bad_hosts,
558 callback=self._submit_task_jobs_callback,
559 callback_args=[itasks_batch],
560 callback_255=self._submit_task_jobs_callback_255,
561 )
562 return done_tasks
563
564 def _select_new_platform(self, itask: 'TaskProxy') -> bool:
565 """Try to select a new platform for a task if it is using a
566 platform group and the current platform is not available.
567
568 Return True if a new platform was selected.
569 """
570 rtconf = self.task_events_mgr.broadcast_mgr.get_updated_rtconfig(
571 itask
572 )
573 try:
574 new_platform = get_platform(rtconf, bad_hosts=self.bad_hosts)
575 except PlatformLookupError:
576 return False
577 # If were able to select a new platform;
578 if new_platform and new_platform != itask.platform:
579 # store the previous platform's hosts so that when
580 # we record a submit fail we can clear all hosts
581 # from all platforms from bad_hosts.
582 self.bad_hosts_to_clear.update(itask.platform['hosts'])
583 itask.platform = new_platform
584 self._prep_submit_task_job_impl(itask, rtconf)
585 return True
586 return False
587
588 def _platform_submit_failure(self, itask: 'TaskProxy') -> None:
589 """If there are no good platforms for a task then we set it to
590 submit-failed."""
591 itask.waiting_on_job_prep = False
592 itask.local_job_file_path = None
593 self._prep_submit_task_job_error(
594 itask,
595 '(remote init)',
596 PlatformError(
597 f"{PlatformError.MSG_INIT} (no hosts were reachable)",
598 itask.platform['name'],
599 ),
600 )
601 # Now that all hosts on all platforms in platform
602 # group selected in task config are exhausted we
603 # clear bad_hosts for all the hosts we have
604 # tried for this platform or group.
605 self.bad_hosts -= set(itask.platform['hosts'])
606 self.bad_hosts -= self.bad_hosts_to_clear
607 self.bad_hosts_to_clear.clear()
608
609 def _create_job_log_path(self, itask):
610 """Create job log directory for a task job, etc.
611
612 Create local job directory, and NN symbolic link.
613 If NN => 01, remove numbered directories with submit numbers greater
614 than 01.
615 Return a string in the form "POINT/NAME/SUBMIT_NUM".
616
617 """
618 job_file_dir = get_task_job_log(
619 self.workflow, itask.point, itask.tdef.name, itask.submit_num
620 )
621 job_file_dir = os.path.expandvars(job_file_dir)
622 task_log_dir = os.path.dirname(job_file_dir)
623 if itask.submit_num == 1:
624 try:
625 names = os.listdir(task_log_dir)
626 except OSError:
627 pass
628 else:
629 for name in names:
630 if name not in ["01", NN]:
631 rmtree(
632 os.path.join(task_log_dir, name),
633 ignore_errors=True)
634 else:
635 rmtree(job_file_dir, ignore_errors=True)
636
637 os.makedirs(job_file_dir, exist_ok=True)
638 target = os.path.join(task_log_dir, NN)
639 source = os.path.basename(job_file_dir)
640 try:
641 prev_source = os.readlink(target)
642 except OSError:
643 prev_source = None
644 if prev_source == source:
645 return
646 try:
647 if prev_source:
648 os.unlink(target)
649 os.symlink(source, target)
650 except OSError as exc:
651 if not exc.filename:
652 exc.filename = target
653 raise exc
654
655 def _job_cmd_out_callback(self, itask, cmd_ctx, line):
656 """Callback on job command STDOUT/STDERR."""
657 if cmd_ctx.cmd_kwargs.get("host"):
658 host = "(%(host)s) " % cmd_ctx.cmd_kwargs
659 else:
660 host = ""
661 try:
662 timestamp, _, content = line.split("|")
663 except ValueError:
664 pass
665 else:
666 line = "%s %s" % (timestamp, content)
667 job_activity_log = get_task_job_activity_log(
668 self.workflow, itask.point, itask.tdef.name)
669 if not line.endswith("\n"):
670 line += "\n"
671 line = host + line
672 try:
673 with open(os.path.expandvars(job_activity_log), "a") as handle:
674 handle.write(line)
675 except IOError as exc:
676 LOG.warning("%s: write failed\n%s" % (job_activity_log, exc))
677 LOG.warning(f"[{itask}] {host}{line}")
678
679 def _kill_task_jobs_callback(self, ctx, itasks):
680 """Callback when kill tasks command exits."""
681 self._manip_task_jobs_callback(
682 ctx,
683 itasks,
684 self._kill_task_job_callback,
685 {self.job_runner_mgr.OUT_PREFIX_COMMAND:
686 self._job_cmd_out_callback}
687 )
688
689 def _kill_task_jobs_callback_255(self, ctx, itasks):
690 """Callback when kill tasks command exits."""
691 self._manip_task_jobs_callback(
692 ctx,
693 itasks,
694 self._kill_task_job_callback_255,
695 {self.job_runner_mgr.OUT_PREFIX_COMMAND:
696 self._job_cmd_out_callback}
697 )
698
699 def _kill_task_job_callback_255(self, itask, cmd_ctx, line):
700 """Helper for _kill_task_jobs_callback, on one task job."""
701 with suppress(NoHostsError):
702 # if there is another host to kill on, try again, otherwise fail
703 get_host_from_platform(itask.platform, bad_hosts=self.bad_hosts)
704 self.kill_task_jobs([itask])
705
706 def _kill_task_job_callback(self, itask, cmd_ctx, line):
707 """Helper for _kill_task_jobs_callback, on one task job."""
708 ctx = SubProcContext(self.JOBS_KILL, None)
709 ctx.out = line
710 try:
711 ctx.timestamp, _, ctx.ret_code = line.split("|", 2)
712 except ValueError:
713 ctx.ret_code = 1
714 ctx.cmd = cmd_ctx.cmd # print original command on failure
715 else:
716 ctx.ret_code = int(ctx.ret_code)
717 if ctx.ret_code:
718 ctx.cmd = cmd_ctx.cmd # print original command on failure
719 log_task_job_activity(ctx, self.workflow, itask.point, itask.tdef.name)
720 log_lvl = WARNING
721 log_msg = 'job killed'
722 if ctx.ret_code: # non-zero exit status
723 log_lvl = WARNING
724 log_msg = 'job kill failed'
725 itask.state.kill_failed = True
726 elif itask.state(TASK_STATUS_SUBMITTED):
727 self.task_events_mgr.process_message(
728 itask, CRITICAL, self.task_events_mgr.EVENT_SUBMIT_FAILED,
729 ctx.timestamp)
730 elif itask.state(TASK_STATUS_RUNNING):
731 self.task_events_mgr.process_message(
732 itask, CRITICAL, TASK_OUTPUT_FAILED)
733 else:
734 log_lvl = DEBUG
735 log_msg = (
736 'ignoring job kill result, unexpected task state: %s' %
737 itask.state.status)
738 self.data_store_mgr.delta_job_msg(itask.job_tokens, log_msg)
739 LOG.log(log_lvl, f"[{itask}] {log_msg}")
740
741 def _manip_task_jobs_callback(
742 self, ctx, itasks, summary_callback, more_callbacks=None
743 ):
744 """Callback when submit/poll/kill tasks command exits."""
745 # Swallow SSH 255 (can't contact host) errors unless debugging.
746 if (
747 (ctx.ret_code and LOG.isEnabledFor(DEBUG))
748 or (ctx.ret_code and ctx.ret_code != 255)
749 ):
750 LOG.error(ctx)
751 # A dict for easy reference of (CYCLE, NAME, SUBMIT_NUM) -> TaskProxy
752 #
753 # Note for "reload": A TaskProxy instance may be replaced on reload, so
754 # the "itasks" list may not reference the TaskProxy objects that
755 # replace the old ones. The .reload_successor attribute provides the
756 # link(s) for us to get to the latest replacement.
757 #
758 # Note for "kill": It is possible for a job to trigger its trap and
759 # report back to the workflow before (or after?) this logic is called.
760 # If so, it will no longer be status SUBMITTED or RUNNING, and
761 # its output line will be ignored here.
762 tasks = {}
763 for itask in itasks:
764 while itask.reload_successor is not None:
765 # Note submit number could be incremented since reload.
766 subnum = itask.submit_num
767 itask = itask.reload_successor
768 itask.submit_num = subnum
769 if itask.point is not None and itask.submit_num:
770 submit_num = "%02d" % (itask.submit_num)
771 tasks[(str(itask.point), itask.tdef.name, submit_num)] = itask
772 handlers = [(self.job_runner_mgr.OUT_PREFIX_SUMMARY, summary_callback)]
773 if more_callbacks:
774 for prefix, callback in more_callbacks.items():
775 handlers.append((prefix, callback))
776 out = ctx.out
777 if not out:
778 out = ""
779 bad_tasks = dict(tasks)
780 for line in out.splitlines(True):
781 for prefix, callback in handlers:
782 if line.startswith(prefix):
783 line = line[len(prefix):].strip()
784 try:
785 # TODO this massive try block should be unpacked.
786 path = line.split("|", 2)[1] # timestamp, path, status
787 point, name, submit_num = path.split(os.sep, 2)
788 if prefix == self.job_runner_mgr.OUT_PREFIX_SUMMARY:
789 del bad_tasks[(point, name, submit_num)]
790 itask = tasks[(point, name, submit_num)]
791 callback(itask, ctx, line)
792 except (LookupError, ValueError) as exc:
793 # (Note this catches KeyError too).
794 LOG.warning(
795 'Unhandled %s output: %s', ctx.cmd_key, line)
796 LOG.warning(str(exc))
797 # Task jobs that are in the original command but did not get a status
798 # in the output. Handle as failures.
799 for key, itask in sorted(bad_tasks.items()):
800 line = (
801 "|".join([ctx.timestamp, os.sep.join(key), "1"]) + "\n")
802 summary_callback(itask, ctx, line)
803
804 def _poll_task_jobs_callback(self, ctx, itasks):
805 """Callback when poll tasks command exits."""
806 self._manip_task_jobs_callback(
807 ctx,
808 itasks,
809 self._poll_task_job_callback,
810 {self.job_runner_mgr.OUT_PREFIX_MESSAGE:
811 self._poll_task_job_message_callback})
812
813 def _poll_task_jobs_callback_255(self, ctx, itasks):
814 """Callback when poll tasks command exits."""
815 self._manip_task_jobs_callback(
816 ctx,
817 itasks,
818 self._poll_task_job_callback_255,
819 {self.job_runner_mgr.OUT_PREFIX_MESSAGE:
820 self._poll_task_job_message_callback})
821
822 def _poll_task_job_callback_255(self, itask, cmd_ctx, line):
823 with suppress(NoHostsError):
824 # if there is another host to poll on, try again, otherwise fail
825 get_host_from_platform(itask.platform, bad_hosts=self.bad_hosts)
826 self.poll_task_jobs([itask])
827
828 def _poll_task_job_callback(
829 self,
830 itask: 'TaskProxy',
831 cmd_ctx: SubProcContext,
832 line: str,
833 ):
834 """Helper for _poll_task_jobs_callback, on one task job."""
835 ctx = SubProcContext(self.JOBS_POLL, None)
836 ctx.out = line
837 ctx.ret_code = 0
838 # See cylc.flow.job_runner_mgr.JobPollContext
839 try:
840 job_log_dir, context = line.split('|')[1:3]
841 items = json.loads(context)
842 jp_ctx = JobPollContext(job_log_dir, **items)
843 except (TypeError, ValueError):
844 self.data_store_mgr.delta_job_msg(itask.job_tokens, self.POLL_FAIL)
845 ctx.cmd = cmd_ctx.cmd # print original command on failure
846 return
847 finally:
848 log_task_job_activity(
849 ctx, self.workflow, itask.point, itask.tdef.name
850 )
851
852 flag = self.task_events_mgr.FLAG_POLLED
853 # Only log at INFO level if manually polling
854 log_lvl = DEBUG if (
855 itask.platform.get('communication method') == 'poll'
856 ) else INFO
857
858 if jp_ctx.run_signal == JOB_FILES_REMOVED_MESSAGE:
859 LOG.error(
860 f"platform: {itask.platform['name']} - job log directory "
861 f"{itask.job_tokens.relative_id} no longer exists"
862 )
863
864 if jp_ctx.run_status == 1 and jp_ctx.run_signal in ["ERR", "EXIT"]:
865 # Failed normally
866 self.task_events_mgr.process_message(
867 itask, log_lvl, TASK_OUTPUT_FAILED, jp_ctx.time_run_exit, flag)
868 elif jp_ctx.run_status == 1 and jp_ctx.job_runner_exit_polled == 1:
869 # Failed by a signal, and no longer in job runner
870 self.task_events_mgr.process_message(
871 itask, log_lvl, f"{FAIL_MESSAGE_PREFIX}/{jp_ctx.run_signal}",
872 jp_ctx.time_run_exit,
873 flag)
874 elif jp_ctx.run_status == 1: # noqa: SIM114
875 # The job has terminated, but is still managed by job runner.
876 # Some job runners may restart a job in this state, so don't
877 # mark as failed yet.
878 self.task_events_mgr.process_message(
879 itask, log_lvl, TASK_OUTPUT_STARTED, jp_ctx.time_run, flag)
880 elif jp_ctx.run_status == 0:
881 # The job succeeded
882 self.task_events_mgr.process_message(
883 itask, log_lvl, TASK_OUTPUT_SUCCEEDED, jp_ctx.time_run_exit,
884 flag)
885 elif jp_ctx.time_run and jp_ctx.job_runner_exit_polled == 1:
886 # The job has terminated without executing the error trap
887 self.task_events_mgr.process_message(
888 itask, log_lvl, TASK_OUTPUT_FAILED, get_current_time_string(),
889 flag)
890 elif jp_ctx.time_run:
891 # The job has started, and is still managed by job runner
892 self.task_events_mgr.process_message(
893 itask, log_lvl, TASK_OUTPUT_STARTED, jp_ctx.time_run, flag)
894 elif jp_ctx.job_runner_exit_polled == 1:
895 # The job never ran, and no longer in job runner
896 self.task_events_mgr.process_message(
897 itask, log_lvl, self.task_events_mgr.EVENT_SUBMIT_FAILED,
898 jp_ctx.time_submit_exit, flag)
899 else:
900 # The job never ran, and is in job runner
901 self.task_events_mgr.process_message(
902 itask, log_lvl, TASK_STATUS_SUBMITTED, jp_ctx.time_submit_exit,
903 flag)
904
905 def _poll_task_job_message_callback(self, itask, cmd_ctx, line):
906 """Helper for _poll_task_jobs_callback, on message of one task job."""
907 ctx = SubProcContext(self.JOBS_POLL, None)
908 ctx.out = line
909 try:
910 event_time, severity, message = line.split("|")[2:5]
911 except ValueError:
912 ctx.ret_code = 1
913 ctx.cmd = cmd_ctx.cmd # print original command on failure
914 else:
915 ctx.ret_code = 0
916 self.task_events_mgr.process_message(
917 itask, severity, message, event_time,
918 self.task_events_mgr.FLAG_POLLED)
919 log_task_job_activity(ctx, self.workflow, itask.point, itask.tdef.name)
920
921 def _run_job_cmd(
922 self, cmd_key, itasks, callback, callback_255
923 ):
924 """Run job commands, e.g. poll, kill, etc.
925
926 Group itasks with their platform_name and host.
927 Put a job command for each group to the multiprocess pool.
928
929 """
930 if not itasks:
931 return
932 # sort itasks into lists based upon where they were run.
933 auth_itasks = {}
934 for itask in itasks:
935 auth_itasks.setdefault(itask.platform['name'], []).append(itask)
936
937 # Go through each list of itasks and carry out commands as required.
938 for platform_name, itasks in sorted(auth_itasks.items()):
939 try:
940 platform = get_platform(platform_name)
941 except NoPlatformsError:
942 LOG.error(
943 f'Unable to run command {cmd_key}: Unable to find'
944 f' platform {platform_name} with accessible hosts.'
945 )
946 continue
947 except PlatformLookupError:
948 LOG.error(
949 f'Unable to run command {cmd_key}: Unable to find'
950 f' platform {platform_name}.'
951 )
952 continue
953 if is_remote_platform(platform):
954 remote_mode = True
955 cmd = [cmd_key]
956 else:
957 cmd = ["cylc", cmd_key]
958 remote_mode = False
959 if LOG.isEnabledFor(DEBUG):
960 cmd.append("--debug")
961 cmd.append("--")
962 cmd.append(get_remote_workflow_run_job_dir(self.workflow))
963 job_log_dirs = []
964 host = 'localhost'
965
966 ctx = SubProcContext(cmd_key, cmd, host=host)
967 if remote_mode:
968 try:
969 host = get_host_from_platform(
970 platform, bad_hosts=self.bad_hosts
971 )
972 cmd = construct_ssh_cmd(
973 cmd, platform, host
974 )
975 except NoHostsError:
976 ctx.err = f'No available hosts for {platform["name"]}'
977 LOG.debug(ctx)
978 callback_255(ctx, itasks)
979 continue
980 else:
981 ctx = SubProcContext(cmd_key, cmd, host=host)
982
983 for itask in sorted(itasks, key=lambda task: task.identity):
984 job_log_dirs.append(itask.job_tokens.relative_id)
985 cmd += job_log_dirs
986 LOG.debug(f'{cmd_key} for {platform["name"]} on {host}')
987 self.proc_pool.put_command(
988 ctx,
989 bad_hosts=self.bad_hosts,
990 callback=callback,
991 callback_args=[itasks],
992 callback_255=callback_255,
993 )
994
995 @staticmethod
996 def _set_retry_timers(
997 itask: 'TaskProxy',
998 rtconfig: Optional[dict] = None
999 ) -> None:
1000 """Set try number and retry delays."""
1001 if rtconfig is None:
1002 rtconfig = itask.tdef.rtconfig
1003
1004 submit_delays = (
1005 rtconfig['submission retry delays']
1006 or itask.platform['submission retry delays']
1007 )
1008
1009 for key, delays in [
1010 (TimerFlags.SUBMISSION_RETRY, submit_delays),
1011 (TimerFlags.EXECUTION_RETRY, rtconfig['execution retry delays'])
1012 ]:
1013 if delays is None:
1014 delays = []
1015 try:
1016 itask.try_timers[key].set_delays(delays)
1017 except KeyError:
1018 itask.try_timers[key] = TaskActionTimer(delays=delays)
1019
1020 def submit_nonlive_task_jobs(
1021 self: 'TaskJobManager',
1022 itasks: 'Iterable[TaskProxy]',
1023 workflow_run_mode: RunMode,
1024 ) -> 'Tuple[List[TaskProxy], List[TaskProxy]]':
1025 """Identify task mode and carry out alternative submission
1026 paths if required:
1027
1028 * Simulation: Job submission.
1029 * Skip: Entire job lifecycle happens here!
1030 * Dummy: Pre-submission preparation (removing task script's content)
1031 before returning to live pathway.
1032 * Live: return to main submission pathway without doing anything.
1033
1034 Returns:
1035 lively_tasks:
1036 A list of tasks which require subsequent
1037 processing **as if** they were live mode tasks.
1038 (This includes live and dummy mode tasks)
1039 nonlive_tasks:
1040 A list of tasks which require no further processing
1041 because their apparent execution is done entirely inside
1042 the scheduler. (This includes skip and simulation mode tasks).
1043 """
1044 lively_tasks: 'List[TaskProxy]' = []
1045 nonlive_tasks: 'List[TaskProxy]' = []
1046 now = time()
1047 now = (now, get_time_string_from_unix_time(now))
1048
1049 for itask in itasks:
1050 # Get task config with broadcasts applied:
1051 rtconfig = self.task_events_mgr.broadcast_mgr.get_updated_rtconfig(
1052 itask)
1053
1054 # Apply task run mode
1055 if workflow_run_mode.value in WORKFLOW_ONLY_MODES:
1056 # Task run mode cannot override workflow run-mode sim or dummy:
1057 itask.run_mode = workflow_run_mode
1058 else:
1059 # If workflow mode is skip or live and task mode is set,
1060 # override workflow mode, else use workflow mode.
1061 itask.run_mode = RunMode(
1062 rtconfig.get('run mode', workflow_run_mode))
1063
1064 # Submit nonlive tasks, or add live-like (live or dummy)
1065 # tasks to list of tasks to put through live submission pipeline.
1066 submit_func = itask.run_mode.get_submit_method()
1067 if submit_func and submit_func(self, itask, rtconfig, now):
1068 # A submit function returns true if this is a nonlive task:
1069 self.workflow_db_mgr.put_insert_task_states(itask)
1070 nonlive_tasks.append(itask)
1071 else:
1072 lively_tasks.append(itask)
1073
1074 return lively_tasks, nonlive_tasks
1075
1076 def _submit_task_jobs_callback(self, ctx, itasks):
1077 """Callback when submit task jobs command exits."""
1078 self._manip_task_jobs_callback(
1079 ctx,
1080 itasks,
1081 self._submit_task_job_callback,
1082 {self.job_runner_mgr.OUT_PREFIX_COMMAND:
1083 self._job_cmd_out_callback}
1084 )
1085
1086 def _submit_task_jobs_callback_255(self, ctx, itasks):
1087 """Callback when submit task jobs command exits."""
1088 self._manip_task_jobs_callback(
1089 ctx,
1090 itasks,
1091 self._submit_task_job_callback_255,
1092 {self.job_runner_mgr.OUT_PREFIX_COMMAND:
1093 self._job_cmd_out_callback}
1094 )
1095
1096 def _submit_task_job_callback_255(self, itask, cmd_ctx, line):
1097 """Helper for _submit_task_jobs_callback, on one task job."""
1098 # send this task back for submission again
1099 itask.waiting_on_job_prep = True # (task is in the preparing state)
1100
1101 def _submit_task_job_callback(self, itask, cmd_ctx, line):
1102 """Helper for _submit_task_jobs_callback, on one task job."""
1103 ctx = SubProcContext(self.JOBS_SUBMIT, None, cmd_ctx.host)
1104 ctx.out = line
1105 items = line.split("|")
1106 try:
1107 ctx.timestamp, _, ctx.ret_code = items[0:3]
1108 except ValueError:
1109 ctx.ret_code = 1
1110 ctx.cmd = cmd_ctx.cmd # print original command on failure
1111 else:
1112 ctx.ret_code = int(ctx.ret_code)
1113 if ctx.ret_code:
1114 ctx.cmd = cmd_ctx.cmd # print original command on failure
1115 if cmd_ctx.ret_code != 255:
1116 log_task_job_activity(
1117 ctx, self.workflow, itask.point, itask.tdef.name
1118 )
1119 if ctx.ret_code == SubProcPool.RET_CODE_WORKFLOW_STOPPING:
1120 return
1121
1122 try:
1123 itask.summary['submit_method_id'] = items[3]
1124 except IndexError:
1125 itask.summary['submit_method_id'] = None
1126 if itask.summary['submit_method_id'] == "None":
1127 itask.summary['submit_method_id'] = None
1128 if itask.summary['submit_method_id'] and ctx.ret_code == 0:
1129 self.task_events_mgr.process_message(
1130 itask, DEBUG, TASK_OUTPUT_SUBMITTED, ctx.timestamp)
1131 else:
1132 self.task_events_mgr.process_message(
1133 itask, CRITICAL, self.task_events_mgr.EVENT_SUBMIT_FAILED,
1134 ctx.timestamp)
1135
1136 def _prep_submit_task_job(
1137 self,
1138 itask: 'TaskProxy',
1139 check_syntax: bool = True
1140 ) -> 'Union[TaskProxy, None, Literal[False]]':
1141 """Prepare a task job submission.
1142
1143 Returns:
1144 * itask - preparation complete.
1145 * None - preparation in progress.
1146 * False - preparation failed.
1147
1148 """
1149 if itask.local_job_file_path:
1150 return itask
1151
1152 # Handle broadcasts
1153 rtconfig = self.task_events_mgr.broadcast_mgr.get_updated_rtconfig(
1154 itask
1155 )
1156
1157 # BACK COMPAT: host logic
1158 # Determine task host or platform now, just before job submission,
1159 # because dynamic host/platform selection may be used.
1160 # cases:
1161 # - Platform exists, host does = throw error here:
1162 # Although errors of this sort should ideally be caught on config
1163 # load this cannot be done because inheritance may create conflicts
1164 # which appear later. Although this error is also raised
1165 # by the platforms module it's probably worth putting it here too
1166 # to prevent trying to run the remote_host/platform_select logic for
1167 # tasks which will fail anyway later.
1168 # - Platform exists, host doesn't = eval platform_name
1169 # - host exists - eval host_n
1170 # remove at:
1171 # Cylc8.x
1172 fail_if_platform_and_host_conflict(rtconfig, itask.tdef.name)
1173
1174 host_name, platform_name = None, None
1175 try:
1176 # We need to assume that we want a host if any of the items
1177 # for the old host/batch system plaform selection system are set.
1178 if any(
1179 rtconfig[section][key] is not None
1180 for section, values in FORBIDDEN_WITH_PLATFORM.items()
1181 for key in values
1182 ):
1183 host_name = self.task_remote_mgr.eval_host(
1184 rtconfig['remote']['host']
1185 )
1186 else:
1187 platform_name = self.task_remote_mgr.eval_platform(
1188 rtconfig['platform']
1189 )
1190
1191 except PlatformError as exc:
1192 self._prep_submit_task_job_platform_error(itask, rtconfig, exc)
1193 return False
1194 else:
1195 if host_name is None and platform_name is None:
1196 # host/platform select not ready
1197 return None
1198 elif (
1199 host_name is None
1200 and rtconfig['platform']
1201 and rtconfig['platform'] != platform_name
1202 ):
1203 msg = (
1204 f"for task {itask.identity}: platform = "
1205 f"{rtconfig['platform']} evaluated as '{platform_name}'"
1206 )
1207 if not platform_name:
1208 self._prep_submit_task_job_platform_error(
1209 itask, rtconfig, msg
1210 )
1211 return False
1212 LOG.debug(msg)
1213 elif (
1214 platform_name is None
1215 and rtconfig['remote']['host'] != host_name
1216 ):
1217 msg = (
1218 f"[{itask}] host = "
1219 f"{rtconfig['remote']['host']} evaluated as '{host_name}'"
1220 )
1221 if not host_name:
1222 self._prep_submit_task_job_platform_error(
1223 itask, rtconfig, msg
1224 )
1225 return False
1226 LOG.debug(msg)
1227
1228 try:
1229 platform = cast(
1230 # We know this is not None because eval_platform() or
1231 # eval_host() called above ensure it is set or else we
1232 # return early if the subshell is still evaluating.
1233 'dict',
1234 get_platform(
1235 platform_name or rtconfig,
1236 itask.tdef.name,
1237 bad_hosts=self.bad_hosts,
1238 evaluated_host=host_name,
1239 ),
1240 )
1241 except PlatformLookupError as exc:
1242 itask.waiting_on_job_prep = False
1243 itask.summary['platforms_used'][itask.submit_num] = ''
1244 # Retry delays, needed for the try_num
1245 self._create_job_log_path(itask)
1246 msg = '(platform not defined)'
1247 if isinstance(exc, NoPlatformsError):
1248 msg = '(no platforms available)'
1249 # Clear all hosts from all platforms in group from
1250 # bad_hosts:
1251 self.bad_hosts -= exc.hosts_consumed
1252 self._set_retry_timers(itask, rtconfig)
1253 # Provide dummy platform otherwise it will incorrectly show as
1254 # the default localhost platform in the data store:
1255 itask.platform = {
1256 'name': rtconfig['platform'],
1257 'job runner': '',
1258 }
1259 self._prep_submit_task_job_error(itask, msg, exc)
1260 return False
1261
1262 itask.platform = platform
1263 # Retry delays, needed for the try_num
1264 self._set_retry_timers(itask, rtconfig)
1265
1266 try:
1267 job_conf = self._prep_submit_task_job_impl(
1268 itask,
1269 rtconfig,
1270 )
1271 itask.jobs.append(job_conf)
1272
1273 local_job_file_path = get_task_job_job_log(
1274 self.workflow,
1275 itask.point,
1276 itask.tdef.name,
1277 itask.submit_num,
1278 )
1279 self.job_file_writer.write(
1280 local_job_file_path,
1281 job_conf,
1282 check_syntax=check_syntax,
1283 )
1284 except Exception as exc:
1285 # Could be a bad command template, IOError, etc
1286 itask.waiting_on_job_prep = False
1287 self._prep_submit_task_job_error(itask, '(prepare job file)', exc)
1288 return False
1289
1290 itask.local_job_file_path = local_job_file_path
1291 return itask
1292
1293 def _prep_submit_task_job_platform_error(
1294 self, itask: 'TaskProxy', rtconfig: dict, exc: Exception | str
1295 ):
1296 """Helper for self._prep_submit_task_job. On platform selection error.
1297 """
1298 itask.waiting_on_job_prep = False
1299 itask.summary['platforms_used'][itask.submit_num] = ''
1300 # Retry delays, needed for the try_num
1301 self._create_job_log_path(itask)
1302 self._set_retry_timers(itask, rtconfig)
1303 self._prep_submit_task_job_error(
1304 itask, '(remote host select)', exc
1305 )
1306
1307 def _prep_submit_task_job_error(
1308 self,
1309 itask: 'TaskProxy',
1310 action: str,
1311 exc: Union[Exception, str],
1312 ) -> None:
1313 """Helper for self._prep_submit_task_job. On error."""
1314 log_task_job_activity(
1315 SubProcContext(self.JOBS_SUBMIT, action, err=exc, ret_code=1),
1316 self.workflow,
1317 itask.point,
1318 itask.tdef.name,
1319 submit_num=itask.submit_num
1320 )
1321 itask.is_manual_submit = False
1322 # job failed in preparation i.e. is really preparation-failed rather
1323 # than submit-failed
1324 try_num = itask.get_try_num()
1325 if not itask.jobs or (
1326 itask.jobs[-1]['submit_num'] != itask.submit_num
1327 ):
1328 # provide a dummy job config - this info will be added to the data
1329 # store
1330 itask.jobs.append({
1331 'task_id': itask.identity,
1332 'platform': itask.platform,
1333 'job_runner_name': itask.platform['job runner'],
1334 'submit_num': itask.submit_num,
1335 'try_num': try_num,
1336 'flow_nums': itask.flow_nums,
1337 })
1338 # create a DB entry for the submit-failed job
1339 self.workflow_db_mgr.put_insert_task_jobs(
1340 itask,
1341 {
1342 'flow_nums': serialise_set(itask.flow_nums),
1343 'job_id': itask.summary.get('submit_method_id'),
1344 'is_manual_submit': itask.is_manual_submit,
1345 'try_num': try_num,
1346 'time_submit': get_current_time_string(),
1347 'platform_name': itask.platform['name'],
1348 'job_runner_name': itask.summary['job_runner_name'],
1349 }
1350 )
1351 self.task_events_mgr.process_message(
1352 itask, CRITICAL, self.task_events_mgr.EVENT_SUBMIT_FAILED)
1353
1354 def _prep_submit_task_job_impl(self, itask, rtconfig):
1355 """Helper for self._prep_submit_task_job."""
1356
1357 itask.summary['platforms_used'][
1358 itask.submit_num] = itask.platform['name']
1359
1360 itask.summary['job_runner_name'] = itask.platform['job runner']
1361
1362 # None is an allowed non-float number for Execution time limit.
1363 itask.summary[
1364 self.KEY_EXECUTE_TIME_LIMIT
1365 ] = self.get_execution_time_limit(rtconfig['execution time limit'])
1366
1367 # Location of job file, etc
1368 self._create_job_log_path(itask)
1369 job_d = itask.job_tokens.relative_id
1370 job_file_path = get_remote_workflow_run_job_dir(
1371 self.workflow, job_d, JOB_LOG_JOB
1372 )
1373
1374 return self.get_job_conf(
1375 itask,
1376 rtconfig,
1377 job_file_path=job_file_path,
1378 job_d=job_d
1379 )
1380
1381 @staticmethod
1382 def get_execution_time_limit(
1383 config_execution_time_limit: Any
1384 ) -> Union[None, float]:
1385 """Get execution time limit from config and process it.
1386
1387 If the etl from the config is a Falsy then return None.
1388 Otherwise try and parse value as float.
1389
1390 Examples:
1391 >>> from pytest import raises
1392 >>> this = TaskJobManager.get_execution_time_limit
1393
1394 >>> this(None)
1395 >>> this("54")
1396 54.0
1397 >>> this({})
1398 >>> with raises(ValueError):
1399 ... this('🇳🇿')
1400 """
1401 if config_execution_time_limit:
1402 return float(config_execution_time_limit)
1403 return None
1404
1405 def get_job_conf(
1406 self,
1407 itask: 'TaskProxy',
1408 rtconfig: dict,
1409 job_file_path: Optional[str] = None,
1410 job_d: Optional[str] = None,
1411 ):
1412 """Return a job config.
1413
1414 Note that rtconfig should have any broadcasts applied.
1415 """
1416 return {
1417 # NOTE: these fields should match get_simulation_job_conf
1418 # TODO: formalise this
1419 # https://github.com/cylc/cylc-flow/issues/5387
1420 'job_runner_name': itask.platform['job runner'],
1421 'job_runner_command_template': (
1422 itask.platform['job runner command template']
1423 ),
1424 'dependencies': itask.state.get_resolved_dependencies(),
1425 'directives': {
1426 **itask.platform['directives'], **rtconfig['directives']
1427 },
1428 'environment': rtconfig['environment'],
1429 'execution_time_limit': itask.summary[self.KEY_EXECUTE_TIME_LIMIT],
1430 'env-script': rtconfig['env-script'],
1431 'err-script': rtconfig['err-script'],
1432 'exit-script': rtconfig['exit-script'],
1433 'platform': itask.platform,
1434 'init-script': rtconfig['init-script'],
1435 'job_file_path': job_file_path,
1436 'job_d': job_d,
1437 'namespace_hierarchy': itask.tdef.namespace_hierarchy,
1438 'param_var': itask.tdef.param_var,
1439 'post-script': rtconfig['post-script'],
1440 'pre-script': rtconfig['pre-script'],
1441 'script': rtconfig['script'],
1442 'submit_num': itask.submit_num,
1443 'flow_nums': itask.flow_nums,
1444 'workflow_name': self.workflow,
1445 'task_id': itask.identity,
1446 'try_num': itask.get_try_num(),
1447 'uuid_str': self.task_events_mgr.uuid_str,
1448 'work_d': rtconfig['work sub-directory'],
1449 }
1450
1451 def get_simulation_job_conf(self, itask):
1452 """Return a job config for a simulated task."""
1453 return {
1454 # NOTE: these fields should match _prep_submit_task_job_impl
1455 'job_runner_name': 'SIMULATION',
1456 'job_runner_command_template': '',
1457 'dependencies': itask.state.get_resolved_dependencies(),
1458 'directives': {},
1459 'environment': {},
1460 'execution_time_limit': itask.summary[self.KEY_EXECUTE_TIME_LIMIT],
1461 'env-script': 'SIMULATION',
1462 'err-script': 'SIMULATION',
1463 'exit-script': 'SIMULATION',
1464 'platform': itask.platform,
1465 'init-script': 'simulation',
1466 'job_file_path': 'simulation',
1467 'job_d': 'SIMULATION',
1468 'namespace_hierarchy': itask.tdef.namespace_hierarchy,
1469 'param_var': itask.tdef.param_var,
1470 'post-script': 'SIMULATION',
1471 'pre-script': 'SIMULATION',
1472 'script': 'SIMULATION',
1473 'submit_num': itask.submit_num,
1474 'flow_nums': itask.flow_nums,
1475 'workflow_name': self.workflow,
1476 'task_id': itask.identity,
1477 'try_num': itask.get_try_num(),
1478 'uuid_str': self.task_events_mgr.uuid_str,
1479 'work_d': 'SIMULATION',
1480 }