cloud.py
5.83 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
"""云端接口客户端(v1 协议,见 server/app/api/edge_api.py)。门店电脑主动连出,云端不需要能连进门店。
所有请求带 X-Edge-Token(设备令牌)、X-Edge-Version(版本号)。连云端不走系统代理;
https 固定校验证书:系统证书 + 自带 ca/cacert.pem(Win7 证书库太旧)。
CloudError.status:0 = 网络不通 / 超时;>= 400 = 云端明确拒绝(4xx 不重试,5xx 可重试)。
"""
import json
import logging
import os
import ssl
import time
import urllib.error
import urllib.parse
import urllib.request
from .. import __version__
log = logging.getLogger("edge")
class CloudError(Exception):
def __init__(self, message, status=0):
super(CloudError, self).__init__(message)
self.status = status
@property
def retryable(self):
return self.status == 0 or self.status >= 500 or self.status == 429
class CloudClient(object):
def __init__(self, cfg):
if not cfg.cloud_url:
raise CloudError("云端地址没有配置:config.ini 的 [cloud] url(运行 install.bat 重新填写)", 400)
if not cfg.edge_token:
raise CloudError("config.ini 的 [cloud] edge_token(设备令牌)没有填写", 400)
self.cfg = cfg
handlers = []
if cfg.cloud_url.startswith("https"):
ctx = ssl.create_default_context()
if cfg.ca_file and os.path.exists(cfg.ca_file):
ctx.load_verify_locations(cfg.ca_file)
handlers.append(urllib.request.HTTPSHandler(context=ctx))
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), *handlers)
def _req(self, method, path, body=None, ctype="application/json", timeout=30):
data = None
if body is not None:
data = body if isinstance(body, bytes) else json.dumps(body, ensure_ascii=False, default=str).encode("utf-8")
req = urllib.request.Request(self.cfg.cloud_url + path, data=data, method=method, headers={
"X-Edge-Token": self.cfg.edge_token, "X-Edge-Version": __version__, "Content-Type": ctype})
try:
with self.opener.open(req, timeout=timeout) as r:
text = r.read().decode("utf-8")
except urllib.error.HTTPError as e:
detail = e.read()[:300].decode("utf-8", "replace")
raise CloudError("云端返回 HTTP %d:%s" % (e.code, detail), e.code)
except Exception as e: # noqa: BLE001
if isinstance(e, ssl.SSLError) or isinstance(getattr(e, "reason", None), ssl.SSLError):
raise CloudError("连云端 %s 时证书 / TLS 出错:%s(运行 tool.bat 菜单 9 网络诊断,看云端那一行)"
% (self.cfg.cloud_url, e))
raise CloudError("连不上云端 %s:%s" % (self.cfg.cloud_url, e))
try:
return json.loads(text) if text else {}
except ValueError:
raise CloudError("云端返回的不是 JSON:%s" % text[:200], 502)
# ---------------- 接口 ----------------
def config(self):
return self._req("GET", "/api/edge/v1/config", timeout=30)
def heartbeat(self, data):
return self._req("POST", "/api/edge/v1/heartbeat", data, timeout=15)
def next_task(self, wait):
return self._req("GET", "/api/edge/v1/tasks/next?wait=%d" % wait, timeout=wait + 20).get("task")
def progress(self, task_id, step, status, detail="", timeout=None, error=""):
return self._req("POST", "/api/edge/v1/tasks/%s/progress" % task_id,
{"step": step, "status": status, "detail": detail[:300], "timeout": timeout,
"error": (error or "")[:1000]}, timeout=10)
def result(self, task_id, ok, result, error="", error_code=""):
return self._req("POST", "/api/edge/v1/tasks/%s/result" % task_id,
{"ok": ok, "result": result or {}, "error": error or "", "error_code": error_code or ""},
timeout=60)
def upload_file(self, task_id, path, kind="file", tries=3):
with open(path, "rb") as f:
data = f.read()
name = urllib.parse.quote(os.path.basename(path))
low = path.lower()
mime = "image/png" if low.endswith(".png") else "text/csv" if low.endswith(".csv") else "application/octet-stream"
for i in range(tries):
try:
return self._req("POST", "/api/edge/v1/tasks/%s/file?name=%s&kind=%s" % (task_id, name, kind), data,
mime, timeout=max(120, len(data) // 50000))
except CloudError as e:
if not e.retryable or i == tries - 1:
raise
log.warning("上传文件 %s 失败(%d/%d):%s", os.path.basename(path), i + 1, tries, e)
time.sleep(2 ** i)
def logs(self, lines):
return self._req("POST", "/api/edge/v1/logs", {"lines": lines}, timeout=30)
def download(self, path, dest, timeout=300):
"""下载文件到 dest(更新包用);返回 (字节数, 响应头)。"""
req = urllib.request.Request(self.cfg.cloud_url + path, method="GET", headers={
"X-Edge-Token": self.cfg.edge_token, "X-Edge-Version": __version__})
try:
with self.opener.open(req, timeout=timeout) as r, open(dest, "wb") as f:
n = 0
while True:
chunk = r.read(65536)
if not chunk:
break
f.write(chunk)
n += len(chunk)
return n, dict(r.headers)
except urllib.error.HTTPError as e:
raise CloudError("云端返回 HTTP %d:%s" % (e.code, e.read()[:300].decode("utf-8", "replace")), e.code)
except Exception as e: # noqa: BLE001
raise CloudError("下载 %s 失败:%s" % (path, e))