nghttpx.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. #***************************************************************************
  4. # _ _ ____ _
  5. # Project ___| | | | _ \| |
  6. # / __| | | | |_) | |
  7. # | (__| |_| | _ <| |___
  8. # \___|\___/|_| \_\_____|
  9. #
  10. # Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  11. #
  12. # This software is licensed as described in the file COPYING, which
  13. # you should have received as part of this distribution. The terms
  14. # are also available at https://curl.se/docs/copyright.html.
  15. #
  16. # You may opt to use, copy, modify, merge, publish, distribute and/or sell
  17. # copies of the Software, and permit persons to whom the Software is
  18. # furnished to do so, under the terms of the COPYING file.
  19. #
  20. # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  21. # KIND, either express or implied.
  22. #
  23. # SPDX-License-Identifier: curl
  24. #
  25. ###########################################################################
  26. #
  27. import logging
  28. import os
  29. import signal
  30. import subprocess
  31. import time
  32. from typing import Optional
  33. from datetime import datetime, timedelta
  34. from .env import Env
  35. from .curl import CurlClient
  36. log = logging.getLogger(__name__)
  37. class Nghttpx:
  38. def __init__(self, env: Env, port: int, https_port: int, name: str):
  39. self.env = env
  40. self._name = name
  41. self._port = port
  42. self._https_port = https_port
  43. self._cmd = env.nghttpx
  44. self._run_dir = os.path.join(env.gen_dir, name)
  45. self._pid_file = os.path.join(self._run_dir, 'nghttpx.pid')
  46. self._conf_file = os.path.join(self._run_dir, 'nghttpx.conf')
  47. self._error_log = os.path.join(self._run_dir, 'nghttpx.log')
  48. self._stderr = os.path.join(self._run_dir, 'nghttpx.stderr')
  49. self._tmp_dir = os.path.join(self._run_dir, 'tmp')
  50. self._process: Optional[subprocess.Popen] = None
  51. self._rmf(self._pid_file)
  52. self._rmf(self._error_log)
  53. self._mkpath(self._run_dir)
  54. self._write_config()
  55. @property
  56. def https_port(self):
  57. return self._https_port
  58. def exists(self):
  59. return self._cmd and os.path.exists(self._cmd)
  60. def clear_logs(self):
  61. self._rmf(self._error_log)
  62. self._rmf(self._stderr)
  63. def is_running(self):
  64. if self._process:
  65. self._process.poll()
  66. return self._process.returncode is None
  67. return False
  68. def start_if_needed(self):
  69. if not self.is_running():
  70. return self.start()
  71. return True
  72. def start(self, wait_live=True):
  73. pass
  74. def stop_if_running(self):
  75. if self.is_running():
  76. return self.stop()
  77. return True
  78. def stop(self, wait_dead=True):
  79. self._mkpath(self._tmp_dir)
  80. if self._process:
  81. self._process.terminate()
  82. self._process.wait(timeout=2)
  83. self._process = None
  84. return not wait_dead or self.wait_dead(timeout=timedelta(seconds=5))
  85. return True
  86. def restart(self):
  87. self.stop()
  88. return self.start()
  89. def reload(self, timeout: timedelta):
  90. if self._process:
  91. running = self._process
  92. self._process = None
  93. os.kill(running.pid, signal.SIGQUIT)
  94. end_wait = datetime.now() + timeout
  95. if not self.start(wait_live=False):
  96. self._process = running
  97. return False
  98. while datetime.now() < end_wait:
  99. try:
  100. log.debug(f'waiting for nghttpx({running.pid}) to exit.')
  101. running.wait(2)
  102. log.debug(f'nghttpx({running.pid}) terminated -> {running.returncode}')
  103. break
  104. except subprocess.TimeoutExpired:
  105. log.warning(f'nghttpx({running.pid}), not shut down yet.')
  106. os.kill(running.pid, signal.SIGQUIT)
  107. if datetime.now() >= end_wait:
  108. log.error(f'nghttpx({running.pid}), terminate forcefully.')
  109. os.kill(running.pid, signal.SIGKILL)
  110. running.terminate()
  111. running.wait(1)
  112. return self.wait_live(timeout=timedelta(seconds=5))
  113. return False
  114. def wait_dead(self, timeout: timedelta):
  115. curl = CurlClient(env=self.env, run_dir=self._tmp_dir)
  116. try_until = datetime.now() + timeout
  117. while datetime.now() < try_until:
  118. if self._https_port > 0:
  119. check_url = f'https://{self.env.domain1}:{self._https_port}/'
  120. r = curl.http_get(url=check_url, extra_args=[
  121. '--trace', 'curl.trace', '--trace-time',
  122. '--connect-timeout', '1'
  123. ])
  124. else:
  125. check_url = f'https://{self.env.domain1}:{self._port}/'
  126. r = curl.http_get(url=check_url, extra_args=[
  127. '--trace', 'curl.trace', '--trace-time',
  128. '--http3-only', '--connect-timeout', '1'
  129. ])
  130. if r.exit_code != 0:
  131. return True
  132. log.debug(f'waiting for nghttpx to stop responding: {r}')
  133. time.sleep(.1)
  134. log.debug(f"Server still responding after {timeout}")
  135. return False
  136. def wait_live(self, timeout: timedelta):
  137. curl = CurlClient(env=self.env, run_dir=self._tmp_dir)
  138. try_until = datetime.now() + timeout
  139. while datetime.now() < try_until:
  140. if self._https_port > 0:
  141. check_url = f'https://{self.env.domain1}:{self._https_port}/'
  142. r = curl.http_get(url=check_url, extra_args=[
  143. '--trace', 'curl.trace', '--trace-time',
  144. '--connect-timeout', '1'
  145. ])
  146. else:
  147. check_url = f'https://{self.env.domain1}:{self._port}/'
  148. r = curl.http_get(url=check_url, extra_args=[
  149. '--http3-only', '--trace', 'curl.trace', '--trace-time',
  150. '--connect-timeout', '1'
  151. ])
  152. if r.exit_code == 0:
  153. return True
  154. log.debug(f'waiting for nghttpx to become responsive: {r}')
  155. time.sleep(.1)
  156. log.error(f"Server still not responding after {timeout}")
  157. return False
  158. def _rmf(self, path):
  159. if os.path.exists(path):
  160. return os.remove(path)
  161. def _mkpath(self, path):
  162. if not os.path.exists(path):
  163. return os.makedirs(path)
  164. def _write_config(self):
  165. with open(self._conf_file, 'w') as fd:
  166. fd.write('# nghttpx test config')
  167. fd.write("\n".join([
  168. '# do we need something here?'
  169. ]))
  170. class NghttpxQuic(Nghttpx):
  171. def __init__(self, env: Env):
  172. super().__init__(env=env, name='nghttpx-quic', port=env.h3_port,
  173. https_port=env.nghttpx_https_port)
  174. def start(self, wait_live=True):
  175. self._mkpath(self._tmp_dir)
  176. if self._process:
  177. self.stop()
  178. creds = self.env.get_credentials(self.env.domain1)
  179. assert creds # convince pytype this isn't None
  180. args = [
  181. self._cmd,
  182. f'--frontend=*,{self.env.h3_port};quic',
  183. f'--frontend=*,{self.env.nghttpx_https_port};tls',
  184. f'--backend=127.0.0.1,{self.env.https_port};{self.env.domain1};sni={self.env.domain1};proto=h2;tls',
  185. f'--backend=127.0.0.1,{self.env.http_port}',
  186. '--log-level=INFO',
  187. f'--pid-file={self._pid_file}',
  188. f'--errorlog-file={self._error_log}',
  189. f'--conf={self._conf_file}',
  190. f'--cacert={self.env.ca.cert_file}',
  191. creds.pkey_file,
  192. creds.cert_file,
  193. '--frontend-http3-window-size=1M',
  194. '--frontend-http3-max-window-size=10M',
  195. '--frontend-http3-connection-window-size=10M',
  196. '--frontend-http3-max-connection-window-size=100M',
  197. # f'--frontend-quic-debug-log',
  198. ]
  199. ngerr = open(self._stderr, 'a')
  200. self._process = subprocess.Popen(args=args, stderr=ngerr)
  201. if self._process.returncode is not None:
  202. return False
  203. return not wait_live or self.wait_live(timeout=timedelta(seconds=5))
  204. class NghttpxFwd(Nghttpx):
  205. def __init__(self, env: Env):
  206. super().__init__(env=env, name='nghttpx-fwd', port=env.h2proxys_port,
  207. https_port=0)
  208. def start(self, wait_live=True):
  209. self._mkpath(self._tmp_dir)
  210. if self._process:
  211. self.stop()
  212. creds = self.env.get_credentials(self.env.proxy_domain)
  213. assert creds # convince pytype this isn't None
  214. args = [
  215. self._cmd,
  216. '--http2-proxy',
  217. f'--frontend=*,{self.env.h2proxys_port}',
  218. f'--backend=127.0.0.1,{self.env.proxy_port}',
  219. '--log-level=INFO',
  220. f'--pid-file={self._pid_file}',
  221. f'--errorlog-file={self._error_log}',
  222. f'--conf={self._conf_file}',
  223. f'--cacert={self.env.ca.cert_file}',
  224. creds.pkey_file,
  225. creds.cert_file,
  226. ]
  227. ngerr = open(self._stderr, 'a')
  228. self._process = subprocess.Popen(args=args, stderr=ngerr)
  229. if self._process.returncode is not None:
  230. return False
  231. return not wait_live or self.wait_live(timeout=timedelta(seconds=5))
  232. def wait_dead(self, timeout: timedelta):
  233. curl = CurlClient(env=self.env, run_dir=self._tmp_dir)
  234. try_until = datetime.now() + timeout
  235. while datetime.now() < try_until:
  236. check_url = f'https://{self.env.proxy_domain}:{self.env.h2proxys_port}/'
  237. r = curl.http_get(url=check_url)
  238. if r.exit_code != 0:
  239. return True
  240. log.debug(f'waiting for nghttpx-fwd to stop responding: {r}')
  241. time.sleep(.1)
  242. log.debug(f"Server still responding after {timeout}")
  243. return False
  244. def wait_live(self, timeout: timedelta):
  245. curl = CurlClient(env=self.env, run_dir=self._tmp_dir)
  246. try_until = datetime.now() + timeout
  247. while datetime.now() < try_until:
  248. check_url = f'https://{self.env.proxy_domain}:{self.env.h2proxys_port}/'
  249. r = curl.http_get(url=check_url, extra_args=[
  250. '--trace', 'curl.trace', '--trace-time'
  251. ])
  252. if r.exit_code == 0:
  253. return True
  254. log.debug(f'waiting for nghttpx-fwd to become responsive: {r}')
  255. time.sleep(.1)
  256. log.error(f"Server still not responding after {timeout}")
  257. return False