Files
ayurishchevandClaude Sonnet 5.5 ea1592800a HAProxy как приватный шлюз к S3 VK Cloud: конфигурация, Lua, тесты, документация
- haproxy.cfg: терминация TLS (самоподписанный сертификат, wildcard), подмена Host/SNI,
  переписывание Location/Server и тел ответов (s3_rewrite.lua)
- s3_resign.lua: проверка подписи SigV4 клиента и повторная подпись под реальный Host
- s3gw-snat.nft: SNAT клиентской подсети (nftables) для прямого доступа
- tests: автотесты Lua (SHA-256/HMAC/SigV4), сборщик метрик и расчёт сводок нагрузочных тестов
- docs: планы и итоги всех итераций, отчёт о пути пакета, сравнительные тесты CPU/RAM
  (512 МБ, 2 ГБ multipart 5/20/40 потоков, 1 и 4 vCPU), Mermaid-диаграммы, сырые данные замеров
- Секреты (hostinfo.txt, hostkey.key, s3_creds.lua) исключены через .gitignore

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 12:44:07 +03:00

63 lines
2.7 KiB
Python

#!/usr/bin/env python3
"""Сборщик метрик Egress Node раз в секунду: python3 cpu_sampler.py out.csv [iface1 iface2]
Колонки: epoch, cpu_busy, user, system, softirq, iowait, steal (% от всех ядер), haproxy_cpu (% ядра),
haproxy_rss_kb, mem_used_kb, <iface>_rx, <iface>_tx (счётчики байт), core<N> (% занятости каждого ядра)."""
import os, sys, time
IFACES = sys.argv[2:] or ["eth0", "eth1"]
def cpu():
v = [int(x) for x in open("/proc/stat").readline().split()[1:]]
# user nice system idle iowait irq softirq steal
return v[0] + v[1], v[2], v[6] + v[5], v[4], v[7], sum(v[:8]), v[3]
def cores():
out = []
for l in open("/proc/stat"):
if l.startswith("cpu") and l[3].isdigit():
v = [int(x) for x in l.split()[1:9]]
out.append((sum(v) - v[3] - v[4], sum(v))) # занято (без idle и iowait), всего
return out
def haproxy():
ticks, rss = 0, 0
for pid in filter(str.isdigit, os.listdir("/proc")):
try:
if open(f"/proc/{pid}/comm").read().strip() != "haproxy":
continue
f = open(f"/proc/{pid}/stat").read().rsplit(")", 1)[1].split()
ticks += int(f[11]) + int(f[12])
rss += int(f[21]) * os.sysconf("SC_PAGE_SIZE") // 1024
except OSError:
pass
return ticks, rss
def mem_used():
m = {l.split(":")[0]: int(l.split()[1]) for l in open("/proc/meminfo")}
return m["MemTotal"] - m["MemAvailable"]
def net():
out = []
for i in IFACES:
d = f"/sys/class/net/{i}/statistics/"
out += [int(open(d + "rx_bytes").read()), int(open(d + "tx_bytes").read())]
return out
hz = os.sysconf("SC_CLK_TCK")
ncpu = os.cpu_count()
with open(sys.argv[1], "w") as o:
o.write("epoch,cpu_busy,user,system,softirq,iowait,steal,haproxy_cpu,haproxy_rss_kb,mem_used_kb,"
+ ",".join(f"{i}_rx,{i}_tx" for i in IFACES) + "," + ",".join(f"core{n}" for n in range(ncpu)) + "\n")
prev, pt, ph, pc = cpu(), time.time(), haproxy()[0], cores()
while True:
time.sleep(1)
cur, t, (hp, rss), cc = cpu(), time.time(), haproxy(), cores()
dt = [cur[i] - prev[i] for i in range(7)]
tot = dt[5] or 1
busy = tot - dt[6] - dt[3] # всё, кроме idle и iowait
row = [t, 100 * busy / tot, 100 * dt[0] / tot, 100 * dt[1] / tot, 100 * dt[2] / tot,
100 * dt[3] / tot, 100 * dt[4] / tot, 100 * (hp - ph) / hz / (t - pt), rss, mem_used()] + net() + [100 * (c[0] - p[0]) / ((c[1] - p[1]) or 1) for c, p in zip(cc, pc)]
o.write(",".join(f"{x:.2f}" if isinstance(x, float) else str(x) for x in row) + "\n")
o.flush()
prev, pt, ph, pc = cur, t, hp, cc