serial_worker.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. package device
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "sync/atomic"
  7. "time"
  8. "google.golang.org/protobuf/types/known/timestamppb"
  9. "hth/internal/backend"
  10. "hth/internal/config"
  11. hthv1 "hth/internal/gen/hth/api/v1"
  12. "hth/internal/grpcserver"
  13. "hth/internal/protocol"
  14. )
  15. type jobKind int
  16. const (
  17. jobOpen jobKind = iota
  18. jobGetTemp
  19. jobGetMotor
  20. jobSetAllApply
  21. jobSetAllHB
  22. jobSetAllSafe
  23. )
  24. const originEpochBaseline = "epoch_safe_baseline"
  25. const originShutdown = "shutdown"
  26. type serialJob struct {
  27. id uint64
  28. portGen uint64
  29. epoch uint64
  30. kind jobKind
  31. origin string
  32. commandID string
  33. peerUID int32
  34. peerGID int32
  35. peerPID int32
  36. startedAt time.Time
  37. deadline time.Time
  38. timeout time.Duration
  39. frame protocol.SetAll
  40. ax ActionExecutionContext
  41. }
  42. // ActionExecutionContext is the Actor-owned identity of one physical SET_ALL.
  43. // Call sites must not invent command IDs, epochs, or peer credentials ad hoc.
  44. type ActionExecutionContext struct {
  45. CommandID string
  46. Origin string
  47. Mode hthv1.ActionMode
  48. DeviceEpoch uint64
  49. PortGeneration uint64
  50. JobID uint64
  51. LeaseID string
  52. LeaseEpoch uint64
  53. PeerUID int32
  54. PeerGID int32
  55. PeerPID int32
  56. RequestedAt time.Time
  57. QueuedAt time.Time
  58. DispatchStartedAt time.Time
  59. ValidUntil time.Time
  60. Frame protocol.SetAll
  61. Requested *hthv1.ActionBatch
  62. Normalized protocol.SetAll
  63. Accepted protocol.SetAll
  64. EffectiveTarget protocol.SetAll
  65. }
  66. func (d *Device) newActionContext(commandID, origin string, mode hthv1.ActionMode, frame protocol.SetAll, rpcCtx context.Context) ActionExecutionContext {
  67. now := d.clk.Now()
  68. if commandID == "" {
  69. commandID = d.nextInternalCommandID(origin)
  70. }
  71. ax := ActionExecutionContext{
  72. CommandID: commandID,
  73. Origin: origin,
  74. Mode: mode,
  75. DeviceEpoch: d.store.Epoch(),
  76. PortGeneration: d.portGen,
  77. Frame: frame,
  78. RequestedAt: now,
  79. QueuedAt: now,
  80. EffectiveTarget: frame,
  81. }
  82. if rpcCtx != nil {
  83. if cred, ok := grpcserver.PeerFromContext(rpcCtx); ok {
  84. ax.PeerUID, ax.PeerGID, ax.PeerPID = cred.UID, cred.GID, cred.PID
  85. }
  86. }
  87. return ax
  88. }
  89. func (d *Device) serialJobFromAction(kind jobKind, timeout time.Duration, ax ActionExecutionContext) serialJob {
  90. return serialJob{
  91. kind: kind,
  92. timeout: timeout,
  93. frame: ax.Frame,
  94. origin: ax.Origin,
  95. commandID: ax.CommandID,
  96. peerUID: ax.PeerUID,
  97. peerGID: ax.PeerGID,
  98. peerPID: ax.PeerPID,
  99. portGen: ax.PortGeneration,
  100. epoch: ax.DeviceEpoch,
  101. ax: ax,
  102. }
  103. }
  104. func bindActionRecord(rec *hthv1.ActionRecord, ax ActionExecutionContext, dispatch hthv1.ActionDispatchState) *hthv1.ActionRecord {
  105. if rec == nil {
  106. return nil
  107. }
  108. if rec.CommandId == "" {
  109. rec.CommandId = ax.CommandID
  110. }
  111. rec.Origin = ax.Origin
  112. rec.ActionMode = ax.Mode
  113. rec.ActionEpoch = ax.DeviceEpoch
  114. rec.PortGeneration = ax.PortGeneration
  115. rec.PeerUid = ax.PeerUID
  116. rec.PeerGid = ax.PeerGID
  117. rec.PeerPid = ax.PeerPID
  118. rec.DispatchState = dispatch
  119. return rec
  120. }
  121. type serialResult struct {
  122. id uint64
  123. portGen uint64
  124. epoch uint64
  125. kind jobKind
  126. origin string
  127. commandID string
  128. peerUID int32
  129. peerGID int32
  130. peerPID int32
  131. started time.Time
  132. wr backend.WriteResult
  133. err error
  134. temp *backend.TempReport
  135. motor *backend.MotorReport
  136. frame protocol.SetAll
  137. ax ActionExecutionContext
  138. }
  139. type inflightIdent struct {
  140. id uint64
  141. portGen uint64
  142. epoch uint64
  143. kind jobKind
  144. origin string
  145. startedAt time.Time
  146. }
  147. type pendingResumeState struct {
  148. req req
  149. prepared *hthv1.ActionResult
  150. target protocol.SetAll
  151. credit map[string]float64
  152. commandID string
  153. leaseID string
  154. leaseEp uint64
  155. devEpoch uint64
  156. validUntil time.Time
  157. acceptedAt time.Time
  158. }
  159. type pendingSafeState struct {
  160. commandID string
  161. reason string
  162. origin string
  163. peerUID int32
  164. peerGID int32
  165. peerPID int32
  166. enqueued time.Time
  167. deadline time.Time
  168. epoch uint64
  169. requestedAt time.Time
  170. attempts int
  171. maxAttempts int
  172. nextRetry time.Time
  173. }
  174. const safeNotStartedRetry = 50 * time.Millisecond
  175. const safeNotStartedMaxAttempts = 8
  176. func (d *Device) newPendingSafe(cmd, reason, origin string, rpcCtx context.Context) *pendingSafeState {
  177. now := d.clk.Now()
  178. wait := d.cfg.SetAllTimeout() + d.remainingInflight()
  179. st := &pendingSafeState{
  180. commandID: cmd,
  181. reason: reason,
  182. origin: origin,
  183. enqueued: now,
  184. deadline: now.Add(wait),
  185. epoch: d.store.Epoch(),
  186. requestedAt: now,
  187. maxAttempts: safeNotStartedMaxAttempts,
  188. }
  189. if rpcCtx != nil {
  190. if cred, ok := grpcserver.PeerFromContext(rpcCtx); ok {
  191. st.peerUID, st.peerGID, st.peerPID = cred.UID, cred.GID, cred.PID
  192. }
  193. }
  194. return st
  195. }
  196. func (d *Device) markProgress() {
  197. atomic.StoreInt64(&d.progressUnix, time.Now().UnixNano())
  198. }
  199. func (d *Device) ActorProgress() time.Time {
  200. n := atomic.LoadInt64(&d.progressUnix)
  201. if n == 0 {
  202. return time.Time{}
  203. }
  204. return time.Unix(0, n)
  205. }
  206. func (d *Device) serialInflight() bool {
  207. return atomic.LoadInt64(&d.inflightSinceNano) != 0
  208. }
  209. func (d *Device) beginInflight(j serialJob) {
  210. atomic.StoreInt64(&d.inflightSinceNano, time.Now().UnixNano())
  211. d.inflightMu.Lock()
  212. d.currentInflight = inflightIdent{
  213. id: j.id, portGen: j.portGen, epoch: j.epoch, kind: j.kind,
  214. origin: j.origin, startedAt: j.startedAt,
  215. }
  216. d.inflightMu.Unlock()
  217. }
  218. func (d *Device) endInflight() {
  219. atomic.StoreInt64(&d.inflightSinceNano, 0)
  220. d.inflightTimeout = 0
  221. d.inflightKind = 0
  222. d.inflightMu.Lock()
  223. d.currentInflight = inflightIdent{}
  224. d.inflightMu.Unlock()
  225. }
  226. func (d *Device) inflightSnapshot() inflightIdent {
  227. d.inflightMu.Lock()
  228. defer d.inflightMu.Unlock()
  229. return d.currentInflight
  230. }
  231. func (d *Device) resultMatchesInflight(res serialResult) bool {
  232. inf := d.inflightSnapshot()
  233. if inf.id == 0 {
  234. return false
  235. }
  236. return res.id == inf.id && res.portGen == inf.portGen && res.epoch == inf.epoch && res.kind == inf.kind
  237. }
  238. func (d *Device) SerialBusy() time.Duration {
  239. n := atomic.LoadInt64(&d.inflightSinceNano)
  240. if n == 0 {
  241. return 0
  242. }
  243. return time.Since(time.Unix(0, n))
  244. }
  245. func (d *Device) schedulerMargin() time.Duration {
  246. if d.caps != nil && d.caps.Timing != nil && d.caps.Timing.SchedulerMarginMs > 0 {
  247. return time.Duration(d.caps.Timing.SchedulerMarginMs) * time.Millisecond
  248. }
  249. return 50 * time.Millisecond
  250. }
  251. func (d *Device) remainingInflight() time.Duration {
  252. if !d.serialInflight() {
  253. return 0
  254. }
  255. to := d.inflightTimeout
  256. if to <= 0 {
  257. to = d.worstCaseJob(d.inflightKind)
  258. }
  259. elapsed := d.SerialBusy()
  260. rem := to - elapsed
  261. if rem < 0 {
  262. rem = 0
  263. }
  264. return rem + d.schedulerMargin()
  265. }
  266. func (d *Device) worstCaseJob(k jobKind) time.Duration {
  267. switch k {
  268. case jobGetTemp:
  269. return d.cfg.GetTempTimeout(d.prof)
  270. case jobGetMotor:
  271. return d.cfg.GetMotorTimeout()
  272. case jobOpen:
  273. return d.cfg.OpenTimeout()
  274. default:
  275. return d.cfg.SetAllTimeout()
  276. }
  277. }
  278. func (d *Device) minControlPeriod() time.Duration {
  279. if d.caps != nil && d.caps.Timing != nil && d.caps.Timing.MinimumControlPeriodMs > 0 {
  280. return time.Duration(d.caps.Timing.MinimumControlPeriodMs) * time.Millisecond
  281. }
  282. return 50 * time.Millisecond
  283. }
  284. func (d *Device) leaseActive(now time.Time) bool {
  285. if d.lease == nil {
  286. return false
  287. }
  288. l := d.lease.Current()
  289. return l != nil && l.Active(now)
  290. }
  291. func (d *Device) controlWindowOpen(now time.Time) bool {
  292. return d.leaseActive(now) && !d.controlWindowUntil.IsZero() && now.Before(d.controlWindowUntil)
  293. }
  294. func (d *Device) deadlineUnmeetable(batch *hthv1.ActionBatch) string {
  295. if batch == nil || batch.ValidUntil == nil {
  296. return ""
  297. }
  298. now := d.clk.Now()
  299. until := batch.ValidUntil.AsTime()
  300. if !until.After(now) {
  301. return "valid_until expired before first hardware write"
  302. }
  303. need := d.remainingInflight()
  304. if need <= 0 {
  305. return ""
  306. }
  307. if !until.After(now.Add(need)) {
  308. return fmt.Sprintf("valid_until cannot wait for in-flight serial (%s remaining); rejected before enqueue", need.Round(time.Millisecond))
  309. }
  310. return ""
  311. }
  312. func (d *Device) nextJobID() uint64 {
  313. d.jobSeq++
  314. return d.jobSeq
  315. }
  316. func (d *Device) nextInternalCommandID(origin string) string {
  317. d.cmdSeq++
  318. return fmt.Sprintf("%s:%d:%d:%s", d.daemon, d.store.Epoch(), d.cmdSeq, origin)
  319. }
  320. func (d *Device) enqueueSerial(j serialJob) bool {
  321. if d.serialInflight() {
  322. return false
  323. }
  324. if j.kind != jobOpen && !d.connected {
  325. return false
  326. }
  327. now := d.clk.Now()
  328. j.id = d.nextJobID()
  329. if j.portGen == 0 {
  330. j.portGen = d.portGen
  331. }
  332. if j.epoch == 0 {
  333. j.epoch = d.store.Epoch()
  334. }
  335. j.startedAt = now
  336. j.ax.JobID = j.id
  337. if j.ax.PortGeneration == 0 {
  338. j.ax.PortGeneration = j.portGen
  339. }
  340. if j.ax.DeviceEpoch == 0 {
  341. j.ax.DeviceEpoch = j.epoch
  342. }
  343. j.ax.DispatchStartedAt = now
  344. if j.ax.QueuedAt.IsZero() {
  345. j.ax.QueuedAt = now
  346. }
  347. if j.timeout > 0 {
  348. j.deadline = now.Add(j.timeout)
  349. }
  350. d.inflightTimeout = j.timeout
  351. d.inflightKind = j.kind
  352. d.beginInflight(j)
  353. select {
  354. case d.jobs <- j:
  355. return true
  356. default:
  357. d.endInflight()
  358. return false
  359. }
  360. }
  361. func (d *Device) serialWorker(ctx context.Context) {
  362. for {
  363. select {
  364. case <-ctx.Done():
  365. return
  366. case j := <-d.jobs:
  367. res := d.execSerial(ctx, j)
  368. select {
  369. case d.results <- res:
  370. case <-ctx.Done():
  371. return
  372. }
  373. }
  374. }
  375. }
  376. func (d *Device) execSerial(parent context.Context, j serialJob) serialResult {
  377. to := j.timeout
  378. if to <= 0 {
  379. to = 2 * time.Second
  380. }
  381. ctx, cancel := context.WithTimeout(parent, to)
  382. defer cancel()
  383. out := serialResult{
  384. id: j.id, portGen: j.portGen, epoch: j.epoch, kind: j.kind,
  385. origin: j.origin, commandID: j.commandID,
  386. peerUID: j.peerUID, peerGID: j.peerGID, peerPID: j.peerPID,
  387. started: j.startedAt, frame: j.frame, ax: j.ax,
  388. }
  389. switch j.kind {
  390. case jobOpen:
  391. out.err = d.backend.Open(ctx)
  392. if out.err != nil {
  393. _ = d.backend.Close()
  394. }
  395. case jobGetTemp:
  396. out.temp, out.err = d.backend.GetTemperature(ctx)
  397. case jobGetMotor:
  398. out.motor, out.err = d.backend.GetMotorStatus(ctx)
  399. case jobSetAllApply, jobSetAllHB, jobSetAllSafe:
  400. out.wr, out.err = d.backend.WriteSetAll(ctx, j.frame)
  401. }
  402. return out
  403. }
  404. func (d *Device) applySerialResult(ctx context.Context, res serialResult, backoff *time.Duration, next *time.Time) {
  405. if !d.resultMatchesInflight(res) {
  406. inf := d.inflightSnapshot()
  407. d.log.Warn("discarding stale serial result",
  408. "job_id", res.id, "job_epoch", res.epoch, "job_port_gen", res.portGen,
  409. "inflight_id", inf.id, "inflight_epoch", inf.epoch,
  410. "inflight_port_gen", inf.portGen, "kind", int(res.kind))
  411. return
  412. }
  413. d.endInflight()
  414. d.markProgress()
  415. if res.kind == jobOpen {
  416. d.onOpenResult(ctx, res, backoff, next)
  417. return
  418. }
  419. if res.err != nil && res.kind != jobSetAllApply && res.kind != jobSetAllHB && res.kind != jobSetAllSafe {
  420. d.log.Warn("serial transaction failed", "kind", int(res.kind), "origin", res.origin, "err", res.err)
  421. if errors.Is(res.err, backend.ErrResponseTimeout) {
  422. d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_RESPONSE_TIMEOUT, d.id, "", res.err.Error(), "", nil)
  423. if res.kind == jobGetTemp {
  424. d.pendingTemp = true
  425. }
  426. d.kickPendingSerial(ctx)
  427. return
  428. }
  429. d.handleIOErr(ctx, res.err, backoff, next)
  430. d.kickPendingSerial(ctx)
  431. return
  432. }
  433. switch res.kind {
  434. case jobGetTemp:
  435. if res.temp != nil {
  436. d.lastTemp = d.clk.Now()
  437. d.applyTempMeas(res.temp)
  438. d.publishNow()
  439. }
  440. if d.leaseActive(d.clk.Now()) {
  441. d.controlWindowUntil = d.clk.Now().Add(d.minControlPeriod())
  442. }
  443. case jobGetMotor:
  444. if res.motor != nil {
  445. d.applyMotorReport(res.motor)
  446. }
  447. case jobSetAllApply:
  448. d.finishApplyWrite(ctx, res)
  449. case jobSetAllHB:
  450. d.finishHeartbeat(ctx, res)
  451. case jobSetAllSafe:
  452. d.finishSafeWrite(ctx, res)
  453. }
  454. d.kickPendingSerial(ctx)
  455. }
  456. func (d *Device) onOpenResult(ctx context.Context, res serialResult, backoff *time.Duration, next *time.Time) {
  457. if res.err != nil {
  458. kind := backend.ClassifyOpen(res.err)
  459. t := hthv1.FaultType_FAULT_TYPE_SERIAL_DEVICE_NOT_FOUND
  460. if kind == "permission" {
  461. t = hthv1.FaultType_FAULT_TYPE_SERIAL_PERMISSION_DENIED
  462. }
  463. if d.cfg.Backend == config.BackendSerial {
  464. d.book.Raise(d.clk.Now(), t, d.id, "", res.err.Error(), "", map[string]string{"class": kind})
  465. d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_SERIAL_RECONNECTING, d.id, "", "reconnect backoff", "", nil)
  466. }
  467. *backoff = serialBackoff(*backoff)
  468. *next = d.clk.Now().Add(*backoff)
  469. d.connected = false
  470. d.log.Warn("serial open failed", "class", kind, "err", res.err)
  471. d.publishNow()
  472. return
  473. }
  474. *backoff = 0
  475. d.connected = true
  476. d.inflightMu.Lock()
  477. d.portGen++
  478. d.inflightMu.Unlock()
  479. d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_PROBING)
  480. d.book.Clear(hthv1.FaultType_FAULT_TYPE_SERIAL_DISCONNECTED, d.id, "", d.clk.Now())
  481. d.book.Clear(hthv1.FaultType_FAULT_TYPE_SERIAL_RECONNECTING, d.id, "", d.clk.Now())
  482. d.publishNow()
  483. frame := d.safeFrame()
  484. ax := d.newActionContext("", originEpochBaseline, hthv1.ActionMode_ACTION_MODE_SAFE, frame, nil)
  485. if !d.enqueueSerial(d.serialJobFromAction(jobSetAllSafe, d.cfg.SetAllTimeout(), ax)) {
  486. d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_DEGRADED)
  487. }
  488. }
  489. func (d *Device) finishApplyWrite(ctx context.Context, sr serialResult) {
  490. job := d.applyJob
  491. d.applyJob = nil
  492. if job == nil || job.result == nil {
  493. if backend.WriteNeedsReconnect(sr.wr, sr.err) {
  494. d.onDrop(ctx, fmt.Errorf("orphaned apply write %s: %v", sr.wr.Outcome, sr.err))
  495. }
  496. return
  497. }
  498. now := d.clk.Now()
  499. out := job.result
  500. if sr.wr.Outcome == backend.WriteNotStarted {
  501. out.Accepted = false
  502. out.RejectReason = hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE
  503. out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED
  504. out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED
  505. out.Message = "serial write not started"
  506. if job.resume {
  507. d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, "resume_not_started")
  508. }
  509. d.recordAction(out)
  510. d.publishActionResult(out)
  511. replyNonblock(job.reply, res{action: out})
  512. return
  513. }
  514. conf := hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED
  515. if backend.WriteNeedsReconnect(sr.wr, sr.err) {
  516. conf = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN
  517. d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_CONTROL_OUTCOME_UNKNOWN, d.id, job.batch.GetCommandId(), fmt.Sprintf("write outcome unknown: %v", sr.err), "", nil)
  518. out.Confirmation = conf
  519. out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN
  520. out.Message = "OUTCOME_UNKNOWN; transport closed, epoch bumped, lease invalidated; action not auto-replayed"
  521. out.DeviceEpoch = d.store.Epoch()
  522. if job.resume {
  523. d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, "resume_unknown")
  524. }
  525. d.lease.Cache().Store(job.batch.CommandId, job.payload, out)
  526. d.recordAction(out)
  527. d.publishActionResult(out)
  528. replyNonblock(job.reply, res{action: out})
  529. d.onDrop(ctx, fmt.Errorf("ambiguous serial write outcome=%v err=%v", sr.wr.Outcome, sr.err))
  530. return
  531. }
  532. d.lastCont = job.target
  533. d.haveCont = true
  534. d.haveDispatch = true
  535. d.lastDispatchAt = now
  536. d.lastHWHeartbeat = now
  537. d.hbPendingSince = time.Time{}
  538. d.pendingHB = false
  539. if job.credit != nil {
  540. d.slewCredit = job.credit
  541. }
  542. if job.resume {
  543. d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL, "resume_dispatched")
  544. d.safeMode = false
  545. if d.startupDone {
  546. d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_READY)
  547. }
  548. d.publishEvent(hthv1.EventKind_EVENT_KIND_RESUME_FROM_SAFE, job.batch.GetCommandId())
  549. }
  550. d.store.BumpControlRevision()
  551. out.Confirmation = conf
  552. out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED
  553. out.ControlRevision = d.store.ControlRevision()
  554. ax := job.ax
  555. if ax.CommandID == "" {
  556. ax = d.newActionContext(job.batch.GetCommandId(), "apply", hthv1.ActionMode_ACTION_MODE_NORMAL, job.target, nil)
  557. }
  558. ax.EffectiveTarget = job.target
  559. stampResultContext(out, ax)
  560. out.DeviceEpoch = ax.DeviceEpoch
  561. out.PortGeneration = ax.PortGeneration
  562. out.Dispatched = recordFromAction(ax, now, conf, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED)
  563. out.AcceptedAction = recordFromAction(ax, now, conf, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED)
  564. d.lease.Cache().Store(job.batch.CommandId, job.payload, out)
  565. d.recordAction(out)
  566. d.publishActionResult(out)
  567. d.publishNow()
  568. replyNonblock(job.reply, res{action: out})
  569. }
  570. func (d *Device) finishHeartbeat(ctx context.Context, res serialResult) {
  571. now := d.clk.Now()
  572. origin := res.origin
  573. if origin == "" {
  574. origin = "watchdog_heartbeat_repeat_continuous"
  575. }
  576. cmd := res.commandID
  577. if cmd == "" {
  578. cmd = fmt.Sprintf("%s:heartbeat-job:%d", d.daemon, res.id)
  579. }
  580. if res.wr.Outcome == backend.WriteFullyWritten && res.err == nil {
  581. d.lastHWHeartbeat = now
  582. d.hbPendingSince = time.Time{}
  583. d.pendingHB = false
  584. d.hbDeliveryState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED
  585. d.hub.PublishEvent(&hthv1.Event{
  586. EventId: d.store.NextEventID(), Kind: hthv1.EventKind_EVENT_KIND_WATCHDOG_HEARTBEAT,
  587. WallTime: timestamppb.New(now), DeviceId: d.id, Message: origin,
  588. PortGeneration: res.portGen,
  589. })
  590. ax := res.ax
  591. if ax.CommandID == "" {
  592. ax = ActionExecutionContext{
  593. CommandID: cmd, Origin: origin, Mode: hthv1.ActionMode_ACTION_MODE_HEARTBEAT,
  594. DeviceEpoch: res.epoch, PortGeneration: res.portGen, EffectiveTarget: res.frame, Frame: res.frame,
  595. }
  596. }
  597. rec := recordFromAction(ax, now, hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED,
  598. hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED)
  599. d.publishActionResult(&hthv1.ActionResult{
  600. CommandId: cmd, Accepted: true, DeviceEpoch: ax.DeviceEpoch, PortGeneration: ax.PortGeneration,
  601. ActionOrigin: origin, Dispatched: rec,
  602. Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED,
  603. DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED,
  604. Message: "hardware heartbeat dispatched UNCONFIRMED; control_revision unchanged",
  605. ControlRevision: d.store.ControlRevision(),
  606. })
  607. d.publishNow()
  608. return
  609. }
  610. if res.wr.Outcome == backend.WriteNotStarted {
  611. d.hbDeliveryState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED
  612. d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_SAFE_ACTION_NOT_DELIVERED, d.id, origin,
  613. fmt.Sprintf("heartbeat NOT_STARTED n=%d err=%v", res.wr.N, res.err), "", nil)
  614. d.publishActionResult(&hthv1.ActionResult{
  615. CommandId: cmd, Accepted: false,
  616. Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED,
  617. DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED,
  618. Message: "hardware heartbeat not started; not counted as success",
  619. DeviceEpoch: res.epoch, PortGeneration: res.portGen, ActionOrigin: origin,
  620. ControlRevision: d.store.ControlRevision(),
  621. })
  622. d.publishNow()
  623. if d.watchdogMargin() < d.cfg.Heartbeat()*2 {
  624. d.pendingHB = true
  625. }
  626. return
  627. }
  628. d.hbDeliveryState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN
  629. d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_CONTROL_OUTCOME_UNKNOWN, d.id, origin,
  630. fmt.Sprintf("heartbeat %s: %v", res.wr.Outcome, res.err), "", nil)
  631. d.publishActionResult(&hthv1.ActionResult{
  632. CommandId: cmd, Accepted: false,
  633. Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN,
  634. DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN,
  635. Message: "hardware heartbeat outcome unknown; transport dropped",
  636. DeviceEpoch: res.epoch, PortGeneration: res.portGen, ActionOrigin: origin,
  637. ControlRevision: d.store.ControlRevision(),
  638. })
  639. d.onDrop(ctx, fmt.Errorf("heartbeat write %s: %v", res.wr.Outcome, res.err))
  640. }
  641. func (d *Device) watchdogTimeout() time.Duration {
  642. if d.prof != nil && d.prof.Watchdog.TimeoutSeconds > 0 {
  643. return time.Duration(d.prof.Watchdog.TimeoutSeconds) * time.Second
  644. }
  645. return 30 * time.Second
  646. }
  647. func (d *Device) watchdogMargin() time.Duration {
  648. to := d.watchdogTimeout()
  649. if d.lastHWHeartbeat.IsZero() {
  650. return 0
  651. }
  652. elapsed := d.clk.Now().Sub(d.lastHWHeartbeat)
  653. if elapsed >= to {
  654. return 0
  655. }
  656. return to - elapsed
  657. }
  658. func (d *Device) markHeartbeatPending() {
  659. if d.draining || !d.connected || !d.startupDone || !d.baselineReady || !d.haveCont {
  660. return
  661. }
  662. d.pendingHB = true
  663. if d.hbPendingSince.IsZero() {
  664. d.hbPendingSince = d.clk.Now()
  665. }
  666. }
  667. func (d *Device) heartbeatDue() bool {
  668. if d.draining || !d.connected || !d.startupDone || !d.baselineReady || !d.haveCont {
  669. return false
  670. }
  671. if d.backend.PollMode() != backend.PollUART {
  672. return false
  673. }
  674. if d.pendingHB {
  675. return true
  676. }
  677. if d.lastHWHeartbeat.IsZero() {
  678. return true
  679. }
  680. return !d.clk.Now().Before(d.lastHWHeartbeat.Add(d.cfg.Heartbeat()))
  681. }
  682. func (d *Device) maxAllowedHeartbeatGap() time.Duration {
  683. fw := d.watchdogTimeout()
  684. gap := d.cfg.Heartbeat() * 3
  685. if gap >= fw {
  686. gap = fw - time.Second
  687. if gap < d.cfg.Heartbeat() {
  688. gap = d.cfg.Heartbeat()
  689. }
  690. }
  691. return gap
  692. }
  693. func (d *Device) temperatureWouldStarveWatchdog() bool {
  694. if d.lastHWHeartbeat.IsZero() {
  695. return true
  696. }
  697. margin := d.watchdogMargin()
  698. need := d.cfg.GetTempTimeout(d.prof) + d.cfg.SetAllTimeout() + 2*time.Second
  699. return margin < need
  700. }
  701. func (d *Device) kickPendingSerial(ctx context.Context) {
  702. if !d.connected || d.serialInflight() {
  703. return
  704. }
  705. if d.draining {
  706. return
  707. }
  708. d.expirePendingResume(ctx)
  709. if d.pendingSafeJob != nil {
  710. job := d.pendingSafeJob
  711. now := d.clk.Now()
  712. origin := "queued_safe"
  713. if job.origin != "" {
  714. origin = job.origin
  715. }
  716. if !job.deadline.IsZero() && now.After(job.deadline) {
  717. if d.serialInflight() {
  718. job.deadline = now.Add(d.remainingInflight() + d.cfg.SetAllTimeout())
  719. return
  720. }
  721. d.pendingSafeJob = nil
  722. ax := ActionExecutionContext{
  723. CommandID: job.commandID, Origin: origin, Mode: hthv1.ActionMode_ACTION_MODE_SAFE,
  724. DeviceEpoch: job.epoch, PortGeneration: d.portGen,
  725. PeerUID: job.peerUID, PeerGID: job.peerGID, PeerPID: job.peerPID,
  726. }
  727. if ax.DeviceEpoch == 0 {
  728. ax.DeviceEpoch = d.store.Epoch()
  729. }
  730. out := &hthv1.ActionResult{
  731. CommandId: job.commandID, Accepted: false, DeviceEpoch: ax.DeviceEpoch, PortGeneration: ax.PortGeneration,
  732. ActionOrigin: origin, ControlRevision: d.store.ControlRevision(),
  733. Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED,
  734. DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED,
  735. Message: "SAFE_DELIVERY_FAILED: WriteNotStarted retry budget/deadline exhausted; explicit EnterSafeMode may retry",
  736. }
  737. stampResultContext(out, ax)
  738. d.publishActionResult(out)
  739. if d.controlMode != hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
  740. d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING, "safe_retry_deadline")
  741. }
  742. d.publishNow()
  743. return
  744. }
  745. if !job.nextRetry.IsZero() && now.Before(job.nextRetry) {
  746. return
  747. }
  748. frame := d.safeFrame()
  749. ax := ActionExecutionContext{
  750. CommandID: job.commandID, Origin: origin, Mode: hthv1.ActionMode_ACTION_MODE_SAFE,
  751. DeviceEpoch: job.epoch, PortGeneration: d.portGen, Frame: frame, EffectiveTarget: frame,
  752. PeerUID: job.peerUID, PeerGID: job.peerGID, PeerPID: job.peerPID,
  753. }
  754. if ax.DeviceEpoch == 0 {
  755. ax.DeviceEpoch = d.store.Epoch()
  756. }
  757. if !d.enqueueSerial(d.serialJobFromAction(jobSetAllSafe, d.cfg.SetAllTimeout(), ax)) {
  758. return
  759. }
  760. return
  761. }
  762. if d.pendingResume != nil {
  763. d.dispatchPendingResume(ctx)
  764. return
  765. }
  766. if len(d.pendingApply) > 0 {
  767. r := d.pendingApply[0]
  768. d.pendingApply = d.pendingApply[1:]
  769. if r.rpcCtx != nil && r.rpcCtx.Err() != nil {
  770. replyNonblock(r.reply, res{action: cancelledResult(r.batch, r.rpcCtx.Err()), err: r.rpcCtx.Err()})
  771. d.kickPendingSerial(ctx)
  772. return
  773. }
  774. d.beginApply(ctx, r)
  775. return
  776. }
  777. if d.heartbeatDue() {
  778. d.pendingHB = false
  779. d.heartbeat(ctx)
  780. return
  781. }
  782. if d.pendingMotor && d.backend.PollMode() == backend.PollUART {
  783. d.pendingMotor = false
  784. d.enqueueSerial(serialJob{kind: jobGetMotor, timeout: d.cfg.GetMotorTimeout(), origin: "readiness_probe"})
  785. return
  786. }
  787. if d.pendingTemp && d.startupDone {
  788. if d.pendingSafeJob != nil || d.pendingResume != nil || len(d.pendingApply) > 0 || d.controlWindowOpen(d.clk.Now()) {
  789. return
  790. }
  791. if d.heartbeatDue() || d.temperatureWouldStarveWatchdog() {
  792. d.markHeartbeatPending()
  793. d.heartbeat(ctx)
  794. return
  795. }
  796. d.pendingTemp = false
  797. d.enqueueSerial(serialJob{kind: jobGetTemp, timeout: d.cfg.GetTempTimeout(d.prof)})
  798. return
  799. }
  800. }
  801. func replyNonblock(ch chan res, r res) {
  802. if ch == nil {
  803. return
  804. }
  805. select {
  806. case ch <- r:
  807. default:
  808. }
  809. }