package device import ( "context" "fmt" "time" "google.golang.org/protobuf/types/known/timestamppb" "hth/internal/backend" "hth/internal/control" hthv1 "hth/internal/gen/hth/api/v1" "hth/internal/grpcserver" "hth/internal/safety" ) func (d *Device) latchedSafe() bool { switch d.controlMode { case hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING, hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_RESUME_PENDING: return true default: return d.safeMode } } func (d *Device) currentTransport() hthv1.TransportState { if d.connected { return hthv1.TransportState_TRANSPORT_STATE_CONNECTED } if d.serialInflight() { return hthv1.TransportState_TRANSPORT_STATE_CONNECTING } return hthv1.TransportState_TRANSPORT_STATE_DISCONNECTED } func (d *Device) readinessFrom(lc hthv1.DeviceLifecycleState) hthv1.DeviceReadiness { if lc == hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_DEGRADED { return hthv1.DeviceReadiness_DEVICE_READINESS_DEGRADED } if !d.connected { return hthv1.DeviceReadiness_DEVICE_READINESS_STARTING } if !d.startupDone { return hthv1.DeviceReadiness_DEVICE_READINESS_PROBING } return hthv1.DeviceReadiness_DEVICE_READINESS_READY } func (d *Device) annotateSnapshot(s *hthv1.Snapshot) { if s == nil { return } s.TransportState = d.currentTransport() s.DeviceReadiness = d.readinessFrom(s.Lifecycle) s.SafetyControlMode = d.controlMode s.PortGeneration = d.portGen s.HardwareWatchdogTimeoutMs = uint32(d.watchdogTimeout() / time.Millisecond) s.HeartbeatDeliveryState = d.hbDeliveryState if !d.lastHWHeartbeat.IsZero() { s.LastSuccessfulHardwareHeartbeat = timestamppb.New(d.lastHWHeartbeat) s.RemainingWatchdogMarginMs = uint32(d.watchdogMargin() / time.Millisecond) } if !d.haveCont || !d.baselineReady { s.ContinuousTargets = nil } } func (d *Device) setControlMode(mode hthv1.SafetyControlMode, reason string) { if d.controlMode == mode { return } d.controlMode = mode d.safeMode = mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE || mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING || mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_RESUME_PENDING d.publishEvent(hthv1.EventKind_EVENT_KIND_SAFETY_MODE_CHANGED, reason+":"+mode.String()) } func (d *Device) enterSafe(ctx context.Context, reason string) *hthv1.ActionResult { _ = ctx now := d.clk.Now() d.lease.Invalidate() frame := d.safeFrame() cmd := d.nextInternalCommandID("safe:" + reason) res := &hthv1.ActionResult{ CommandId: cmd, Accepted: true, DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: reason, DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_ACCEPTED, Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNSPECIFIED, Message: "safe action accepted; physical SAFE only after a complete SET_ALL write. " + safety.DoorZeroIsFullOpen, } batch := &hthv1.ActionBatch{CommandId: cmd, ClientId: "hthd"} res.AcceptedAction = actionRecord(batch, now, res.Confirmation, frame) if res.AcceptedAction != nil { res.AcceptedAction.ActionMode = hthv1.ActionMode_ACTION_MODE_SAFE res.AcceptedAction.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_ACCEPTED } d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING, reason) if !d.connected { res.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED res.Message += "; transport down: host SAFE_PENDING, serial not dispatched" d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_SAFE_ACTION_NOT_DELIVERED, d.id, cmd, "transport down", "", nil) } else if d.serialInflight() { d.pendingSafeJob = d.newPendingSafe(cmd, reason, "enter_safe:"+reason, ctx) res.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_QUEUED res.Message += "; queued after current serial transaction" if res.AcceptedAction != nil { res.AcceptedAction.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_QUEUED } } else if !d.enqueueSerial(d.serialJobFromAction(jobSetAllSafe, d.cfg.ShutdownSafeTimeout(), d.newActionContext(cmd, "enter_safe:"+reason, hthv1.ActionMode_ACTION_MODE_SAFE, frame, ctx))) { d.pendingSafeJob = d.newPendingSafe(cmd, reason, "enter_safe:"+reason, ctx) res.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_QUEUED res.Message += "; serial worker busy, safe write queued" } else { res.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_DISPATCH_STARTED res.Message += "; serial dispatch started" if res.AcceptedAction != nil { res.AcceptedAction.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_DISPATCH_STARTED } } d.recordAction(res) // Do not publish SAFE_MODE_ENTERED until a complete Safe Frame is written. d.publishNow() return res } func (d *Device) beginResume(ctx context.Context, r req) { _ = ctx now := d.clk.Now() batch := r.batch out := &hthv1.ActionResult{CommandId: batch.GetCommandId(), DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: "resume_from_safe"} if d.draining { out.Accepted = false out.RejectReason = hthv1.RejectReason_REJECT_REASON_SUPERSEDED_BY_SHUTDOWN out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED out.Message = "daemon draining" d.publishActionResult(out) replyNonblock(r.reply, res{action: out}) return } if d.pendingResume != nil { out.Accepted = false out.RejectReason = hthv1.RejectReason_REJECT_REASON_QUEUE_FULL out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED out.Message = "a pending ResumeFromSafe already exists" d.publishActionResult(out) replyNonblock(r.reply, res{action: out}) return } if d.controlMode != hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE { out.Accepted = false out.RejectReason = hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED out.Message = "ResumeFromSafe requires latched SAFE after a complete safe write" replyNonblock(r.reply, res{action: out}) return } if batch != nil && batch.AllowClamp { out.Accepted = false out.RejectReason = hthv1.RejectReason_REJECT_REASON_PARTIAL_NOT_ALLOWED out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED out.Message = "ResumeFromSafe does not allow partial/clamp batches" replyNonblock(r.reply, res{action: out}) return } if !safety.CoversAllActuators(batch, d.prof) { out.Accepted = false out.RejectReason = hthv1.RejectReason_REJECT_REASON_PARTIAL_NOT_ALLOWED out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED out.Message = "ResumeFromSafe requires a complete action batch covering every actuator" replyNonblock(r.reply, res{action: out}) return } prep := d.prepareApply(ctx, r) if prep == nil { return } if !prep.Accepted || prep.ReplayedFromCache { replyNonblock(r.reply, res{action: prep}) return } assembled := safety.Assemble(d.lastCont, batch, d.prof) elapsed := time.Duration(0) if d.haveDispatch { elapsed = now.Sub(d.lastDispatchAt) } credit := copyCredit(d.slewCredit) slew := safety.LimitSlew(d.lastCont, assembled.SetAll, d.prof, safety.SlewOpts{ Elapsed: elapsed, AllowClamp: false, Credit: credit, }) if slew.Reject != 0 { prep.Accepted = false prep.RejectReason = slew.Reject prep.Message = slew.Message prep.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED prep.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED replyNonblock(r.reply, res{action: prep}) return } if msg := d.deadlineUnmeetable(batch); msg != "" { prep.Accepted = false prep.RejectReason = hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE prep.Message = msg prep.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED prep.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED replyNonblock(r.reply, res{action: prep}) return } vu := time.Time{} if batch != nil && batch.ValidUntil != nil { vu = batch.ValidUntil.AsTime() } leaseID, leaseEp := "", uint64(0) if batch != nil { leaseID, leaseEp = batch.LeaseId, batch.LeaseEpoch } d.pendingResume = &pendingResumeState{ req: r, prepared: prep, target: slew.SetAll, credit: credit, commandID: batch.GetCommandId(), leaseID: leaseID, leaseEp: leaseEp, devEpoch: d.store.Epoch(), validUntil: vu, acceptedAt: now, } prep.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_QUEUED prep.Message = "resume accepted; waiting for serial dispatch; control mode remains SAFE" if d.serialInflight() { return } d.dispatchPendingResume(ctx) } func (d *Device) dispatchPendingResume(ctx context.Context) { pr := d.pendingResume if pr == nil || d.serialInflight() || !d.connected || d.draining { return } if pr.req.rpcCtx != nil && pr.req.rpcCtx.Err() != nil { d.abortPendingResume("rpc cancelled", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED) return } if !pr.validUntil.IsZero() && !pr.validUntil.After(d.clk.Now()) { d.abortPendingResume("valid_until expired before dispatch", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED) return } if pr.leaseID != "" { 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 { d.abortPendingResume("lease invalid before resume dispatch", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED) return } } d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_RESUME_PENDING, "resume") d.applyJob = &applyJobState{ reply: pr.req.reply, batch: pr.req.batch, payload: control.PayloadHash(pr.req.batch), target: pr.target, result: pr.prepared, resume: true, credit: pr.credit, } d.pendingResume = nil if !d.enqueueSerial(d.serialJobFromAction(jobSetAllApply, d.cfg.SetAllTimeout(), d.newActionContext(pr.commandID, "resume_from_safe", hthv1.ActionMode_ACTION_MODE_NORMAL, pr.target, pr.req.rpcCtx))) { d.applyJob = nil d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, "resume_enqueue_failed") prep := pr.prepared prep.Accepted = false prep.Message = "serial worker busy; resume not started" prep.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED prep.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED d.publishActionResult(prep) replyNonblock(pr.req.reply, res{action: prep}) return } if pr.prepared != nil { pr.prepared.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_DISPATCH_STARTED } } func (d *Device) abortPendingResume(msg string, conf hthv1.ConfirmationStatus, st hthv1.ActionDispatchState) { pr := d.pendingResume d.pendingResume = nil if d.controlMode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_RESUME_PENDING { d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, msg) } else if d.controlMode != hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE { d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, msg) } if pr == nil { return } out := pr.prepared if out == nil { out = &hthv1.ActionResult{CommandId: pr.commandID} } out.Accepted = false out.Message = msg out.Confirmation = conf out.DispatchState = st out.DeviceEpoch = d.store.Epoch() out.PortGeneration = d.portGen out.ActionOrigin = "resume_from_safe" d.publishActionResult(out) replyNonblock(pr.req.reply, res{action: out}) } func (d *Device) expirePendingResume(ctx context.Context) { _ = ctx pr := d.pendingResume if pr == nil { return } if pr.req.rpcCtx != nil && pr.req.rpcCtx.Err() != nil { d.abortPendingResume("rpc cancelled", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED) return } if !pr.validUntil.IsZero() && !pr.validUntil.After(d.clk.Now()) { d.abortPendingResume("valid_until expired", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED) } } func (d *Device) finishSafeWrite(ctx context.Context, sr serialResult) { now := d.clk.Now() if d.draining && sr.origin == originShutdown { d.shutdownSafeResult = d.safeWriteResult(sr) } if sr.wr.Outcome == backend.WriteNotStarted { d.handleSafeNotStarted(ctx, sr) return } if backend.WriteNeedsReconnect(sr.wr, sr.err) || sr.wr.Outcome != backend.WriteFullyWritten { 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) conf := hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN st := hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN msg := "SAFE_OUTCOME_UNKNOWN; UART/port unusable; original Safe action not auto-replayed" if sr.wr.Outcome == backend.WriteDisconnected && sr.wr.N == 0 { conf = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED st = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED msg = "SAFE_NOT_DELIVERED WriteDisconnected; transport closed" } d.publishSafeTerminal(sr, conf, st, msg) if d.controlMode != hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE { d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING, "safe_write_failed") } d.onDrop(ctx, fmt.Errorf("safe write %s: %v", sr.wr.Outcome, sr.err)) return } d.lastCont = sr.frame d.haveCont = true d.haveDispatch = true d.lastDispatchAt = now d.slewCredit = map[string]float64{} d.baselineReady = true d.pendingSafeJob = nil d.store.BumpControlRevision() cmd := sr.commandID if cmd == "" { cmd = d.nextInternalCommandID("safe:" + sr.origin) } rec := d.makeSafeRecord(cmd, sr.origin, now, sr) if sr.origin == originEpochBaseline { if d.latchedSafe() { d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, "epoch_safe_baseline_keeps_latch") d.publishEvent(hthv1.EventKind_EVENT_KIND_SAFE_MODE_ENTERED, "SAFE_LATCHED epoch_safe_baseline UNCONFIRMED; not a device ACK") } else { d.controlMode = hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL d.safeMode = false } d.commitSafeTargets(rec) d.publishActionResult(&hthv1.ActionResult{ CommandId: cmd, Accepted: true, DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: sr.origin, Dispatched: rec, ControlRevision: d.store.ControlRevision(), Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED, DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED, Message: "epoch Safe baseline dispatched UNCONFIRMED", }) d.publishNow() if d.backend.PollMode() == backend.PollUART { if !d.enqueueSerial(serialJob{kind: jobGetMotor, timeout: d.cfg.ProbeTimeout(), origin: "readiness_probe"}) { d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_DEGRADED) } } return } d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, sr.origin) d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_SAFE) d.commitSafeTargets(rec) d.publishEvent(hthv1.EventKind_EVENT_KIND_SAFE_MODE_ENTERED, "SAFE_LATCHED origin="+sr.origin+"; host dispatched complete Safe Frame UNCONFIRMED; not a device ACK") d.publishActionResult(&hthv1.ActionResult{ CommandId: cmd, Accepted: true, DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: sr.origin, Dispatched: rec, ControlRevision: d.store.ControlRevision(), Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED, DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED, Message: "SAFE_DISPATCHED_UNCONFIRMED origin=" + sr.origin, }) d.publishNow() } func (d *Device) commitSafeTargets(rec *hthv1.ActionRecord) { d.store.Commit(func(s *hthv1.Snapshot) { s.LastDispatched = rec s.DeviceConfirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED s.ContinuousTargets = d.commandedTargetsAt(s.DeviceEpoch) d.annotateSnapshot(s) }) } func (d *Device) makeSafeRecord(cmd, origin string, now time.Time, sr serialResult) *hthv1.ActionRecord { rec := actionRecord(&hthv1.ActionBatch{CommandId: cmd, ClientId: "hthd"}, now, hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED, sr.frame) if rec == nil { return nil } rec.ActionMode = hthv1.ActionMode_ACTION_MODE_SAFE rec.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED rec.ActionEpoch = d.store.Epoch() rec.PortGeneration = d.portGen if sr.peerUID == 0 && sr.peerGID == 0 && sr.peerPID == 0 { rec.Origin = "daemon/internal" } else { rec.Origin = origin rec.PeerUid = sr.peerUID rec.PeerGid = sr.peerGID rec.PeerPid = sr.peerPID } return rec } func (d *Device) publishSafeTerminal(sr serialResult, conf hthv1.ConfirmationStatus, st hthv1.ActionDispatchState, msg string) { cmd := sr.commandID if cmd == "" { cmd = d.nextInternalCommandID("safe:" + sr.origin) } d.publishActionResult(&hthv1.ActionResult{ CommandId: cmd, Accepted: false, DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: sr.origin, ControlRevision: d.store.ControlRevision(), Confirmation: conf, DispatchState: st, Message: msg, }) } func (d *Device) handleSafeNotStarted(ctx context.Context, sr serialResult) { now := d.clk.Now() job := d.pendingSafeJob if job == nil { dl := now.Add(d.cfg.SetAllTimeout()) if !sr.started.IsZero() { dl = sr.started.Add(d.cfg.SetAllTimeout()) } cmd := sr.commandID if cmd == "" { cmd = d.nextInternalCommandID(sr.origin) } job = &pendingSafeState{ commandID: cmd, origin: sr.origin, reason: sr.origin, peerUID: sr.peerUID, peerGID: sr.peerGID, peerPID: sr.peerPID, enqueued: sr.started, requestedAt: sr.started, deadline: dl, epoch: sr.epoch, maxAttempts: safeNotStartedMaxAttempts, } } job.attempts++ job.commandID = firstNonEmpty(job.commandID, sr.commandID) expired := (!job.deadline.IsZero() && !now.Before(job.deadline)) || (job.maxAttempts > 0 && job.attempts >= job.maxAttempts) if expired { d.pendingSafeJob = nil d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_SAFE_ACTION_NOT_DELIVERED, d.id, job.commandID, "WriteNotStarted retries exhausted", "", nil) d.publishSafeTerminal(sr, hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED, "SAFE_NOT_DELIVERED after bounded WriteNotStarted retries; command_id unchanged") if d.controlMode != hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE { d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING, "safe_not_started_deadline") } if sr.origin == originEpochBaseline { d.onDrop(ctx, fmt.Errorf("epoch baseline WriteNotStarted retries exhausted")) return } d.publishNow() return } job.nextRetry = now.Add(safeNotStartedRetry) d.pendingSafeJob = job if d.controlMode != hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE { d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING, "safe_write_not_started_retry") } d.publishNow() } func firstNonEmpty(a, b string) string { if a != "" { return a } return b } func (d *Device) safeWriteResult(sr serialResult) *hthv1.ActionResult { cmd := sr.commandID if cmd == "" { cmd = d.nextInternalCommandID(sr.origin) } out := &hthv1.ActionResult{ CommandId: cmd, DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen, Accepted: true, ActionOrigin: sr.origin, } switch { case sr.wr.Outcome == backend.WriteFullyWritten && sr.err == nil: out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED out.Message = "shutdown safe dispatched UNCONFIRMED" out.Dispatched = actionRecord(&hthv1.ActionBatch{CommandId: out.CommandId}, d.clk.Now(), out.Confirmation, sr.frame) if out.Dispatched != nil { out.Dispatched.PeerUid = sr.peerUID out.Dispatched.PeerGid = sr.peerGID out.Dispatched.PeerPid = sr.peerPID } case sr.wr.Outcome == backend.WriteNotStarted || sr.wr.Outcome == backend.WriteDisconnected: out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED out.Message = "shutdown safe not delivered" default: out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN out.Message = "shutdown safe outcome unknown" } return out } func (d *Device) runShutdown() { d.draining = true d.pendingTemp = false d.pendingHB = false d.supersedePendingApplies("SUPERSEDED_BY_SHUTDOWN") if d.pendingResume != nil { d.abortPendingResume("shutdown", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED) } d.pendingSafeJob = d.newPendingSafe(d.nextInternalCommandID("shutdown"), "shutdown", originShutdown, nil) d.pendingSafeJob.deadline = time.Now().Add(d.cfg.ShutdownSafeTimeout()) deadline := time.Now().Add(d.cfg.ShutdownSafeTimeout()) dummyB, dummyN := time.Duration(0), time.Time{} if d.serialInflight() { if ir, ok := d.backend.(backend.Interrupter); ok { ir.Interrupt() } } for d.serialInflight() && time.Now().Before(deadline) { select { case sr := <-d.results: d.applySerialResult(context.Background(), sr, &dummyB, &dummyN) case <-time.After(20 * time.Millisecond): } } if d.connected && !d.serialInflight() { frame := d.safeFrame() job := d.pendingSafeJob d.pendingSafeJob = nil ax := d.newActionContext("", originShutdown, hthv1.ActionMode_ACTION_MODE_SAFE, frame, nil) if job != nil && job.commandID != "" { ax.CommandID, ax.PeerUID, ax.PeerGID, ax.PeerPID = job.commandID, job.peerUID, job.peerGID, job.peerPID ax.Origin = originShutdown } to := time.Until(deadline) if to < d.cfg.SetAllTimeout() { to = d.cfg.SetAllTimeout() } sj := d.serialJobFromAction(jobSetAllSafe, to, ax) enqueued := d.enqueueSerial(sj) for !enqueued && d.connected && time.Now().Before(deadline) { if d.serialInflight() { select { case sr := <-d.results: d.applySerialResult(context.Background(), sr, &dummyB, &dummyN) case <-time.After(20 * time.Millisecond): } } else { time.Sleep(2 * time.Millisecond) } enqueued = d.enqueueSerial(sj) } if enqueued { for d.serialInflight() && time.Now().Before(deadline) { select { case sr := <-d.results: d.applySerialResult(context.Background(), sr, &dummyB, &dummyN) case <-time.After(20 * time.Millisecond): } } } } if d.shutdownSafeResult == nil { d.shutdownSafeResult = &hthv1.ActionResult{ CommandId: d.nextInternalCommandID("shutdown"), Accepted: true, Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED, Message: "shutdown safe not delivered", DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: originShutdown, } d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_SAFE_ACTION_NOT_DELIVERED, d.id, "shutdown", "not delivered before stop deadline", "", nil) } d.publishActionResult(d.shutdownSafeResult) if time.Now().After(deadline) { _ = d.backend.Close() } if d.workerCancel != nil { d.workerCancel() } d.drainPending(context.Canceled) } func (d *Device) attachPeer(r req, res *hthv1.ActionResult) { if res == nil || res.Requested == nil { return } if cred, ok := grpcserver.PeerFromContext(r.rpcCtx); ok { res.Requested.PeerUid = cred.UID res.Requested.PeerGid = cred.GID res.Requested.PeerPid = cred.PID } }