#!/usr/bin/env python3
"""VPS 超售监控 · 采集脚本  v7

长期测量这台 VPS 实际拿到了多少资源（CPU 被抢、性能波动、内存回收、磁盘、网络、崩溃），
上报到网站统一分析，和其他人的机器公开对比。说明与排行：https://oversell.zhiwei.show

安装（需要邀请码）:
  curl -fsSL https://oversell.zhiwei.show/agent.py | python3 - --invite 邀请码 --label "商家/套餐/机房"

命令:
  python3 vps_oversell.py status          运行状态、上报状态、是否有新版本
  python3 vps_oversell.py report          这台机器的网页链接和结论
  python3 vps_oversell.py label "商家/套餐/机房"   修改标签
  python3 vps_oversell.py stop            停止监控并移除开机自启
  python3 vps_oversell.py forget          停止监控，并从网站删除这台机器的全部数据
  python3 vps_oversell.py quick           约 1.5 分钟本地快速体检（不上报）
  通用参数: --dir DIR  数据目录（默认 ~/.vps_oversell）

对机器的影响: 每 5 分钟一次约 5 秒的探测（满载 3 秒），每 23 小时一次 60 秒持续满载，低优先级运行；
  每天磁盘写入约 40MB。机器自己很忙时，速度类指标会标记为不计入。
上报的数据: 虚拟化类型、核数、CPU 型号、内存、swap、是否有内存气球、时区、脚本版本；每次探测的测量值；
  崩溃/重启/监控启停事件；持续满载结果；你填的标签。
不上报: 主机名、IP、用户名、进程、任何文件内容。
不会自动升级: 有新版本时 status 会提示，重新执行安装命令即可升级。
"""
import argparse, csv, fcntl, json, mmap, os, random, shutil, signal, socket, statistics as st
import subprocess, sys, time, unicodedata, urllib.error, urllib.request

VERSION = "7"
SERVER = "https://oversell.zhiwei.show"
CRON_TAG = "# vps_oversell"
TEST = os.environ.get("VPSO_TEST") == "1"          # 仅用于开发测试：缩短各种间隔
CPU_SEC, SINGLE_SEC, SUSTAIN_SEC = 3, 1, 60
MIN_IV, MAX_IV, IV_FACTOR = (15, 60, 3) if TEST else (300, 1800, 60)  # 间隔 = 探测耗时 × 60，限制 5~30 分钟
SUSTAIN_FIRST, SUSTAIN_EVERY = (20, 90) if TEST else (3600, 23 * 3600)
COLD_BLOCKS, COLD_BLOCK_MB = 8, 4     # 8 块闲置内存轮流回读，每块约闲置 8 个探测间隔（~40 分钟）
DISK_MB, FSYNC_N = 8, 32
BUSY_LIMIT = 30                       # 探测前本机自身 CPU 占用 > 30% 时，速度类指标不计入
NET_TARGETS = [("1.1.1.1", 443), ("8.8.8.8", 443), ("9.9.9.9", 443)]
NET_TRIES, NET_TIMEOUT = 2, 1.5
BATCH, MAX_BATCHES = 1000, 5                        # 每批最多 1000 条，每轮最多 5 批（补传积压时逐轮消化）
SPOOL_MAX_BYTES, SPOOL_MAX_AGE = 20 << 20, 14 * 86400

# ---------- 工具 ----------
def cpu_times():
    with open("/proc/stat") as f:
        v = list(map(int, f.readline().split()[1:])) + [0] * 8
    user, nice, system, idle, iowait, irq, softirq, steal = v[:8]
    return dict(busy=user + nice + system + irq + softirq, idle=idle + iowait, steal=steal)

def q(xs, p): xs = sorted(xs); return xs[min(len(xs) - 1, int(len(xs) * p))]
def tstr(t=None): return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(t))
def log(msg): print(f"{tstr()} {msg}", flush=True)
def run_out(cmd): return subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
                                        universal_newlines=True).stdout

def fnum(x):
    try: return float(x)
    except (TypeError, ValueError): return None

def meminfo():
    d = {}
    with open("/proc/meminfo") as f:
        for line in f:
            k, v = line.split(":"); d[k] = int(v.split()[0])
    return d

def boot_id():
    try: return open("/proc/sys/kernel/random/boot_id").read().strip()[:8]
    except OSError: return "?"

def boot_epoch(): return time.time() - float(open("/proc/uptime").read().split()[0])
def majflt(): return int(open("/proc/self/stat").read().rsplit(")", 1)[1].split()[9])

def level(v, limits, higher_better=True):
    """limits 从好到差排列，返回 0~3；v 为 None 返回 None。"""
    if v is None: return None
    for i, l in enumerate(limits):
        if (v >= l if higher_better else v <= l): return i
    return 3

def dw(s): return sum(2 if unicodedata.east_asian_width(c) in "WF" else 1 for c in str(s))
def pad(s, w): s = str(s); return s + " " * max(0, w - dw(s))
def pr(x, f="{:.0%}"): return "-" if x is None else f.format(x)

# ---------- 探测 ----------
def _cpu_worker(sec):
    n, end = 0, time.monotonic() + sec
    while time.monotonic() < end:
        x = 0
        for i in range(20_000): x += i * i
        n += 1
    return n

def _cpu_slices(args):
    sec, sl = args; out = []
    for _ in range(int(sec // sl)): out.append(_cpu_worker(sl))
    return out

def _pool_map(fn, arg, n):
    if n == 1: return [fn(arg)]
    import multiprocessing as mp
    with mp.get_context("fork").Pool(n) as pool:
        return pool.map(fn, [arg] * n)

def guest_busy(sec=1.0):
    a = cpu_times(); time.sleep(sec); b = cpu_times()
    tot = sum(b[k] - a[k] for k in a)
    return 100.0 * (b["busy"] - a["busy"]) / tot if tot else 0.0

def probe_cpu():
    """全核满载 CPU_SEC 秒：steal 占比 + 每核算力；多核机器先测 1 秒单核算力，用于判断多核是否缩水。"""
    n = os.cpu_count() or 1; r = {}
    if n > 1: r["single_ops"] = _cpu_worker(SINGLE_SEC) / SINGLE_SEC
    a = cpu_times(); t = time.monotonic()
    units = _pool_map(_cpu_worker, CPU_SEC, n)
    dt = time.monotonic() - t; b = cpu_times()
    busy, steal = b["busy"] - a["busy"], b["steal"] - a["steal"]
    r.update(steal=100.0 * steal / (busy + steal) if busy + steal else 0.0, cpu_ops=sum(units) / n / dt)
    return r

def probe_mem(cold):
    mb = int(max(4, min(32, meminfo()["MemAvailable"] / 1024 / 16)))  # 可用内存少时自动缩小
    n = mb << 20; r = {}
    src = bytearray(os.urandom(1 << 20)) * mb; dst = bytearray(n); dst[:] = src; best = 0
    for _ in range(3):
        t = time.perf_counter(); dst[:] = src; best = max(best, mb / 1024 / (time.perf_counter() - t))
    del src, dst
    r["mem_gbps"] = best
    m = mmap.mmap(-1, n); t = time.perf_counter()
    for i in range(0, n, 4096): m[i] = 1
    r["alloc_us"] = (time.perf_counter() - t) * 1e6 / (n // 4096); m.close()
    if cold is not None:
        # 逐页计时：CPU 被抢只会让个别页变慢；被宿主机换出时大量页都要从宿主机硬盘读回
        f0 = majflt(); lat = []; pc = time.perf_counter
        for i in range(0, len(cold), 4096):
            t = pc(); cold[i]; lat.append(pc() - t)
        if majflt() == f0:  # 有 major fault 是虚拟机自己的 swap，不算宿主机
            r["cold_us"] = st.median(lat) * 1e6
            r["cold_slow"] = sum(1 for x in lat if x > 50e-6) / len(lat) * 100
    return r

def probe_disk(path):
    """固定小文件里 FSYNC_N 次 4K 随机写 + fsync：数据必须真正落到宿主机存储。"""
    if not os.path.exists(path) or os.path.getsize(path) != DISK_MB << 20:
        if shutil.disk_usage(os.path.dirname(path)).free < (DISK_MB * 4) << 20:
            raise RuntimeError("磁盘空间不足")
        with open(path, "wb") as f:
            f.write(os.urandom(DISK_MB << 20)); f.flush(); os.fsync(f.fileno())
    data = os.urandom(4096); lat = []
    fd = os.open(path, os.O_WRONLY)
    try:
        for _ in range(FSYNC_N):
            os.lseek(fd, random.randrange(DISK_MB * 256) * 4096, 0)
            t = time.perf_counter(); os.write(fd, data); os.fsync(fd); lat.append(time.perf_counter() - t)
    finally:
        os.close(fd)
    return dict(fsync_iops=len(lat) / sum(lat), fsync_max_ms=max(lat) * 1000)

def probe_net():
    """到几个任播 DNS 的 TCP 建连耗时和失败数：带宽/出口超售通常表现为晚高峰延迟暴涨、丢包。"""
    ok, fail = [], 0
    for _ in range(NET_TRIES):
        for host, port in NET_TARGETS:
            t = time.perf_counter()
            try:
                socket.create_connection((host, port), timeout=NET_TIMEOUT).close()
                ok.append((time.perf_counter() - t) * 1000)
            except OSError:
                fail += 1
    return dict(net_ms=st.median(ok) if ok else None, net_fail=fail, net_tries=fail + len(ok))

def probe(d, cold=None, disk_name="disk_probe.bin"):
    t0 = time.monotonic(); busy = guest_busy()
    r = dict(guest_busy=busy, excluded=int(busy > BUSY_LIMIT))
    for name, fn in (("CPU", probe_cpu), ("内存", lambda: probe_mem(cold)),
                     ("磁盘", lambda: probe_disk(os.path.join(d, disk_name))), ("网络", probe_net)):
        try: r.update(fn())
        except Exception as e: log(f"{name}探测跳过: {e!r}")
    m = meminfo(); now = time.time()
    r.update(epoch=now, time=tstr(now), boot_id=boot_id(), dur_s=time.monotonic() - t0, load1=os.getloadavg()[0],
             mem_total_mb=m["MemTotal"] // 1024, mem_avail_mb=m["MemAvailable"] // 1024)
    r["interval_s"] = int(min(MAX_IV, max(MIN_IV, r["dur_s"] * IV_FACTOR)))
    return r

def sustained_test():
    """60 秒全核持续满载，每 10 秒一段：看后段相比开头是否被限速（CPU 积分 / 限额）。"""
    n = os.cpu_count() or 1; k = SUSTAIN_SEC // 10
    import multiprocessing as mp
    with mp.get_context("fork").Pool(n) as pool:
        res = pool.map_async(_cpu_slices, [(SUSTAIN_SEC, 10)] * n)
        snaps = [cpu_times()]
        for _ in range(k): time.sleep(10); snaps.append(cpu_times())
        counts = res.get()
    st_ = []
    for a, b in zip(snaps, snaps[1:]):
        busy, steal = b["busy"] - a["busy"], b["steal"] - a["steal"]
        st_.append(100.0 * steal / (busy + steal) if busy + steal else 0.0)
    ops = [sum(c[i] for c in counts) / n / 10 for i in range(k)]
    now = time.time()
    return dict(epoch=now, time=tstr(now), steal_first=st_[0], steal_last=st.mean(st_[-2:]),
                ops_first=ops[0], ops_last=st.mean(ops[-2:]))

# ---------- 重启原因 ----------
SHUTDOWN_MARKS = ("Journal stopped", "Received SIGTERM from PID 1 (systemd-shutdow", "Reached target reboot.target",
                  "Reached target poweroff.target", "Reached target System Reboot", "Reached target System Power Off",
                  "System is rebooting", "System is powering down", "reboot: Restarting system", "reboot: Power down",
                  "systemd-shutdown")

def classify_prev_boot():
    """上一次开机是正常关机还是被直接断电。返回 (类型, 说明)。"""
    if shutil.which("journalctl"):
        out = run_out(["journalctl", "-b", "-1", "-n", "80", "--no-pager", "-q"])
        if out.strip():
            if any(m in out for m in SHUTDOWN_MARKS):
                return "正常重启", "上次开机的日志里有关机流程"
            return "崩溃", "上次开机的日志没有关机流程，像是被直接断电/重置"
    if shutil.which("last"):
        lines = [l for l in run_out(["last", "-x", "-n", "20", "reboot"]).splitlines() if l.startswith("reboot")]
        if len(lines) >= 2:
            return ("崩溃", "last 显示上次开机以 crash 结束") if "crash" in lines[1] else \
                   ("正常重启", "last 显示上次开机正常结束")
    return "未知重启", "没有 journalctl/last 或无权限，无法判断原因"

def machine_info():
    """上报用的机器信息（不含主机名）。"""
    m = meminfo(); virt = ""
    if shutil.which("systemd-detect-virt"):
        virt = run_out(["systemd-detect-virt"]).strip()
    if not virt or virt == "none":
        if os.path.exists("/proc/vz") or os.path.exists("/proc/user_beancounters"): virt = "openvz"
        elif " hypervisor" in open("/proc/cpuinfo").read(): virt = "vm"
        else: virt = virt or "未知"
    model = next((l.split(":", 1)[1].strip() for l in open("/proc/cpuinfo") if l.startswith("model name")), "?")
    return dict(virt=virt, cores=os.cpu_count() or 1, model=model, mem=m["MemTotal"] // 1024,
                swap=m.get("SwapTotal", 0) // 1024, balloon=os.path.isdir("/sys/bus/virtio/drivers/virtio_balloon"),
                tz=time.strftime("%Z"), version=VERSION)

# ---------- 配置 / 状态 ----------
def paths(d):
    p = {k: os.path.join(d, f) for k, f in dict(lock="lock", pid="pid", log="monitor.log", config="config.json",
                                                  state="state.json", spool="spool").items()}
    os.makedirs(p["spool"], exist_ok=True)
    return p

def load_json(path):
    try:
        with open(path) as f: return json.load(f)
    except (OSError, ValueError):
        return {}

def save_json(path, obj, mode=0o600):
    tmp = path + ".tmp"
    fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
    with os.fdopen(fd, "w") as f: json.dump(obj, f, ensure_ascii=False)
    os.chmod(tmp, mode); os.replace(tmp, path)

def parse_label(s):
    parts = [x.strip() for x in str(s or "").split("/")] + ["", ""]
    return dict(provider=parts[0][:40], plan=parts[1][:40], location="/".join(p for p in parts[2:] if p)[:40])

def label_str(c): return " / ".join(x for x in (c.get("provider"), c.get("plan"), c.get("location")) if x)

# ---------- 本地队列：探测结果先写这里，服务端确认收到后才删除 ----------
def spool_put(d, kind, rec):
    rec = dict(rec, k=kind)
    with open(os.path.join(paths(d)["spool"], time.strftime("%Y%m%d") + ".jsonl"), "a") as f:
        f.write(json.dumps(rec, ensure_ascii=False) + "\n")

def spool_files(d):
    sp = paths(d)["spool"]
    return [os.path.join(sp, f) for f in sorted(os.listdir(sp)) if f.endswith(".jsonl")]

def spool_count(d):
    n = 0
    for f in spool_files(d):
        with open(f) as fh: n += sum(1 for _ in fh)
    return n

def spool_trim(d):
    """服务端长期不可用时，丢弃 14 天前或超过 20MB 的最旧数据，防止写满磁盘。"""
    cutoff = time.strftime("%Y%m%d", time.localtime(time.time() - SPOOL_MAX_AGE))
    files = spool_files(d)
    for f in files:
        if os.path.basename(f)[:8] < cutoff: os.remove(f)
    files = spool_files(d)
    while len(files) > 1 and sum(os.path.getsize(f) for f in files) > SPOOL_MAX_BYTES:
        os.remove(files.pop(0))

# ---------- 与服务端通信 ----------
def api(cfg, method, path, body=None, timeout=20):
    headers = {"Content-Type": "application/json", "User-Agent": f"vps-oversell-agent/{VERSION}"}
    if cfg.get("token"): headers["Authorization"] = "Bearer " + cfg["token"]
    data = None if body is None else json.dumps(body, ensure_ascii=False).encode()
    req = urllib.request.Request(cfg.get("server", SERVER) + path, data=data, method=method, headers=headers)
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.status, json.loads(r.read() or b"{}")
    except urllib.error.HTTPError as e:
        try: return e.code, json.loads(e.read() or b"{}")
        except ValueError: return e.code, {"error": f"HTTP {e.code}"}
    except (urllib.error.URLError, OSError, ValueError) as e:
        return 0, {"error": f"连不上服务器: {e}"}

def register(d, cfg, state):
    """用邀请码换机器令牌。返回 (成功, 说明, 是否值得重试)。"""
    body = dict(invite=cfg.get("invite"), provider=cfg.get("provider"), plan=cfg.get("plan"),
                location=cfg.get("location"), meta=machine_info())
    code, r = api(cfg, "POST", "/api/register", body)
    if code == 200 and r.get("token"):
        cfg["token"] = r["token"]; cfg["machine_id"] = r.get("machine_id"); cfg.pop("invite", None)
        save_json(paths(d)["config"], cfg)
        state.update(url=r.get("url"), latest_version=r.get("latest_version"), error=None)
        save_json(paths(d)["state"], state, 0o644)
        return True, f"已注册，网页: {r.get('url')}", False
    msg = r.get("error") or f"HTTP {code}"
    return False, msg, code == 0 or code == 429 or code >= 500

def upload(d, cfg, state):
    """把队列里的数据批量上报。成功的才删；网络问题时保留，下一轮再试。"""
    p = paths(d)
    if not cfg.get("token"):
        if not cfg.get("invite"): return
        ok, msg, _ = register(d, cfg, state)
        if not ok:
            state["error"] = f"注册失败: {msg}"; save_json(p["state"], state, 0o644); return
    batches, sent_meta = 0, False
    for f in spool_files(d):
        with open(f) as fh:
            recs = []
            for line in fh:
                try: recs.append(json.loads(line))
                except ValueError: pass
        i = 0
        while i < len(recs):
            chunk = recs[i:i + BATCH]
            body = dict(probes=[r for r in chunk if r.get("k") == "probe"],
                        events=[r for r in chunk if r.get("k") == "event"],
                        sustained=[r for r in chunk if r.get("k") == "sustained"])
            if not sent_meta: body["meta"] = machine_info()
            code, r = api(cfg, "POST", "/api/ingest", body)
            if code == 200:
                i += len(chunk); sent_meta = True
                state.update(last_ok=time.time(), latest_version=r.get("latest_version"), url=r.get("url"), error=None)
            elif code == 401:
                state["error"] = "令牌无效（这台机器可能已在网站上被删除）。重新注册: 删除 config.json 后带邀请码重新安装"
                save_json(p["state"], state, 0o644); return
            elif code in (400, 413):          # 这批数据本身有问题，丢弃，避免永远卡住
                log(f"上报被拒绝并丢弃 {len(chunk)} 条: {r.get('error')}"); i += len(chunk)
            else:                             # 连不上 / 限流 / 服务端出错：保留剩余数据，下轮再试
                state["error"] = r.get("error") or f"HTTP {code}"
                _rewrite(f, recs[i:]); save_json(p["state"], state, 0o644); return
            batches += 1
            if batches >= MAX_BATCHES and i < len(recs):
                _rewrite(f, recs[i:]); save_json(p["state"], state, 0o644); return
        os.remove(f)
        if batches >= MAX_BATCHES: break
    save_json(p["state"], state, 0o644)

def _rewrite(path, recs):
    tmp = path + ".tmp"
    with open(tmp, "w") as fh:
        for r in recs: fh.write(json.dumps(r, ensure_ascii=False) + "\n")
    os.replace(tmp, path)

# ---------- v6 本地历史数据：首次运行时放进队列补传 ----------
def migrate_v6(d):
    """返回 v6 最后一条探测的 boot_id（用于判断升级期间是否重启过）。"""
    last_boot, cutoff = None, time.time() - 30 * 86400
    for name, kind in (("probe.csv", "probe"), ("events.csv", "event"), ("sustained.csv", "sustained")):
        f = os.path.join(d, name)
        if not os.path.exists(f): continue
        n = 0
        with open(f) as fh:
            for r in csv.DictReader(fh):
                try: t = float(r.get("epoch") or 0)
                except ValueError: continue
                if t < cutoff: continue
                if kind == "probe": last_boot = r.get("boot_id") or last_boot
                spool_put(d, kind, {k: v for k, v in r.items() if v not in ("", None)}); n += 1
        os.rename(f, f + ".uploaded-v6")
        log(f"已把 v6 的 {name} 中 {n} 条历史数据放入上报队列")
    return last_boot

# ---------- 开机自启 ----------
def persist(d, cfg):
    me = os.path.join(d, "vps_oversell.py")
    try:
        if os.path.isfile(sys.argv[0]):
            if os.path.abspath(sys.argv[0]) != me: shutil.copyfile(sys.argv[0], me)
        else:  # curl | python3 - 运行时磁盘上没有脚本，下载一份供开机启动
            urllib.request.urlretrieve(cfg.get("server", SERVER) + "/agent.py", me)
    except Exception as e:
        return f"未能保存脚本副本（{e}），重启后需手动启动"
    if not shutil.which("crontab"):
        return "系统没有 crontab，重启后需手动启动"
    line = f"@reboot sleep 30 && {sys.executable} {me} --dir {d} >/dev/null 2>&1 {CRON_TAG}"
    lines = [l for l in run_out(["crontab", "-l"]).splitlines() if CRON_TAG not in l] + [line]
    r = subprocess.run(["crontab", "-"], input="\n".join(lines) + "\n", universal_newlines=True)
    return "已加入开机自启（crontab @reboot）" if r.returncode == 0 else "写入 crontab 失败，重启后需手动启动"

def unpersist():
    if not shutil.which("crontab"): return
    cur = run_out(["crontab", "-l"]).splitlines()
    if any(CRON_TAG in l for l in cur):
        lines = [l for l in cur if CRON_TAG not in l]
        subprocess.run(["crontab", "-"], input="\n".join(lines) + ("\n" if lines else ""), universal_newlines=True)
        print("已移除开机自启")

# ---------- 常驻 ----------
def monitor_loop(d):
    p = paths(d); lockf = open(p["lock"], "a")
    try: fcntl.flock(lockf, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError: print("监控已在运行。"); return 1
    main = os.getpid()
    lockf.truncate(0); lockf.write(f"{main} {VERSION}"); lockf.flush()   # pid 文件丢了也能从锁文件找到进程
    with open(p["pid"], "w") as f: f.write(f"{main} {VERSION}")
    def bye(*_):
        if os.getpid() != main: os._exit(0)  # 测试用的子进程被结束时不能执行主进程的清理
        log("收到停止信号，退出"); spool_put(d, "event", dict(epoch=time.time(), time=tstr(), kind="监控停止"))
        try: os.remove(p["pid"])
        except OSError: pass
        sys.exit(0)
    signal.signal(signal.SIGTERM, bye); signal.signal(signal.SIGINT, bye)
    try: os.nice(10)
    except OSError: pass

    cfg, state = load_json(p["config"]), load_json(p["state"])
    v6_boot = migrate_v6(d)
    last_boot = state.get("last_boot") or v6_boot
    if last_boot and last_boot != boot_id():
        kind, detail = classify_prev_boot(); t = boot_epoch()
        spool_put(d, "event", dict(epoch=t, time=tstr(t), kind=kind, detail=detail))
        log(f"检测到上次监控后系统重启过: {kind}（{detail}）")
    spool_put(d, "event", dict(epoch=time.time(), time=tstr(), kind="监控启动"))
    cold = []
    for _ in range(COLD_BLOCKS):  # 随机内容，避免被 KSM 合并或当成零页
        m = mmap.mmap(-1, COLD_BLOCK_MB << 20); m[:] = os.urandom(COLD_BLOCK_MB << 20); cold.append(m)
    log(f"监控启动 v{VERSION} pid={main} boot_id={boot_id()} 服务器={cfg.get('server', SERVER)}")

    rnd, next_sus = 0, time.time() + SUSTAIN_FIRST
    while True:
        if time.time() >= next_sus:
            try:
                s = sustained_test(); spool_put(d, "sustained", s)
                log(f"持续满载测试: 后段算力为开头的 {s['ops_last'] / s['ops_first']:.0%}")
            except Exception as ex:
                log(f"持续满载测试跳过: {ex!r}")
            next_sus = time.time() + SUSTAIN_EVERY
        t0 = time.time()
        # 第 rnd 轮回读第 rnd%8 块；它上次被读是 8 轮之前，所以每块都闲置了约 8 个间隔
        r = probe(d, cold[rnd % COLD_BLOCKS] if rnd >= COLD_BLOCKS else None); rnd += 1
        spool_put(d, "probe", {k: v for k, v in r.items() if v is not None})
        state["last_boot"], state["last_probe"] = r["boot_id"], r["epoch"]
        try:
            cfg = load_json(p["config"])     # label / forget 可能改了配置
            upload(d, cfg, state); spool_trim(d)
        except Exception as ex:
            log(f"上报出错: {ex!r}")
        save_json(p["state"], state, 0o644)
        time.sleep(max(1, t0 + r["interval_s"] - time.time()))

def running(d):
    p = paths(d)
    try:
        with open(p["lock"], "a") as f:
            fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB); fcntl.flock(f, fcntl.LOCK_UN)
        return None, None
    except BlockingIOError:
        for f in (p["pid"], p["lock"]):
            try:
                parts = open(f).read().split()
                return int(parts[0]), (parts[1] if len(parts) > 1 else None)
            except (OSError, ValueError, IndexError):
                continue
        return -1, None

def start(d, a):
    p = paths(d); cfg = load_json(p["config"]); state = load_json(p["state"])
    if a.server: cfg["server"] = a.server.rstrip("/")
    cfg.setdefault("server", SERVER)
    if a.label: cfg.update(parse_label(a.label))
    if a.invite and not cfg.get("token"): cfg["invite"] = a.invite.strip()
    if not cfg.get("token") and not cfg.get("invite"):
        print("首次使用需要邀请码和标签:\n  curl -fsSL %s/agent.py | python3 - --invite 邀请码 --label \"商家/套餐/机房\"" % cfg["server"])
        return 1
    if not cfg.get("provider"):
        print('还没有填标签，请加上 --label "商家/套餐/机房"，例如 --label "RackNerd/1C1G/洛杉矶"'); return 1
    save_json(p["config"], cfg)
    if not cfg.get("token"):
        ok, msg, retry = register(d, cfg, state)
        if ok: print(msg)
        elif retry: print(f"暂时无法注册（{msg}），监控照常启动，会在后台自动重试注册。")
        else: print(f"注册失败: {msg}"); return 1

    pid, ver = running(d)
    if pid:
        if ver == VERSION: print("监控已在后台运行。"); return status(d, a)
        print(f"检测到旧版本监控在运行 (pid {pid})，自动升级到 v{VERSION} …")
        if stop(d, a, keep_cron=True) != 0: return 1
    msg = persist(d, cfg)
    sys.stdout.flush(); sys.stderr.flush()
    if os.fork() > 0:
        for _ in range(30):
            time.sleep(0.1); pid, _ = running(d)
            if pid: break
        if not pid: print(f"启动失败，请查看 {p['log']}"); return 1
        me = os.path.join(d, "vps_oversell.py"); url = load_json(p["state"]).get("url")
        print(f"已在后台启动超售监控 v{VERSION} (pid {pid})，{msg}")
        print(f"  标签: {label_str(cfg)}")
        if url: print(f"  网页: {url}（至少 1 天后出结论，2~3 天更准）")
        print(f"  状态: python3 {me} status\n  停止: python3 {me} stop")
        return 0
    os.setsid()
    if os.fork() > 0: os._exit(0)
    os.chdir(d); os.umask(0o022)
    fd = os.open(p["log"], os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o644)
    devnull = os.open(os.devnull, os.O_RDONLY)
    os.dup2(devnull, 0); os.dup2(fd, 1); os.dup2(fd, 2)
    try: monitor_loop(d)
    finally: os._exit(0)

def stop(d, a=None, keep_cron=False):
    if not keep_cron: unpersist()
    pid, _ = running(d)
    if not pid: print("监控没有在运行。"); return 0
    if pid < 0: print("监控在运行但找不到 pid 文件。"); return 1
    os.kill(pid, signal.SIGTERM)
    for _ in range(50):
        if not running(d)[0]: print(f"已停止 (pid {pid})"); return 0
        time.sleep(0.1)
    print(f"已发送停止信号给 pid {pid}，但它还没退出"); return 1

def status(d, a=None):
    p = paths(d); cfg, s = load_json(p["config"]), load_json(p["state"]); pid, ver = running(d)
    print(f"监控: {'运行中 (pid %s, v%s)' % (pid, ver or '旧版') if pid else '未运行'}   数据目录: {d}")
    print(f"标签: {label_str(cfg) or '-'}   服务器: {cfg.get('server', SERVER)}")
    print(f"注册: {'已注册' if cfg.get('token') else '未注册（等待重试）' if cfg.get('invite') else '未注册'}"
          + (f"   网页: {s['url']}" if s.get("url") else ""))
    lp, lo = s.get("last_probe"), s.get("last_ok")
    print(f"最近探测: {tstr(lp) if lp else '-'}   最近上报成功: {tstr(lo) if lo else '-'}   待上报: {spool_count(d)} 条")
    if s.get("error"): print(f"上次上报问题: {s['error']}")
    lv = s.get("latest_version")
    if lv and lv != VERSION:
        print(f"有新版本 v{lv}，升级: curl -fsSL {cfg.get('server', SERVER)}/agent.py | python3 -")
    return 0

def report(d, a=None):
    cfg = load_json(paths(d)["config"])
    if not cfg.get("token"): print("还没有注册，先启动监控。"); return 1
    code, r = api(cfg, "GET", "/api/machine/summary")
    if code != 200: print(f"获取失败: {r.get('error')}"); return 1
    print(f"{r.get('label')}\n网页: {r['url']}")
    if r.get("overall"):
        cg = r.get("cpu_got") or [None, None]
        print(f"结论: {r['overall']}" + (f"（主要问题: {'、'.join(r['worst'])}）" if r.get("worst") else "")
              + f"  可靠性: {r['reliability']}  超售分: {r['score']}  数据: {r['days']} 天"
              + (f"  CPU 实际拿到: 平时 {cg[0]:.0f}%" if cg[0] is not None else ""))
    else:
        print("数据还不够，暂时没有结论。")
    return 0

def label_cmd(d, a):
    p = paths(d); cfg = load_json(p["config"])
    if not a.text: print(f"当前标签: {label_str(cfg) or '-'}\n修改: label \"商家/套餐/机房\""); return 0
    new = parse_label(a.text)
    if not new["provider"]: print("至少要填商家"); return 1
    if cfg.get("token"):
        code, r = api(cfg, "PATCH", "/api/machine", new)
        if code != 200: print(f"修改失败: {r.get('error')}"); return 1
    cfg.update(new); save_json(p["config"], cfg)
    print(f"标签已改为: {label_str(cfg)}"); return 0

def forget(d, a):
    p = paths(d); cfg = load_json(p["config"])
    if not a.yes:
        if not sys.stdin.isatty(): print("确认删除请加 --yes"); return 1
        if input("将停止监控，并从网站删除这台机器的全部数据（不可恢复）。输入 yes 确认: ").strip() != "yes":
            print("已取消"); return 1
    stop(d, a)
    if cfg.get("token"):
        code, r = api(cfg, "DELETE", "/api/machine")
        if code not in (200, 401): print(f"网站上的数据删除失败: {r.get('error')}，请稍后重试 forget"); return 1
    for f in spool_files(d): os.remove(f)
    for k in ("config", "state"):
        try: os.remove(p[k])
        except OSError: pass
    print("已删除网站上的数据和本地的令牌、队列。"); return 0

def quick(d, a=None):
    print("快速体检: 连续探测 12 次（约 1.5 分钟，本地运行，不上报）…", flush=True)
    rows = []
    try:
        for k in range(12):
            r = probe(d, None, "disk_quick.bin"); rows.append(r)
            print(f"  {k + 1:>2}/12  CPU 被抢 {r.get('steal', 0):.0f}%  内存 {pr(r.get('mem_gbps'), '{:.1f}GB/s')}  "
                  f"同步写 {pr(r.get('fsync_iops'), '{:.0f}IOPS')}  网络 {pr(r.get('net_ms'), '{:.0f}ms')}", flush=True)
            if k < 11: time.sleep(3)
    finally:
        try: os.remove(os.path.join(d, "disk_quick.bin"))
        except OSError: pass
    got = st.median(100 - r["steal"] for r in rows if r.get("steal") is not None)
    lv = "不超售" if got >= 95 else "轻度超售" if got >= 85 else "明显超售" if got >= 70 else "严重超售"
    print(f"\nCPU 实际拿到的算力约 {got:.0f}% → 按 CPU 看属于「{lv}」。")
    print("这只是快照。完整评估（波动、内存回收、可靠性、按时段）需要常驻监控 1~3 天，结果在网站上查看。")
    return 0

if __name__ == "__main__":
    ap = argparse.ArgumentParser(description="VPS 超售监控采集脚本（默认后台常驻并上报）")
    ap.add_argument("cmd", nargs="?", default="start",
                    choices=["start", "run", "status", "report", "stop", "label", "forget", "quick"])
    ap.add_argument("text", nargs="?", help="label 命令的新标签，格式 商家/套餐/机房")
    ap.add_argument("--invite", help="邀请码（首次注册用）")
    ap.add_argument("--label", help='标签，格式 "商家/套餐/机房"')
    ap.add_argument("--server", help=argparse.SUPPRESS)
    ap.add_argument("--yes", action="store_true", help="forget 时不再询问")
    ap.add_argument("--dir", default=os.path.expanduser("~/.vps_oversell"), help="数据目录")
    a = ap.parse_args()
    a.dir = os.path.abspath(a.dir); os.makedirs(a.dir, exist_ok=True)
    fn = {"start": start, "run": lambda d, a: monitor_loop(d), "status": status, "report": report, "stop": stop,
          "label": label_cmd, "forget": forget, "quick": quick}[a.cmd]
    sys.exit(fn(a.dir, a) or 0)
