#!/usr/bin/env python3 """ Simple Python-based reverse proxy with multi-process management No supervisord needed - runs nginx and sshd as subprocesses """ import os import signal import subprocess import sys import time from pathlib import Path # Track running processes processes = [] def signal_handler(sig, frame): """Handle shutdown signals gracefully""" print(f"\nReceived signal {sig}, shutting down gracefully...") for proc in processes: try: proc.terminate() proc.wait(timeout=5) except subprocess.TimeoutExpired: proc.kill() except Exception as e: print(f"Error stopping process: {e}") sys.exit(0) def setup_ssh(): """Generate SSH host keys if they don't exist""" key_dir = Path("/home/user/.ssh/hostkeys") key_dir.mkdir(parents=True, exist_ok=True) rsa_key = key_dir / "ssh_host_rsa_key" ed_key = key_dir / "ssh_host_ed25519_key" if not rsa_key.exists() or not ed_key.exists(): print("Generating SSH host keys...") subprocess.run( ["ssh-keygen", "-t", "rsa", "-b", "4096", "-f", str(rsa_key), "-N", ""], check=True, ) subprocess.run( ["ssh-keygen", "-t", "ed25519", "-f", str(ed_key), "-N", ""], check=True ) else: print("SSH host keys already exist") # Add SSH public key from environment if provided ssh_public_key = os.getenv("SSH_PUBLIC_KEY") if ssh_public_key: print("Adding SSH public key from environment...") ssh_dir = Path("/home/user/.ssh") ssh_dir.mkdir(parents=True, exist_ok=True) authorized_keys = ssh_dir / "authorized_keys" with open(authorized_keys, "a") as f: f.write(f"{ssh_public_key}\n") os.chmod(ssh_dir, 0o700) os.chmod(authorized_keys, 0o600) subprocess.run(["chown", "-R", "user:user", str(ssh_dir)], check=True) print("SSH public key added successfully") def start_nginx(): """Start nginx in foreground mode""" print("Starting nginx...") proc = subprocess.Popen( ["/usr/sbin/nginx", "-g", "daemon off;"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, ) processes.append(proc) return proc def start_sshd(): """Start sshd in non-daemon mode""" print("Starting sshd...") proc = subprocess.Popen( ["/usr/sbin/sshd", "-D"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, ) processes.append(proc) return proc def start_tailscale(): """Start Tailscale if auth key is provided""" auth_key = os.getenv("TAILSCALE_AUTHKEY") if not auth_key: print("No TAILSCALE_AUTHKEY provided, skipping Tailscale") return None, None print("Starting tailscaled...") tailscaled = subprocess.Popen( [ "/usr/sbin/tailscaled", "--state=/var/lib/tailscale/tailscaled.state", "--socket=/var/run/tailscale/tailscaled.sock", "--tun=userspace-networking", ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, ) processes.append(tailscaled) # Wait for tailscaled to be ready print("Waiting for tailscaled to start...") for i in range(30): result = subprocess.run( ["tailscale", "status"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) if result.returncode == 0: break time.sleep(1) else: print("Warning: tailscaled did not start in time") return tailscaled, None # Connect to Tailscale network print("Connecting to Tailscale network...") tailscale_up = subprocess.Popen( ["tailscale", "up", "--authkey", auth_key, "--accept-routes"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, ) tailscale_up.wait() print("Tailscale connection initiated") return tailscaled, tailscale_up def monitor_processes(): """Monitor all processes and restart if they crash""" restart_count = {} max_restarts = 3 restart_window = 60 # seconds while True: time.sleep(5) for i, proc in enumerate(processes[:]): # Copy list to iterate safely if proc.poll() is not None: # Process has died proc_name = {0: "nginx", 1: "sshd", 2: "tailscaled"}.get( i, f"process-{i}" ) print( f"WARNING: {proc_name} (PID {proc.pid}) has stopped with code {proc.returncode}" ) # Check restart limits now = time.time() if proc_name not in restart_count: restart_count[proc_name] = [] # Remove old restart timestamps restart_count[proc_name] = [ ts for ts in restart_count[proc_name] if now - ts < restart_window ] if len(restart_count[proc_name]) >= max_restarts: print(f"ERROR: {proc_name} has restarted too many times, giving up") continue # Restart the process print(f"Restarting {proc_name}...") restart_count[proc_name].append(now) if i == 0: # nginx new_proc = start_nginx() processes[i] = new_proc elif i == 1: # sshd new_proc = start_sshd() processes[i] = new_proc # Don't auto-restart tailscaled as it's more complex def main(): """Main entry point""" print("=" * 60) print("Starting Multi-Process Service Manager") print("=" * 60) # Register signal handlers signal.signal(signal.SIGTERM, signal_handler) signal.signal(signal.SIGINT, signal_handler) # Setup SSH setup_ssh() # Start Tailscale (optional) start_tailscale() # Start core services start_nginx() start_sshd() print("\n" + "=" * 60) print("All services started successfully!") print("=" * 60) print(f"Running with {len(processes)} processes") print("Press Ctrl+C to stop\n") # Monitor processes indefinitely try: monitor_processes() except KeyboardInterrupt: signal_handler(signal.SIGINT, None) if __name__ == "__main__": main()