fmode-artifact-push.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. #!/usr/bin/env python3
  2. """fmode-artifact-push.py — 一步做完 report + enqueueArtifact + drain + 回读校验
  3. 用法:
  4. fmode-artifact-push.py push --files /opt/data/work/a.md [/b.pdf ...] \
  5. [--title T] [--summary S] [--agent-id ID] [--no-drain]
  6. 链路(缺一不可):
  7. ① action=report -> 建 Deliverable 记录,返回 id == deliverableId
  8. ② action=enqueueArtifact -> 入队(deliverableId/agentId/source/filename/index)
  9. ③ action=pendingArtifacts -> 取签名 uploadUrl,PUT 文件,ackArtifact(ok)
  10. ④ curl publicUrl 回读 -> 字节数/md5 必须与本地产物一致才算成功
  11. 退出码: 0 全部拿到 https 且内容一致; 1 任一步失败(详细信息打 stdout)
  12. """
  13. import argparse
  14. import hashlib
  15. import json
  16. import os
  17. import socket
  18. import ssl
  19. import sys
  20. import urllib.error
  21. import urllib.request
  22. BASE = "https://server.fmode.cn/api/functions"
  23. FN = "lfYlgU7SkK"
  24. DEFAULT_AGENT_ID = "agent-node-lj-test"
  25. def _token():
  26. t = os.environ.get("FMODE_SESSION_TOKEN")
  27. if t:
  28. return t.strip()
  29. for p in ("/run/s6/container_environment/FMODE_SESSION_TOKEN",
  30. "/opt/data/.fmode/config/user.json"):
  31. try:
  32. raw = open(p).read().strip()
  33. except Exception:
  34. continue
  35. if not raw:
  36. continue
  37. if p.endswith(".json"):
  38. try:
  39. d = json.loads(raw)
  40. except Exception:
  41. continue
  42. for k in ("sessionToken", "session_token", "token"):
  43. if d.get(k):
  44. return d[k]
  45. else:
  46. return raw
  47. raise SystemExit("[push] FATAL: 找不到 FMODE_SESSION_TOKEN")
  48. TOK = _token()
  49. def call(params):
  50. body = json.dumps({"id": FN, "token": TOK, "params": params}).encode()
  51. req = urllib.request.Request(BASE, data=body, headers={
  52. "Content-Type": "application/json",
  53. "X-Parse-Application-Id": "ncloudmaster"})
  54. try:
  55. with urllib.request.urlopen(req, timeout=30) as r:
  56. return json.loads(r.read())
  57. except urllib.error.HTTPError as e:
  58. return {"code": e.code, "error": e.read().decode("utf-8", "replace")[:400]}
  59. except Exception as e:
  60. return {"code": -1, "error": str(e)[:400]}
  61. def md5_bytes(b):
  62. return hashlib.md5(b).hexdigest()
  63. def put_signed_url(url, data, headers, timeout=180):
  64. """PUT to a signed OBS URL, sending the path as RAW UTF-8 bytes.
  65. 中文/非 ASCII 文件名会让你踩到两种 403,都不是权限问题:
  66. - urllib 直接 PUT:'ascii' codec can't encode —— 客户端就地炸
  67. - 先 percent-encode 再 PUT:OBS 返回 403 SignatureDoesNotMatch
  68. —— 服务端签名按 UTF-8 原始字节算,quote 后字节变了
  69. 唯一正确姿势:请求行里写裸 UTF-8 path,query 原样不动,不二次编码。
  70. """
  71. parts = urllib.parse.urlsplit(url)
  72. host = parts.hostname
  73. port = parts.port or (443 if parts.scheme == "https" else 80)
  74. target = (parts.path + ("?" + parts.query if parts.query else "")).encode("utf-8")
  75. lines = [b"PUT " + target + b" HTTP/1.1",
  76. b"Host: " + parts.netloc.encode("utf-8"),
  77. b"Connection: close",
  78. b"Content-Length: %d" % len(data)]
  79. sent_lower = set()
  80. for k, v in headers.items():
  81. sent_lower.add(k.lower())
  82. lines.append(("%s: %s" % (k, v)).encode("utf-8"))
  83. if "content-type" not in sent_lower:
  84. lines.append(b"Content-Type: application/octet-stream")
  85. request = b"\r\n".join(lines) + b"\r\n\r\n" + data
  86. if parts.scheme == "https":
  87. ctx = ssl.create_default_context()
  88. sock = ctx.wrap_socket(socket.create_connection((host, port), timeout=timeout),
  89. server_hostname=host)
  90. else:
  91. sock = socket.create_connection((host, port), timeout=timeout)
  92. try:
  93. sock.sendall(request)
  94. buf = b""
  95. while True:
  96. chunk = sock.recv(65536)
  97. if not chunk:
  98. break
  99. buf += chunk
  100. finally:
  101. sock.close()
  102. head, _, body = buf.partition(b"\r\n\r\n")
  103. status_line = head.split(b"\r\n")[0].decode("latin-1")
  104. code = int(status_line.split()[1]) if len(status_line.split()) > 1 else 0
  105. if code // 100 != 2:
  106. raise RuntimeError("%s %s" % (code, body[:200].decode("utf-8", "replace")))
  107. return code
  108. def fetch_signed_url(url, timeout=120):
  109. """GET a public URL, again using RAW UTF-8 in the request line (中文 key 同理)."""
  110. parts = urllib.parse.urlsplit(url)
  111. host = parts.hostname
  112. port = parts.port or (443 if parts.scheme == "https" else 80)
  113. target = (parts.path + ("?" + parts.query if parts.query else "")).encode("utf-8")
  114. lines = [b"GET " + target + b" HTTP/1.1",
  115. b"Host: " + parts.netloc.encode("utf-8"),
  116. b"Connection: close"]
  117. ctx = ssl.create_default_context()
  118. sock = ctx.wrap_socket(socket.create_connection((host, port), timeout=timeout),
  119. server_hostname=host)
  120. try:
  121. sock.sendall(b"\r\n".join(lines) + b"\r\n\r\n")
  122. raw = b""
  123. while True:
  124. chunk = sock.recv(65536)
  125. if not chunk:
  126. break
  127. raw += chunk
  128. finally:
  129. sock.close()
  130. head, _, body = raw.partition(b"\r\n\r\n")
  131. head_txt = head.decode("latin-1")
  132. first = head_txt.split("\r\n")[0]
  133. code = int(first.split()[1]) if len(first.split()) > 1 else 0
  134. clen = None
  135. for line in head_txt.split("\r\n")[1:]:
  136. if line.lower().startswith("content-length:"):
  137. clen = line.split(":", 1)[1].strip()
  138. if "transfer-encoding: chunked" in head_txt.lower():
  139. body = _dechunk(body)
  140. if code // 100 != 2:
  141. raise RuntimeError("%s %s" % (code, body[:200].decode("utf-8", "replace")))
  142. return code, body, clen
  143. def _dechunk(body):
  144. out = b""
  145. while body:
  146. line, _, rest = body.partition(b"\r\n")
  147. try:
  148. size = int(line.strip().split(b";")[0], 16)
  149. except ValueError:
  150. return out + body
  151. if size == 0:
  152. break
  153. out += rest[:size]
  154. body = rest[size + 2:]
  155. return out
  156. def push(files, agent_id, title, summary, do_drain=True, cleanup=False):
  157. ok_all = True
  158. files = [os.path.abspath(f) for f in files]
  159. for f in files:
  160. if not os.path.isfile(f):
  161. print("[push] FATAL 源文件不存在: %s" % f)
  162. return 1
  163. # ① report —— 🔴 2026-11-14 用户裁决:report 全链路只允许主链路
  164. # (fmode-deliverable-hook.py)执行一次。本函数是 legacy 兜底通道,
  165. # 先查已有 deliverable,命中就复用,绝不新建第二条台账记录。
  166. did = None
  167. for f in files:
  168. try:
  169. hist = call({"action": "list", "agentId": agent_id, "limit": 50})
  170. except Exception:
  171. hist = {}
  172. base = os.path.basename(f)
  173. for old in (hist.get("deliverables") or []):
  174. if not isinstance(old, dict):
  175. continue
  176. for art in (old.get("artifacts") or []):
  177. if not isinstance(art, dict):
  178. continue
  179. if (art.get("name") or "") == base and (art.get("url") or "").startswith("http"):
  180. did = old.get("id")
  181. print("[push] REUSE existing deliverable %s for %s" % (did, f))
  182. break
  183. if did:
  184. break
  185. if did:
  186. break
  187. if did:
  188. print("[push] ① skip report (reuse did=%s)" % did)
  189. else:
  190. rep = call({"action": "report", "agentId": agent_id,
  191. "title": title or os.path.basename(files[0]),
  192. "summary": summary or "",
  193. "artifacts": files})
  194. print("[push] ① report ->", json.dumps(rep, ensure_ascii=False))
  195. did = rep.get("id")
  196. if rep.get("code") != 200 or not did:
  197. print("[push] FATAL report 未返回 deliverableId")
  198. return 1
  199. # ② enqueueArtifact
  200. enq = []
  201. for idx, f in enumerate(files):
  202. r = call({"action": "enqueueArtifact", "deliverableId": did,
  203. "agentId": agent_id, "source": f,
  204. "filename": os.path.basename(f), "index": idx})
  205. print("[push] ② enqueueArtifact[%d] %s -> %s"
  206. % (idx, os.path.basename(f), json.dumps(r, ensure_ascii=False)))
  207. enq.append(r)
  208. if r.get("code") != 200:
  209. ok_all = False
  210. if not do_drain:
  211. return 0 if ok_all else 1
  212. # ③ pendingArtifacts -> PUT -> ackArtifact
  213. pend = call({"action": "pendingArtifacts", "agentId": agent_id})
  214. jobs = (pend.get("jobs") or []) if pend.get("code") == 200 else []
  215. print("[push] ③ pendingArtifacts -> jobs=%d %s" % (len(jobs), "" if jobs else json.dumps(pend, ensure_ascii=False)))
  216. # 只处理本次 report 产生的 job:同一 source 会被多次入队,按 source 匹配会把历史 job 一起重传
  217. mine = [j for j in jobs if j.get("source") in files and j.get("deliverableId") == did]
  218. if not mine:
  219. print("[push] WARN 队列里没有本次文件(可能已被 drain 或入队失败)")
  220. ok_all = False
  221. # 先自己把文件读进内存算 md5,后面回读比对
  222. local = {}
  223. for j in mine:
  224. try:
  225. local[j["source"]] = open(j["source"], "rb").read()
  226. except Exception as e:
  227. print("[push] FATAL 读本地失败 %s: %s" % (j["source"], e))
  228. ok_all = False
  229. for j in mine:
  230. src = j["source"]
  231. data = local.get(src)
  232. if data is None:
  233. continue
  234. try:
  235. put_signed_url(j["uploadUrl"], data, j.get("headers") or {}, timeout=180)
  236. except Exception as e:
  237. msg = str(e)[:200]
  238. call({"action": "ackArtifact", "objectId": j["id"], "ok": False, "error": msg})
  239. print("[push] FAIL PUT %s: %s" % (os.path.basename(src), msg))
  240. ok_all = False
  241. continue
  242. ack = call({"action": "ackArtifact", "objectId": j["id"],
  243. "ok": True, "publicUrl": j["publicUrl"]})
  244. print("[push] ack %s -> %s" % (os.path.basename(src), json.dumps(ack, ensure_ascii=False)))
  245. # ④ public 回读校验
  246. url = j["publicUrl"]
  247. try:
  248. code, got, clen = fetch_signed_url(url, timeout=120)
  249. except Exception as e:
  250. print("[push] VERIFY FAIL 回读异常 %s: %s" % (url, e))
  251. ok_all = False
  252. continue
  253. same = md5_bytes(got) == md5_bytes(data)
  254. print("[push] VERIFY url=%s" % url)
  255. print("[push] http=%s content-length=%s size=%d local=%d"
  256. % (code, clen, len(got), len(data)))
  257. print("[push] md5_remote=%s md5_local=%s identical=%s"
  258. % (md5_bytes(got), md5_bytes(data), "YES" if same else "NO"))
  259. if not same:
  260. ok_all = False
  261. continue
  262. # ⑤ C-2 清理:线上回读 md5 与本地产物一致 → 删除本地源文件(本地只做秒级中转)
  263. if cleanup:
  264. try:
  265. os.remove(src)
  266. print("[push] CLEANUP removed local: %s" % src)
  267. except OSError as e:
  268. print("[push] CLEANUP-FAIL %s: %s" % (src, e))
  269. ok_all = False
  270. print("[push] RESULT", "OK" if ok_all else "PARTIAL/FAIL")
  271. return 0 if ok_all else 1
  272. def main():
  273. # 🔴 2026-11-14 用户裁决:交付只走 fmode-deliverable-hook.py 这一条通道。
  274. # 本脚本的 report/enqueue/PUT/ack 与 hook 第 652-718 行完全重复,
  275. # 两条同时跑会产生两条台账记录(tags=[] 与 tags=["auto-deliverable-hook"])。
  276. # 这里直接退出,避免模型调用后产生重复记录。
  277. # ⚠️ 重要:本模块仍被 fmode-deliverable-hook.py 以 import 方式使用
  278. # (call / put_signed_url / fetch_signed_url / md5_bytes),
  279. # 所以只能拦 CLI 入口,绝不能删函数或让 import 失败。
  280. import sys as _sys
  281. _sys.stderr.write(
  282. "[fmode-artifact-push] DISABLED: 交付统一走 fmode-deliverable-hook.py。"
  283. "本脚本不再上传、不再写台账。\n")
  284. _sys.exit(2)
  285. def _legacy_main():
  286. ap = argparse.ArgumentParser()
  287. sub = ap.add_subparsers(dest="cmd", required=True)
  288. p = sub.add_parser("push")
  289. p.add_argument("--files", nargs="+", required=True)
  290. p.add_argument("--title", default="")
  291. p.add_argument("--summary", default="")
  292. p.add_argument("--agent-id", default=os.environ.get("AGENT_ID") or DEFAULT_AGENT_ID)
  293. p.add_argument("--no-drain", action="store_true")
  294. p.add_argument("--cleanup", action="store_true",
  295. help="回读 md5 校验一致后删除本地源文件(本地只做秒级中转)")
  296. a = ap.parse_args()
  297. if a.cmd == "push":
  298. sys.exit(push(a.files, a.agent_id, a.title, a.summary, not a.no_drain, a.cleanup))
  299. if __name__ == "__main__":
  300. main()