cloud.py
8.4 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
# -*- coding: utf-8 -*-
"""连接云端:长轮询拉任务 → 本地执行(actions)→ 回传结果 / 截图 / 库存分页。门店电脑主动连出,云端不需要能连进门店。
协议(云端 cloud/replenish_cloud/edge_hub.py 实现):所有请求带 X-Edge-Token / X-Edge-Id
GET /api/edge/tasks/next?wait=25 → {"task": null | {"id","type","params"}}
POST /api/edge/tasks/<id>/result ← {"ok","result","error","logs"}
POST /api/edge/tasks/<id>/file?name=x.png ← 图片原始字节
POST /api/edge/tasks/<id>/stock-page ← {"page","total","rows"}(全量库存边拉边推)
"""
import json
import logging
import os
import ssl
import time
import urllib.error
import urllib.parse
import urllib.request
from . import __version__, actions, logs
from .dms_api import DmsSession
log = logging.getLogger("edge")
class CloudError(Exception):
pass
class CloudClient(object):
def __init__(self, cfg):
if not cfg.cloud_url:
raise CloudError("云端地址没有配置:config.ini 的 [cloud] env = %s,请在 [cloud.%s] 段填写 url" % (cfg.cloud_env, cfg.cloud_env))
if not cfg.edge_token:
raise CloudError("config.ini 的 [cloud] edge_token 没有填写")
self.cfg = cfg
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) # Win7 证书库较旧,用自带的根证书
if not cfg.cloud_verify_ssl:
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
handlers = [urllib.request.HTTPSHandler(context=ctx)]
else:
handlers = []
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), *handlers)
def _req(self, method, path, body=None, ctype="application/json", timeout=40):
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-Id": self.cfg.edge_id,
"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:
raise CloudError("云端返回 HTTP %d:%s" % (e.code, e.read()[:200].decode("utf-8", "replace")))
except Exception as e: # noqa: BLE001
if isinstance(e, ssl.SSLError) or isinstance(getattr(e, "reason", None), ssl.SSLError):
raise CloudError("连云端 %s 时证书/TLS 出错:%s(可在 config.ini 对应环境段设 verify_ssl = false 排查)"
% (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])
def next_task(self):
return self._req("GET", "/api/edge/tasks/next?wait=%d" % self.cfg.poll_wait,
timeout=self.cfg.poll_wait + 15).get("task")
def post_result(self, task_id, ok, result=None, error="", tries=8):
body = {"ok": ok, "result": result or {}, "error": error, "logs": logs.drain()}
for i in range(tries):
try:
return self._req("POST", "/api/edge/tasks/%s/result" % task_id, body)
except CloudError as e:
log.error("回传任务 %s 结果失败(%d/%d):%s", task_id, i + 1, tries, e)
time.sleep(min(2 ** i, 30))
log.error("任务 %s 的结果始终没能回传云端,结果已保存在本地结果目录", task_id)
return None
def upload_file(self, task_id, path):
with open(path, "rb") as f:
data = f.read()
name = urllib.parse.quote(os.path.basename(path))
return self._req("POST", "/api/edge/tasks/%s/file?name=%s" % (task_id, name), data, "image/png", timeout=120)
def push_stock_page(self, task_id, page, total, rows):
for i in range(5):
try:
return self._req("POST", "/api/edge/tasks/%s/stock-page" % task_id,
{"page": page, "total": total, "rows": rows}, timeout=60)
except CloudError as e:
log.warning("推送库存第 %d 页失败(%d/5):%s", page, i + 1, e)
time.sleep(2 ** i)
raise CloudError("推送库存第 %d 页连续失败,停止全量同步" % page)
class _Executed(object):
"""建单任务防重:执行过的 create_po 任务 id 记在本地,同一个任务绝不执行第二次。"""
def __init__(self, data_dir):
os.makedirs(data_dir, exist_ok=True)
self.path = os.path.join(data_dir, "executed_create_tasks.txt")
def seen(self, tid):
if not os.path.exists(self.path):
return False
with open(self.path, encoding="utf-8") as f:
return tid in {l.strip() for l in f}
def add(self, tid):
with open(self.path, "a", encoding="utf-8") as f:
f.write(tid + "\n")
def run_task(cfg, cc, sess, task, executed):
tid, typ, p = str(task["id"]), task["type"], task.get("params") or {}
log.info("收到云端任务 %s:%s", tid, typ)
if typ == "ping":
return {"pong": True, "version": __version__}
if typ == "check":
return actions.check(cfg, sess, p.get("parts") or [])
if typ == "sync_stock_full":
return actions.sync_stock_full(cfg, sess, sink=lambda page, rows, total: cc.push_stock_page(tid, page, total, rows))
if typ == "scan":
r = actions.scan(cfg, sess, p.get("parts") or [], p.get("warehouses"), p.get("supplier_code"),
p.get("order_type"))
# 部分配件查询失败(配件码写错 / 无订货主数据)不拖垮整张补货单:只要还有查到的配件就算成功,
# 出错的配件带着 error 回传,云端在补货单里标「查询失败」
if not r["ok"] and any(not it.get("error") for it in r["items"]):
r.update(ok=True, partial=True)
return r
if typ == "create_po":
if executed.seen(tid):
raise actions.ActionError("建单任务 %s 已经执行过,取数端拒绝重复建单" % tid)
executed.add(tid) # 先记再做:宁可漏建,不可重建
return actions.create_po(cfg, sess, p.get("lines") or [], p.get("supplier_code"), p.get("order_type"),
p.get("remark") or "")
if typ == "screenshot_po":
r = actions.screenshot_po(cfg, sess, p.get("order_no"), p.get("row"), p.get("part_nos") or [])
urls = []
for f in r["files"]:
urls.append(cc.upload_file(tid, f).get("url"))
r["urls"] = urls
return r
raise actions.ActionError("不认识的任务类型 %s" % typ)
def serve(cfg, stop_after=None):
"""常驻:拉任务 → 执行 → 回传。连不上云端时每 10 秒重试并报错,不会退出。stop_after 仅测试用。"""
cc = CloudClient(cfg)
sess = DmsSession(cfg)
executed = _Executed(cfg.data_dir)
log.info("已启动云端连接:%s %s(取数端 id=%s)", cfg.cloud_env_label, cfg.cloud_url, cfg.edge_id)
done, fails = 0, 0
while stop_after is None or done < stop_after:
try:
task = cc.next_task()
if fails:
log.info("云端已恢复连接")
fails = 0
except CloudError as e:
fails += 1
log.error("拉取任务失败(第 %d 次):%s", fails, e)
time.sleep(10)
continue
if not task:
continue
try:
result = run_task(cfg, cc, sess, task, executed)
ok = bool(result.get("ok", True))
cc.post_result(task["id"], ok, result, "" if ok else (result.get("message") or "执行未成功"))
except Exception as e: # noqa: BLE001
log.error("任务 %s 失败:%s: %s", task.get("id"), type(e).__name__, e)
cc.post_result(task["id"], False, {}, "%s: %s" % (type(e).__name__, e))
done += 1
return 0