Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
1# SPDX-License-Identifier: GPL-2.0
2
3import json as _json
4import os
5import re
6import select
7import socket
8import subprocess
9import time
10
11
12class CmdExitFailure(Exception):
13 def __init__(self, msg, cmd_obj):
14 super().__init__(msg)
15 self.cmd = cmd_obj
16
17
18def fd_read_timeout(fd, timeout):
19 rlist, _, _ = select.select([fd], [], [], timeout)
20 if rlist:
21 return os.read(fd, 1024)
22 raise TimeoutError("Timeout waiting for fd read")
23
24
25class cmd:
26 """
27 Execute a command on local or remote host.
28
29 @shell defaults to false, and class will try to split @comm into a list
30 if it's a string with spaces.
31
32 Use bkg() instead to run a command in the background.
33 """
34 def __init__(self, comm, shell=None, fail=True, ns=None, background=False,
35 host=None, timeout=5, ksft_wait=None):
36 if ns:
37 comm = f'ip netns exec {ns} ' + comm
38
39 self.stdout = None
40 self.stderr = None
41 self.ret = None
42 self.ksft_term_fd = None
43
44 self.comm = comm
45 if host:
46 self.proc = host.cmd(comm)
47 else:
48 # If user doesn't explicitly request shell try to avoid it.
49 if shell is None and isinstance(comm, str) and ' ' in comm:
50 comm = comm.split()
51
52 # ksft_wait lets us wait for the background process to fully start,
53 # we pass an FD to the child process, and wait for it to write back.
54 # Similarly term_fd tells child it's time to exit.
55 pass_fds = ()
56 env = os.environ.copy()
57 if ksft_wait is not None:
58 rfd, ready_fd = os.pipe()
59 wait_fd, self.ksft_term_fd = os.pipe()
60 pass_fds = (ready_fd, wait_fd, )
61 env["KSFT_READY_FD"] = str(ready_fd)
62 env["KSFT_WAIT_FD"] = str(wait_fd)
63
64 self.proc = subprocess.Popen(comm, shell=shell, stdout=subprocess.PIPE,
65 stderr=subprocess.PIPE, pass_fds=pass_fds,
66 env=env)
67 if ksft_wait is not None:
68 os.close(ready_fd)
69 os.close(wait_fd)
70 msg = fd_read_timeout(rfd, ksft_wait)
71 os.close(rfd)
72 if not msg:
73 raise Exception("Did not receive ready message")
74 if not background:
75 self.process(terminate=False, fail=fail, timeout=timeout)
76
77 def process(self, terminate=True, fail=None, timeout=5):
78 if fail is None:
79 fail = not terminate
80
81 if self.ksft_term_fd:
82 os.write(self.ksft_term_fd, b"1")
83 if terminate:
84 self.proc.terminate()
85 stdout, stderr = self.proc.communicate(timeout)
86 self.stdout = stdout.decode("utf-8")
87 self.stderr = stderr.decode("utf-8")
88 self.proc.stdout.close()
89 self.proc.stderr.close()
90 self.ret = self.proc.returncode
91
92 if self.proc.returncode != 0 and fail:
93 if len(stderr) > 0 and stderr[-1] == "\n":
94 stderr = stderr[:-1]
95 raise CmdExitFailure("Command failed: %s\nSTDOUT: %s\nSTDERR: %s" %
96 (self.proc.args, stdout, stderr), self)
97
98
99class bkg(cmd):
100 """
101 Run a command in the background.
102
103 Examples usage:
104
105 Run a command on remote host, and wait for it to finish.
106 This is usually paired with wait_port_listen() to make sure
107 the command has initialized:
108
109 with bkg("socat ...", exit_wait=True, host=cfg.remote) as nc:
110 ...
111
112 Run a command and expect it to let us know that it's ready
113 by writing to a special file descriptor passed via KSFT_READY_FD.
114 Command will be terminated when we exit the context manager:
115
116 with bkg("my_binary", ksft_wait=5):
117 """
118 def __init__(self, comm, shell=None, fail=None, ns=None, host=None,
119 exit_wait=False, ksft_wait=None):
120 super().__init__(comm, background=True,
121 shell=shell, fail=fail, ns=ns, host=host,
122 ksft_wait=ksft_wait)
123 self.terminate = not exit_wait and not ksft_wait
124 self._exit_wait = exit_wait
125 self.check_fail = fail
126
127 if shell and self.terminate:
128 print("# Warning: combining shell and terminate is risky!")
129 print("# SIGTERM may not reach the child on zsh/ksh!")
130
131 def __enter__(self):
132 return self
133
134 def __exit__(self, ex_type, ex_value, ex_tb):
135 # Force termination on exception
136 terminate = self.terminate or (self._exit_wait and ex_type)
137 return self.process(terminate=terminate, fail=self.check_fail)
138
139
140global_defer_queue = []
141
142
143class defer:
144 def __init__(self, func, *args, **kwargs):
145 if not callable(func):
146 raise Exception("defer created with un-callable object, did you call the function instead of passing its name?")
147
148 self.func = func
149 self.args = args
150 self.kwargs = kwargs
151
152 self._queue = global_defer_queue
153 self._queue.append(self)
154
155 def __enter__(self):
156 return self
157
158 def __exit__(self, ex_type, ex_value, ex_tb):
159 return self.exec()
160
161 def exec_only(self):
162 self.func(*self.args, **self.kwargs)
163
164 def cancel(self):
165 self._queue.remove(self)
166
167 def exec(self):
168 self.cancel()
169 self.exec_only()
170
171
172def tool(name, args, json=None, ns=None, host=None):
173 cmd_str = name + ' '
174 if json:
175 cmd_str += '--json '
176 cmd_str += args
177 cmd_obj = cmd(cmd_str, ns=ns, host=host)
178 if json:
179 return _json.loads(cmd_obj.stdout)
180 return cmd_obj
181
182
183def bpftool(args, json=None, ns=None, host=None):
184 return tool('bpftool', args, json=json, ns=ns, host=host)
185
186
187def ip(args, json=None, ns=None, host=None):
188 if ns:
189 args = f'-netns {ns} ' + args
190 return tool('ip', args, json=json, host=host)
191
192
193def ethtool(args, json=None, ns=None, host=None):
194 return tool('ethtool', args, json=json, ns=ns, host=host)
195
196
197def bpftrace(expr, json=None, ns=None, host=None, timeout=None):
198 """
199 Run bpftrace and return map data (if json=True).
200 The output of bpftrace is inconvenient, so the helper converts
201 to a dict indexed by map name, e.g.:
202 {
203 "@": { ... },
204 "@map2": { ... },
205 }
206 """
207 cmd_arr = ['bpftrace']
208 # Throw in --quiet if json, otherwise the output has two objects
209 if json:
210 cmd_arr += ['-f', 'json', '-q']
211 if timeout:
212 expr += ' interval:s:' + str(timeout) + ' { exit(); }'
213 cmd_arr += ['-e', expr]
214 cmd_obj = cmd(cmd_arr, ns=ns, host=host, shell=False)
215 if json:
216 # bpftrace prints objects as lines
217 ret = {}
218 for l in cmd_obj.stdout.split('\n'):
219 if not l.strip():
220 continue
221 one = _json.loads(l)
222 if one.get('type') != 'map':
223 continue
224 for k, v in one["data"].items():
225 if k.startswith('@'):
226 k = k.lstrip('@')
227 ret[k] = v
228 return ret
229 return cmd_obj
230
231
232def rand_port(stype=socket.SOCK_STREAM):
233 """
234 Get a random unprivileged port.
235 """
236 with socket.socket(socket.AF_INET6, stype) as s:
237 s.bind(("", 0))
238 return s.getsockname()[1]
239
240
241def wait_port_listen(port, proto="tcp", ns=None, host=None, sleep=0.005, deadline=5):
242 end = time.monotonic() + deadline
243
244 pattern = f":{port:04X} .* "
245 if proto == "tcp": # for tcp protocol additionally check the socket state
246 pattern += "0A"
247 pattern = re.compile(pattern)
248
249 while True:
250 data = cmd(f'cat /proc/net/{proto}*', ns=ns, host=host, shell=True).stdout
251 for row in data.split("\n"):
252 if pattern.search(row):
253 return
254 if time.monotonic() > end:
255 raise Exception("Waiting for port listen timed out")
256 time.sleep(sleep)
257
258
259def wait_file(fname, test_fn, sleep=0.005, deadline=5, encoding='utf-8'):
260 """
261 Wait for file contents on the local system to satisfy a condition.
262 test_fn() should take one argument (file contents) and return whether
263 condition is met.
264 """
265 end = time.monotonic() + deadline
266
267 with open(fname, "r", encoding=encoding) as fp:
268 while True:
269 if test_fn(fp.read()):
270 break
271 fp.seek(0)
272 if time.monotonic() > end:
273 raise TimeoutError("Wait for file contents failed", fname)
274 time.sleep(sleep)