Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienos.com/blob/main/scripts/agora_activation_namespace.py # aienos.com Source of www.aienos.com, served from my own hardware Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienos.com / scripts / agora_activation_namespace.py` 556 lines ยท 25676 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Owned, disposable network/systemd infrastructure for the activation oracle. 3 4 This is verification infrastructure, not an alternate registration implementation. 5 Only the copied native backend answers API requests. Call setup/rollback/cleanup 6 under root; rollback deliberately retains all profile state until cleanup. 7 """ 8 9 import argparse 10 import ctypes 11 import ipaddress 12 import os 13 from pathlib import Path 14 import pwd 15 import grp 16 import selectors 17 import shutil 18 import socket 19 import sys 20 import threading 21 import time 22 import uuid 23 24 25 REPOSITORY = Path(__file__).resolve().parents[1] 26 27 28 class Fixture: 29 """A single owner of a namespace, backend unit, nginx and fixed tunnels. 30 31 root is the caller's scratch/evidence directory, not the repository. The 32 callback runs argv without a shell and returns CompletedProcess with bytes. 33 setup returns observations/configuration, never an acceptance verdict. 34 """ 35 36 def __init__(self, root: Path, backend: Path, nginx: Path, run, page: Path, client: Path): 37 self.root = Path(root).resolve() 38 self.backend = Path(backend).resolve() 39 self.nginx = Path(nginx).resolve() 40 self.page = Path(page).resolve() 41 self.client = Path(client).resolve() 42 self.run = run 43 self.ident = uuid.uuid4().hex 44 self.name = 'aien-agora-oracle-' + self.ident 45 self.namespace = self.name 46 self.unit = self.name + '.service' 47 # /run is noexec on Spark; only this uniquely owned fixture directory 48 # lives on the executable root filesystem. Never use /opt/aien/bin. 49 self.runtime = Path('/opt') / self.name 50 self.state = Path('/var/lib') / self.name 51 self.unit_path = Path('/run/systemd/system') / self.unit 52 self.dropin_dir = self.unit_path.with_name(self.unit + '.d') 53 self.dropin = self.dropin_dir / 'policy.conf' 54 self.config = {} 55 self._namespace_created = False 56 self._runtime_created = False 57 self._state_created = False 58 self._unit_created = False 59 self._runtime_enabled = False 60 self._state_retained = False 61 self._routing_units = [] 62 self._ports = [] 63 self._setup = False 64 self._closed = False 65 66 def command(self, argv): 67 """Prefix commands whose sockets/listener observations belong in netns.""" 68 return ['ip', 'netns', 'exec', self.namespace, *map(str, argv)] 69 70 def _call(self, argv, **kwargs): 71 return self.run(list(map(str, argv)), **kwargs) 72 73 def _write(self, path, text, mode=0o644): 74 path.write_text(text) 75 path.chmod(mode) 76 77 def _reserve_host_port(self): 78 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 79 sock.bind(('127.0.0.1', 0)) 80 self._ports.append(sock) 81 return sock.getsockname()[1] 82 83 def _release_port(self, port): 84 for sock in self._ports[:]: 85 if sock.getsockname()[1] == port: 86 sock.close() 87 self._ports.remove(sock) 88 89 def setup(self): 90 if self._setup or self._closed: 91 raise RuntimeError('Fixture setup is single use') 92 if os.geteuid() != 0: 93 raise PermissionError('Fixture must be hosted by the root oracle process') 94 if pwd.getpwnam('aien-agora').pw_uid != 976: 95 raise RuntimeError('Unexpected aien-agora UID') 96 if grp.getgrnam('aien-agora').gr_gid != 964: 97 raise RuntimeError('Unexpected aien-agora GID') 98 # Every mutable or executable service path is outside host /tmp, which 99 # PrivateTmp hides. No production state, env, unit or nginx file is used. 100 try: 101 self.runtime.mkdir(mode=0o755) 102 self._runtime_created = True 103 self.state.mkdir(mode=0o750) 104 self._state_created = True 105 os.chown(self.state, 976, 964) 106 executable = self.runtime / 'agora' 107 shutil.copyfile(self.backend, executable) 108 executable.chmod(0o755) 109 nginx = self.runtime / 'nginx' 110 shutil.copyfile(self.nginx, nginx) 111 nginx.chmod(0o755) 112 module = self.nginx.parent.parent / 'lib/nginx/modules/ngx_stream_module.so' 113 shutil.copyfile(module, self.runtime / module.name) 114 shutil.copyfile(Path(__file__).resolve(), self.runtime / 'tunnel.py') 115 self._provision_site() 116 self._call(['ip', 'netns', 'add', self.namespace]) 117 self._namespace_created = True 118 self._call(self.command(['ip', 'link', 'set', 'lo', 'up'])) 119 # These high ports exist only inside this fixture's isolated netns. 120 backend_port, frontend_port, tls_port, plain_port, normal_port = ( 121 28132, 28443, 28444, 28080, 28445) 122 host_tls = self._reserve_host_port() 123 host_plain = self._reserve_host_port() 124 display_argv = (f'{executable} serve --state {self.state} ' 125 f'--listen 127.0.0.1 --port {backend_port} --bits 20') 126 self._write(self.runtime / 'runtime.env', 127 'AGORA_LISTEN=127.0.0.1\n', 0o600) 128 template = (REPOSITORY / 'om/agora/deploy/aien-agora.service').read_text() 129 template = template.replace('StateDirectory=aien-agora', 130 'StateDirectory=' + self.name) 131 template = template.replace('/var/lib/aien-agora', str(self.state)) 132 template = template.replace('/etc/aien-agora/runtime.env', 133 str(self.runtime / 'runtime.env')) 134 template = template.replace( 135 '/opt/aien/bin/agora serve --state ' + str(self.state) 136 + ' --listen ${AGORA_LISTEN} --port 18132 --bits 20', display_argv) 137 template = template.replace('Restart=always', 'Restart=no') 138 template = template.replace('[Service]\n', 139 '[Service]\nNetworkNamespacePath=/run/netns/' + self.namespace + '\n') 140 if '/opt/aien/' in template or '--port 18132' in template: 141 raise RuntimeError('Backend template relocation was incomplete') 142 # Exclusive paths ensure cleanup cannot acquire another owner's unit. 143 with self.unit_path.open('x') as stream: 144 stream.write(template) 145 self._unit_created = True 146 self.dropin_dir.mkdir(mode=0o755) 147 self._write_policy(['127.0.0.1/32', '127.0.0.2/32']) 148 nginx_config = self._provision_nginx(backend_port, frontend_port, 149 tls_port, plain_port, normal_port) 150 nginx_args = [str(nginx), '-p', str(self.runtime) + '/', 151 '-c', str(nginx_config)] 152 self.config = { 153 'namespace': self.namespace, 'unit': self.unit, 154 'state': str(self.state), 'executable': str(executable), 155 'display_argv': display_argv, 156 'fragment': str(self.unit_path), 'dropin': str(self.dropin), 157 'backend_host': '127.0.0.1', 'backend_port': backend_port, 158 'allowed_source': '127.0.0.2', 'denied_source': '127.0.0.3', 159 'interface': 'lo', 'uid': 976, 'gid': 964, 160 'tls_url': f'https://www.aienos.com:{host_tls}', 161 'browser_url': f'https://www.aienos.com:{host_tls}/aienet/', 162 'plain_url': f'http://127.0.0.1:{host_plain}', 163 'browser_host': 'www.aienos.com', 'browser_address': '127.0.0.1', 164 'curl_resolve': f'www.aienos.com:{host_tls}:127.0.0.1', 165 'namespace_prefix': self.command([]), 166 'host_tls_port': host_tls, 'host_plain_port': host_plain, 167 'frontend_host': '127.0.0.1', 'frontend_port': frontend_port, 168 'proxy_tls_port': tls_port, 'plain_port': plain_port, 169 'normal_tls_port': normal_port, 170 'normal_site_host': 'normal.aienet.invalid', 171 'normal_site_path': '/normal-site-control.txt', 172 'nginx_config': str(nginx_config), 'nginx_args': nginx_args, 173 'nginx_pid_file': str(self.runtime / 'nginx.pid'), 174 'certificate': str(self.runtime / 'cert.pem'), 175 'logs': [str(self.runtime / 'access.log'), 176 str(self.runtime / 'error.log')], 177 'temp_dirs': [str(self.runtime / name) for name in 178 ('body', 'proxy', 'fastcgi', 'uwsgi', 'scgi')], 179 'runtime': str(self.runtime), 'routing_units': [], 180 'copied_artifacts': [ 181 (str(executable), str(self.backend), 0o755), 182 (str(self.runtime / 'public/aienet/index.html'), str(self.page), 0o644), 183 (str(self.runtime / 'public/js/aienet.js'), str(self.client), 0o644)], 184 } 185 self._call(['systemctl', 'daemon-reload']) 186 self.start_backend() 187 self.start_routing() 188 self._setup = True 189 return self.config 190 except BaseException: 191 self.cleanup() 192 raise 193 194 def _provision_site(self): 195 public = self.runtime / 'public' 196 public.mkdir(mode=0o755) 197 for name in ('assets', 'js', 'vendor', 'wasm'): 198 source = REPOSITORY / 'public' / name 199 if source.is_dir(): 200 shutil.copytree(source, public / name) 201 for source in (REPOSITORY / 'public').iterdir(): 202 if source.is_file() and source.suffix in ('.svg', '.ico', '.png'): 203 shutil.copyfile(source, public / source.name) 204 (public / 'aienet').mkdir() 205 shutil.copyfile(self.page, public / 'aienet/index.html') 206 shutil.copyfile(self.client, public / 'js/aienet.js') 207 self._write(public / 'normal-site-control.txt', 'activation fixture normal site\n') 208 self._write(public / 'index.html', 209 'Fixture normal site' 210 '

activation fixture normal site

\n') 211 # Readable assets are separate from root-only scratch and private state. 212 for directory, subdirs, files in os.walk(public): 213 Path(directory).chmod(0o755) 214 for name in files: 215 (Path(directory) / name).chmod(0o644) 216 self._call(['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', 217 '-keyout', self.runtime / 'key.pem', 218 '-out', self.runtime / 'cert.pem', '-days', '1', 219 '-subj', '/CN=www.aienos.com', '-addext', 220 'subjectAltName=DNS:www.aienos.com,DNS:normal.aienet.invalid']) 221 (self.runtime / 'key.pem').chmod(0o600) 222 223 def _provision_nginx(self, backend, frontend, tls, plain, normal): 224 deploy = REPOSITORY / 'om/agora/deploy' 225 upstream = self.runtime / 'upstream.conf' 226 self._write(upstream, f'server 127.0.0.1:{backend};\n') 227 http = (deploy / 'nginx-agora-http.conf').read_text().replace( 228 '/etc/nginx/snippets/agora-upstream.conf', str(upstream)) 229 routes = (deploy / 'nginx-agora.conf').read_text() 230 # Preserve the reviewed route template; outgoing socket identity is a 231 # server-level directive inherited by every nested registration route. 232 for name in ('body', 'proxy', 'fastcgi', 'uwsgi', 'scgi'): 233 path = self.runtime / name 234 path.mkdir(mode=0o700) 235 os.chown(path, 976, 964) 236 for name in ('access.log', 'error.log'): 237 self._write(self.runtime / name, '', 0o600) 238 path = self.runtime / 'nginx.conf' 239 self._write(path, f'''load_module {self.runtime}/ngx_stream_module.so; 240 user aien-agora aien-agora; 241 pid {self.runtime}/nginx.pid; 242 lock_file {self.runtime}/nginx.lock; 243 error_log {self.runtime}/error.log notice; 244 worker_processes 1; 245 events {{ worker_connections 256; }} 246 stream {{ 247 map $ssl_preread_server_name $fixture_sni {{ 248 www.aienos.com 127.0.0.1:{tls}; 249 default 127.0.0.1:{normal}; 250 }} 251 server {{ 252 listen 127.0.0.1:{frontend}; 253 ssl_preread on; 254 proxy_protocol on; 255 proxy_pass $fixture_sni; 256 }} 257 }} 258 http {{ 259 default_type application/octet-stream; 260 types {{ text/html html; text/css css; application/javascript js; 261 image/svg+xml svg; application/wasm wasm; }} 262 log_format fixture '$remote_addr $request_method $uri $status'; 263 access_log {self.runtime}/access.log fixture; 264 client_body_temp_path {self.runtime}/body; 265 proxy_temp_path {self.runtime}/proxy; 266 fastcgi_temp_path {self.runtime}/fastcgi; 267 uwsgi_temp_path {self.runtime}/uwsgi; 268 scgi_temp_path {self.runtime}/scgi; 269 ssl_certificate {self.runtime}/cert.pem; 270 ssl_certificate_key {self.runtime}/key.pem; 271 ssl_protocols TLSv1.2 TLSv1.3; 272 {http} 273 server {{ 274 listen 127.0.0.1:{tls} ssl proxy_protocol; 275 listen 127.0.0.1:{plain}; 276 server_name www.aienos.com; 277 root {self.runtime}/public; 278 index index.html; 279 proxy_bind 127.0.0.2; 280 {routes} 281 location / {{ try_files $uri $uri/ =404; }} 282 }} 283 server {{ 284 listen 127.0.0.1:{normal} ssl proxy_protocol; 285 server_name normal.aienet.invalid; 286 root {self.runtime}/public; 287 location / {{ try_files $uri =404; }} 288 }} 289 }} 290 ''') 291 baseline = path.read_text().replace(routes, ''' 292 location ^~ /agora/api/ { 293 access_log off; 294 error_log /dev/null crit; 295 add_header Cache-Control "no-store" always; 296 return 404; 297 } 298 location = /agora/api { 299 access_log off; 300 error_log /dev/null crit; 301 return 404; 302 } 303 ''').replace(http, '') 304 self._write(self.runtime / 'nginx-baseline.conf', baseline) 305 return path 306 307 def _write_policy(self, allow): 308 allowed = [] 309 permitted = {'127.0.0.1/32', '127.0.0.2/32', '127.0.0.3/32'} 310 for address in allow: 311 address = str(ipaddress.IPv4Network(address, strict=True)) 312 if address not in permitted or address in allowed: 313 raise ValueError('Only distinct fixture source host prefixes are allowed') 314 allowed.append(address) 315 self._write(self.dropin, '[Service]\nIPAddressAllow=\n' 316 + ''.join('IPAddressAllow=' + address + '\n' for address in allowed) 317 + 'IPAddressDeny=\nIPAddressDeny=any\n') 318 319 def set_policy(self, allow): 320 """Real dedicated-unit policy change; callers label control phases.""" 321 self._require_open() 322 self._write_policy(allow) 323 self._call(['systemctl', 'daemon-reload']) 324 self.restart_backend() 325 326 def _require_open(self): 327 if not self._unit_created or self._closed: 328 raise RuntimeError('Fixture unit is not provisioned') 329 330 def start_backend(self): 331 self._require_open() 332 self.config['journal_since'] = time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime()) 333 self._call(['systemctl', 'start', self.unit]) 334 self._refresh_backend_identity() 335 336 def restart_backend(self): 337 self._require_open() 338 self.config['journal_since'] = time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime()) 339 self._call(['systemctl', 'restart', self.unit]) 340 self._refresh_backend_identity() 341 342 def _refresh_backend_identity(self): 343 result = self._call(['systemctl', 'show', self.unit, '-p', 'MainPID', 344 '-p', 'ControlGroup']) 345 fields = dict(line.split('=', 1) for line in result.stdout.decode().splitlines() 346 if '=' in line) 347 pid = int(fields.get('MainPID', '0')) 348 if pid <= 0: 349 raise RuntimeError('Fixture backend has no MainPID; readiness is not proven') 350 self.config['backend_pid'] = pid 351 self.config['backend_cgroup'] = fields['ControlGroup'] 352 353 def _start_routing_unit(self, suffix, argv, namespace=False): 354 unit = self.name + '-' + suffix + '.service' 355 self._routing_units.append(unit) 356 args = ['systemd-run', '--quiet', '--unit=' + unit, '--collect', 357 '--service-type=exec', '--property=Restart=no', 358 '--property=StandardOutput=null', '--property=StandardError=null'] 359 if namespace: 360 args.append('--property=NetworkNamespacePath=/run/netns/' + self.namespace) 361 self._call(args + ['--', *map(str, argv)]) 362 return unit 363 364 def start_routing(self): 365 if self._routing_units or self._closed: 366 raise RuntimeError('Routing already started or fixture closed') 367 nginx_unit = self._start_routing_unit( 368 'nginx', self.config['nginx_args'] + ['-g', 'daemon off;'], namespace=True) 369 # Wait only for our nginx pidfile, not a backend readiness verdict. 370 pidfile = Path(self.config['nginx_pid_file']) 371 deadline = time.monotonic() + 10 372 while not pidfile.exists(): 373 if time.monotonic() >= deadline: 374 raise RuntimeError('Fixture nginx did not create its pidfile') 375 time.sleep(0.05) 376 self.config['nginx_pid'] = int(pidfile.read_text().strip()) 377 actual = self._call(['systemctl', 'show', nginx_unit, '-p', 'MainPID', 378 '--value']).stdout.strip() 379 if int(actual) != self.config['nginx_pid']: 380 raise RuntimeError('Fixture nginx pidfile does not match its unit MainPID') 381 self.config['tunnel_pids'] = {} 382 for suffix, host_key, destination in ( 383 ('tls', 'host_tls_port', self.config['frontend_port']), 384 ('plain', 'host_plain_port', self.config['plain_port'])): 385 port = self.config[host_key] 386 self._release_port(port) 387 tunnel_unit = self._start_routing_unit( 388 suffix, [sys.executable, self.runtime / 'tunnel.py', 389 '--tunnel', '--namespace', self.namespace, 390 '--listen-port', str(port), '--destination-port', str(destination)]) 391 # A readiness file is written only after bind. Match its PID to the 392 # dedicated unit rather than accepting any other host port listener. 393 ready = self.runtime / f'tunnel-{port}.ready' 394 deadline = time.monotonic() + 10 395 while not ready.exists(): 396 if time.monotonic() >= deadline: 397 raise RuntimeError('Fixture host tunnel did not bind') 398 time.sleep(0.05) 399 pid = int(ready.read_text()) 400 actual = self._call(['systemctl', 'show', tunnel_unit, '-p', 'MainPID', 401 '--value']).stdout.strip() 402 if pid <= 0 or int(actual) != pid: 403 raise RuntimeError('Fixture tunnel readiness does not match its MainPID') 404 self.config['tunnel_pids'][suffix] = pid 405 self.config['routing_units'] = self._routing_units.copy() 406 407 def enable_backend(self): 408 """Exercise enable-last without leaving a persistent boot target.""" 409 self._require_open() 410 self._runtime_enabled = True 411 self._call(['systemctl', 'enable', '--runtime', self.unit]) 412 413 def _disable_backend(self): 414 if self._runtime_enabled: 415 self._call(['systemctl', 'disable', '--runtime', self.unit]) 416 self._runtime_enabled = False 417 418 def rollback(self): 419 """Remove registration, keep ordinary site/tunnels and preserve profiles.""" 420 self._require_open() 421 active = Path(self.config['nginx_config']) 422 baseline = self.runtime / 'nginx-baseline.conf' 423 # Both candidates were constructed from the same reviewed input. 424 active.write_bytes(baseline.read_bytes()) 425 master = self.config['nginx_pid'] 426 children = Path(f'/proc/{master}/task/{master}/children') 427 old_workers = children.read_text().split() 428 self._call(self.command(self.config['nginx_args'] + ['-s', 'reload'])) 429 deadline = time.monotonic() + 15 430 while any(Path('/proc', pid).exists() for pid in old_workers): 431 if time.monotonic() >= deadline: 432 raise RuntimeError('Fixture rollback workers did not drain') 433 time.sleep(0.05) 434 self._call(['systemctl', 'stop', self.unit]) 435 self._disable_backend() 436 437 def _stop_owned_units(self): 438 errors = [] 439 for unit in reversed(self._routing_units): 440 result = self._call(['systemctl', 'stop', unit], check=False) 441 if result.returncode: 442 # --collect may already have unloaded a failed transient unit. 443 state = self._call(['systemctl', 'show', unit, '-p', 'LoadState', 444 '--value'], check=False) 445 if state.stdout.strip() != b'not-found': 446 errors.append(unit) 447 if self._unit_created: 448 result = self._call(['systemctl', 'stop', self.unit], check=False) 449 if result.returncode: 450 errors.append(self.unit) 451 if errors: 452 raise RuntimeError('Could not stop owned fixture units: ' + ', '.join(errors)) 453 454 def cleanup(self): 455 if self._closed: 456 return 457 # Never unlink files or namespace while an owned service may still run. 458 self._stop_owned_units() 459 self._disable_backend() 460 for sock in self._ports: 461 sock.close() 462 self._ports.clear() 463 if self._namespace_created: 464 self._call(['ip', 'netns', 'delete', self.namespace]) 465 self._namespace_created = False 466 if self._unit_created: 467 if self.dropin_dir.exists(): 468 shutil.rmtree(self.dropin_dir) 469 self.unit_path.unlink() 470 self._unit_created = False 471 self._call(['systemctl', 'daemon-reload']) 472 self._call(['systemctl', 'reset-failed', self.unit], check=False) 473 if self._state_created: 474 if not self._state_retained: 475 retained = self.root / 'retained-state' 476 shutil.copytree(self.state, retained) 477 for directory, _, files in os.walk(retained): 478 Path(directory).chmod(0o700) 479 for name in files: 480 (Path(directory) / name).chmod(0o600) 481 self._state_retained = True 482 shutil.rmtree(self.state) 483 self._state_created = False 484 if self._runtime_created: 485 shutil.rmtree(self.runtime) 486 self._runtime_created = False 487 self._closed = True 488 489 490 def _relay(client, namespace_fd, destination_port): 491 """A byte relay to one compile-time-selected loopback fixture destination.""" 492 remote = None 493 try: 494 # setns affects this worker's OS thread, not the host acceptor thread. 495 # Use libc because supported Python versions do not all expose os.setns. 496 libc = ctypes.CDLL(None, use_errno=True) 497 if libc.setns(namespace_fd, 0) != 0: 498 raise OSError(ctypes.get_errno(), 'Could not enter fixture namespace') 499 remote = socket.create_connection(('127.0.0.1', destination_port), timeout=10) 500 client.settimeout(30) 501 remote.settimeout(30) 502 with selectors.DefaultSelector() as ready: 503 ready.register(client, selectors.EVENT_READ, remote) 504 ready.register(remote, selectors.EVENT_READ, client) 505 while ready.get_map(): 506 events = ready.select(timeout=30) 507 if not events: 508 return 509 for key, _ in events: 510 data = key.fileobj.recv(65536) 511 if not data: 512 ready.unregister(key.fileobj) 513 key.data.shutdown(socket.SHUT_WR) 514 else: 515 key.data.sendall(data) 516 except OSError: 517 # Neither payloads nor connection exceptions are logged. 518 pass 519 finally: 520 client.close() 521 if remote is not None: 522 remote.close() 523 524 525 def _tunnel_main(): 526 parser = argparse.ArgumentParser() 527 parser.add_argument('--tunnel', action='store_true', required=True) 528 parser.add_argument('--namespace', required=True) 529 parser.add_argument('--listen-port', required=True, type=int) 530 parser.add_argument('--destination-port', required=True, type=int) 531 args = parser.parse_args() 532 if not args.namespace.startswith('aien-agora-oracle-') or not all( 533 char in '`0123456789abcdef`' for char in args.namespace.removeprefix( 534 'aien-agora-oracle-')): 535 parser.error('Not a fixture namespace') 536 if args.destination_port not in (28443, 28080): 537 parser.error('Destination is not an allowed fixture frontend') 538 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener: 539 listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 540 listener.bind(('127.0.0.1', args.listen_port)) 541 listener.listen(32) 542 namespace_fd = os.open('/run/netns/' + args.namespace, os.O_RDONLY) 543 ready = Path(__file__).resolve().parent / f'tunnel-{args.listen_port}.ready' 544 with ready.open('x') as stream: 545 stream.write(str(os.getpid())) 546 try: 547 while True: 548 client, _ = listener.accept() 549 threading.Thread(target=_relay, args=(client, namespace_fd, 550 args.destination_port), daemon=True).start() 551 finally: 552 os.close(namespace_fd) 553 554 555 if __name__ == '__main__': 556 _tunnel_main()