utils.py 9.4 KB

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