Debian Codegraph @

lib/ansible/utils/cmd_functions.py

raw
1 # (c) 2012, Michael DeHaan <[email protected]>
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import annotations
19
20 import os
21 import select
22 import shlex
23 import subprocess
24 import sys
25
26 from ansible.module_utils.common.text.converters import to_bytes
27 from ansible.utils.display import Display
28 from ansible.utils.sentinel import Sentinel
29
30 display = Display()
31
32
33 def run_cmd(cmd, live=Sentinel, readsize=10):
34 if live is Sentinel:
35 live = False
36 else:
37 display.deprecated(
38 msg=(
39 "The 'live' argument of run_cmd is deprecated because it writes the "
40 "subprocess output directly to stdout/stderr, bypassing the built-in "
41 "secret masking that is applied to the captured output."
42 ),
43 version="2.25",
44 help_text=(
45 "If you need to stream the subprocess output live, run the subprocess "
46 "yourself (e.g. with subprocess.Popen) so it writes directly to the "
47 "current stdout/stderr. You are then responsible for masking any secrets "
48 "in that output, as this is not handled for you."
49 ),
50 )
51
52 cmdargs = shlex.split(cmd)
53
54 # subprocess should be passed byte strings.
55 cmdargs = [to_bytes(a, errors='surrogate_or_strict') for a in cmdargs]
56
57 p = subprocess.Popen(cmdargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
58
59 stdout = b''
60 stderr = b''
61 rpipes = [p.stdout, p.stderr]
62 while True:
63 rfd, wfd, efd = select.select(rpipes, [], rpipes, 1)
64
65 if p.stdout in rfd:
66 dat = os.read(p.stdout.fileno(), readsize)
67 if live:
68 sys.stdout.buffer.write(dat)
69 stdout += dat
70 if dat == b'':
71 rpipes.remove(p.stdout)
72 if p.stderr in rfd:
73 dat = os.read(p.stderr.fileno(), readsize)
74 stderr += dat
75 if live:
76 sys.stdout.buffer.write(dat)
77 if dat == b'':
78 rpipes.remove(p.stderr)
79 # only break out if we've emptied the pipes, or there is nothing to
80 # read from and the process has finished.
81 if (not rpipes or not rfd) and p.poll() is not None:
82 break
83 # Calling wait while there are still pipes to read can cause a lock
84 elif not rpipes and p.poll() is None:
85 p.wait()
86
87 return p.returncode, stdout, stderr