2
0

nghttpx.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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, name: str):
  39. self.env = env
  40. self._name = name
  41. self._port = port
  42. self._cmd = env.nghttpx
  43. self._run_dir = os.path.join(env.gen_dir, name)
  44. self._pid_file = os.path.join(self._run_dir, 'nghttpx.pid')
  45. self._conf_file = os.path.join(self._run_dir, 'nghttpx.conf')
  46. self._error_log = os.path.join(self._run_dir, 'nghttpx.log')
  47. self._stderr = os.path.join(self._run_dir, 'nghttpx.stderr')
  48. self._tmp_dir = os.path.join(self._run_dir, 'tmp')
  49. self._process = None
  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. def exists(self):
  56. return os.path.exists(self._cmd)
  57. def clear_logs(self):
  58. self._rmf(self._error_log)
  59. self._rmf(self._stderr)
  60. def is_running(self):
  61. if self._process:
  62. self._process.poll()
  63. return self._process.returncode is None
  64. return False
  65. def start_if_needed(self):
  66. if not self.is_running():
  67. return self.start()
  68. return True
  69. def start(self, wait_live=True):
  70. pass
  71. def stop_if_running(self):
  72. if self.is_running():
  73. return self.stop()
  74. return True
  75. def stop(self, wait_dead=True):
  76. self._mkpath(self._tmp_dir)
  77. if self._process:
  78. self._process.terminate()
  79. self._process.wait(timeout=2)
  80. self._process = None
  81. return not wait_dead or self.wait_dead(timeout=timedelta(seconds=5))
  82. return True
  83. def restart(self):
  84. self.stop()
  85. return self.start()
  86. def reload(self, timeout: timedelta):
  87. if self._process:
  88. running = self._process
  89. self._process = None
  90. os.kill(running.pid, signal.SIGQUIT)
  91. end_wait = datetime.now() + timeout
  92. if not self.start(wait_live=False):
  93. self._process = running
  94. return False
  95. while datetime.now() < end_wait:
  96. try:
  97. log.debug(f'waiting for nghttpx({running.pid}) to exit.')
  98. running.wait(2)
  99. log.debug(f'nghttpx({running.pid}) terminated -> {running.returncode}')
  100. break
  101. except subprocess.TimeoutExpired:
  102. log.warning(f'nghttpx({running.pid}), not shut down yet.')
  103. os.kill(running.pid, signal.SIGQUIT)
  104. if datetime.now() >= end_wait:
  105. log.error(f'nghttpx({running.pid}), terminate forcefully.')
  106. os.kill(running.pid, signal.SIGKILL)
  107. running.terminate()
  108. running.wait(1)
  109. return self.wait_live(timeout=timedelta(seconds=5))
  110. return False
  111. def wait_dead(self, timeout: timedelta):
  112. curl = CurlClient(env=self.env, run_dir=self._tmp_dir)
  113. try_until = datetime.now() + timeout
  114. while datetime.now() < try_until:
  115. check_url = f'https://{self.env.domain1}:{self._port}/'
  116. r = curl.http_get(url=check_url, extra_args=[
  117. '--http3-only', '--connect-timeout', '1'
  118. ])
  119. if r.exit_code != 0:
  120. return True
  121. log.debug(f'waiting for nghttpx to stop responding: {r}')
  122. time.sleep(.1)
  123. log.debug(f"Server still responding after {timeout}")
  124. return False
  125. def wait_live(self, timeout: timedelta):
  126. curl = CurlClient(env=self.env, run_dir=self._tmp_dir)
  127. try_until = datetime.now() + timeout
  128. while datetime.now() < try_until:
  129. check_url = f'https://{self.env.domain1}:{self._port}/'
  130. r = curl.http_get(url=check_url, extra_args=[
  131. '--http3-only', '--trace', 'curl.trace', '--trace-time',
  132. '--connect-timeout', '1'
  133. ])
  134. if r.exit_code == 0:
  135. return True
  136. log.debug(f'waiting for nghttpx to become responsive: {r}')
  137. time.sleep(.1)
  138. log.error(f"Server still not responding after {timeout}")
  139. return False
  140. def _rmf(self, path):
  141. if os.path.exists(path):
  142. return os.remove(path)
  143. def _mkpath(self, path):
  144. if not os.path.exists(path):
  145. return os.makedirs(path)
  146. def _write_config(self):
  147. with open(self._conf_file, 'w') as fd:
  148. fd.write(f'# nghttpx test config'),
  149. fd.write("\n".join([
  150. '# do we need something here?'
  151. ]))
  152. class NghttpxQuic(Nghttpx):
  153. def __init__(self, env: Env):
  154. super().__init__(env=env, name='nghttpx-quic', port=env.h3_port)
  155. def start(self, wait_live=True):
  156. self._mkpath(self._tmp_dir)
  157. if self._process:
  158. self.stop()
  159. args = [
  160. self._cmd,
  161. f'--frontend=*,{self.env.h3_port};quic',
  162. f'--backend=127.0.0.1,{self.env.https_port};{self.env.domain1};sni={self.env.domain1};proto=h2;tls',
  163. f'--backend=127.0.0.1,{self.env.http_port}',
  164. f'--log-level=INFO',
  165. f'--pid-file={self._pid_file}',
  166. f'--errorlog-file={self._error_log}',
  167. f'--conf={self._conf_file}',
  168. f'--cacert={self.env.ca.cert_file}',
  169. self.env.get_credentials(self.env.domain1).pkey_file,
  170. self.env.get_credentials(self.env.domain1).cert_file,
  171. f'--frontend-http3-window-size=1M',
  172. f'--frontend-http3-max-window-size=10M',
  173. f'--frontend-http3-connection-window-size=10M',
  174. f'--frontend-http3-max-connection-window-size=100M',
  175. # f'--frontend-quic-debug-log',
  176. ]
  177. ngerr = open(self._stderr, 'a')
  178. self._process = subprocess.Popen(args=args, stderr=ngerr)
  179. if self._process.returncode is not None:
  180. return False
  181. return not wait_live or self.wait_live(timeout=timedelta(seconds=5))
  182. class NghttpxFwd(Nghttpx):
  183. def __init__(self, env: Env):
  184. super().__init__(env=env, name='nghttpx-fwd', port=env.h2proxys_port)
  185. def start(self, wait_live=True):
  186. self._mkpath(self._tmp_dir)
  187. if self._process:
  188. self.stop()
  189. args = [
  190. self._cmd,
  191. f'--http2-proxy',
  192. f'--frontend=*,{self.env.h2proxys_port}',
  193. f'--backend=127.0.0.1,{self.env.proxy_port}',
  194. f'--log-level=INFO',
  195. f'--pid-file={self._pid_file}',
  196. f'--errorlog-file={self._error_log}',
  197. f'--conf={self._conf_file}',
  198. f'--cacert={self.env.ca.cert_file}',
  199. self.env.get_credentials(self.env.proxy_domain).pkey_file,
  200. self.env.get_credentials(self.env.proxy_domain).cert_file,
  201. ]
  202. ngerr = open(self._stderr, 'a')
  203. self._process = subprocess.Popen(args=args, stderr=ngerr)
  204. if self._process.returncode is not None:
  205. return False
  206. return not wait_live or self.wait_live(timeout=timedelta(seconds=5))
  207. def wait_dead(self, timeout: timedelta):
  208. curl = CurlClient(env=self.env, run_dir=self._tmp_dir)
  209. try_until = datetime.now() + timeout
  210. while datetime.now() < try_until:
  211. check_url = f'https://{self.env.proxy_domain}:{self.env.h2proxys_port}/'
  212. r = curl.http_get(url=check_url)
  213. if r.exit_code != 0:
  214. return True
  215. log.debug(f'waiting for nghttpx-fwd to stop responding: {r}')
  216. time.sleep(.1)
  217. log.debug(f"Server still responding after {timeout}")
  218. return False
  219. def wait_live(self, timeout: timedelta):
  220. curl = CurlClient(env=self.env, run_dir=self._tmp_dir)
  221. try_until = datetime.now() + timeout
  222. while datetime.now() < try_until:
  223. check_url = f'https://{self.env.proxy_domain}:{self.env.h2proxys_port}/'
  224. r = curl.http_get(url=check_url, extra_args=[
  225. '--trace', 'curl.trace', '--trace-time'
  226. ])
  227. if r.exit_code == 0:
  228. return True
  229. log.debug(f'waiting for nghttpx-fwd to become responsive: {r}')
  230. time.sleep(.1)
  231. log.error(f"Server still not responding after {timeout}")
  232. return False