main.py 2.62 KB
# -*- coding: utf-8 -*-
"""门店取数端入口(启动器):python main.py [命令](命令说明见 edgeclient/app/cli.py;不带命令进入菜单)。

远程更新装的版本在 app\\<版本>\\edgeclient\\,run\\version.json 的 current 指向它;没有就用本目录的 edgeclient(安装包自带)。
以服务运行(service)时,待确认的新版本连续 3 次启动都没连上云端(没有转正),自动回滚到上一个版本。
这个文件只用标准库、不依赖 edgeclient,远程更新不会改它。
"""
import json
import os
import re
import sys
import time

HERE = os.path.dirname(os.path.abspath(__file__))
MAX_BOOT_TRIES = 3


def _bundled_version(home):
    try:
        with open(os.path.join(home, "edgeclient", "__init__.py"), encoding="utf-8") as f:
            m = re.search(r"""__version__\s*=\s*["']([\d.]+)["']""", f.read())
            return m.group(1) if m else "?"
    except OSError:
        return "?"


def _write(path, data):
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    os.replace(tmp, path)


def pick_code_dir(home, service_mode):
    """返回加载 edgeclient 的目录;服务模式下顺带累计待确认版本的启动次数,超过上限就回滚。"""
    path = os.path.join(home, "run", "version.json")
    try:
        with open(path, encoding="utf-8") as f:
            st = json.load(f)
    except (OSError, ValueError):
        return home
    if service_mode and st.get("pending"):
        st["boot_tries"] = int(st.get("boot_tries") or 0) + 1
        if st["boot_tries"] > MAX_BOOT_TRIES:
            bad = st["pending"]
            st.update(current=st.get("previous"), previous=None, pending=None, boot_tries=0)
            _write(os.path.join(home, "run", "update_result.json"), {
                "ok": False, "from": st.get("from"), "to": bad, "current": st["current"] or _bundled_version(home),
                "at": time.strftime("%Y-%m-%d %H:%M:%S"),
                "error": "新版本连续 %d 次启动都没能连上云端,已自动回滚" % MAX_BOOT_TRIES})
        try:
            _write(path, st)
        except OSError:
            pass
    cur = st.get("current")
    d = os.path.join(home, "app", cur) if cur else ""
    return d if d and os.path.isfile(os.path.join(d, "edgeclient", "__init__.py")) else home


if __name__ == "__main__":
    os.environ["STOREEDGE_HOME"] = HERE
    sys.path.insert(0, pick_code_dir(HERE, len(sys.argv) > 1 and sys.argv[1] == "service"))   # 嵌入式 Python 不会自动加脚本目录
    from edgeclient.app.cli import main
    sys.exit(main())