| 1 | +#!/usr/bin/env python3 |
| 2 | +"""ComfyUI lazy proxy for a volumeless RunPod on-demand pod. |
| 3 | + |
| 4 | +SillyTavern's fallback chain points at this proxy as a normal ComfyUI server; |
| 5 | +the pod downloads its models at boot (boot-models.py in the image), so no |
| 6 | +network volume or region lock is needed. |
| 7 | + |
| 8 | +Control API (CORS-enabled, used by the ST warmup UI and the CLI script): |
| 9 | + GET /lazy/status -> {"state": "red"|"orange"|"green", ...} |
| 10 | + POST /lazy/warmup -> start pod with MODELS=all (idempotent) |
| 11 | + POST /lazy/shutdown -> terminate pod now |
| 12 | + POST /lazy/ping -> keepalive (extends idle timer; never starts a pod) |
| 13 | + |
| 14 | +Wake semantics: a ComfyUI /prompt POST arriving with no pod starts one that |
| 15 | +downloads only the model group the workflow references (flux/qwen/all). |
| 16 | +The idle timer lives HERE (NAS side): IDLE_SECONDS after the last activity |
| 17 | +signal (comfy traffic or keepalive ping) the pod is terminated - regardless |
| 18 | +of whether any frontend still exists. |
| 19 | + |
| 20 | +stdlib only; runs on python:3.12-alpine. |
| 21 | +""" |
| 22 | +import json |
| 23 | +import os |
| 24 | +import threading |
| 25 | +import time |
| 26 | +import urllib.error |
| 27 | +import urllib.request |
| 28 | +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 29 | + |
| 30 | +RUNPOD_KEY = os.environ['RUNPOD_KEY'] |
| 31 | +LISTEN_PORT = int(os.environ.get('LISTEN_PORT', '8189')) |
| 32 | +IDLE_SECONDS = int(os.environ.get('IDLE_SECONDS', '900')) |
| 33 | +DATACENTERS = [d for d in os.environ.get('DATACENTERS', '').split(',') if d] # empty = any |
| 34 | +CLOUD_TYPE = os.environ.get('CLOUD_TYPE', 'SECURE') |
| 35 | +IMAGE = os.environ.get('IMAGE', 'ghcr.io/permissionbrick/comfyui-runpod-worker:latest') |
| 36 | +GPU_TYPES = os.environ.get('GPU_TYPES', 'NVIDIA RTX 6000 Ada Generation,NVIDIA L40S,NVIDIA L40,NVIDIA RTX A6000,NVIDIA A40').split(',') |
| 37 | +POD_NAME = os.environ.get('POD_NAME', 'comfyui-lazy') |
| 38 | +START_TIMEOUT = int(os.environ.get('START_TIMEOUT', '1500')) |
| 39 | +HF_TOKEN = os.environ.get('HF_TOKEN', '') |
| 40 | +COMFY_ARGS = os.environ.get('COMFY_ARGS', '--listen 0.0.0.0 --port 8188 --use-pytorch-cross-attention') |
| 41 | +CACHE_FILE = os.environ.get('CACHE_FILE', '/app/system_stats.cache') |
| 42 | + |
| 43 | +# Model-group detection: filename fragment (lowercased) -> group |
| 44 | +GROUP_HINTS = {'flux-2-klein': 'flux', 'flux2-klein': 'flux', 'flux2-vae': 'flux', 'qwen-rapid': 'qwen'} |
| 45 | + |
| 46 | +state = { |
| 47 | + 'pod_id': None, # current pod id (may still be booting) |
| 48 | + 'models': None, # MODELS value the pod was created with |
| 49 | + 'phase': 'red', # red | orange | green |
| 50 | + 'gpu': None, |
| 51 | + 'since': time.time(), |
| 52 | + 'last': time.monotonic(), |
| 53 | + 'lock': threading.Lock(), |
| 54 | +} |
| 55 | + |
| 56 | + |
| 57 | +def log(*args): |
| 58 | + print(time.strftime('%H:%M:%S'), *args, flush=True) |
| 59 | + |
| 60 | + |
| 61 | +def api(method, path, body=None): |
| 62 | + req = urllib.request.Request( |
| 63 | + f'https://rest.runpod.io/v1{path}', |
| 64 | + json.dumps(body).encode() if body is not None else None, |
| 65 | + {'Authorization': f'Bearer {RUNPOD_KEY}', 'Content-Type': 'application/json'}, |
| 66 | + method=method) |
| 67 | + with urllib.request.urlopen(req, timeout=60) as resp: |
| 68 | + data = resp.read() |
| 69 | + return json.loads(data) if data else {} |
| 70 | + |
| 71 | + |
| 72 | +def find_pod(): |
| 73 | + try: |
| 74 | + for pod in api('GET', '/pods'): |
| 75 | + if pod.get('name') == POD_NAME and pod.get('desiredStatus') == 'RUNNING': |
| 76 | + return pod['id'], (pod.get('env') or {}).get('MODELS'), pod.get('machine', {}).get('gpuTypeId') |
| 77 | + except Exception as err: |
| 78 | + log('find_pod failed:', err) |
| 79 | + return None, None, None |
| 80 | + |
| 81 | + |
| 82 | +def create_pod(models): |
| 83 | + body = { |
| 84 | + 'name': POD_NAME, |
| 85 | + 'imageName': IMAGE, |
| 86 | + 'gpuTypeIds': GPU_TYPES, |
| 87 | + 'gpuCount': 1, |
| 88 | + 'cloudType': CLOUD_TYPE, |
| 89 | + 'containerDiskInGb': 80, |
| 90 | + 'ports': ['8188/http'], |
| 91 | + 'env': {'MODELS': models, 'HF_TOKEN': HF_TOKEN}, |
| 92 | + 'dockerStartCmd': ['bash', '-c', f'python3 /boot-models.py && cd /comfyui && exec python main.py {COMFY_ARGS}'], |
| 93 | + } |
| 94 | + if DATACENTERS: |
| 95 | + body['dataCenterIds'] = DATACENTERS |
| 96 | + pod = api('POST', '/pods', body) |
| 97 | + log(f"pod created: {pod['id']} MODELS={models} {pod.get('machine', {}).get('gpuTypeId')} ${pod.get('costPerHr')}/hr") |
| 98 | + return pod['id'], pod.get('machine', {}).get('gpuTypeId') |
| 99 | + |
| 100 | + |
| 101 | +def pod_url(pod_id): |
| 102 | + return f'https://{pod_id}-8188.proxy.runpod.net' |
| 103 | + |
| 104 | + |
| 105 | +def upstream_ready(pod_id): |
| 106 | + try: |
| 107 | + with urllib.request.urlopen(pod_url(pod_id) + '/system_stats', timeout=5) as resp: |
| 108 | + if resp.status == 200: |
| 109 | + data = resp.read() |
| 110 | + with open(CACHE_FILE, 'wb') as f: |
| 111 | + f.write(data) |
| 112 | + return True |
| 113 | + except Exception: |
| 114 | + pass |
| 115 | + return False |
| 116 | + |
| 117 | + |
| 118 | +def groups_cover(have, need): |
| 119 | + if not have: |
| 120 | + return False |
| 121 | + have_set = set(have.split(',')) |
| 122 | + need_set = set(need.split(',')) |
| 123 | + return 'all' in have_set or need_set <= have_set |
| 124 | + |
| 125 | + |
| 126 | +def ensure_pod(models='all', wait=True): |
| 127 | + """Ensures a pod covering the requested model groups; optionally waits for readiness.""" |
| 128 | + with state['lock']: |
| 129 | + pod_id, have, gpu = (state['pod_id'], state['models'], state['gpu']) |
| 130 | + if not pod_id: |
| 131 | + pod_id, have, gpu = find_pod() |
| 132 | + if pod_id and not groups_cover(have, models): |
| 133 | + log(f'pod has MODELS={have}, need {models} - recreating with all') |
| 134 | + try: |
| 135 | + api('DELETE', f'/pods/{pod_id}') |
| 136 | + except Exception as err: |
| 137 | + log('delete failed:', err) |
| 138 | + pod_id, have, gpu = None, None, None |
| 139 | + models = 'all' |
| 140 | + if not pod_id: |
| 141 | + state['phase'] = 'orange' |
| 142 | + state['since'] = time.time() |
| 143 | + last_err = None |
| 144 | + for attempt in range(3): |
| 145 | + try: |
| 146 | + pod_id, gpu = create_pod(models) |
| 147 | + break |
| 148 | + except urllib.error.HTTPError as err: |
| 149 | + last_err = err.read().decode()[:200] |
| 150 | + log(f'create_pod attempt {attempt + 1} failed:', last_err) |
| 151 | + time.sleep(5) |
| 152 | + if not pod_id: |
| 153 | + state['phase'] = 'red' |
| 154 | + raise RuntimeError(f'could not create pod: {last_err}') |
| 155 | + have = models |
| 156 | + state['pod_id'], state['models'], state['gpu'] = pod_id, have, gpu |
| 157 | + state['last'] = time.monotonic() |
| 158 | + |
| 159 | + if state['phase'] != 'green': |
| 160 | + state['phase'] = 'orange' |
| 161 | + if not wait: |
| 162 | + return pod_id |
| 163 | + deadline = time.monotonic() + START_TIMEOUT |
| 164 | + while time.monotonic() < deadline: |
| 165 | + if upstream_ready(pod_id): |
| 166 | + if state['phase'] != 'green': |
| 167 | + state['phase'] = 'green' |
| 168 | + state['since'] = time.time() |
| 169 | + log('pod ready:', pod_id) |
| 170 | + state['last'] = time.monotonic() |
| 171 | + return pod_id |
| 172 | + if state['pod_id'] != pod_id: |
| 173 | + raise RuntimeError('pod replaced while waiting') |
| 174 | + time.sleep(5) |
| 175 | + raise RuntimeError('pod not ready within START_TIMEOUT') |
| 176 | + |
| 177 | + |
| 178 | +def detect_groups(workflow_bytes): |
| 179 | + try: |
| 180 | + text = workflow_bytes.decode('utf-8', 'replace').lower() |
| 181 | + except Exception: |
| 182 | + return 'all' |
| 183 | + found = {group for hint, group in GROUP_HINTS.items() if hint in text} |
| 184 | + if len(found) == 1: |
| 185 | + return found.pop() |
| 186 | + return 'all' |
| 187 | + |
| 188 | + |
| 189 | +def idle_reaper(): |
| 190 | + while True: |
| 191 | + time.sleep(30) |
| 192 | + idle = time.monotonic() - state['last'] |
| 193 | + if idle > IDLE_SECONDS: |
| 194 | + pod_id = state['pod_id'] or find_pod()[0] |
| 195 | + if pod_id: |
| 196 | + log(f'idle {int(idle)}s - terminating pod') |
| 197 | + try: |
| 198 | + api('DELETE', f'/pods/{pod_id}') |
| 199 | + except Exception as err: |
| 200 | + log('terminate failed:', err) |
| 201 | + if pod_id or state['phase'] != 'red': |
| 202 | + state.update({'pod_id': None, 'models': None, 'gpu': None, 'phase': 'red', 'since': time.time()}) |
| 203 | + |
| 204 | + |
| 205 | +def status_body(): |
| 206 | + # Refresh green-ness cheaply on demand |
| 207 | + pod_id = state['pod_id'] |
| 208 | + if pod_id and state['phase'] != 'green' and upstream_ready(pod_id): |
| 209 | + state['phase'] = 'green' |
| 210 | + state['since'] = time.time() |
| 211 | + if not pod_id: |
| 212 | + found, have, gpu = find_pod() |
| 213 | + if found: |
| 214 | + state.update({'pod_id': found, 'models': have, 'gpu': gpu}) |
| 215 | + state['phase'] = 'green' if upstream_ready(found) else 'orange' |
| 216 | + else: |
| 217 | + state['phase'] = 'red' |
| 218 | + return json.dumps({ |
| 219 | + 'state': state['phase'], |
| 220 | + 'pod_id': state['pod_id'], |
| 221 | + 'models': state['models'], |
| 222 | + 'gpu': state['gpu'], |
| 223 | + 'since': state['since'], |
| 224 | + 'url': pod_url(state['pod_id']) if state['pod_id'] else None, |
| 225 | + 'idle_seconds_left': max(0, IDLE_SECONDS - int(time.monotonic() - state['last'])) if state['pod_id'] else 0, |
| 226 | + }).encode() |
| 227 | + |
| 228 | + |
| 229 | +class Proxy(BaseHTTPRequestHandler): |
| 230 | + protocol_version = 'HTTP/1.1' |
| 231 | + |
| 232 | + def log_message(self, fmt, *args): |
| 233 | + pass |
| 234 | + |
| 235 | + def _reply(self, code, data, ctype='application/json'): |
| 236 | + self.send_response(code) |
| 237 | + self.send_header('Content-Type', ctype or 'application/json') |
| 238 | + self.send_header('Content-Length', str(len(data))) |
| 239 | + self.send_header('Access-Control-Allow-Origin', '*') |
| 240 | + self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS') |
| 241 | + self.send_header('Access-Control-Allow-Headers', 'Content-Type') |
| 242 | + self.end_headers() |
| 243 | + self.wfile.write(data) |
| 244 | + |
| 245 | + def do_OPTIONS(self): |
| 246 | + self._reply(204, b'') |
| 247 | + |
| 248 | + def _handle(self): |
| 249 | + length = int(self.headers.get('Content-Length') or 0) |
| 250 | + body = self.rfile.read(length) if length else None |
| 251 | + path = self.path.split('?')[0] |
| 252 | + |
| 253 | + # ---- control API ---- |
| 254 | + if path == '/lazy/status': |
| 255 | + return self._reply(200, status_body()) |
| 256 | + if path == '/lazy/ping': |
| 257 | + if state['pod_id']: |
| 258 | + state['last'] = time.monotonic() |
| 259 | + return self._reply(200, b'{"ok": true}') |
| 260 | + if path == '/lazy/warmup': |
| 261 | + threading.Thread(target=self._safe_ensure, args=('all',), daemon=True).start() |
| 262 | + state['phase'] = state['phase'] if state['phase'] == 'green' else 'orange' |
| 263 | + return self._reply(200, status_body()) |
| 264 | + if path == '/lazy/shutdown': |
| 265 | + pod_id = state['pod_id'] or find_pod()[0] |
| 266 | + if pod_id: |
| 267 | + try: |
| 268 | + api('DELETE', f'/pods/{pod_id}') |
| 269 | + except Exception as err: |
| 270 | + return self._reply(500, json.dumps({'error': str(err)}).encode()) |
| 271 | + state.update({'pod_id': None, 'models': None, 'gpu': None, 'phase': 'red', 'since': time.time()}) |
| 272 | + return self._reply(200, status_body()) |
| 273 | + |
| 274 | + # ---- comfy proxying ---- |
| 275 | + state['last'] = time.monotonic() |
| 276 | + pod_id = state['pod_id'] |
| 277 | + ready = pod_id and upstream_ready(pod_id) |
| 278 | + if not ready and self.command == 'GET' and path == '/system_stats': |
| 279 | + # Reachability probe while cold: answer from cache; do NOT wake. |
| 280 | + try: |
| 281 | + with open(CACHE_FILE, 'rb') as f: |
| 282 | + return self._reply(200, f.read()) |
| 283 | + except FileNotFoundError: |
| 284 | + return self._reply(200, json.dumps({'system': {'comfyui_version': 'cold'}, 'devices': []}).encode()) |
| 285 | + if not ready: |
| 286 | + models = detect_groups(body) if (self.command == 'POST' and path == '/prompt' and body) else 'all' |
| 287 | + try: |
| 288 | + pod_id = ensure_pod(models) |
| 289 | + except Exception as err: |
| 290 | + log('ensure_pod failed:', err) |
| 291 | + return self._reply(502, json.dumps({'error': str(err)}).encode()) |
| 292 | + try: |
| 293 | + req = urllib.request.Request(pod_url(pod_id) + self.path, body, method=self.command) |
| 294 | + for header in ('Content-Type', 'Accept'): |
| 295 | + if self.headers.get(header): |
| 296 | + req.add_header(header, self.headers[header]) |
| 297 | + with urllib.request.urlopen(req, timeout=300) as resp: |
| 298 | + self._reply(resp.status, resp.read(), resp.headers.get('Content-Type')) |
| 299 | + except urllib.error.HTTPError as err: |
| 300 | + self._reply(err.code, err.read()) |
| 301 | + except Exception as err: |
| 302 | + log('upstream error:', err) |
| 303 | + self._reply(502, json.dumps({'error': str(err)}).encode()) |
| 304 | + finally: |
| 305 | + state['last'] = time.monotonic() |
| 306 | + |
| 307 | + def _safe_ensure(self, models): |
| 308 | + try: |
| 309 | + ensure_pod(models) |
| 310 | + except Exception as err: |
| 311 | + log('warmup failed:', err) |
| 312 | + |
| 313 | + do_GET = _handle |
| 314 | + do_POST = _handle |
| 315 | + |
| 316 | + |
| 317 | +def main(): |
| 318 | + threading.Thread(target=idle_reaper, daemon=True).start() |
| 319 | + server = ThreadingHTTPServer(('0.0.0.0', LISTEN_PORT), Proxy) |
| 320 | + log(f'runpod-lazy v2 on :{LISTEN_PORT} (pod "{POD_NAME}", DCs {DATACENTERS or "any"}, idle {IDLE_SECONDS}s)') |
| 321 | + server.serve_forever() |
| 322 | + |
| 323 | + |
| 324 | +if __name__ == '__main__': |
| 325 | + main() |