Debian Codegraph @

cylc/flow/subprocpool.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 queueing and pooling of subprocesses for the scheduler."""
17
18 from collections import deque
19 import json
20 import os
21 import select
22 from signal import SIGKILL
23 import sys
24 import shlex
25 from tempfile import SpooledTemporaryFile
26 from threading import RLock
27 from time import time
28 from subprocess import DEVNULL, TimeoutExpired, run # nosec
29 from typing import TYPE_CHECKING, Any, Callable, List, Optional, Set
30
31 from cylc.flow import LOG, iter_entry_points
32 from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
33 from cylc.flow.cylc_subproc import procopen
34 from cylc.flow.exceptions import PlatformLookupError
35 from cylc.flow.hostuserutil import is_remote_host
36 from cylc.flow.platforms import (
37 log_platform_event,
38 get_platform,
39 )
40 from cylc.flow.subprocctx import SubFuncContext
41 from cylc.flow.task_events_mgr import TaskJobLogsRetrieveContext
42 from cylc.flow.task_proxy import TaskProxy
43 from cylc.flow.wallclock import get_current_time_string
44
45 if TYPE_CHECKING:
46 from subprocess import Popen
47 from cylc.flow.subprocctx import SubProcContext
48
49 _XTRIG_MOD_CACHE: dict = {}
50 _XTRIG_FUNC_CACHE: dict = {}
51
52
53 def _killpg(proc, signal):
54 """Kill a process group."""
55 try:
56 os.killpg(proc.pid, signal)
57 except ProcessLookupError:
58 # process group has already exited
59 return False
60 except PermissionError:
61 # process group may contain zombie processes which will result in
62 # PermissionError on some systems, not sure what happens on others
63 #
64 # we could go through the processes in the group and call waitpid on
65 # them but waitpid is blocking and this would be a messy solution for a
66 # problem that shouldn't happen (it's really a bug in the Cylc subproc)
67 LOG.error(
68 f'Could not kill process group: {proc.pid}'
69 f'\nCommand: {" ".join(proc.args)}'
70 )
71 return False
72 return True
73
74
75 def get_xtrig_mod(mod_name, src_dir):
76 """Find, cache, and return a named xtrigger module.
77
78 Locations checked in this order:
79 - <src_dir>/lib/python (prepend to sys.path)
80 - $CYLC_PYTHONPATH (already in sys.path)
81 - `cylc.xtriggers` entry point
82
83 (Check entry point last so users can override with local implementations).
84
85 Workflow source dir passed in - this executes in an independent subprocess.
86
87 Raises:
88 ImportError, if the module is not found
89
90 """
91 if mod_name in _XTRIG_MOD_CACHE:
92 # Found and cached already.
93 return _XTRIG_MOD_CACHE[mod_name]
94
95 # First look in <src-dir>/lib/python.
96 sys.path.insert(0, os.path.join(src_dir, 'lib', 'python'))
97 try:
98 _XTRIG_MOD_CACHE[mod_name] = __import__(mod_name, fromlist=[mod_name])
99 except ImportError:
100 # Then entry point.
101 for entry_point in iter_entry_points('cylc.xtriggers'):
102 if mod_name == entry_point.name:
103 _XTRIG_MOD_CACHE[mod_name] = entry_point.load()
104 return _XTRIG_MOD_CACHE[mod_name]
105 # Still unable to find anything so abort
106 raise
107
108 return _XTRIG_MOD_CACHE[mod_name]
109
110
111 def get_xtrig_func(mod_name, func_name, src_dir):
112 """Find, cache, and return a function from an xtrigger module.
113
114 Raises:
115 ImportError, if the module is not found
116 AttributeError, if the function is not found in the module
117
118 """
119 if (mod_name, func_name) in _XTRIG_FUNC_CACHE:
120 return _XTRIG_FUNC_CACHE[(mod_name, func_name)]
121
122 mod = get_xtrig_mod(mod_name, src_dir)
123
124 _XTRIG_FUNC_CACHE[(mod_name, func_name)] = getattr(mod, func_name)
125
126 return _XTRIG_FUNC_CACHE[(mod_name, func_name)]
127
128
129 def run_function(mod_name, func_name, json_args, json_kwargs, src_dir):
130 """Run a Python function in the process pool.
131
132 func_name(*func_args, **func_kwargs)
133
134 The function is presumed to be in a module of the same name.
135
136 Redirect any function stdout to stderr (and workflow log in debug mode).
137 Return value printed to stdout as a JSON string - allows use of the
138 existing process pool machinery as-is. src_dir is for local modules.
139
140 """
141 func_args = json.loads(json_args)
142 func_kwargs = json.loads(json_kwargs)
143
144 # Find and import then function.
145 func = get_xtrig_func(mod_name, func_name, src_dir)
146
147 # Redirect stdout to stderr.
148 orig_stdout = sys.stdout
149 sys.stdout = sys.stderr
150 res = func(*func_args, **func_kwargs)
151
152 # Restore stdout.
153 sys.stdout = orig_stdout
154
155 # Write function return value as JSON to stdout.
156 sys.stdout.write(json.dumps(res))
157
158
159 class SubProcPool:
160 """Manage queueing and pooling of subprocesses.
161
162 Mainly used by the main loop of the scheduler, although
163 the SubProcPool.run_command can be used as a standalone utility function
164 to run the command in a cylc.flow.subprocctx.SubProcContext.
165
166 A command to run under a subprocess in the pool is expected to be wrapped
167 using a cylc.flow.subprocctx.SubProcContext object. The caller will add the
168 context object using the SubProcPool.put_command method. A callback can
169 be specified to notify the caller on exit of the subprocess.
170
171 A command launched by the pool is expected to write to STDOUT and STDERR.
172 These are captured while the command runs and/or when the command exits.
173 The contents are appended to the `.out` and `.err` attributes of the
174 SubProcContext object as they are read. STDIN can also be specified for the
175 command. This is currently fed into the command using a temporary file.
176
177 Note: For a cylc command that uses
178 `cylc.flow.option_parsers.CylcOptionParser`, the default logging handler
179 writes to the STDERR via a StreamHandler. Therefore, log messages will
180 only be written to the workflow log by the callback function when the
181 command exits (and only if the callback function has the logic to do so).
182
183 """
184
185 ERR_WORKFLOW_STOPPING = 'workflow stopping, command not run'
186 JOBS_SUBMIT = 'jobs-submit'
187 POLLREAD = select.POLLIN | select.POLLPRI
188 RET_CODE_WORKFLOW_STOPPING = 999
189
190 def __init__(self):
191 self.size = glbl_cfg().get(['scheduler', 'process pool size'])
192 self.proc_pool_timeout = glbl_cfg().get(
193 ['scheduler', 'process pool timeout'])
194 self.closed = False # Close queue
195 self.stopping = False # No more job submit if True
196 # .stopping may be set by an API command in a different thread
197 self.stopping_lock = RLock()
198 self.queuings = deque()
199 self.runnings = []
200 try:
201 self.pipepoller = select.poll()
202 except AttributeError: # select.poll not implemented for this OS
203 self.pipepoller = None
204
205 def close(self):
206 """Close pool."""
207 self.set_stopping()
208 self.closed = True
209
210 @staticmethod
211 def get_temporary_file():
212 """Return a SpooledTemporaryFile for feeding data to command STDIN."""
213 return SpooledTemporaryFile()
214
215 def is_not_done(self):
216 """Return True if queuings or runnings not empty."""
217 return self.queuings or self.runnings
218
219 def _is_stopping(self):
220 """Return whether .stopping is True or not.
221
222 Returns:
223 bool: Whether the pool is stopping or not.
224 """
225 with self.stopping_lock:
226 return self.stopping
227
228 def _proc_exit(
229 self,
230 proc: 'Popen[bytes]',
231 err_xtra: str,
232 ctx: 'SubProcContext',
233 callback: Callable,
234 callback_args: list,
235 bad_hosts: Optional[Set[str]] = None,
236 callback_255: Optional[Callable] = None,
237 callback_255_args: Optional[list] = None,
238 ):
239 """Get ret_code, out, err of exited command, and call its callback."""
240 ctx.ret_code = proc.wait()
241 out, err = (f.decode() for f in proc.communicate())
242 if out:
243 if ctx.out is None:
244 ctx.out = ''
245 ctx.out += out
246 if err + err_xtra:
247 if ctx.err is None:
248 ctx.err = ''
249 ctx.err += err + err_xtra
250 LOG.debug(
251 ctx.dump() if isinstance(ctx, SubFuncContext) else ctx
252 )
253 self._run_command_exit(
254 ctx, bad_hosts=bad_hosts,
255 callback=callback, callback_args=callback_args,
256 callback_255=callback_255, callback_255_args=callback_255_args
257 )
258
259 def process(self):
260 """Process done child processes and submit more."""
261 # Handle child processes that are done
262 runnings = []
263 for running in self.runnings:
264 (
265 proc, ctx, bad_hosts,
266 callback, callback_args,
267 callback_255, callback_255_args
268 ) = running
269 # Command completed/exited
270 if proc.poll() is not None:
271 self._proc_exit(
272 proc, "", ctx,
273 callback=callback, callback_args=callback_args,
274 bad_hosts=bad_hosts,
275 callback_255=callback_255,
276 callback_255_args=callback_255_args
277 )
278 continue
279 # Command timed out, kill it
280 if time() > ctx.timeout:
281 err_xtra = ""
282 if _killpg(proc, SIGKILL):
283 err_xtra = (
284 f"\nkilled on timeout ({self.proc_pool_timeout})"
285 )
286 self._proc_exit(
287 proc, err_xtra, ctx,
288 callback=callback,
289 callback_args=callback_args,
290 bad_hosts=bad_hosts
291 )
292 continue
293 # Command still running, see if STDOUT/STDERR are readable or not
294 runnings.append(
295 [
296 proc,
297 ctx,
298 bad_hosts,
299 callback,
300 callback_args,
301 callback_255,
302 callback_255_args,
303 ]
304 )
305 # Unblock proc's STDOUT/STDERR if necessary. Otherwise, a full
306 # STDOUT or STDERR may stop command from proceeding.
307 self._poll_proc_pipes(proc, ctx)
308
309 # Update list of running items
310 self.runnings[:] = runnings
311 # Create more child processes, if items in queue and space in pool
312 stopping = self._is_stopping()
313 while self.queuings and len(self.runnings) < self.size:
314 (
315 ctx, bad_hosts, callback, callback_args,
316 callback_255, callback_255_args
317 ) = self.queuings.popleft()
318 if stopping and ctx.cmd_key == self.JOBS_SUBMIT:
319 ctx.err = self.ERR_WORKFLOW_STOPPING
320 ctx.ret_code = self.RET_CODE_WORKFLOW_STOPPING
321 self._run_command_exit(ctx)
322 else:
323 proc = self._run_command_init(
324 ctx, bad_hosts, callback, callback_args,
325 callback_255, callback_255_args
326 )
327 if proc is not None:
328 ctx.timeout = time() + self.proc_pool_timeout
329 self.runnings.append([
330 proc, ctx, bad_hosts, callback, callback_args,
331 callback_255, callback_255_args
332 ])
333
334 def put_command(
335 self, ctx, bad_hosts=None, callback=None, callback_args=None,
336 callback_255=None, callback_255_args=None
337 ):
338 """Queue a new shell command to execute.
339
340 Arguments:
341 ctx (cylc.flow.subprocctx.SubProcContext):
342 A context object containing the command to run and its status.
343 callback (callable):
344 Function to call back when command exits or on error.
345 Should have signature:
346 callback(ctx, *callback_args) -> None
347 callback_args (list):
348 Extra arguments to the callback function.
349 """
350 if (self.closed or self._is_stopping() and
351 ctx.cmd_key == self.JOBS_SUBMIT):
352 ctx.err = self.ERR_WORKFLOW_STOPPING
353 ctx.ret_code = self.RET_CODE_WORKFLOW_STOPPING
354 self._run_command_exit(
355 ctx, bad_hosts=bad_hosts,
356 callback=callback, callback_args=callback_args,
357 callback_255=callback_255, callback_255_args=callback_255_args
358 )
359 else:
360 self.queuings.append(
361 [
362 ctx, bad_hosts, callback, callback_args,
363 callback_255, callback_255_args
364 ]
365 )
366
367 @classmethod
368 def run_command(cls, ctx, callback: Optional[Callable] = None):
369 """Execute command in ctx and capture its output and exit status.
370
371 Kills the subprocess if it exceeds the subprocess pool timeout.
372
373 Arguments:
374 ctx (cylc.flow.subprocctx.SubProcContext):
375 A context object containing the command to run and its status.
376 callback:
377 Optional callback function.
378 """
379 timeout = glbl_cfg().get(['scheduler', 'process pool timeout'])
380
381 proc = cls._run_command_init(ctx)
382 if not proc:
383 return
384
385 try:
386 ctx.out, ctx.err = (
387 f.decode()
388 for f in proc.communicate(timeout=float(timeout))
389 )
390 except TimeoutExpired:
391 if _killpg(proc, SIGKILL):
392 ctx.err = f"killed on timeout ({timeout})"
393 ctx.ret_code = proc.wait()
394 else:
395 ctx.ret_code = proc.wait()
396
397 if callback is not None:
398 callback(ctx)
399 cls._run_command_exit(ctx)
400
401 def set_stopping(self):
402 """Stop job submission."""
403 with self.stopping_lock:
404 self.stopping = True
405
406 def terminate(self):
407 """Drain queue, and kill and process remaining child processes."""
408 self.close()
409 # Drain queue
410 while self.queuings:
411 ctx = self.queuings.popleft()[0]
412 ctx.err = self.ERR_WORKFLOW_STOPPING
413 ctx.ret_code = self.RET_CODE_WORKFLOW_STOPPING
414 self._run_command_exit(ctx)
415 # Kill remaining processes
416 for value in self.runnings:
417 proc = value[0]
418 if proc:
419 _killpg(proc, SIGKILL)
420 # Wait for child processes
421 self.process()
422
423 def _poll_proc_pipes(self, proc, ctx):
424 """Poll STDOUT/ERR of proc and read some data if possible.
425
426 This helps to unblock the command by unblocking its pipes.
427 """
428 if self.pipepoller is None:
429 return # select.poll not supported on this OS
430 for handle in [proc.stdout, proc.stderr]:
431 if not handle.closed:
432 self.pipepoller.register(handle.fileno(), self.POLLREAD)
433 while True:
434 fileno_list = [
435 fileno
436 for fileno, event in self.pipepoller.poll(0.0)
437 if event & self.POLLREAD]
438 if not fileno_list:
439 # Nothing readable
440 break
441 received_data = []
442 for fileno in fileno_list:
443 # If a file handle is readable, read something from it, add
444 # results into the command context object's `.out` or `.err`,
445 # whichever is relevant. To avoid blocking:
446 # 1. Use `os.read` here instead of `file.read` to avoid any
447 # buffering that may cause the file handle to block.
448 # 2. Call os.read only once after a poll. Poll again before
449 # another read - otherwise the os.read call may block.
450 try:
451 data = os.read(fileno, 65536).decode() # 64K
452 except OSError:
453 continue
454 received_data.append(data != '')
455 if fileno == proc.stdout.fileno():
456 if ctx.out is None:
457 ctx.out = ''
458 ctx.out += data
459 elif fileno == proc.stderr.fileno():
460 if ctx.err is None:
461 ctx.err = ''
462 ctx.err += data
463 if received_data and not all(received_data):
464 # if no data was pushed down the pipe exit the polling loop,
465 # we can always re-enter the polling loop later if there is
466 # more data
467 # NOTE: this suppresses an infinite polling-loop observed
468 # on darwin see:
469 # https://github.com/cylc/cylc-flow/issues/3535
470 # https://github.com/cylc/cylc-flow/pull/3543
471 return
472 self.pipepoller.unregister(proc.stdout.fileno())
473 self.pipepoller.unregister(proc.stderr.fileno())
474
475 @classmethod
476 def _run_command_init(
477 cls, ctx, bad_hosts=None, callback=None, callback_args=None,
478 callback_255=None, callback_255_args=None
479 ):
480 """Prepare and launch shell command in ctx."""
481 try:
482 if ctx.cmd_kwargs.get('stdin_files'):
483 if len(ctx.cmd_kwargs['stdin_files']) > 1:
484 stdin_file = cls.get_temporary_file()
485 for file_ in ctx.cmd_kwargs['stdin_files']:
486 if hasattr(file_, 'read'):
487 stdin_file.write(file_.read())
488 else:
489 with open(file_, 'rb') as openfile:
490 stdin_file.write(openfile.read())
491 stdin_file.seek(0)
492 elif hasattr(ctx.cmd_kwargs['stdin_files'][0], 'read'):
493 stdin_file = ctx.cmd_kwargs['stdin_files'][0]
494 else:
495 stdin_file = open( # noqa: SIM115
496 # (nasty use of file handles, should avoid in future)
497 ctx.cmd_kwargs['stdin_files'][0], 'rb'
498 )
499 elif ctx.cmd_kwargs.get('stdin_str'):
500 stdin_file = cls.get_temporary_file()
501 stdin_file.write(ctx.cmd_kwargs.get('stdin_str').encode())
502 stdin_file.seek(0)
503 else:
504 stdin_file = DEVNULL
505 proc = procopen(
506 ctx.cmd, stdin=stdin_file, stdoutpipe=True, stderrpipe=True,
507 # Execute command as a process group leader,
508 # so we can use "os.killpg" to kill the whole group.
509 preexec_fn=os.setpgrp,
510 env=ctx.cmd_kwargs.get('env'),
511 usesh=ctx.cmd_kwargs.get('shell'))
512 # calls to open a shell are aggregated in cylc_subproc.procopen()
513 # with logging for what is calling it and the commands given
514 except OSError as exc:
515 if exc.filename is None:
516 exc.filename = ctx.cmd[0]
517 LOG.exception(exc)
518 ctx.ret_code = 1
519 ctx.err = str(exc)
520 cls._run_command_exit(
521 ctx, bad_hosts=bad_hosts,
522 callback=callback, callback_args=callback_args,
523 callback_255=callback_255, callback_255_args=callback_255_args
524 )
525 return None
526 else:
527 LOG.debug(ctx.cmd)
528 return proc
529
530 @classmethod
531 def _run_command_exit(
532 cls,
533 ctx: 'SubProcContext',
534 bad_hosts: Optional[Set[str]] = None,
535 callback: Optional[Callable] = None,
536 callback_args: Optional[List[Any]] = None,
537 callback_255: Optional[Callable] = None,
538 callback_255_args: Optional[List[Any]] = None
539 ) -> None:
540 """Process command completion.
541
542 If task has failed with a 255 error, run an alternative callback if
543 one is provided.
544
545 Args:
546 ctx: SubProcContext object for this task.
547 callback: Function to run on command exit.
548 callback_args: Arguments to provide to callback
549 callback_255: Function to run if command exits with a 255
550 error - usually associated with ssh being unable to
551 contact a remote host.
552 callback_255_args: Arguments for the 255 callback function.
553
554 """
555 def _run_callback(callback, args_=None):
556 if callable(callback):
557 if not args_:
558 args_ = []
559 callback(ctx, *args_)
560 else:
561 return False
562 ctx.timestamp = get_current_time_string()
563
564 # If cmd is fileinstall, which uses rsync, get a platform so
565 # that you can use that platform's ssh command.
566 platform_name = None
567 platform = None
568 if isinstance(ctx.cmd_key, TaskJobLogsRetrieveContext):
569 try:
570 platform = get_platform(ctx.cmd_key.platform_name)
571 except PlatformLookupError:
572 log_platform_event(
573 'Unable to retrieve job logs.',
574 {'name': ctx.cmd_key.platform_name},
575 level='warning',
576 )
577 elif callback_args:
578 platform = callback_args[0]
579 if not (
580 isinstance(platform, dict)
581 and 'ssh command' in platform
582 and 'name' in platform
583 ):
584 # the first argument is not a platform
585 platform = None
586 # Backup, get a platform name from the config:
587 for arg in callback_args:
588 if isinstance(arg, TaskProxy):
589 platform_name = arg.tdef.rtconfig['platform']
590 elif (
591 isinstance(arg, list)
592 and isinstance(arg[0], TaskProxy)
593 ):
594 platform_name = arg[0].tdef.rtconfig['platform']
595
596 if cls.ssh_255_fail(ctx) or cls.rsync_255_fail(ctx, platform) is True:
597 # Job log retrieval passes a special object as a command key
598 # Extra logic to provide sensible strings for logging.
599 if isinstance(ctx.cmd_key, TaskJobLogsRetrieveContext):
600 cmd_key = ctx.cmd_key.key
601 else:
602 cmd_key = ctx.cmd_key
603 log_platform_event(
604 # NOTE: the failure of the command should be logged elsewhere
605 (
606 f'Could not connect to {ctx.host}. '
607 f'{cmd_key} will retry if another host is available.'
608 ),
609 platform or {'name': platform_name},
610 level='warning',
611 )
612
613 # If callback_255 takes the same args as callback, we don't
614 # want to spec those args:
615 if callable(callback_255) and callback_255_args is None:
616 callback_255_args = callback_args
617
618 # Run Callback
619 if bad_hosts is not None:
620 bad_hosts.add(ctx.host)
621
622 res = _run_callback(callback_255, callback_255_args)
623 if res is False:
624 _run_callback(callback, callback_args)
625 else:
626 # For every other return code run default callback.
627 _run_callback(callback, callback_args)
628
629 @staticmethod
630 def ssh_255_fail(ctx) -> bool:
631 """Test context for ssh command failing with a 255 error."""
632 ssh_255_fail = False
633 if (
634 ctx.cmd[0] == 'ssh'
635 and ctx.ret_code == 255
636 ):
637 ssh_255_fail = True
638 return ssh_255_fail
639
640 @staticmethod
641 def rsync_255_fail(ctx, platform=None) -> bool:
642 """Tests context for rsync failing to communicate with a host.
643
644 If there has been a failure caused by rsync being unable to connect
645 try a test of ssh connectivity. Necessary because loss of connectivity
646 may cause different rsync failures depending on version, and some of
647 the failures may be caused by other problems.
648 """
649 rsync_255_fail = False
650 platform_rsync_cmd = (
651 platform['rsync command']
652 if platform is not None
653 else 'rsync'
654 )
655 rsync_cmd = shlex.split(platform_rsync_cmd)
656 if (
657 ctx.cmd[0] == rsync_cmd[0]
658 and ctx.ret_code not in [0, 255]
659 and is_remote_host(ctx.host)
660 ):
661 ssh_cmd = (
662 platform['ssh command']
663 if platform is not None
664 else 'ssh'
665 )
666 ssh_test_cmd = shlex.split(f'{ssh_cmd} {ctx.host} true')
667 LOG.info(
668 f'testing connectivity for {ctx.host} using {ssh_test_cmd}'
669 )
670 ssh_test = run(
671 shlex.split(f'{ssh_cmd} {ctx.host} true'), # nosec B603 *
672 capture_output=True
673 )
674 # * (command is trusted input)
675 if ssh_test.returncode == 255:
676 rsync_255_fail = True
677 elif (
678 ctx.cmd[0] == rsync_cmd[0]
679 and ctx.ret_code == 255
680 ):
681 rsync_255_fail = True
682 return rsync_255_fail