netdiag.py 6.33 KB
# -*- coding: utf-8 -*-
"""网络诊断(只读):对 DMS 各域名和云端逐个做 DNS → TCP → TLS → HTTP GET,每个目标测 diag_rounds 轮,
统计成功率,定位是哪一层、多大比例出问题。

  * DNS 失败          本机解析不到(专网 DNS / hosts)
  * TCP 失败          端口不通(防火墙 / 路由)
  * TLS 失败          握手被拒 / 握手时被对端断开(门店实测 auth-api 会间歇性这样)
  * HTTP 网络错误     连上了但服务端不回应就断开(网关/WAF 拦截、负载均衡后有坏节点)
不发送账号密码,不登录。配置了代理时 DNS/TCP/TLS 三项是直连结果,仅供参考。
"""
import logging
import socket
import ssl
import time
import urllib.parse

from ..connectors.gtmc.client import Client

log = logging.getLogger("edge")


def _targets(cfg):
    out = [("DMS 首页", cfg.dms_url, cfg.verify_ssl), ("IAM 登录", cfg.iam_base + "/", cfg.verify_ssl),
           ("auth-api 换 token", cfg.auth_api + "/", cfg.verify_ssl),
           ("parts-api 业务接口", cfg.parts_api + "/", cfg.verify_ssl)]
    if cfg.cloud_url:
        out.append(("云端", cfg.cloud_url + "/healthz", True))
    return out


def _tls_error(e):
    if isinstance(e, ssl.SSLCertVerificationError):
        return "证书校验失败 %s" % (e.verify_message or e)
    if isinstance(e, ssl.SSLError):
        return "失败 %r" % e
    if isinstance(e, socket.timeout):
        return "握手超时"
    # Windows 上握手中途被对端关掉/重置时,ssl 会抛出带残留 errno 的 OSError(如 FileNotFoundError(2))
    return "握手时连接被对端断开(%r)" % e


def _probe_socket(url, verify, ca_file, timeout):
    p = urllib.parse.urlparse(url)
    host, port = p.hostname, p.port or (443 if p.scheme == "https" else 80)
    row = {"host": "%s:%s" % (host, port), "dns": "", "tcp": "", "tls": ""}
    try:
        t0 = time.time()
        addrs = sorted({a[4][0] for a in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)})
        row["dns"] = "%s(%.0fms)" % (",".join(addrs), (time.time() - t0) * 1000)
    except Exception as e:  # noqa: BLE001
        row["dns"] = "失败 %r" % e
        return row, False
    try:
        t0 = time.time()
        sock = socket.create_connection((host, port), timeout=timeout)
        row["tcp"] = "通(%.0fms)" % ((time.time() - t0) * 1000)
    except Exception as e:  # noqa: BLE001
        row["tcp"] = "失败 %r" % e
        return row, False
    try:
        if p.scheme != "https":
            row["tls"] = "-(http)"
            return row, True
        ctx = ssl.create_default_context()
        if verify and ca_file:
            try:
                ctx.load_verify_locations(ca_file)
            except Exception:  # noqa: BLE001
                pass
        if not verify:
            ctx.check_hostname = False
            ctx.verify_mode = ssl.CERT_NONE
        t0 = time.time()
        with ctx.wrap_socket(sock, server_hostname=host) as ss:
            row["tls"] = "%s %s(%.0fms%s)" % (ss.version(), ss.cipher()[0], (time.time() - t0) * 1000,
                                             ",证书已校验" if verify else ",未校验证书")
        return row, True
    except Exception as e:  # noqa: BLE001
        row["tls"] = _tls_error(e)
        return row, False
    finally:
        try:
            sock.close()
        except Exception:  # noqa: BLE001
            pass


def _one_round(client, cfg, url, verify):
    row, ok = _probe_socket(url, verify, cfg.ca_file, min(cfg.timeout, 15))
    if ok:
        r = client.request("GET", url, cookies=False, retries=0, timeout=min(cfg.timeout, 15))
        if r.status:
            row["http"] = "HTTP %d(%.2fs,%dB,Server=%s)" % (r.status, r.elapsed, len(r.body), r.header("Server") or "-")
        else:
            row["http"] = "网络错误 %s" % r.error
            ok = False
    else:
        row["http"] = "-"
    return row, ok


def _short_fail(row):
    for k, label in (("dns", "DNS"), ("tcp", "TCP"), ("tls", "TLS"), ("http", "HTTP")):
        v = row.get(k) or ""
        if v.startswith("失败") or v.startswith("握手") or v.startswith("证书") or v.startswith("网络错误"):
            return "%s %s" % (label, v[:120])
    return "未知"


def run(cfg, client=None, rounds=None):
    """每个目标测 rounds 轮。返回 [{name, host, dns, tcp, tls, http, success, failures, ok}],同时写日志。"""
    client = client or Client(cfg)
    rounds = max(1, int(rounds or getattr(cfg, "diag_rounds", 1) or 1))
    rows = []
    old_penalize = getattr(client, "penalize", True)
    client.penalize = False              # 诊断本来就是在网络出问题时做的,探测失败不让全局限速器降速 / 暂停
    try:
        return _run(cfg, client, rounds, rows)
    finally:
        client.penalize = old_penalize


def _run(cfg, client, rounds, rows):
    for name, url, verify in _targets(cfg):
        first_ok, first_fail, fails, good = None, None, [], 0
        for _ in range(rounds):
            row, ok = _one_round(client, cfg, url, verify)
            if ok:
                good += 1
                first_ok = first_ok or row
            else:
                first_fail = first_fail or row
                fails.append(_short_fail(row))
                if row["dns"].startswith("失败") or row["tcp"].startswith("失败"):
                    break                       # 根本不通,不用再测
        tested = good + len(fails)
        out = dict(first_ok or first_fail)
        out.update({"name": name, "success": "%d/%d" % (good, tested), "ok": good == tested,
                    "failures": ";".join(sorted(set(fails), key=fails.index))})
        rows.append(out)
        log.log(logging.INFO if out["ok"] else logging.ERROR,
                "[网络诊断] %s %s:成功 %s DNS %s / TCP %s / TLS %s / %s%s", name, out["host"], out["success"],
                out["dns"], out["tcp"], out["tls"], out["http"], (" 失败原因:" + out["failures"]) if fails else "")
        if 0 < good < tested:
            log.error("[网络诊断] %s 时好时坏(%s 成功),属于对方服务/网络不稳定,程序已对登录换 token 做了重试", name, out["success"])
    if cfg.proxy or cfg.use_system_proxy:
        log.info("[网络诊断] 注意:配置了代理,DNS/TCP/TLS 是直连结果,HTTP 一栏走代理")
    return rows