updater.py
16.5 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
# -*- coding: utf-8 -*-
"""自更新:云端下发 sys.update → 下载更新包 → 校验 sha256 → 解压到 app\\<版本>\\ → 试导入 → 记 run\\version.json → 重启。
安装目录\\main.py 启动器(稳定不变):按 version.json 选择从哪个目录加载 edgeclient
安装目录\\edgeclient\\ 安装包自带的版本(version.json 没有 current 时用它)
安装目录\\app\\3.2.1\\edgeclient\\ 远程更新装的版本(只保留最近 3 个)
run\\version.json {"current": 当前版本, "previous": 上一个(null = 安装包自带), "pending": 待确认版本,
"boot_tries": 待确认版本已启动次数, "from": 更新前版本, "at": 安装时间}
run\\update_result.json 最近一次更新结果(随心跳上报云端)
新版本启动后第一次连上云端(心跳成功)即确认;以服务运行时连续 3 次启动都没确认,启动器自动回滚到上一个版本。
转正后同步根目录文件(sync_root):更新包里的 edgeclient/_root/(bat、README.txt、config.example.ini)拷到安装目录,
config.example.ini 里新增的配置项以注释形式补进 config.ini,写 VERSION.txt。放在 edgeclient/ 下是为了老版本客户端
(只认 edgeclient/ 开头的路径)也能照常装这个包。
不在远程更新范围:main.py 启动器、Python 运行时、Chromium、WinSW(这些变了要重新装整包)。
logs\ / edge_data\ / run\(审计、日志、结果、待补发数据)更新时一律不动。
"""
import hashlib
import json
import logging
import os
import re
import shutil
import subprocess
import sys
import time
import zipfile
from .. import __version__
from .tasks import TaskError
log = logging.getLogger("edge")
KEEP_VERSIONS = 3
RESTART_CODE = 7
RESTART = {"pending": False, "auto": False} # pending:sys.update 装好 / sys.restart 后置 True,worker 回传结果后重启进程;auto:重启是否由服务自动完成
def code_root():
"""当前运行的 edgeclient 所在目录(安装目录,或 app\\<版本>)。"""
import edgeclient
return os.path.dirname(os.path.dirname(os.path.abspath(edgeclient.__file__)))
def build_info():
try:
from .. import _build
return getattr(_build, "BUILD", "")
except ImportError:
return ""
def _state_path(root):
return os.path.join(root, "run", "version.json")
def _result_path(root):
return os.path.join(root, "run", "update_result.json")
def load_state(root):
try:
with open(_state_path(root), encoding="utf-8") as f:
return json.load(f)
except (OSError, ValueError):
return {}
def _write_json(path, data):
os.makedirs(os.path.dirname(path), exist_ok=True)
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 save_state(root, st):
_write_json(_state_path(root), st)
def read_result(root):
try:
with open(_result_path(root), encoding="utf-8") as f:
return json.load(f)
except (OSError, ValueError):
return None
def _now():
return time.strftime("%Y-%m-%d %H:%M:%S")
def _check_zip(path, version):
try:
z = zipfile.ZipFile(path)
except zipfile.BadZipFile:
raise TaskError("更新包不是有效的 zip 文件", "update_bad_package")
with z:
names = z.namelist()
for n in names:
if n.startswith("/") or ".." in n.split("/") or ":" in n or not n.startswith("edgeclient/"):
raise TaskError("更新包里有不允许的路径:%s" % n, "update_bad_package")
if "edgeclient/__init__.py" not in names:
raise TaskError("更新包缺少 edgeclient/__init__.py", "update_bad_package")
init = z.read("edgeclient/__init__.py").decode("utf-8", "replace")
if '"%s"' % version not in init and "'%s'" % version not in init:
raise TaskError("更新包里的版本号与要安装的 %s 不一致" % version, "update_bad_package")
def _try_import(code_dir, version):
"""用同一个 Python 在子进程里试导入新版本,导入失败就不切换。"""
script = ("import sys; sys.path.insert(0, %r); import edgeclient, edgeclient.app.cli, edgeclient.plugins; "
"print(edgeclient.__version__)" % code_dir)
env = dict(os.environ, PYTHONNOUSERSITE="1", PYTHONIOENCODING="utf-8")
r = subprocess.run([sys.executable, "-c", script], capture_output=True, timeout=120, env=env, cwd=code_dir)
out = r.stdout.decode("utf-8", "replace").strip()
if r.returncode != 0 or out.splitlines()[-1:] != [version]:
err = r.stderr.decode("utf-8", "replace").strip().splitlines()[-3:]
raise TaskError("新版本 %s 试运行失败:%s" % (version, " | ".join(err) or out), "update_import_failed")
def _cleanup_versions(root, st):
adir = os.path.join(root, "app")
if not os.path.isdir(adir):
return
keep = {st.get("current"), st.get("previous"), st.get("pending")}
vers = [v for v in os.listdir(adir) if os.path.isdir(os.path.join(adir, v)) and not v.endswith(".tmp")]
def key(v):
return tuple(int("".join(ch for ch in p if ch.isdigit()) or 0) for p in v.split("."))
extra = [v for v in sorted(vers, key=key, reverse=True) if v not in keep]
for v in extra[max(0, KEEP_VERSIONS - len(keep - {None})):]:
shutil.rmtree(os.path.join(adir, v), ignore_errors=True)
def install(cc, root, version, sha256, steps, size=None):
"""下载、校验、解压、试导入新版本,写好 version.json(pending)。返回结果 dict;失败抛 TaskError。"""
running = code_root()
target = os.path.join(root, "app", version)
if version == __version__:
raise TaskError("取数端已经是 %s 版本,不需要更新" % version, "update_same_version")
if os.path.abspath(target) == os.path.abspath(running):
raise TaskError("不能覆盖正在运行的版本目录 %s" % target, "update_same_version")
tmp_zip = os.path.join(root, "run", "update_%s.zip" % version)
os.makedirs(os.path.dirname(tmp_zip), exist_ok=True)
with steps.step("download", "%s → %s" % (__version__, version), timeout=600):
n, _ = cc.download("/api/edge/v1/releases/%s/download" % version, tmp_zip)
if size and n != int(size):
raise TaskError("更新包大小不对(收到 %d 字节,应为 %s)" % (n, size), "update_bad_package")
try:
with steps.step("verify", version, timeout=60):
h = hashlib.sha256()
with open(tmp_zip, "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
if sha256 and h.hexdigest() != sha256:
raise TaskError("更新包 sha256 校验失败(下载不完整或被篡改)", "update_bad_package")
_check_zip(tmp_zip, version)
with steps.step("install", version, timeout=240):
stage = target + ".tmp"
shutil.rmtree(stage, ignore_errors=True)
with zipfile.ZipFile(tmp_zip) as z:
z.extractall(stage)
_try_import(stage, version)
shutil.rmtree(target, ignore_errors=True)
os.rename(stage, target)
old = load_state(root)
st = {"current": version, "previous": old.get("current") if old.get("current") != version else None,
"pending": version, "boot_tries": 0, "from": __version__, "at": _now()}
if os.path.abspath(running) == os.path.abspath(root):
st["previous"] = None # 回滚目标 = 安装包自带的版本
save_state(root, st)
_cleanup_versions(root, st)
finally:
try:
os.remove(tmp_zip)
except OSError:
pass
log.warning("已安装新版本 %s(原 %s),回传结果后重启进程加载新版本", version, __version__)
RESTART["pending"] = True
auto = RESTART["auto"]
return {"ok": True, "installed": version, "from": __version__, "dir": target, "auto_restart": auto,
"message": "已安装 %s(原 %s),%s" % (version, __version__, "取数端马上重启" if auto else
"取数端会退出,请在门店电脑上重新打开取数端(tool.bat 菜单 7)加载新版本")}
def confirm(root):
"""新版本第一次连上云端:确认更新成功(pending → 转正),同步根目录文件,写更新结果。"""
st = load_state(root)
if not st.get("pending") or st["pending"] != __version__:
return None
res = {"ok": True, "from": st.get("from"), "to": __version__, "current": __version__, "at": _now(), "error": ""}
st.update(pending=None, boot_tries=0)
save_state(root, st)
try:
res.update(sync_root(root, __version__, st.get("from")))
except Exception as e: # noqa: BLE001 同步根目录文件失败不影响转正
log.error("同步安装目录根下的文件失败(不影响新版本运行):%s", e)
res["root_error"] = str(e)[:300]
_write_json(_result_path(root), res)
log.info("取数端已更新到 %s(原 %s),新版本运行正常", __version__, st.get("from") or "?")
return res
# ---------------------------------------------------------------- 转正后同步根目录文件
# 只同步这些文件名(更新包 edgeclient/_root/ 里有才同步);main.py、config.ini、*.xml、WinSW、运行时、数据目录一律不碰
ROOT_FILES = ("install.bat", "uninstall.bat", "status.bat", "tool.bat", "update.bat", "cleanup.bat",
"README.txt", "config.example.ini")
def _read_bytes(path):
try:
with open(path, "rb") as f:
return f.read()
except OSError:
return None
def _replace_file(path, data):
tmp = path + ".tmp"
with open(tmp, "wb") as f:
f.write(data)
os.replace(tmp, path)
def sync_root(root, version, from_version=None):
"""把 app\\<版本>\\edgeclient\\_root\\ 里的白名单文件同步到安装目录根下,补配置项注释,写 VERSION.txt。
跑的是安装包自带的版本(没有 app\\<版本>)时什么都不做。返回 {"root_files": [...], "config_added": [...]}。
"""
code_dir = os.path.join(root, "app", version)
src = os.path.join(code_dir, "edgeclient", "_root")
out = {"root_files": [], "config_added": []}
if not os.path.isdir(code_dir):
return out
if os.path.isdir(src):
for name in ROOT_FILES:
data = _read_bytes(os.path.join(src, name))
if data is None or _read_bytes(os.path.join(root, name)) == data:
continue
_replace_file(os.path.join(root, name), data)
out["root_files"].append(name)
if out["root_files"]:
log.info("已同步安装目录根下的文件:%s", "、".join(out["root_files"]))
cfg, example = os.path.join(root, "config.ini"), os.path.join(root, "config.example.ini")
if os.path.exists(cfg) and os.path.exists(example):
out["config_added"] = merge_example(cfg, example, version, from_version,
backup_dir=os.path.join(root, "run"))
write_version_txt(root, version, from_version)
return out
def write_version_txt(root, version, from_version=None):
lines = [
"门店取数端当前运行版本(远程更新后自动生成,仅供查看,改它没有作用)",
"",
"版本:%s%s" % (version, "(%s)" % build_info() if build_info() else ""),
"代码目录:app\\%s\\edgeclient" % version,
"更新时间:%s%s" % (_now(), "(从 %s 更新)" % from_version if from_version else ""),
"",
"说明:远程更新只替换程序代码,新版本装在 app\\<版本>\\ 下(保留最近 3 个,坏了会自动回滚);",
" 安装目录根下的 edgeclient\\ 是安装包自带的版本,只作回滚兜底,日期不变是正常的。",
" bat 脚本、README.txt、config.example.ini 随更新自动同步;config.ini 只会补注释,不改已有的值。",
" logs\\、edge_data\\、run\\(日志、审计、结果、待补发数据)更新时一律不动。",
]
_replace_file(os.path.join(root, "VERSION.txt"), ("\r\n".join(lines) + "\r\n").encode("utf-8-sig"))
# ---------------------------------------------------------------- config.ini 补新配置项(只加注释)
_SEC = re.compile(r"^\s*\[([^\]]+)\]\s*$")
_SEC_COMMENTED = re.compile(r"^\s*#\s*\[([\w.\-]+)\]\s*$")
_KEY = re.compile(r"^\s*#?\s*([A-Za-z_][\w.]*)\s*=")
SKIP_KEYS = {("local", "instance")} # 安装向导负责的项不补
def _skip_section(sec):
return sec == "cloud" or sec.startswith("cloud.") # 云端地址 / 令牌 / 环境由安装向导管
def _example_items(example):
"""config.example.ini → [(段, [(键, 值行, [说明注释行...]), ...]), ...],保持原顺序。"""
with open(example, encoding="utf-8-sig") as f:
lines = f.read().splitlines()
out, sec, notes = [], None, []
for line in lines:
m = _SEC.match(line)
if m:
sec = m.group(1).strip()
out.append((sec, []))
notes = []
continue
if sec is None:
continue
s = line.strip()
if not s:
notes = []
elif s.startswith("#") or s.startswith(";"):
notes.append(s)
else:
km = _KEY.match(line)
if km:
out[-1][1].append((km.group(1), s, notes))
notes = []
return out
def merge_example(cfg_path, example, version, from_version=None, backup_dir=None):
"""config.example.ini 里有、config.ini 里没有的配置项,以注释形式补进 config.ini(已有的行一字不改)。
段已有:插在该段最后一个非空行后面;整段没有:整段注释掉追加到末尾。[cloud*] 段和 [local] instance 不补。
该段里已经有 key = 或 # key = 就不再补(重复执行结果不变)。改之前把原文件备份到 backup_dir。
返回补上的 ["段.键", ...]。
"""
raw = _read_bytes(cfg_path)
if raw is None:
return []
bom = raw.startswith(b"\xef\xbb\xbf")
text = raw.decode("utf-8-sig", "replace")
nl = "\r\n" if "\r\n" in text else "\n"
lines = text.splitlines()
# 现有每段的键(含注释掉的)和该段最后一个非空行的位置;整段被注释掉的段头(以前补过的)也记下,不再重复追加
have, last, sec = {}, {}, None
offered = {m.group(1).strip() for m in (_SEC_COMMENTED.match(x) for x in lines) if m}
for i, line in enumerate(lines):
m = _SEC.match(line)
if m:
sec = m.group(1).strip()
have.setdefault(sec, set())
last[sec] = i
continue
if sec is None:
continue
if line.strip():
last[sec] = i
km = _KEY.match(line)
if km:
have[sec].add(km.group(1).lower())
tag = "# [%s 新增,去掉行首 # 才生效]" % version
inserts, tail, added = {}, [], []
for sec, items in _example_items(example):
if _skip_section(sec):
continue
missing = [it for it in items if (sec, it[0]) not in SKIP_KEYS and it[0].lower() not in have.get(sec, set())]
if not missing:
continue
block = []
for key, val_line, notes in missing:
block += [tag] + notes + ["# " + val_line]
added.append("%s.%s" % (sec, key))
if sec in have:
inserts.setdefault(last[sec], []).extend(block)
elif sec in offered: # 整段以前已经以注释形式补过了
del added[-len(missing):]
else:
tail += ["", "# [%s] 段(%s 新增,需要时去掉下面各行行首的 #)" % (sec, version), "# [%s]" % sec] + \
[b for b in block if b != tag]
if not added:
return []
out = []
for i, line in enumerate(lines):
out.append(line)
out.extend(inserts.get(i, []))
out += tail
if backup_dir:
os.makedirs(backup_dir, exist_ok=True)
shutil.copy2(cfg_path, os.path.join(backup_dir, "config.ini.bak-%s-%s" % (from_version or "old", version)))
data = (nl.join(out) + nl).encode("utf-8")
_replace_file(cfg_path, (b"\xef\xbb\xbf" if bom else b"") + data)
log.info("config.ini 补上了 %d 个新配置项(都是注释,不影响现有配置):%s", len(added), "、".join(added))
return added