1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
| """ Chrome Cluster Manager — CDP 多实例编排框架
管理 N 个独立的 Chrome 进程,支持: - 自动启动和端口分配 - 连接池管理 - 多种任务分发策略 - 优雅关闭和资源清理 """ import asyncio import json import os import platform import signal import subprocess import tempfile import shutil import time import urllib.request import websockets import itertools from dataclasses import dataclass, field from typing import Optional, List, Callable, Awaitable
CMD_ID = [0]
async def cdp(ws, method, params=None, session_id=None): CMD_ID[0] += 1 msg = {"id": CMD_ID[0], "method": method, "params": params or {}} if session_id: msg["sessionId"] = session_id await ws.send(json.dumps(msg)) async for resp in ws: data = json.loads(resp) if data.get("id") == CMD_ID[0]: return data.get("result", {})
def get_chrome_path(): """获取系统 Chrome 路径""" system = platform.system().lower() paths = { 'windows': [ r'C:\Program Files\Google\Chrome\Application\chrome.exe', r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe', ], 'darwin': ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'], 'linux': ['google-chrome', 'chromium-browser', 'chromium'], } for p in paths.get(system, paths['linux']): if os.path.exists(p) or shutil.which(p): return p raise FileNotFoundError('Chrome not found. Install Google Chrome or Chromium.')
def is_port_available(port): """检查端口是否可用""" import socket with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.bind(('127.0.0.1', port)) return True except OSError: return False
def check_process_alive(pid): """检查进程是否存活(信号 0 检测)""" if not pid: return False try: os.kill(pid, 0) return True except (OSError, ProcessLookupError): return False
@dataclass class ChromeInstance: port: int pid: int user_data_dir: str ws_url: str = '' ws: Optional[websockets.WebSocketClientProtocol] = None _busy: bool = False task_count: int = 0 name: str = '' @property def is_busy(self): return self._busy @property def is_alive(self): return check_process_alive(self.pid) async def connect(self): self.ws = await websockets.connect(self.ws_url, max_size=2**24) await cdp(self.ws, 'Target.setAutoAttach', { 'autoAttach': True, 'flatten': True, 'waitForDebuggerOnStart': False }) return self async def close(self): if self.ws: await self.ws.close() self.ws = None
class ChromeClusterManager: """ Chrome 集群管理器 with ChromeClusterManager(count=4, headless=True) as cluster: await cluster.start() results = await cluster.run_on_all(some_task) """ def __init__( self, count: int = 2, base_port: int = 9222, headless: bool = True, chrome_path: Optional[str] = None, proxy: Optional[str] = None, dispatcher_type: str = 'round_robin', ): self.count = count self.base_port = base_port self.headless = headless self.chrome_path = chrome_path or get_chrome_path() self.proxy = proxy self.dispatcher_type = dispatcher_type self.instances: List[ChromeInstance] = [] self._dispatcher = None self._cleanup_done = False async def start(self): """启动所有 Chrome 实例""" print(f'[Cluster] Starting {self.count} Chrome instances...') for i in range(self.count): port = self.base_port + i if not is_port_available(port): raise RuntimeError(f'Port {port} is already in use') user_data_dir = tempfile.mkdtemp(prefix=f'chrome_{port}_') args = [ self.chrome_path, f'--remote-debugging-port={port}', '--remote-allow-origins=*', '--no-first-run', '--no-default-browser-check', f'--user-data-dir={user_data_dir}', '--disable-sync', '--disable-default-apps', '--disable-extensions', ] if self.headless: args.append('--headless=new') if self.proxy: args.append(f'--proxy-server={self.proxy}') proc = subprocess.Popen( args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) ws_url = self._wait_for_ws_url(port) instance = ChromeInstance( port=port, pid=proc.pid, user_data_dir=user_data_dir, ws_url=ws_url, name=f'chrome-{port}' ) await instance.connect() self.instances.append(instance) print(f' [OK] Instance {i+1}/{self.count}: port={port}, pid={proc.pid}') self._init_dispatcher() print(f'[Cluster] All {self.count} instances ready.') return self def _wait_for_ws_url(self, port, max_retries=20, delay=0.5): """等待 Chrome 初始化并返回 WS URL""" for attempt in range(max_retries): try: resp = urllib.request.urlopen( f'http://127.0.0.1:{port}/json/version', timeout=2 ) data = json.loads(resp.read()) return data['webSocketDebuggerUrl'] except Exception: if attempt < max_retries - 1: time.sleep(delay) continue raise RuntimeError(f'Chrome on port {port} failed to start') def _init_dispatcher(self): """初始化任务分发器""" if self.dispatcher_type == 'round_robin': self._dispatcher = RoundRobinDispatcher(self.instances) elif self.dispatcher_type == 'least_loaded': self._dispatcher = LeastLoadedDispatcher(self.instances) else: self._dispatcher = RoundRobinDispatcher(self.instances) async def get_idle_instance(self) -> Optional[ChromeInstance]: """获取一个空闲实例""" return await self._dispatcher.get_instance() async def run_on_one(self, task_fn: Callable[[ChromeInstance], Awaitable], timeout: int = 60) -> Optional[any]: """在某个空闲实例上执行任务(阻塞直到有空闲)""" while True: instance = await self.get_idle_instance() if instance: return await self._run_task(instance, task_fn, timeout) await asyncio.sleep(0.5) async def run_on_all(self, task_fn: Callable[[ChromeInstance], Awaitable], timeout: int = 60) -> List[any]: """在所有实例上并行执行任务""" tasks = [self._run_task(inst, task_fn, timeout) for inst in self.instances] return await asyncio.gather(*tasks, return_exceptions=True) async def run_batch(self, tasks: List, task_fn: Callable, timeout: int = 60) -> List[any]: """批量执行任务列表(自动分发到空闲实例)""" results = [None] * len(tasks) pending = list(enumerate(tasks)) async def worker(): while pending: idx, task = pending.pop(0) instance = await self.get_idle_instance() if instance: results[idx] = await self._run_task( instance, lambda inst: task_fn(inst, task), timeout ) else: pending.append((idx, task)) await asyncio.sleep(0.3) workers = [worker() for _ in range(min(len(tasks), self.count))] await asyncio.gather(*workers) return results async def _run_task(self, instance: ChromeInstance, task_fn: Callable, timeout: int): """在指定实例上执行任务""" instance._busy = True try: result = await asyncio.wait_for(task_fn(instance), timeout=timeout) instance.task_count += 1 return result finally: instance._busy = False async def shutdown(self): """优雅关闭所有实例""" if self._cleanup_done: return self._cleanup_done = True print('\n[Cluster] Shutting down...') await asyncio.gather( *[inst.close() for inst in self.instances], return_exceptions=True ) for inst in self.instances: if inst.is_alive: try: if os.name == 'nt': subprocess.run( ['taskkill', '/F', '/PID', str(inst.pid)], capture_output=True, timeout=5 ) else: os.kill(inst.pid, signal.SIGTERM) except Exception as e: print(f' [Warn] Failed to kill PID {inst.pid}: {e}') for inst in self.instances: if inst.user_data_dir and os.path.exists(inst.user_data_dir): try: shutil.rmtree(inst.user_data_dir, ignore_errors=True) except Exception: pass print(f'[Cluster] Shutdown complete. {self.count} instances terminated.') async def __aenter__(self): return await self.start() async def __aexit__(self, *args): await self.shutdown()
class RoundRobinDispatcher: def __init__(self, instances): self.instances = instances self.iterator = itertools.cycle(instances) async def get_instance(self): for _ in range(len(self.instances)): inst = next(self.iterator) if not inst._busy: return inst return None
class LeastLoadedDispatcher: def __init__(self, instances): self.instances = instances async def get_instance(self): idle = [i for i in self.instances if not i._busy] if not idle: return None return min(idle, key=lambda i: i.task_count)
|