setup.py 19.9 KB
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 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
# -*- coding: utf-8 -*-
"""安装向导 / 查看状态(install.bat、status.bat 调用;输出中文由 Python 负责,bat 里只有英文)。

本机只需要填云端地址和设备令牌;DMS 账号密码等全部在企业后台配置、由云端下发。
"""
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import time

from .. import __version__, connectors
from ..infra.config import (ENV_NAMES, ENVS, ConfigError, norm_env, norm_instance, read_instance, service_name,
                             service_name_for, token_conflicts)

BANNER = "=" * 60


def _say(text=""):
    try:
        print(text, flush=True)
    except UnicodeEncodeError:
        print(text.encode("gbk", "replace").decode("gbk"), flush=True)


def _ask(prompt, default=""):
    try:
        v = input("%s%s:" % (prompt, "(直接回车 = %s)" % default if default else "")).strip()
    except EOFError:
        v = ""
    return v or default


# ---------------------------------------------------------------- config.ini 原地修改(保留注释)
def read_ini_value(path, section, key):
    sec = None
    with open(path, encoding="utf-8-sig") as f:
        for line in f:
            m = re.match(r"^\s*\[([^\]]+)\]\s*$", line)
            if m:
                sec = m.group(1).strip()
                continue
            if sec == section:
                m = re.match(r"^\s*%s\s*=\s*(.*)$" % re.escape(key), line)
                if m:
                    return m.group(1).strip()
    return ""


def set_ini_value(path, section, key, value):
    with open(path, encoding="utf-8-sig") as f:
        lines = f.read().splitlines()
    sec, sec_line, done = None, None, False
    for i, line in enumerate(lines):
        m = re.match(r"^\s*\[([^\]]+)\]\s*$", line)
        if m:
            if sec == section and not done:
                break
            sec = m.group(1).strip()
            if sec == section:
                sec_line = i
            continue
        if sec == section and re.match(r"^\s*%s\s*=" % re.escape(key), line):
            lines[i] = "%s = %s" % (key, value)
            done = True
            break
    if not done:
        if sec_line is None:
            lines += ["", "[%s]" % section, "%s = %s" % (key, value)]
        else:
            lines.insert(sec_line + 1, "%s = %s" % (key, value))
    with open(path, "w", encoding="utf-8", newline="") as f:      # 不让文本模式再把 CRLF 转一次(否则每改一次空行翻倍)
        f.write("\r\n".join(lines) + "\r\n")


def _rename_section(path, old, new):
    """把 [old] 段头原地改名为 [new](段里的内容、注释都不动)。改了返回 True。"""
    with open(path, encoding="utf-8-sig") as f:
        lines = f.read().splitlines()
    hit = False
    for i, line in enumerate(lines):
        if re.match(r"^\s*\[%s\]\s*$" % re.escape(old), line):
            lines[i], hit = "[%s]" % new, True
    if hit:
        with open(path, "w", encoding="utf-8", newline="") as f:
            f.write("\r\n".join(lines) + "\r\n")
    return hit


def _sections(path):
    with open(path, encoding="utf-8-sig") as f:
        return [m.group(1).strip() for m in re.finditer(r"^\s*\[([^\]]+)\]\s*$", f.read(), re.M)]


# ---------------------------------------------------------------- 老格式 config.ini → 新格式
_KV = re.compile(r"^\s*(#\s*)?([A-Za-z_][\w.]*)\s*=\s*(.*?)\s*$")


def _norm_url(u):
    return (u or "").strip().rstrip("/").lower()


def is_legacy(path):
    """老格式:没有 [cloud] env,也没有任何 [cloud.xxx] 环境段(只有 [cloud] url / edge_token,靠注释切换环境)。"""
    return not read_ini_value(path, "cloud", "env") and not any(s.startswith("cloud.") for s in _sections(path))


def _parse_legacy(path):
    """读老 config.ini:生效的 (段, 键, 值) 列表 + [cloud] 里生效 / 被注释的 url、edge_token。"""
    active, cloud = [], {"url": [], "edge_token": [], "#url": [], "#edge_token": []}
    sec = None
    with open(path, encoding="utf-8-sig") as f:
        for line in f:
            m = re.match(r"^\s*\[([^\]]+)\]\s*$", line)
            if m:
                sec = m.group(1).strip()
                continue
            m = _KV.match(line)
            if not m or sec is None:
                continue
            commented, key, val = bool(m.group(1)), m.group(2), m.group(3)
            if sec == "cloud" and key in ("url", "edge_token"):
                if val:
                    cloud[("#" if commented else "") + key].append(val)
            elif not commented:
                active.append((sec, key, val))
    return active, cloud


def migrate_legacy(config_path, now=None):
    """安装向导里把老格式 config.ini 转成新格式([cloud] env + [cloud.dev/sit/uat/prd] 各一段)。

    原文件先备份为 config.ini.bak-<时间>(永久保留,不删);新文件从 config.example.ini 生成,
    老文件里改过的其它值([local] 等)原样写回;生效的 / 被注释掉的 url + edge_token 按地址对上模板里预设的环境段。
    不是老格式(或缺模板)返回 None;否则返回 {"backup", "env", "placed": {env: url}, "unmatched": (url, token) 或 None}。
    """
    root = os.path.dirname(os.path.abspath(config_path))
    example = os.path.join(root, "config.example.ini")
    if not os.path.exists(config_path) or not os.path.exists(example) or not is_legacy(config_path):
        return None
    active, cloud = _parse_legacy(config_path)
    stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(now))
    backup = "%s.bak-%s" % (config_path, stamp)
    shutil.copy2(config_path, backup)
    shutil.copy(example, config_path)
    presets = {_norm_url(read_ini_value(example, "cloud." + e, "url")): e for e in ENVS
               if read_ini_value(example, "cloud." + e, "url")}
    for sec, key, val in active:                                    # 改过的其它值写回(与模板默认值相同的不写)
        if (sec, key) != ("cloud", "env") and read_ini_value(config_path, sec, key) != val:
            set_ini_value(config_path, sec, key, val)
    placed, unmatched, env = {}, None, ""
    # 被注释掉的那几组:第 n 个被注释的 url 配第 n 个被注释的 edge_token
    pairs = [(u, (cloud["#edge_token"][i] if i < len(cloud["#edge_token"]) else ""), False)
             for i, u in enumerate(cloud["#url"])]
    if cloud["url"]:
        pairs.append((cloud["url"][-1], cloud["edge_token"][-1] if cloud["edge_token"] else "", True))
    for url, tok, is_active in pairs:
        e = presets.get(_norm_url(url))
        if not e:
            if is_active:
                unmatched = (url.rstrip("/"), tok)
            continue
        set_ini_value(config_path, "cloud." + e, "url", url.rstrip("/"))
        if tok:
            set_ini_value(config_path, "cloud." + e, "edge_token", tok)
        placed[e] = url.rstrip("/")
        if is_active:
            env = e
    set_ini_value(config_path, "cloud", "env", env)            # 生效的地址对不上预设环境时先空着,由向导询问
    return {"backup": backup, "env": env, "placed": placed, "unmatched": unmatched}


# ---------------------------------------------------------------- 环境检查
def _dotnet35():
    if os.name != "nt":
        return False
    try:
        import winreg
        k = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5")
        return winreg.QueryValueEx(k, "Install")[0] == 1
    except OSError:
        return False


def check_env(root):
    ok = True
    _say("系统:%s,Python %s,取数端 %s" % (platform.platform(), sys.version.split()[0], __version__))
    _say("[通过] 嵌入式 Python 可以运行(说明 KB2999226 通用 C 运行库已安装)")
    if _dotnet35():
        _say("[通过] .NET Framework 3.5 已安装(Windows 服务程序需要)")
    else:
        ok = False
        _say("[失败] 没有检测到 .NET Framework 3.5:控制面板 → 程序和功能 → 打开或关闭 Windows 功能 → 勾选 .NET Framework 3.5.1")
    exe = service_name_for(root) + ".exe"
    if os.path.exists(os.path.join(root, exe)):
        _say("[通过] 服务程序 %s 存在" % exe)
    else:
        ok = False
        _say("[失败] 找不到 %s,请确认压缩包解压完整" % exe)
    chrome = os.path.join(root, "browser", "chrome-win", "chrome.exe")
    _say("[%s] 截图用的便携 Chromium:%s" % ("通过" if os.path.exists(chrome) else "注意", chrome))
    return ok


# ---------------------------------------------------------------- 向导
def write_service_xml(root, instance):
    """命名实例的 WinSW 配置:拿 service/StoreEdge.xml 换掉 id / name,写成 <服务名>.xml(和 <服务名>.exe 同名)。"""
    svc = service_name(instance)
    with open(os.path.join(root, "service", "StoreEdge.xml"), encoding="utf-8") as f:
        xml = f.read()
    xml = re.sub(r"<id>[^<]*</id>", "<id>%s</id>" % svc, xml, count=1)
    xml = re.sub(r"<name>[^<]*</name>", "<name>%s (门店取数端·%s)</name>" % (svc, instance), xml, count=1)
    path = os.path.join(root, svc + ".xml")
    with open(path, "w", encoding="utf-8") as f:
        f.write(xml)
    return path


def _bind_instance(config_path, instance):
    """install.bat <实例名> 调用:把实例名写进 config.ini,并生成该实例的服务 xml。返回 False = 不能继续。"""
    root = os.path.dirname(os.path.abspath(config_path))
    try:
        instance = norm_instance(instance)
    except ConfigError as e:
        _say("[失败] %s" % e)
        return False
    cur = read_instance(root)
    if cur and cur != instance:
        _say("[失败] 这个目录已经是实例「%s」,不能改成「%s」(换实例请装到新目录:install.bat %s)" % (cur, instance, instance))
        return False
    if instance and cur != instance:
        set_ini_value(config_path, "local", "instance", instance)
    if instance:
        _say("[通过] 实例 %s:服务名 %s,生成 %s" % (instance, service_name(instance),
                                               os.path.basename(write_service_xml(root, instance))))
    return True


def setup(config_path, instance=None):
    root = os.path.dirname(os.path.abspath(config_path))
    _say(BANNER)
    from ..core.updater import build_info
    _say(" 门店取数端 %s %s 安装向导" % (__version__, build_info()))
    _say(BANNER)
    fresh = not os.path.exists(config_path)
    mig = None
    if fresh:
        shutil.copy(os.path.join(root, "config.example.ini"), config_path)
        _say("已从模板生成 config.ini")
    else:
        mig = migrate_legacy(config_path)
        if mig:
            _say("已把老格式的 config.ini 转成新格式([cloud] env 一行切换 %s),原文件备份为 %s"
                 % (" / ".join(ENVS), os.path.basename(mig["backup"])))
            for e, u in sorted(mig["placed"].items()):
                _say("        %s %s 环境:%s" % (e, ENV_NAMES.get(e, ""), u))
        if "cloud.test" in _sections(config_path) and "cloud.sit" not in _sections(config_path):
            _rename_section(config_path, "cloud.test", "cloud.sit")        # 旧名字 test 统一改叫 sit(内容不动)
            _say("已把 config.ini 里的 [cloud.test] 改名为 [cloud.sit](测试环境改叫 sit)")
    if instance is not None and not _bind_instance(config_path, instance):
        return 3
    inst = norm_env(read_instance(root))
    env_ok = check_env(root)
    env = norm_env(read_ini_value(config_path, "cloud", "env"))
    if env or any(s.startswith("cloud.") for s in _sections(config_path)):
        default_env = inst if (fresh and inst in ENVS) else (env if env in ENVS else "prd")
        while True:
            env = norm_env(_ask("连哪套环境?%s" % " / ".join("%s %s" % (e, ENV_NAMES[e]) for e in ENVS), default_env))
            if env in ENVS:
                break
            _say("只能填 %s" % "、".join(ENVS))
        set_ini_value(config_path, "cloud", "env", env)
        sec = "cloud." + env
        if mig and mig["unmatched"]:          # 老配置里生效的地址对不上任何预设环境:放进刚选的这套环境
            set_ini_value(config_path, sec, "url", mig["unmatched"][0])
            if mig["unmatched"][1]:
                set_ini_value(config_path, sec, "edge_token", mig["unmatched"][1])
    else:                                  # 老格式且没有模板可迁移:只有 [cloud] url / edge_token
        sec = "cloud"
    url = _ask("云端地址(如 https://restock.example.com)",
               read_ini_value(config_path, sec, "url") or read_ini_value(config_path, "cloud", "url"))
    if url:
        set_ini_value(config_path, sec, "url", url.rstrip("/"))
    tok = read_ini_value(config_path, sec, "edge_token") or read_ini_value(config_path, "cloud", "edge_token")
    hint = (tok[:10] + "…") if tok else ""
    new_tok = _ask("设备令牌(企业后台「取数端 → 设备」里生成,以 edg_ 开头)", hint)
    eff_url = (url or read_ini_value(config_path, sec, "url") or read_ini_value(config_path, "cloud", "url"))
    clash = token_conflicts(root, eff_url, new_tok if (new_tok and new_tok != hint) else tok)
    if clash:
        _say("[失败] 这个设备令牌已经被本机另一个取数端在用:%s" % "、".join(clash))
        _say("       两个取数端不能共用一个令牌(会互相抢任务):请在这套环境的企业后台再新建一个取数端,用新令牌")
        return 3
    if new_tok and new_tok != hint:
        set_ini_value(config_path, sec, "edge_token", new_tok)
    elif tok and not read_ini_value(config_path, sec, "edge_token"):
        set_ini_value(config_path, sec, "edge_token", tok)
    _say(BANNER)
    _say("连接测试……")
    rc = _connect_test(config_path)
    _say(BANNER)
    return 0 if (env_ok and rc == 0) else 2


def _connect_test(config_path):
    from ..core.cloud import CloudClient, CloudError
    from ..core.remote import RemoteConfig
    from ..core.sessions import SessionManager
    from ..infra.config import ConfigError, load_local
    try:
        local = load_local(config_path)
        cc = CloudClient(local)
        cc.heartbeat({"version": __version__, "state": "setup", "host": platform.node()})
        _say("[通过] 已连上云端 %s,设备令牌有效" % local.cloud_url)
        remote = RemoteConfig(local, cc)
        remote.refresh()
    except (ConfigError, CloudError) as e:
        _say("[失败] %s" % e)
        return 2
    d = remote.data or {}
    _say("[通过] 已拉取云端配置:门店「%s」(%s),配置版本 %s" % (
        (d.get("store") or {}).get("name"), (d.get("store") or {}).get("code"), d.get("version")))
    accounts = d.get("dms") or []
    if not accounts:
        _say("[注意] 云端还没有配置 DMS 账号:请到企业后台「取数端 → 厂商账号」填写,保存后取数端自动拉取")
        return 0
    for a in accounts:
        _say("        厂商账号:%s / %s" % (connectors.name(a.get("dms")), a.get("username")))
    if _ask("现在测试登录 DMS 吗?输入 Y 测试,直接回车跳过", "").upper() == "Y":
        try:
            cfg, sess = SessionManager(remote).get()
            how = sess.ensure_valid()
            _say("[通过] DMS 登录%s" % ("正常(复用已有登录)" if how == "reused" else "成功"))
        except Exception as e:  # noqa: BLE001
            _say("[失败] DMS 登录失败:%s(账号密码不对请在企业后台修改)" % e)
            return 2
    return 0


def status(config_path):
    root = os.path.dirname(os.path.abspath(config_path))
    _say(BANNER)
    _say(" 门店取数端状态")
    _say(BANNER)
    svc = service_name_for(root)
    _say("安装目录:%s 实例:%s" % (root, read_instance(root) or "默认"))
    from ..core.updater import load_state
    cur = load_state(root).get("current")
    if cur and os.path.isfile(os.path.join(root, "app", cur, "edgeclient", "__init__.py")):
        _say("代码目录:app\\%s\\edgeclient(远程更新装的版本;根目录下的 edgeclient\\ 是安装包自带的,只作回滚兜底)" % cur)
    else:
        _say("代码目录:edgeclient\\(安装包自带的版本)")
    if os.name == "nt":
        try:
            out = subprocess.run(["sc", "query", svc], capture_output=True, timeout=10).stdout.decode("gbk", "replace")
            state = re.search(r"STATE\s*:\s*\d+\s+(\w+)", out)
            _say("Windows 服务 %s:%s" % (svc, {"RUNNING": "运行中", "STOPPED": "已停止", "START_PENDING": "正在启动",
                                                  "STOP_PENDING": "正在停止"}.get(state.group(1), state.group(1))
                                                 if state else "未安装"))
        except Exception as e:  # noqa: BLE001
            _say("查询服务状态失败:%s" % e)
    st_path = os.path.join(root, "run", "status.json")
    if os.path.exists(st_path):
        with open(st_path, encoding="utf-8") as f:
            st = json.load(f)
        logins = st.get("dms_login") or {}
        _say("最近更新:%s 版本 %s%s 运行 %d 分钟 已完成任务 %s 个" % (
            st.get("updated"), st.get("version"), "(%s)" % st["build"] if st.get("build") else "",
            (st.get("uptime") or 0) // 60, st.get("tasks_done")))
        ur = st.get("update_result") or {}
        if ur:
            _say("最近一次远程更新(%s):%s" % (ur.get("at"), "%s → %s 成功" % (ur.get("from"), ur.get("to")) if ur.get("ok")
                                             else "更新到 %s 失败,已回滚到 %s:%s" % (ur.get("to"), ur.get("current"),
                                                                              ur.get("error"))))
        _say("云端:%s %s(最后成功 %s)" % (st.get("cloud"), "连接正常" if st.get("cloud_ok") else "连不上",
                                       st.get("last_cloud_ok") or "-"))
        _say("当前:%s%s" % ("执行任务 %s(%s)" % (st.get("task_type"), st.get("step") or "-") if st.get("state") == "busy"
                           else "空闲", ""))
        _say("门店:%s 云端配置版本:%s(来自%s)" % (st.get("store") or "-", st.get("config_version"),
                                               "云端" if st.get("config_source") == "cloud" else "本地缓存"))
        if not logins:
            _say("DMS 登录:还没登录过")
        for code, lg in (logins.items() if isinstance(logins, dict) else []):
            state = {"ok": "正常", "failed": "失败", "rejected": "账号密码被拒(已暂停自动登录)", "none": "未登录"}.get(
                lg.get("state"), lg.get("state"))
            left = lg.get("token_left_s")
            _say("DMS 登录(%s / %s):%s 最近登录 %s 今日登录 %s 次%s%s" % (
                connectors.name(code), lg.get("username"), state, lg.get("last_login_at") or "-",
                lg.get("today_logins") or 0, " token 剩 %.1f 小时" % (left / 3600.0) if left else "",
                " 错误:%s" % lg.get("last_error") if lg.get("last_error") else ""))
        _say("待补发:%s 条 磁盘剩余:%s MB 日志占用:%s MB 结果目录占用:%s MB 心跳间隔:%s 秒" % (
            st.get("outbox"), st.get("disk_free_mb"), st.get("logs_mb", "-"), st.get("data_mb", "-"),
            st.get("heartbeat_seconds", "-")))
    else:
        _say("还没有运行状态(服务没启动过?)")
    crash = os.path.join(root, "run", "last_crash.txt")
    if os.path.exists(crash):
        with open(crash, encoding="utf-8") as f:
            tail = f.read().splitlines()[-3:]
        _say("最近的看门狗重启:")
        for line in tail:
            _say("  " + line)
    from ..infra.logs import latest_file
    log_path = latest_file(os.path.join(root, "logs"), "edge")
    if log_path and os.path.exists(log_path):
        _say(BANNER)
        _say("最近 20 行日志(%s):" % log_path)
        with open(log_path, encoding="utf-8", errors="replace") as f:
            for line in f.read().splitlines()[-20:]:
                _say(line)
    return 0