lifecycle.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. package device
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "google.golang.org/protobuf/types/known/timestamppb"
  7. "hth/internal/backend"
  8. "hth/internal/control"
  9. hthv1 "hth/internal/gen/hth/api/v1"
  10. "hth/internal/grpcserver"
  11. "hth/internal/safety"
  12. )
  13. func (d *Device) latchedSafe() bool {
  14. switch d.controlMode {
  15. case hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE,
  16. hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING,
  17. hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_RESUME_PENDING:
  18. return true
  19. default:
  20. return d.safeMode
  21. }
  22. }
  23. func (d *Device) currentTransport() hthv1.TransportState {
  24. if d.connected {
  25. return hthv1.TransportState_TRANSPORT_STATE_CONNECTED
  26. }
  27. if d.serialInflight() {
  28. return hthv1.TransportState_TRANSPORT_STATE_CONNECTING
  29. }
  30. return hthv1.TransportState_TRANSPORT_STATE_DISCONNECTED
  31. }
  32. func (d *Device) readinessFrom(lc hthv1.DeviceLifecycleState) hthv1.DeviceReadiness {
  33. if lc == hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_DEGRADED {
  34. return hthv1.DeviceReadiness_DEVICE_READINESS_DEGRADED
  35. }
  36. if !d.connected {
  37. return hthv1.DeviceReadiness_DEVICE_READINESS_STARTING
  38. }
  39. if !d.startupDone {
  40. return hthv1.DeviceReadiness_DEVICE_READINESS_PROBING
  41. }
  42. return hthv1.DeviceReadiness_DEVICE_READINESS_READY
  43. }
  44. func (d *Device) annotateSnapshot(s *hthv1.Snapshot) {
  45. if s == nil {
  46. return
  47. }
  48. s.TransportState = d.currentTransport()
  49. s.DeviceReadiness = d.readinessFrom(s.Lifecycle)
  50. s.SafetyControlMode = d.controlMode
  51. s.PortGeneration = d.portGen
  52. s.HardwareWatchdogTimeoutMs = uint32(d.watchdogTimeout() / time.Millisecond)
  53. s.HeartbeatDeliveryState = d.hbDeliveryState
  54. if !d.lastHWHeartbeat.IsZero() {
  55. s.LastSuccessfulHardwareHeartbeat = timestamppb.New(d.lastHWHeartbeat)
  56. s.RemainingWatchdogMarginMs = uint32(d.watchdogMargin() / time.Millisecond)
  57. }
  58. if !d.haveCont || !d.baselineReady {
  59. s.ContinuousTargets = nil
  60. } else {
  61. for _, a := range s.ContinuousTargets {
  62. if a != nil {
  63. a.TargetEpoch = s.DeviceEpoch
  64. }
  65. }
  66. }
  67. }
  68. func (d *Device) setControlMode(mode hthv1.SafetyControlMode, reason string) {
  69. if d.controlMode == mode {
  70. return
  71. }
  72. d.controlMode = mode
  73. d.safeMode = mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE ||
  74. mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING ||
  75. mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_RESUME_PENDING
  76. d.publishEvent(hthv1.EventKind_EVENT_KIND_SAFETY_MODE_CHANGED, reason+":"+mode.String())
  77. }
  78. func (d *Device) enterSafe(ctx context.Context, reason string) *hthv1.ActionResult {
  79. _ = ctx
  80. now := d.clk.Now()
  81. d.lease.Invalidate()
  82. frame := d.safeFrame()
  83. cmd := d.nextInternalCommandID("safe:" + reason)
  84. res := &hthv1.ActionResult{
  85. CommandId: cmd,
  86. Accepted: true,
  87. DeviceEpoch: d.store.Epoch(),
  88. PortGeneration: d.portGen,
  89. ActionOrigin: reason,
  90. DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_ACCEPTED,
  91. Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNSPECIFIED,
  92. Message: "safe action accepted; physical SAFE only after a complete SET_ALL write. " + safety.DoorZeroIsFullOpen,
  93. }
  94. batch := &hthv1.ActionBatch{CommandId: cmd, ClientId: "hthd"}
  95. res.AcceptedAction = actionRecord(batch, now, res.Confirmation, frame)
  96. if res.AcceptedAction != nil {
  97. res.AcceptedAction.ActionMode = hthv1.ActionMode_ACTION_MODE_SAFE
  98. res.AcceptedAction.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_ACCEPTED
  99. }
  100. d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING, reason)
  101. if !d.connected {
  102. res.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED
  103. res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED
  104. res.Message += "; transport down: host SAFE_PENDING, serial not dispatched"
  105. d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_SAFE_ACTION_NOT_DELIVERED, d.id, cmd, "transport down", "", nil)
  106. } else if d.serialInflight() {
  107. d.pendingSafe = true
  108. d.pendingSafeJob = &pendingSafeState{
  109. commandID: cmd, reason: reason, origin: "enter_safe:" + reason,
  110. enqueued: now, deadline: now.Add(d.cfg.SetAllTimeout()), epoch: d.store.Epoch(),
  111. }
  112. res.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_QUEUED
  113. res.Message += "; queued after current serial transaction"
  114. if res.AcceptedAction != nil {
  115. res.AcceptedAction.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_QUEUED
  116. }
  117. } else if !d.enqueueSerial(serialJob{kind: jobSetAllSafe, timeout: d.cfg.ShutdownSafeTimeout(), frame: frame, origin: "enter_safe:" + reason}) {
  118. d.pendingSafe = true
  119. d.pendingSafeJob = &pendingSafeState{
  120. commandID: cmd, reason: reason, origin: "enter_safe:" + reason,
  121. enqueued: now, deadline: now.Add(d.cfg.SetAllTimeout()), epoch: d.store.Epoch(),
  122. }
  123. res.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_QUEUED
  124. res.Message += "; serial worker busy, safe write queued"
  125. } else {
  126. res.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_DISPATCH_STARTED
  127. res.Message += "; serial dispatch started"
  128. if res.AcceptedAction != nil {
  129. res.AcceptedAction.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_DISPATCH_STARTED
  130. }
  131. }
  132. d.recordAction(res)
  133. d.publishEvent(hthv1.EventKind_EVENT_KIND_SAFE_MODE_ENTERED, reason)
  134. d.publishNow()
  135. return res
  136. }
  137. func (d *Device) beginResume(ctx context.Context, r req) {
  138. _ = ctx
  139. now := d.clk.Now()
  140. batch := r.batch
  141. out := &hthv1.ActionResult{CommandId: batch.GetCommandId(), DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: "resume_from_safe"}
  142. if d.draining {
  143. out.Accepted = false
  144. out.RejectReason = hthv1.RejectReason_REJECT_REASON_SUPERSEDED_BY_SHUTDOWN
  145. out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED
  146. out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED
  147. out.Message = "daemon draining"
  148. d.publishActionResult(out)
  149. replyNonblock(r.reply, res{action: out})
  150. return
  151. }
  152. if d.pendingResume != nil {
  153. out.Accepted = false
  154. out.RejectReason = hthv1.RejectReason_REJECT_REASON_QUEUE_FULL
  155. out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED
  156. out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED
  157. out.Message = "a pending ResumeFromSafe already exists"
  158. d.publishActionResult(out)
  159. replyNonblock(r.reply, res{action: out})
  160. return
  161. }
  162. if d.controlMode != hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
  163. out.Accepted = false
  164. out.RejectReason = hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY
  165. out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED
  166. out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED
  167. out.Message = "ResumeFromSafe requires latched SAFE after a complete safe write"
  168. replyNonblock(r.reply, res{action: out})
  169. return
  170. }
  171. if batch != nil && batch.AllowClamp {
  172. out.Accepted = false
  173. out.RejectReason = hthv1.RejectReason_REJECT_REASON_PARTIAL_NOT_ALLOWED
  174. out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED
  175. out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED
  176. out.Message = "ResumeFromSafe does not allow partial/clamp batches"
  177. replyNonblock(r.reply, res{action: out})
  178. return
  179. }
  180. if !safety.CoversAllActuators(batch, d.prof) {
  181. out.Accepted = false
  182. out.RejectReason = hthv1.RejectReason_REJECT_REASON_PARTIAL_NOT_ALLOWED
  183. out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED
  184. out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED
  185. out.Message = "ResumeFromSafe requires a complete action batch covering every actuator"
  186. replyNonblock(r.reply, res{action: out})
  187. return
  188. }
  189. prep := d.prepareApply(ctx, r)
  190. if prep == nil {
  191. return
  192. }
  193. if !prep.Accepted || prep.ReplayedFromCache {
  194. replyNonblock(r.reply, res{action: prep})
  195. return
  196. }
  197. assembled := safety.Assemble(d.lastCont, batch, d.prof)
  198. elapsed := time.Duration(0)
  199. if d.haveDispatch {
  200. elapsed = now.Sub(d.lastDispatchAt)
  201. }
  202. credit := copyCredit(d.slewCredit)
  203. slew := safety.LimitSlew(d.lastCont, assembled.SetAll, d.prof, safety.SlewOpts{
  204. Elapsed: elapsed, AllowClamp: false, Credit: credit,
  205. })
  206. if slew.Reject != 0 {
  207. prep.Accepted = false
  208. prep.RejectReason = slew.Reject
  209. prep.Message = slew.Message
  210. prep.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED
  211. prep.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED
  212. replyNonblock(r.reply, res{action: prep})
  213. return
  214. }
  215. if msg := d.deadlineUnmeetable(batch); msg != "" {
  216. prep.Accepted = false
  217. prep.RejectReason = hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE
  218. prep.Message = msg
  219. prep.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED
  220. prep.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED
  221. replyNonblock(r.reply, res{action: prep})
  222. return
  223. }
  224. vu := time.Time{}
  225. if batch != nil && batch.ValidUntil != nil {
  226. vu = batch.ValidUntil.AsTime()
  227. }
  228. leaseID, leaseEp := "", uint64(0)
  229. if batch != nil {
  230. leaseID, leaseEp = batch.LeaseId, batch.LeaseEpoch
  231. }
  232. d.pendingResume = &pendingResumeState{
  233. req: r, prepared: prep, target: slew.SetAll, credit: credit,
  234. commandID: batch.GetCommandId(), leaseID: leaseID, leaseEp: leaseEp,
  235. devEpoch: d.store.Epoch(), validUntil: vu, acceptedAt: now,
  236. }
  237. prep.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_QUEUED
  238. prep.Message = "resume accepted; waiting for serial dispatch; control mode remains SAFE"
  239. if d.serialInflight() {
  240. return
  241. }
  242. d.dispatchPendingResume(ctx)
  243. }
  244. func (d *Device) dispatchPendingResume(ctx context.Context) {
  245. pr := d.pendingResume
  246. if pr == nil || d.serialInflight() || !d.connected || d.draining {
  247. return
  248. }
  249. if pr.req.rpcCtx != nil && pr.req.rpcCtx.Err() != nil {
  250. d.abortPendingResume("rpc cancelled", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED)
  251. return
  252. }
  253. if !pr.validUntil.IsZero() && !pr.validUntil.After(d.clk.Now()) {
  254. d.abortPendingResume("valid_until expired before dispatch", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED)
  255. return
  256. }
  257. if pr.leaseID != "" {
  258. if rr := d.lease.CheckAction(d.clk.Now(), &hthv1.ActionBatch{CommandId: pr.commandID, LeaseId: pr.leaseID, LeaseEpoch: pr.leaseEp}, d.store.Seq(), d.store.ControlRevision()); rr == hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED || rr == hthv1.RejectReason_REJECT_REASON_LEASE_MISSING || rr == hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH {
  259. d.abortPendingResume("lease invalid before resume dispatch", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED)
  260. return
  261. }
  262. }
  263. d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_RESUME_PENDING, "resume")
  264. d.applyJob = &applyJobState{
  265. reply: pr.req.reply, batch: pr.req.batch, payload: control.PayloadHash(pr.req.batch),
  266. target: pr.target, result: pr.prepared, resume: true, credit: pr.credit,
  267. }
  268. d.pendingResume = nil
  269. if !d.enqueueSerial(serialJob{kind: jobSetAllApply, timeout: d.cfg.SetAllTimeout(), frame: pr.target, origin: "resume_from_safe"}) {
  270. d.applyJob = nil
  271. d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, "resume_enqueue_failed")
  272. prep := pr.prepared
  273. prep.Accepted = false
  274. prep.Message = "serial worker busy; resume not started"
  275. prep.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED
  276. prep.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED
  277. d.publishActionResult(prep)
  278. replyNonblock(pr.req.reply, res{action: prep})
  279. return
  280. }
  281. if pr.prepared != nil {
  282. pr.prepared.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_DISPATCH_STARTED
  283. }
  284. }
  285. func (d *Device) abortPendingResume(msg string, conf hthv1.ConfirmationStatus, st hthv1.ActionDispatchState) {
  286. pr := d.pendingResume
  287. d.pendingResume = nil
  288. if d.controlMode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_RESUME_PENDING {
  289. d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, msg)
  290. } else if d.controlMode != hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
  291. d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, msg)
  292. }
  293. if pr == nil {
  294. return
  295. }
  296. out := pr.prepared
  297. if out == nil {
  298. out = &hthv1.ActionResult{CommandId: pr.commandID}
  299. }
  300. out.Accepted = false
  301. out.Message = msg
  302. out.Confirmation = conf
  303. out.DispatchState = st
  304. out.DeviceEpoch = d.store.Epoch()
  305. out.PortGeneration = d.portGen
  306. out.ActionOrigin = "resume_from_safe"
  307. d.publishActionResult(out)
  308. replyNonblock(pr.req.reply, res{action: out})
  309. }
  310. func (d *Device) expirePendingResume(ctx context.Context) {
  311. _ = ctx
  312. pr := d.pendingResume
  313. if pr == nil {
  314. return
  315. }
  316. if pr.req.rpcCtx != nil && pr.req.rpcCtx.Err() != nil {
  317. d.abortPendingResume("rpc cancelled", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED)
  318. return
  319. }
  320. if !pr.validUntil.IsZero() && !pr.validUntil.After(d.clk.Now()) {
  321. d.abortPendingResume("valid_until expired", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED)
  322. }
  323. }
  324. func (d *Device) finishSafeWrite(ctx context.Context, sr serialResult) {
  325. now := d.clk.Now()
  326. if d.draining && sr.origin == originShutdown {
  327. d.shutdownSafeResult = d.safeWriteResult(sr)
  328. }
  329. if backend.WriteNeedsReconnect(sr.wr, sr.err) || sr.wr.Outcome != backend.WriteFullyWritten {
  330. d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_SAFE_ACTION_NOT_DELIVERED, d.id, sr.origin, fmt.Sprintf("safe write %s: %v", sr.wr.Outcome, sr.err), "", nil)
  331. if sr.wr.Outcome == backend.WriteNotStarted || sr.wr.Outcome == backend.WriteDisconnected {
  332. if d.controlMode != hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
  333. d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING, "safe_not_delivered")
  334. }
  335. } else {
  336. d.onDrop(ctx, fmt.Errorf("safe write %s: %v", sr.wr.Outcome, sr.err))
  337. return
  338. }
  339. d.publishNow()
  340. return
  341. }
  342. d.lastCont = sr.frame
  343. d.haveCont = true
  344. d.haveDispatch = true
  345. d.lastDispatchAt = now
  346. d.slewCredit = map[string]float64{}
  347. d.baselineReady = true
  348. if sr.origin == originEpochBaseline {
  349. if d.latchedSafe() {
  350. d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, "epoch_safe_baseline_keeps_latch")
  351. } else {
  352. d.controlMode = hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL
  353. d.safeMode = false
  354. }
  355. if d.backend.PollMode() == backend.PollUART {
  356. if !d.enqueueSerial(serialJob{kind: jobGetMotor, timeout: d.cfg.ProbeTimeout(), origin: "readiness_probe"}) {
  357. d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_DEGRADED)
  358. }
  359. return
  360. }
  361. return
  362. }
  363. d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, sr.origin)
  364. d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_SAFE)
  365. cmd := d.nextInternalCommandID("safe:" + sr.origin)
  366. rec := actionRecord(&hthv1.ActionBatch{CommandId: cmd, ClientId: "hthd"}, now,
  367. hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED, sr.frame)
  368. if rec != nil {
  369. rec.ActionMode = hthv1.ActionMode_ACTION_MODE_SAFE
  370. rec.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED
  371. rec.ActionEpoch = d.store.Epoch()
  372. rec.PortGeneration = d.portGen
  373. }
  374. d.store.Commit(func(s *hthv1.Snapshot) {
  375. s.LastDispatched = rec
  376. s.DeviceConfirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED
  377. s.ContinuousTargets = d.commandedTargets()
  378. d.annotateSnapshot(s)
  379. })
  380. d.publishActionResult(&hthv1.ActionResult{
  381. CommandId: cmd, Accepted: true, DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen,
  382. ActionOrigin: sr.origin, Dispatched: rec,
  383. Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED,
  384. DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED,
  385. Message: "SAFE dispatched UNCONFIRMED origin=" + sr.origin,
  386. })
  387. d.publishNow()
  388. }
  389. func (d *Device) safeWriteResult(sr serialResult) *hthv1.ActionResult {
  390. out := &hthv1.ActionResult{
  391. CommandId: d.nextInternalCommandID(sr.origin), DeviceEpoch: d.store.Epoch(),
  392. PortGeneration: d.portGen, Accepted: true, ActionOrigin: sr.origin,
  393. }
  394. switch {
  395. case sr.wr.Outcome == backend.WriteFullyWritten && sr.err == nil:
  396. out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED
  397. out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED
  398. out.Message = "shutdown safe dispatched UNCONFIRMED"
  399. out.Dispatched = actionRecord(&hthv1.ActionBatch{CommandId: out.CommandId}, d.clk.Now(), out.Confirmation, sr.frame)
  400. case sr.wr.Outcome == backend.WriteNotStarted || sr.wr.Outcome == backend.WriteDisconnected:
  401. out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED
  402. out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED
  403. out.Message = "shutdown safe not delivered"
  404. default:
  405. out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN
  406. out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN
  407. out.Message = "shutdown safe outcome unknown"
  408. }
  409. return out
  410. }
  411. func (d *Device) runShutdown() {
  412. d.draining = true
  413. d.pendingTemp = false
  414. d.pendingHB = false
  415. d.supersedePendingApplies("SUPERSEDED_BY_SHUTDOWN")
  416. if d.pendingResume != nil {
  417. d.abortPendingResume("shutdown", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED)
  418. }
  419. d.pendingSafe = false
  420. d.pendingSafeJob = &pendingSafeState{
  421. commandID: d.nextInternalCommandID("shutdown"),
  422. reason: "shutdown",
  423. origin: originShutdown,
  424. enqueued: d.clk.Now(),
  425. deadline: time.Now().Add(d.cfg.ShutdownSafeTimeout()),
  426. epoch: d.store.Epoch(),
  427. }
  428. deadline := time.Now().Add(d.cfg.ShutdownSafeTimeout())
  429. dummyB, dummyN := time.Duration(0), time.Time{}
  430. if d.serialInflight() {
  431. if ir, ok := d.backend.(backend.Interrupter); ok {
  432. ir.Interrupt()
  433. }
  434. }
  435. for d.serialInflight() && time.Now().Before(deadline) {
  436. select {
  437. case sr := <-d.results:
  438. d.applySerialResult(context.Background(), sr, &dummyB, &dummyN)
  439. case <-time.After(20 * time.Millisecond):
  440. }
  441. }
  442. if d.connected && !d.serialInflight() {
  443. frame := d.safeFrame()
  444. d.pendingSafeJob = nil
  445. if d.enqueueSerial(serialJob{kind: jobSetAllSafe, timeout: time.Until(deadline), frame: frame, origin: originShutdown}) {
  446. for d.serialInflight() && time.Now().Before(deadline) {
  447. select {
  448. case sr := <-d.results:
  449. d.applySerialResult(context.Background(), sr, &dummyB, &dummyN)
  450. case <-time.After(20 * time.Millisecond):
  451. }
  452. }
  453. }
  454. }
  455. if d.shutdownSafeResult == nil {
  456. d.shutdownSafeResult = &hthv1.ActionResult{
  457. CommandId: d.nextInternalCommandID("shutdown"),
  458. Accepted: true,
  459. Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED,
  460. DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED,
  461. Message: "shutdown safe not delivered",
  462. DeviceEpoch: d.store.Epoch(),
  463. PortGeneration: d.portGen,
  464. ActionOrigin: originShutdown,
  465. }
  466. d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_SAFE_ACTION_NOT_DELIVERED, d.id, "shutdown", "not delivered before stop deadline", "", nil)
  467. }
  468. d.publishActionResult(d.shutdownSafeResult)
  469. if time.Now().After(deadline) {
  470. _ = d.backend.Close()
  471. }
  472. if d.workerCancel != nil {
  473. d.workerCancel()
  474. }
  475. d.drainPending(context.Canceled)
  476. }
  477. func (d *Device) attachPeer(r req, res *hthv1.ActionResult) {
  478. if res == nil || res.Requested == nil {
  479. return
  480. }
  481. if cred, ok := grpcserver.PeerFromContext(r.rpcCtx); ok {
  482. res.Requested.PeerUid = cred.UID
  483. res.Requested.PeerGid = cred.GID
  484. res.Requested.PeerPid = cred.PID
  485. }
  486. }