executor.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. package faultRecordQueue
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "fwh-toolbox-server/domain"
  10. faultRecordFile "fwh-toolbox-server/function/FaultRecordFile"
  11. proto "fwh-toolbox-server/function/FaultRecordProtocol"
  12. minioRepo "fwh-toolbox-server/repositories/minio"
  13. "fwh-toolbox-server/repositories/mqtt/fwh_mqtt"
  14. "go.mongodb.org/mongo-driver/bson"
  15. "go.mongodb.org/mongo-driver/bson/primitive"
  16. "go.uber.org/zap"
  17. )
  18. // BuildRequest 按操作构造 377 的 dataArea
  19. func BuildRequest(op *domain.FaultRecordOperation) (proto.Request, error) {
  20. switch op.Kind {
  21. case domain.FaultRecordOpDeviceInfo:
  22. return proto.NewRealtimeRequest(op.DeviceType, op.DeviceSn, op.Request.CodeList)
  23. case domain.FaultRecordOpRecordFetch:
  24. return proto.NewGetRecordRequest(op.DeviceType, op.DeviceSn, op.Request.Indexes())
  25. case domain.FaultRecordOpParamRead:
  26. return proto.NewQueryParamRequest(op.DeviceType, op.DeviceSn, op.Request.IdList)
  27. case domain.FaultRecordOpParamWrite:
  28. return proto.NewSetParamRequest(op.DeviceType, op.DeviceSn, op.Request.ParaList)
  29. }
  30. return proto.Request{}, fmt.Errorf("unknown operation kind %s", op.Kind)
  31. }
  32. func lockKey(op *domain.FaultRecordOperation) string {
  33. return fmt.Sprintf("fault-record:gateway:%s:%s", op.Env, op.GatewaySn)
  34. }
  35. // 需要记录到操作中的接收报文类型
  36. var recordedCmdTypes = map[uint]bool{
  37. proto.CmdTypeAck: true, proto.CmdTypeReply: true, proto.CmdTypeReplyAck: true,
  38. proto.CmdTypeUploadCall: true, proto.CmdTypeUploadAck: true,
  39. proto.CmdTypeUploadDone: true, proto.CmdTypeUploadDoneA: true,
  40. }
  41. // execution 一次操作的执行过程
  42. type execution struct {
  43. d deps
  44. op *domain.FaultRecordOperation
  45. bus mqttBus
  46. events chan fwh_mqtt.Message
  47. batch string // 379.filename
  48. msgCount int // 已记录的报文条数(本执行器是该操作报文的唯一写入方)
  49. lastFail *downloadFailure
  50. }
  51. // downloadFailure 最近一条下载失败记录;连续相同的失败只更新这一条并累计次数
  52. type downloadFailure struct {
  53. index int
  54. key string
  55. count int
  56. firstAt time.Time
  57. }
  58. func (e *execution) s2cTopic() string { return fwh_mqtt.S2CTopic("mng/" + e.op.GatewaySn) }
  59. func (e *execution) c2sTopic() string { return fwh_mqtt.C2STopic("mng/" + e.op.GatewaySn) }
  60. // 文件上传消息 607~610 走 debug topic:607/610 为 s2c,608/609 为 c2s(用户确认,2026-10-19)
  61. func (e *execution) uploadTopics() []string {
  62. return []string{fwh_mqtt.S2CTopic("debug/" + e.op.GatewaySn), fwh_mqtt.C2STopic("debug/" + e.op.GatewaySn)}
  63. }
  64. // run 执行或恢复一个操作。业务失败写入操作状态并返回 nil;只有存储故障或 ctx 取消才返回错误,交给 asynq 重试/重新投递。
  65. func (d deps) run(ctx context.Context, id primitive.ObjectID) error {
  66. op, err := d.store.Get(ctx, id)
  67. if err != nil {
  68. return err
  69. }
  70. if op.Status.Terminal() {
  71. return nil
  72. }
  73. e := &execution{d: d, op: op, batch: proto.BatchFromUploadFileName(op.FileName), msgCount: len(op.Messages)}
  74. if op.CancelReq && op.Status == domain.FaultRecordStatusPending {
  75. return e.finish(ctx, domain.FaultRecordStatusCancelled, "", nil)
  76. }
  77. switch op.Status {
  78. case domain.FaultRecordStatusSent, domain.FaultRecordStatusAccepted:
  79. // 重发会清空设备导出文件,也无法确认设备当前状态,交由用户重新发起
  80. return e.finish(ctx, domain.FaultRecordStatusInterrupted, "服务重启时命令已发出但未收到结果,无法确认设备状态,请重新发起", nil)
  81. }
  82. release, ok, err := d.lock.Acquire(ctx, lockKey(op), op.ID.Hex(), d.timeouts.lockTTL)
  83. if err != nil {
  84. return err
  85. }
  86. if !ok {
  87. return e.finish(ctx, domain.FaultRecordStatusGatewayLocked, "该网关在本工具内有其他操作正在进行,请稍后再试", nil)
  88. }
  89. defer release()
  90. switch op.Status {
  91. case domain.FaultRecordStatusUploaded:
  92. if op.DownloadRetryAt != nil {
  93. // 手动重试下载:最多尝试 manualRetryAttempts 次
  94. return e.downloadUntilTimeout(ctx, 0, d.timeouts.manualRetryAttempts)
  95. }
  96. return e.downloadUntilTimeout(ctx, 0, 0)
  97. case domain.FaultRecordStatusDownloaded:
  98. data, err := d.files.Get(ctx, op.MinioObject)
  99. if err != nil {
  100. return e.finish(ctx, domain.FaultRecordStatusDownloadFailed, "读取已保存的文件失败:"+err.Error(), nil)
  101. }
  102. return e.parse(ctx, data)
  103. }
  104. if e.bus, err = d.bus(op.Env); err != nil {
  105. return e.finish(ctx, domain.FaultRecordStatusError, "MQTT 不可用:"+err.Error(), nil)
  106. }
  107. e.events = make(chan fwh_mqtt.Message, 128)
  108. handler := func(m fwh_mqtt.Message) {
  109. select {
  110. case e.events <- m:
  111. case <-ctx.Done():
  112. }
  113. }
  114. cancelC2S, err := e.bus.Subscribe(ctx, e.c2sTopic(), handler)
  115. if err != nil {
  116. if ctx.Err() != nil {
  117. return ctx.Err()
  118. }
  119. return e.finish(ctx, domain.FaultRecordStatusError, "订阅设备上行 topic 失败:"+err.Error(), nil)
  120. }
  121. defer cancelC2S()
  122. // 平台下发的 607/380/610 在 s2c 方向;订阅失败不影响主流程,只是看不到这些消息
  123. if cancelS2C, err := e.bus.Subscribe(ctx, e.s2cTopic(), handler); err == nil {
  124. defer cancelS2C()
  125. } else {
  126. zap.L().Warn("fault record subscribe s2c failed", zap.String("topic", e.s2cTopic()), zap.Error(err))
  127. }
  128. if op.Kind == domain.FaultRecordOpRecordFetch {
  129. for _, topic := range e.uploadTopics() {
  130. cancelUpload, err := e.bus.Subscribe(ctx, topic, handler)
  131. if err != nil {
  132. // 订阅失败时收不到 607~610,只能在超时后按规则直接下载
  133. zap.L().Warn("fault record subscribe upload topic failed", zap.String("topic", topic), zap.Error(err))
  134. continue
  135. }
  136. defer cancelUpload()
  137. }
  138. }
  139. // 结束前把已到达和稍后到达的报文(如 609 之后的 610)记录下来;先于取消订阅执行
  140. defer e.drain(ctx)
  141. switch op.Status {
  142. case domain.FaultRecordStatusPending:
  143. if done, err := e.send(ctx); done || err != nil {
  144. return err
  145. }
  146. case domain.FaultRecordStatusReady, domain.FaultRecordStatusUploading:
  147. // 恢复:文件名已知,先直接尝试下载,下载不到再继续等待 609
  148. if data, err := e.download(ctx); err == nil {
  149. return e.storeAndParse(ctx, data)
  150. }
  151. }
  152. return e.loop(ctx)
  153. }
  154. // send 发送 377;返回 done=true 表示操作已结束
  155. func (e *execution) send(ctx context.Context) (bool, error) {
  156. req, err := BuildRequest(e.op)
  157. if err != nil {
  158. return true, e.finish(ctx, domain.FaultRecordStatusError, "构造请求失败:"+err.Error(), nil)
  159. }
  160. if err := e.publish(ctx, req); err != nil {
  161. if ctx.Err() != nil {
  162. return true, ctx.Err()
  163. }
  164. return true, e.finish(ctx, domain.FaultRecordStatusError, "发送失败:"+err.Error(), nil)
  165. }
  166. return false, e.advance(ctx, domain.FaultRecordStatusSent, nil)
  167. }
  168. func (e *execution) publish(ctx context.Context, req proto.Request) error {
  169. msg, err := fwh_mqtt.NewEnvelope(proto.CmdTypeRequest, e.op.GatewaySn, req)
  170. if err != nil {
  171. return err
  172. }
  173. if err := e.bus.Publish(ctx, e.s2cTopic(), msg); err != nil {
  174. return err
  175. }
  176. raw, _ := json.Marshal(msg)
  177. e.record(ctx, "send", e.s2cTopic(), proto.CmdTypeRequest, raw, time.Now())
  178. return nil
  179. }
  180. func (e *execution) loop(ctx context.Context) error {
  181. ticker := time.NewTicker(e.d.timeouts.cancelPoll)
  182. defer ticker.Stop()
  183. for {
  184. timer := time.NewTimer(time.Until(e.deadline()))
  185. select {
  186. case <-ctx.Done():
  187. timer.Stop()
  188. return ctx.Err()
  189. case m := <-e.events:
  190. timer.Stop()
  191. if done, err := e.handle(ctx, m); done || err != nil {
  192. return err
  193. }
  194. case <-ticker.C:
  195. timer.Stop()
  196. if cur, err := e.d.store.Get(ctx, e.op.ID); err == nil && cur.CancelReq {
  197. return e.cancel(ctx)
  198. }
  199. case <-timer.C:
  200. return e.onTimeout(ctx)
  201. }
  202. }
  203. }
  204. func (e *execution) stageTime(s domain.FaultRecordOpStatus) time.Time {
  205. if t, ok := e.op.StageTimes[string(s)]; ok {
  206. return t
  207. }
  208. return time.Now()
  209. }
  210. func (e *execution) deadline() time.Time {
  211. t := e.d.timeouts
  212. switch e.op.Status {
  213. case domain.FaultRecordStatusSent:
  214. return e.stageTime(domain.FaultRecordStatusSent).Add(t.ack)
  215. case domain.FaultRecordStatusAccepted:
  216. if e.op.Kind == domain.FaultRecordOpRecordFetch {
  217. return e.stageTime(domain.FaultRecordStatusAccepted).Add(t.replyRecord + time.Duration(e.extraRecords())*t.replyPerRecord)
  218. }
  219. return e.stageTime(domain.FaultRecordStatusAccepted).Add(t.reply)
  220. default: // ready / uploading / uploaded
  221. start := e.stageTime(domain.FaultRecordStatusReady)
  222. if e.op.DownloadRetryAt != nil && e.op.Status == domain.FaultRecordStatusUploaded {
  223. start = *e.op.DownloadRetryAt // 手动重试下载:从重试时刻起重新计算总超时
  224. }
  225. return start.Add(t.upload + time.Duration(e.extraRecords())*t.uploadPerRecord)
  226. }
  227. }
  228. // extraRecords 第一条之外的记录数,用于按记录数延长等待
  229. func (e *execution) extraRecords() int {
  230. if n := len(e.op.Request.Indexes()); n > 1 {
  231. return n - 1
  232. }
  233. return 0
  234. }
  235. func (e *execution) onTimeout(ctx context.Context) error {
  236. switch e.op.Status {
  237. case domain.FaultRecordStatusSent:
  238. return e.finishTimeout(ctx, domain.FaultRecordStatusAccepted, "设备未应答指令(378)")
  239. case domain.FaultRecordStatusAccepted:
  240. return e.finishTimeout(ctx, domain.FaultRecordStatusReady, "设备未上传结果(379)")
  241. default:
  242. // 609 可能漏收,最后再尝试一次下载
  243. if data, err := e.download(ctx); err == nil {
  244. return e.storeAndParse(ctx, data)
  245. }
  246. return e.finishTimeout(ctx, domain.FaultRecordStatusUploaded, "未收到文件上传结果(609),且文件无法下载")
  247. }
  248. }
  249. // handle 处理一条收到的消息;返回 done=true 表示操作已结束
  250. func (e *execution) handle(ctx context.Context, m fwh_mqtt.Message) (bool, error) {
  251. cmdType, equipNo, da, err := proto.SplitEnvelope(m.Raw)
  252. if err != nil || (equipNo != "" && equipNo != e.op.GatewaySn) || !recordedCmdTypes[cmdType] {
  253. return false, nil
  254. }
  255. e.record(ctx, "recv", m.Topic, cmdType, m.Raw, m.ReceivedAt)
  256. switch cmdType {
  257. case proto.CmdTypeAck:
  258. ack, err := proto.ParseAck(da)
  259. if err != nil || ack.Cmd != e.op.Cmd || e.op.Status != domain.FaultRecordStatusSent {
  260. return false, nil
  261. }
  262. if !ack.Ok() {
  263. return true, e.finish(ctx, domain.FaultRecordStatusRejected, fmt.Sprintf("设备拒绝指令(378.result=%d)", ack.Result), nil)
  264. }
  265. return false, e.advance(ctx, domain.FaultRecordStatusAccepted, nil)
  266. case proto.CmdTypeReply:
  267. r, err := proto.ParseReply(da)
  268. if err != nil || r.Cmd != e.op.Cmd {
  269. return false, nil
  270. }
  271. if e.op.Status != domain.FaultRecordStatusSent && e.op.Status != domain.FaultRecordStatusAccepted {
  272. return false, nil
  273. }
  274. return e.handleReply(ctx, r)
  275. case proto.CmdTypeUploadCall:
  276. call, err := proto.ParseUploadCall(da)
  277. if err != nil || proto.BatchFromUploadFileName(call.FileName) != e.batch {
  278. return false, nil
  279. }
  280. switch e.op.Status {
  281. case domain.FaultRecordStatusReady:
  282. return false, e.advance(ctx, domain.FaultRecordStatusUploading, bson.M{"faultRecordId": call.FaultRecordID})
  283. case domain.FaultRecordStatusUploading, domain.FaultRecordStatusUploaded:
  284. // 608 可能先于 607 到达并已推进状态,此时只补记平台记录 ID
  285. return false, e.d.store.SetFields(ctx, e.op.ID, bson.M{"faultRecordId": call.FaultRecordID})
  286. }
  287. return false, nil
  288. case proto.CmdTypeUploadAck:
  289. // 608 在设备上行方向;订阅不到 607 时,靠它确认上传已开始并取得平台记录 ID
  290. ack, err := proto.ParseUploadAck(da)
  291. if err != nil || ack.Filename != e.batch || e.op.Status != domain.FaultRecordStatusReady {
  292. return false, nil
  293. }
  294. // 修复后的固件 608 不再带 id,此时不覆盖 607 给出的平台记录 ID
  295. extra := bson.M{}
  296. if ack.Id != 0 {
  297. extra["faultRecordId"] = ack.Id
  298. }
  299. return false, e.advance(ctx, domain.FaultRecordStatusUploading, extra)
  300. case proto.CmdTypeUploadDone:
  301. done, err := proto.ParseUploadDone(da)
  302. if err != nil || proto.BatchFromUploadFileName(done.FileName) != e.batch {
  303. return false, nil
  304. }
  305. if e.op.Status != domain.FaultRecordStatusReady && e.op.Status != domain.FaultRecordStatusUploading {
  306. return false, nil
  307. }
  308. if !done.Ok() {
  309. return true, e.finish(ctx, domain.FaultRecordStatusUploadFailed, fmt.Sprintf("设备上传文件失败(609.result=%d)", done.Result), nil)
  310. }
  311. if equipNo == "" {
  312. equipNo = e.op.GatewaySn
  313. }
  314. // 609 成功只推进状态,等平台应答 610 后再下载
  315. // 609.fileName 有的固件带 .tar.bz2、有的不带;统一补齐后缀,避免下载地址缺少后缀
  316. return false, e.advance(ctx, domain.FaultRecordStatusUploaded, bson.M{"fileName": proto.UploadFileName(done.FileName), "uploadEquipNo": equipNo})
  317. case proto.CmdTypeUploadDoneA:
  318. // 610 没有文件名,按“本操作收到 609 之后的下一条 610”对应;result 含义未确认,只记录不判断
  319. if e.op.Status != domain.FaultRecordStatusUploaded {
  320. return false, nil
  321. }
  322. return true, e.downloadUntilTimeout(ctx, e.d.timeouts.afterUploadAck, 0)
  323. }
  324. return false, nil
  325. }
  326. func (e *execution) handleReply(ctx context.Context, r proto.Reply) (bool, error) {
  327. if r.Busy() {
  328. return true, e.finish(ctx, domain.FaultRecordStatusBusy, "设备正在处理其他命令(可能来自 FWH 平台),请稍后再试", bson.M{"reply": r})
  329. }
  330. if r.IsErrorReply() {
  331. return true, e.finish(ctx, domain.FaultRecordStatusRejected, "设备拒绝命令:"+proto.DescribeReplyResult(r.Result), bson.M{"reply": r})
  332. }
  333. info, ok := r.FindInfo(e.op.DeviceType, e.op.DeviceSn)
  334. if !ok {
  335. return true, e.finish(ctx, domain.FaultRecordStatusRejected, "设备回复中没有目标设备", bson.M{"reply": r})
  336. }
  337. if e.op.Kind != domain.FaultRecordOpRecordFetch {
  338. status := domain.FaultRecordStatusDone
  339. if !r.Ok() {
  340. status = domain.FaultRecordStatusItemFailed
  341. }
  342. return true, e.finish(ctx, status, "", bson.M{"reply": r})
  343. }
  344. allOk := r.Ok() && len(info.IndexInfo) > 0
  345. for _, it := range info.IndexInfo {
  346. if it.ResultOne != proto.ResultOk {
  347. allOk = false
  348. }
  349. }
  350. if !allOk {
  351. return true, e.finish(ctx, domain.FaultRecordStatusItemFailed, "设备读取录波记录失败", bson.M{"reply": r})
  352. }
  353. if r.Filename == "" {
  354. return true, e.finish(ctx, domain.FaultRecordStatusRejected, "设备回复中没有文件名", bson.M{"reply": r})
  355. }
  356. e.batch = r.Filename
  357. return false, e.advance(ctx, domain.FaultRecordStatusReady, bson.M{"reply": r, "fileName": proto.UploadFileName(r.Filename)})
  358. }
  359. // uploadFileName 上传文件名:由批次名统一拼接 .tar.bz2
  360. func (e *execution) uploadFileName() string {
  361. return proto.UploadFileName(e.batch)
  362. }
  363. func (e *execution) uploadEquipNo() string {
  364. if e.op.UploadEquipNo != "" {
  365. return e.op.UploadEquipNo
  366. }
  367. return e.op.GatewaySn
  368. }
  369. // downloadUntilTimeout 等待 firstWait 后开始下载,失败后每隔 downloadInterval 再试,直到总超时;
  370. // 等待期间响应取消请求
  371. // maxAttempts 为 0 时不限次数(一直重试至总超时)
  372. func (e *execution) downloadUntilTimeout(ctx context.Context, firstWait time.Duration, maxAttempts int) error {
  373. deadline := e.deadline()
  374. wait := firstWait
  375. attempts := 0
  376. for {
  377. if cancelled, err := e.sleepCancellable(ctx, wait); err != nil {
  378. return err
  379. } else if cancelled {
  380. return e.cancel(ctx)
  381. }
  382. data, err := e.download(ctx)
  383. attempts++
  384. if err == nil {
  385. return e.storeAndParse(ctx, data)
  386. }
  387. if maxAttempts > 0 && attempts >= maxAttempts {
  388. return e.finish(ctx, domain.FaultRecordStatusDownloadFailed,
  389. fmt.Sprintf("重试下载失败,已尝试 %d 次:%s", attempts, err.Error()), nil)
  390. }
  391. remaining := time.Until(deadline)
  392. if remaining <= 0 {
  393. return e.finish(ctx, domain.FaultRecordStatusDownloadFailed,
  394. fmt.Sprintf("下载文件失败,已尝试 %d 次直至总超时:%s", attempts, err.Error()), nil)
  395. }
  396. wait = min(e.d.timeouts.downloadInterval, remaining)
  397. }
  398. }
  399. // sleepCancellable 等待 d;期间检查取消请求。返回 cancelled=true 表示用户请求取消
  400. func (e *execution) sleepCancellable(ctx context.Context, d time.Duration) (bool, error) {
  401. if d <= 0 {
  402. return false, nil
  403. }
  404. timer := time.NewTimer(d)
  405. defer timer.Stop()
  406. ticker := time.NewTicker(e.d.timeouts.cancelPoll)
  407. defer ticker.Stop()
  408. for {
  409. select {
  410. case <-ctx.Done():
  411. return false, ctx.Err()
  412. case <-timer.C:
  413. return false, nil
  414. case <-ticker.C:
  415. if cur, err := e.d.store.Get(ctx, e.op.ID); err == nil && cur.CancelReq {
  416. return true, nil
  417. }
  418. }
  419. }
  420. }
  421. func (e *execution) storeAndParse(ctx context.Context, data []byte) error {
  422. key, err := minioRepo.FaultRecordObjectKey(e.op.Env, e.op.GatewaySn, e.uploadFileName())
  423. if err != nil {
  424. return e.finish(ctx, domain.FaultRecordStatusDownloadFailed, err.Error(), nil)
  425. }
  426. if err := e.d.files.Put(ctx, key, data); err != nil {
  427. return e.finish(ctx, domain.FaultRecordStatusDownloadFailed, "保存文件失败:"+err.Error(), nil)
  428. }
  429. if err := e.advance(ctx, domain.FaultRecordStatusDownloaded, bson.M{"minioObject": key, "fileSize": len(data)}); err != nil {
  430. return err
  431. }
  432. return e.parse(ctx, data)
  433. }
  434. func (e *execution) parse(ctx context.Context, data []byte) error {
  435. records, err := faultRecordFile.ParseArchive(data, e.op.DeviceType)
  436. if err != nil {
  437. return e.finish(ctx, domain.FaultRecordStatusParseFailed, "文件已保存,但解析失败:"+err.Error(), nil)
  438. }
  439. // 核对压缩包中是否包含全部请求的记录
  440. got := map[int]bool{}
  441. for _, r := range records {
  442. got[r.RecordIndex] = true
  443. }
  444. var missing []string
  445. for _, i := range e.op.Request.Indexes() {
  446. if !got[i] {
  447. missing = append(missing, strconv.Itoa(i))
  448. }
  449. }
  450. msg := ""
  451. if len(missing) > 0 {
  452. msg = "压缩包中缺少记录序号:" + strings.Join(missing, ",")
  453. }
  454. return e.finish(ctx, domain.FaultRecordStatusDone, msg, nil)
  455. }
  456. // download 下载上传的文件,并把每次下载作为一条 http 记录写入原始报文
  457. func (e *execution) download(ctx context.Context) ([]byte, error) {
  458. equipNo := e.uploadEquipNo()
  459. // 每次下载都按规则重新拼接文件名(批次名 + .tar.bz2),不依赖已保存的文件名是否带后缀
  460. fileName := e.uploadFileName()
  461. entry := map[string]any{
  462. "env": e.op.Env,
  463. "path": "/hes-upload/v1/file/download/logger/" + equipNo + "/" + fileName,
  464. }
  465. if e.d.downloadURL != nil {
  466. entry["url"] = e.d.downloadURL(e.op.Env, equipNo, fileName)
  467. }
  468. start := time.Now()
  469. data, err := e.d.download(e.op.Env, equipNo, fileName)
  470. now := time.Now()
  471. entry["durationMs"] = now.Sub(start).Milliseconds()
  472. topic := "GET " + entry["path"].(string)
  473. if err == nil {
  474. entry["result"] = "ok"
  475. entry["size"] = len(data)
  476. raw, _ := json.Marshal(entry)
  477. e.record(ctx, "http", topic, 0, raw, now)
  478. e.lastFail = nil
  479. return data, nil
  480. }
  481. entry["result"] = "failed"
  482. entry["error"] = err.Error()
  483. key := topic + "|" + err.Error()
  484. // 与上一条记录是同一种失败:只保留最后一条,累计次数
  485. if f := e.lastFail; f != nil && f.key == key && f.index == e.msgCount-1 {
  486. f.count++
  487. entry["count"] = f.count
  488. entry["firstAt"] = f.firstAt
  489. raw, _ := json.Marshal(entry)
  490. e.replaceMessage(ctx, f.index, domain.FaultRecordOpMessage{Direction: "http", Topic: topic, At: now, Raw: string(raw)})
  491. return nil, err
  492. }
  493. entry["count"] = 1
  494. entry["firstAt"] = now
  495. raw, _ := json.Marshal(entry)
  496. e.record(ctx, "http", topic, 0, raw, now)
  497. e.lastFail = &downloadFailure{index: e.msgCount - 1, key: key, count: 1, firstAt: now}
  498. return nil, err
  499. }
  500. // drain 记录结束时缓冲区中的报文,并在短时间内继续记录随后到达的报文
  501. func (e *execution) drain(ctx context.Context) {
  502. if e.events == nil || ctx.Err() != nil {
  503. return
  504. }
  505. timer := time.NewTimer(e.d.timeouts.drain)
  506. defer timer.Stop()
  507. for {
  508. select {
  509. case m := <-e.events:
  510. if cmdType, equipNo, _, err := proto.SplitEnvelope(m.Raw); err == nil && recordedCmdTypes[cmdType] && (equipNo == "" || equipNo == e.op.GatewaySn) {
  511. e.record(ctx, "recv", m.Topic, cmdType, m.Raw, m.ReceivedAt)
  512. }
  513. case <-timer.C:
  514. return
  515. case <-ctx.Done():
  516. return
  517. }
  518. }
  519. }
  520. // cancel 设备正在处理本操作的命令时发送 cmd=4,其余阶段只停止等待
  521. func (e *execution) cancel(ctx context.Context) error {
  522. extra := bson.M{}
  523. msg := ""
  524. if e.op.Status == domain.FaultRecordStatusSent || e.op.Status == domain.FaultRecordStatusAccepted {
  525. if err := e.publish(ctx, proto.NewExitRequest()); err != nil {
  526. msg = "发送退出命令失败:" + err.Error()
  527. } else {
  528. extra["exitSent"] = true
  529. }
  530. }
  531. return e.finish(ctx, domain.FaultRecordStatusCancelled, msg, extra)
  532. }
  533. func (e *execution) record(ctx context.Context, dir, topic string, cmdType uint, raw []byte, at time.Time) {
  534. err := e.d.store.AppendMessage(ctx, e.op.ID, domain.FaultRecordOpMessage{
  535. Direction: dir, Topic: topic, CmdType: cmdType, At: at, Raw: string(raw),
  536. })
  537. if err != nil {
  538. zap.L().Warn("fault record append message failed", zap.String("id", e.op.ID.Hex()), zap.Error(err))
  539. return
  540. }
  541. e.msgCount++
  542. }
  543. func (e *execution) replaceMessage(ctx context.Context, index int, msg domain.FaultRecordOpMessage) {
  544. if err := e.d.store.SetFields(ctx, e.op.ID, bson.M{fmt.Sprintf("messages.%d", index): msg}); err != nil {
  545. zap.L().Warn("fault record replace message failed", zap.String("id", e.op.ID.Hex()), zap.Error(err))
  546. }
  547. }
  548. func (e *execution) advance(ctx context.Context, status domain.FaultRecordOpStatus, extra bson.M) error {
  549. if _, err := e.d.store.UpdateStatus(ctx, e.op.ID, status, extra); err != nil {
  550. return err
  551. }
  552. e.op.Status = status
  553. if e.op.StageTimes == nil {
  554. e.op.StageTimes = map[string]time.Time{}
  555. }
  556. e.op.StageTimes[string(status)] = time.Now()
  557. if v, ok := extra["fileName"].(string); ok {
  558. e.op.FileName = v
  559. }
  560. if v, ok := extra["uploadEquipNo"].(string); ok {
  561. e.op.UploadEquipNo = v
  562. }
  563. return nil
  564. }
  565. func (e *execution) finish(ctx context.Context, status domain.FaultRecordOpStatus, msg string, extra bson.M) error {
  566. if extra == nil {
  567. extra = bson.M{}
  568. }
  569. if msg != "" {
  570. extra["error"] = msg
  571. }
  572. return e.advance(ctx, status, extra)
  573. }
  574. func (e *execution) finishTimeout(ctx context.Context, waiting domain.FaultRecordOpStatus, msg string) error {
  575. return e.finish(ctx, domain.FaultRecordStatusTimeout, msg, bson.M{"timeoutStage": waiting})
  576. }