Debian Codegraph @

cylc/flow/remote.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 """Run command on a remote, (i.e. a remote [user@]host)."""
17
18 import os
19 from pathlib import Path
20 from posix import WIFSIGNALED
21 import shlex
22 from shlex import quote
23 import signal
24
25 # CODACY ISSUE:
26 # Consider possible security implications associated with Popen module.
27 # REASON IGNORED:
28 # Subprocess is needed, but we use it with security in mind.
29 from subprocess import (
30 DEVNULL,
31 PIPE,
32 Popen,
33 )
34 import sys
35 from time import (
36 sleep,
37 time,
38 )
39 from typing import (
40 Any,
41 Dict,
42 List,
43 Literal,
44 Optional,
45 Tuple,
46 Union,
47 overload,
48 )
49
50 from cylc.flow import (
51 LOG,
52 __version__ as CYLC_VERSION,
53 )
54 import cylc.flow.flags
55 from cylc.flow.log_level import verbosity_to_opts
56 from cylc.flow.platforms import (
57 get_host_from_platform,
58 get_platform,
59 )
60 from cylc.flow.util import format_cmd
61
62
63 def get_proc_ancestors():
64 """Return list of parent PIDs back to init."""
65 pid = os.getpid()
66 ancestors = []
67 while True:
68 p = Popen( # nosec
69 ["ps", "-p", str(pid), "-oppid="],
70 stdout=PIPE,
71 stderr=PIPE,
72 text=True
73 )
74 # * there is no untrusted output
75 ppid = p.communicate()[0].strip()
76 if not ppid:
77 return ancestors
78 ancestors.append(ppid)
79 pid = ppid
80
81
82 def watch_and_kill(proc):
83 """Kill proc if my PPID (etc.) changed - e.g. ssh connection dropped."""
84 gpa = get_proc_ancestors()
85 ps_interval = 60 # secs
86 last_ps_time = time()
87 while True:
88 if proc.poll() is not None:
89 break
90 if time() - last_ps_time > ps_interval:
91 # Run ps command
92 if get_proc_ancestors() != gpa:
93 sleep(1)
94 os.kill(proc.pid, signal.SIGTERM)
95 break
96 last_ps_time = time()
97 sleep(1)
98
99
100 def run_cmd(
101 command,
102 stdin=None,
103 stdin_str=None,
104 capture_process=False,
105 capture_status=False,
106 manage=False,
107 text=True,
108 ):
109 """Run a given cylc command on another host.
110
111 Arguments:
112 command (list):
113 command inclusive of all opts and args required to run via ssh.
114 stdin (file):
115 If specified, it should be a readable file object.
116 If None, DEVNULL is set if output is to be captured.
117 stdin_str (str):
118 A string to be passed to stdin.
119 Implies `stdin=PIPE`.
120 capture_process (boolean):
121 If True, set stdout=PIPE and return the Popen object.
122 capture_status (boolean):
123 If True, and the remote command is unsuccessful, return the
124 associated exit code instead of exiting with an error.
125 manage (boolean):
126 If True, watch ancestor processes and kill command if they change
127 (e.g. kill tail-follow commands when parent ssh connection dies).
128 text (boolean):
129 If True, use string mode instead of bytes for communicating
130 with subprocess.
131
132 Return:
133 * If capture_process=True: the Popen[str|bytes] object if created
134 successfully.
135 * Else if capture_status=True: the remote command exit code.
136 * Else if the remote command is executed successfully: 0.
137 * Else exits with an error message instead of returning.
138
139 Exits with code 1 in the event of certain command errors.
140
141 """
142 # CODACY ISSUE:
143 # subprocess call - check for execution of untrusted input.
144 # REASON IGNORED:
145 # The command is read from the site/user global config file, but we check
146 # above that it ends in 'cylc', and in any case the user could execute
147 # any such command directly via ssh.
148 stdout = None
149 stderr = None
150 if capture_process:
151 stdout = PIPE
152 stderr = PIPE
153 if stdin is None:
154 stdin = DEVNULL
155 if stdin_str:
156 read, write = os.pipe()
157 os.write(write, stdin_str.encode())
158 os.close(write)
159 stdin = read
160
161 try:
162 LOG.debug(f'running command:\n$ {format_cmd(command)}')
163 proc = Popen( # nosec
164 command,
165 stdin=stdin,
166 stdout=stdout,
167 stderr=stderr,
168 text=text
169 )
170 # * this see CODACY ISSUE comment above
171 except OSError as exc:
172 sys.exit(r'ERROR: %s: %s' % (
173 exc, ' '.join(quote(item) for item in command)))
174
175 if capture_process:
176 return proc
177 if manage:
178 watch_and_kill(proc)
179 res = proc.wait()
180 if WIFSIGNALED(res):
181 sys.exit(
182 r'ERROR: command terminated by signal %d: %s'
183 % (res, ' '.join(quote(item) for item in command))
184 )
185 if capture_status or not res:
186 return res
187 sys.exit(
188 r'ERROR: command returns %d: %s'
189 % (res, ' '.join(quote(item) for item in command))
190 )
191
192
193 def get_includes_to_rsync(rsync_includes=None):
194 """Returns list of configured dirs/files for remote file installation."""
195
196 configured_includes = []
197
198 if rsync_includes is not None:
199 for include in rsync_includes:
200 if include.endswith("/"): # item is a directory
201 configured_includes.append("/" + include + "***")
202 else: # item is a file
203 configured_includes.append("/" + include)
204
205 return configured_includes
206
207
208 DEFAULT_RSYNC_OPTS = [
209 '-a',
210 '--checksum',
211 '--out-format=%o %n%L',
212 '--no-t'
213 ]
214 # %o: the operation (send or del.)
215 # %n: filename
216 # %L: "-> symlink_target" if applicable
217
218 DEFAULT_INCLUDES = [
219 '/ana/***', # Rose ana analysis modules
220 '/app/***', # Rose applications
221 '/bin/***', # Cylc bin directory (added to PATH)
222 '/etc/***', # Miscellaneous resources
223 '/lib/***', # Cylc lib directory (lib/python added to PYTHONPATH for
224 # workflow config)
225 ]
226
227
228 def construct_rsync_over_ssh_cmd(
229 src_path: str, dst_path: str, platform: Dict[str, Any],
230 rsync_includes=None, bad_hosts=None
231 ) -> Tuple[List[str], str]:
232 """Constructs the rsync command used for remote file installation.
233
234 Includes as standard the directories: app, bin, etc, lib; and the server
235 key, used for ZMQ authentication.
236
237 Args:
238 src_path: source path
239 dst_path: path of target
240 platform: contains info relating to platform
241 rsync_includes: files and directories to be included in the rsync
242
243 Raises:
244 NoHostsError:
245 If there are no hosts available for the requested platform.
246
247 Developer Warning:
248 The Cylc Subprocess Pool method ``rsync_255_fail`` relies on
249 ``rsync_cmd[0] == 'rsync'``. Please check that changes to this function
250 do not break ``rsync_255_fail``.
251 """
252 dst_path = dst_path.replace('$HOME/', '')
253 dst_host = get_host_from_platform(platform, bad_hosts=bad_hosts)
254 ssh_cmd = platform['ssh command']
255 command = platform['rsync command']
256 rsync_cmd = shlex.split(command)
257 rsync_options = [
258 "--delete",
259 "--rsh=" + ssh_cmd,
260 "--include=/.service/",
261 "--include=/.service/server.key"
262 ] + DEFAULT_RSYNC_OPTS
263 # Note to future devs - be wary of changing the order of the following
264 # rsync options, rsync is very particular about order of in/ex-cludes.
265 rsync_cmd.extend(rsync_options)
266 for exclude in ['/log', '/share', '/work']:
267 rsync_cmd.append(f"--exclude={exclude}")
268 for include in DEFAULT_INCLUDES:
269 rsync_cmd.append(f"--include={include}")
270 for include in get_includes_to_rsync(rsync_includes):
271 rsync_cmd.append(f"--include={include}")
272 # The following excludes are required in case these are added to the
273 rsync_cmd.append("--exclude=*") # exclude everything else
274 rsync_cmd.append(f"{src_path}/")
275 rsync_cmd.append(f"{dst_host}:{dst_path}/")
276 return rsync_cmd, dst_host
277
278
279 def construct_ssh_cmd(
280 raw_cmd,
281 platform,
282 host,
283 forward_x11=False,
284 stdin=False,
285 set_UTC=False,
286 set_verbosity=False,
287 timeout=None,
288 ):
289 """Build an SSH command for execution on a remote platform hosts.
290
291 Arguments:
292 raw_cmd (list):
293 primitive command to run remotely.
294 platform (dict):
295 The Cylc job "platform" to run the command on. This is used
296 to determine the settings used e.g. "ssh command".
297 host (string):
298 remote host name. Use 'localhost' if not specified.
299 forward_x11 (boolean):
300 If True, use 'ssh -Y' to enable X11 forwarding, else just 'ssh'.
301 stdin:
302 If None, the `-n` option will be added to the SSH command line.
303 set_UTC (boolean):
304 If True, check UTC mode and specify if set to True (non-default).
305 set_verbosity (boolean):
306 If True apply -q, -v opts to match cylc.flow.flags.verbosity.
307 timeout (str):
308 String for bash timeout command.
309
310 Returns:
311 list - A list containing a chosen command including all arguments and
312 options necessary to directly execute the bare command on a given host
313 via ssh.
314
315 """
316 command = shlex.split(platform['ssh command'])
317
318 if forward_x11:
319 command.append('-Y')
320 if stdin is None:
321 command.append('-n')
322
323 command.append(host)
324
325 # Pass CYLC_VERSION and optionally, CYLC_CONF_PATH & CYLC_UTC through.
326 command += ['env', quote(r'CYLC_VERSION=%s' % CYLC_VERSION)]
327
328 for envvar in [
329 'CYLC_CONF_PATH',
330 'CYLC_COVERAGE',
331 'CLIENT_COMMS_METH',
332 'CYLC_ENV_NAME',
333 *platform['ssh forward environment variables'],
334 ]:
335 if envvar in os.environ:
336 command.append(
337 quote(f'{envvar}={os.environ[envvar]}')
338 )
339
340 if set_UTC and os.getenv('CYLC_UTC') in ["True", "true"]:
341 command.append(quote(r'CYLC_UTC=True'))
342 command.append(quote(r'TZ=UTC'))
343
344 # Use bash -l?
345 ssh_login_shell = platform['use login shell']
346 if ssh_login_shell:
347 # A login shell will always source /etc/profile and the user's bash
348 # profile file. To avoid having to quote the entire remote command
349 # it is passed as arguments to the bash script.
350 command += ['bash', '--login', '-c', quote(r'exec "$0" "$@"')]
351
352 if timeout:
353 command += ['timeout', timeout]
354
355 # 'cylc' on the remote host
356 remote_cylc_path = platform['cylc path']
357 if remote_cylc_path:
358 cylc_cmd = str(Path(remote_cylc_path) / 'cylc')
359 else:
360 cylc_cmd = 'cylc'
361 command.append(cylc_cmd)
362
363 # Insert core raw command after ssh, but before its own, command options.
364 command += raw_cmd
365
366 if set_verbosity:
367 command.extend(verbosity_to_opts(cylc.flow.flags.verbosity))
368
369 return command
370
371
372 def construct_cylc_server_ssh_cmd(
373 cmd,
374 host,
375 **kwargs,
376 ):
377 """Convenience function to building SSH commands for remote Cylc servers.
378
379 Build an SSH command that connects to the specified host using the
380 localhost platform config.
381
382 * To run commands on job platforms use construct_ssh_cmd.
383 * Use this interface to connect to:
384 * Cylc servers (i.e. `[scheduler][run hosts]available`).
385 * The host `cylc play` was run on, use this interface.
386
387 This assumes the host you are connecting to shares the $HOME filesystem
388 with the localhost platform.
389
390 For arguments and returns see construct_ssh_cmd.
391 """
392 return construct_ssh_cmd(
393 cmd,
394 get_platform(), # use localhost settings
395 host,
396 **kwargs,
397 )
398
399
400 def remote_cylc_cmd(
401 cmd,
402 platform,
403 bad_hosts=None,
404 host=None,
405 stdin=None,
406 stdin_str=None,
407 ssh_login_shell=None,
408 ssh_cmd=None,
409 remote_cylc_path=None,
410 capture_process=False,
411 manage=False,
412 text=True,
413 ):
414 """Execute a Cylc command on a remote platform.
415
416 Uses the provided platform configuration to construct the command.
417
418 For arguments and returns see construct_ssh_cmd and run_cmd.
419
420 Raises:
421 NoHostsError: If the platform is not contactable.
422
423 Exits with code 1 in the event of certain command errors.
424
425 """
426 if not host:
427 # no host selected => perform host selection from platform config
428 host = get_host_from_platform(platform, bad_hosts=bad_hosts)
429
430 return run_cmd(
431 construct_ssh_cmd(
432 cmd,
433 platform,
434 host=host,
435 stdin=True if stdin_str else stdin,
436 ),
437 stdin=stdin,
438 stdin_str=stdin_str,
439 capture_process=capture_process,
440 capture_status=True,
441 manage=manage,
442 text=text
443 )
444
445
446 @overload
447 def cylc_server_cmd(
448 cmd,
449 host: Optional[str] = None,
450 *,
451 capture_process: 'Literal[False]' = False,
452 **kwargs,
453 ) -> int:
454 ...
455
456
457 @overload
458 def cylc_server_cmd(
459 cmd,
460 host: Optional[str] = None,
461 *,
462 capture_process: 'Literal[True]',
463 **kwargs,
464 ) -> Popen:
465 ...
466
467
468 @overload
469 def cylc_server_cmd(
470 cmd,
471 host: Optional[str] = None,
472 *,
473 capture_process: bool,
474 **kwargs,
475 ) -> Union[int, Popen]:
476 ...
477
478
479 def cylc_server_cmd(
480 cmd,
481 host: Optional[str] = None,
482 *,
483 capture_process: bool = False,
484 **kwargs,
485 ) -> Union[int, Popen]:
486 """Convenience function for running commands on remote Cylc servers.
487
488 Executes a Cylc command on the specified host using localhost platform
489 config.
490
491 * To run commands on job platforms use remote_cylc_cmd.
492 * Use this interface to run commands on:
493 * Cylc servers (i.e. `[scheduler][run hosts]available`).
494 * The host `cylc play` was run on.
495
496 Runs a command via SSH using the configuration for the localhost platform.
497 This assumes the host you are connecting to shares the $HOME filesystem
498 with the localhost platform.
499
500 For arguments and returns see construct_ssh_cmd and run_cmd.
501
502 Raises:
503 NoHostsError: If the platform is not contactable.
504
505 Exits with code 1 in the event of certain command errors.
506
507 """
508 return remote_cylc_cmd(
509 cmd,
510 get_platform(), # use localhost settings
511 host=host,
512 capture_process=capture_process,
513 **kwargs,
514 )