feat(node): add confirmed board shutdown with expiring commands

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 15:52:46 +03:00
parent f76928b606
commit ab8e977f11
21 changed files with 967 additions and 4 deletions
+1
View File
@@ -43,6 +43,7 @@ type PairState struct {
Revocations []CoreBinding `json:"revocations,omitempty"`
}
type Pairing struct {
Power *NodePower
Budget *LinkBudget
Routers *routers.Collector
RoverConfiguration *RoverConfigurationStore
@@ -347,6 +347,9 @@ func (p *Pairing) channel(ctx context.Context) {
if p.RoverConfiguration != nil {
payload["rover_configuration"] = p.RoverConfiguration.Snapshot()
}
if p.Power != nil {
payload["power"] = p.Power.Snapshot(ctx)
}
payload["network_profile"] = p.networkSnapshot()
payload["core_endpoint"] = binding.Endpoint
payload["endpoint_revision"] = binding.EndpointRevision
@@ -378,6 +381,9 @@ func (p *Pairing) channel(ctx context.Context) {
p.mu.Lock()
if p.state.Phase == "paired" && p.state.Binding != nil && p.state.Binding.BindingID == binding.BindingID && p.state.Binding.Endpoint == binding.Endpoint && p.state.Binding.EndpointRevision == binding.EndpointRevision {
if e == nil && status == 200 {
if p.Power != nil {
p.Power.Accept(ctx, binding.BindingID, result["power_command"], result["power_ack"])
}
networkRequestResult = result["network_request_result"]
netbirdOffer = result["netbird_offer"]
networkChange = result["network_profile_change"]
+107
View File
@@ -0,0 +1,107 @@
package node
import (
"context"
"encoding/json"
"os/exec"
"strings"
"sync"
"time"
)
const powerSchema = "missioncore.node-power/v1"
type powerCommand struct {
Schema string `json:"schema"`
ID string `json:"id"`
BindingID string `json:"binding_id"`
Epoch string `json:"epoch"`
Action string `json:"action"`
ExpiresAt float64 `json:"expires_at"`
}
type powerResult struct {
ID string `json:"id"`
State string `json:"state"`
}
// NodePower has no durable queue. A new process has a new epoch, so an old
// confirmation cannot shut down a restarted or rebound board.
type NodePower struct {
mu sync.Mutex
epoch string
command powerCommand
result powerResult
seen map[string]bool
now func() time.Time
run func(context.Context, string) ([]byte, error)
}
func NewNodePower() *NodePower {
return &NodePower{epoch: token(), seen: map[string]bool{}, now: time.Now, run: loginPower}
}
func loginPower(ctx context.Context, method string) ([]byte, error) {
// Fixed D-Bus methods only; never a shell, arbitrary unit or user-supplied argv.
args := []string{"--system", "--timeout=3", "call", "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", method}
if method == "PowerOff" {
args = append(args, "b", "false")
}
return exec.CommandContext(ctx, "/usr/bin/busctl", args...).Output()
}
func (p *NodePower) Snapshot(ctx context.Context) any {
call, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
out, err := p.run(call, "CanPowerOff")
p.mu.Lock()
defer p.mu.Unlock()
p.expire()
return map[string]any{"schema": powerSchema, "epoch": p.epoch,
"available": err == nil && strings.TrimSpace(string(out)) == `s "yes"` && len(p.seen) < 64 && p.result.State != "accepted" && p.result.State != "executing" && p.result.State != "submitted", "result": p.result}
}
func (p *NodePower) expire() {
if p.result.State == "accepted" && float64(p.now().UnixNano())/1e9 >= p.command.ExpiresAt {
p.result.State = "expired"
}
}
// Called while Pairing.mu still proves this heartbeat belongs to the current
// owner. Acceptance is reported on the next heartbeat; only its matching ack
// can execute the command. Lost replies and repeated requests never execute twice.
func (p *NodePower) Accept(ctx context.Context, binding string, raw, ackRaw json.RawMessage) {
p.mu.Lock()
defer p.mu.Unlock()
p.expire()
var ack string
if json.Unmarshal(ackRaw, &ack) == nil && ack == p.result.ID && p.result.State == "accepted" && binding == p.command.BindingID {
p.result.State = "executing"
go func() {
call, cancel := context.WithTimeout(ctx, 4*time.Second)
defer cancel()
_, err := p.run(call, "PowerOff")
p.mu.Lock()
defer p.mu.Unlock()
if err != nil {
p.result.State = "failed"
} else {
p.result.State = "submitted"
}
}()
return
}
var c powerCommand
if json.Unmarshal(raw, &c) != nil || c.Schema != powerSchema || c.Action != "poweroff" || c.BindingID != binding || c.Epoch != p.epoch || len(c.ID) != 36 || p.seen[c.ID] {
return
}
if p.result.State == "accepted" || p.result.State == "executing" || p.result.State == "submitted" || len(p.seen) >= 64 {
return
}
now := float64(p.now().UnixNano()) / 1e9
p.seen[c.ID] = true
p.command = c
p.result = powerResult{ID: c.ID, State: "accepted"}
if c.ExpiresAt <= now || c.ExpiresAt > now+30 {
p.result.State = "expired"
}
}
+111
View File
@@ -0,0 +1,111 @@
package node
import (
"context"
"encoding/json"
"errors"
"sync/atomic"
"testing"
"time"
)
func powerFixture() (*NodePower, powerCommand) {
p := NewNodePower()
p.now = func() time.Time { return time.Unix(1000, 0) }
c := powerCommand{Schema: powerSchema, ID: "12345678-1234-4234-8234-123456789abc", BindingID: "owner", Epoch: p.epoch, Action: "poweroff", ExpiresAt: 1020}
return p, c
}
func rawPower(v any) json.RawMessage { b, _ := json.Marshal(v); return b }
func TestPowerRequiresAcknowledgedAcceptanceAndExecutesOnce(t *testing.T) {
p, c := powerFixture()
done := make(chan string, 4)
p.run = func(_ context.Context, m string) ([]byte, error) { done <- m; return nil, nil }
p.Accept(context.Background(), "owner", rawPower(c), nil)
p.Accept(context.Background(), "owner", rawPower(c), rawPower("wrong"))
if len(done) != 0 {
t.Fatal("executed without acknowledgement")
}
p.Accept(context.Background(), "owner", nil, rawPower(c.ID))
select {
case m := <-done:
if m != "PowerOff" {
t.Fatal(m)
}
case <-time.After(time.Second):
t.Fatal("no shutdown")
}
p.Accept(context.Background(), "owner", rawPower(c), rawPower(c.ID))
if len(done) != 0 {
t.Fatal("duplicate shutdown")
}
}
func TestPowerRejectsStaleOrForeignCommands(t *testing.T) {
for _, change := range []func(*powerCommand){
func(c *powerCommand) { c.BindingID = "other" }, func(c *powerCommand) { c.Epoch = "previous-process" },
func(c *powerCommand) { c.ExpiresAt = 999 }, func(c *powerCommand) { c.ExpiresAt = 1100 },
func(c *powerCommand) { c.Action = "reboot" }, func(c *powerCommand) { c.Schema = "wrong" },
} {
p, c := powerFixture()
change(&c)
var calls atomic.Int32
p.run = func(context.Context, string) ([]byte, error) { calls.Add(1); return nil, nil }
p.Accept(context.Background(), "owner", rawPower(c), nil)
p.Accept(context.Background(), "owner", nil, rawPower(c.ID))
if calls.Load() != 0 || p.result.State == "executing" {
t.Fatal("foreign/stale command executed")
}
}
}
func TestPowerLostAckExpiresWithoutShutdown(t *testing.T) {
p, c := powerFixture()
p.run = func(context.Context, string) ([]byte, error) { t.Error("must not execute"); return nil, nil }
p.Accept(context.Background(), "owner", rawPower(c), nil)
p.now = func() time.Time { return time.Unix(1021, 0) }
p.Accept(context.Background(), "owner", nil, rawPower(c.ID))
if p.result.State != "expired" {
t.Fatal(p.result)
}
}
func TestPowerCapabilityProbeIsReadOnlyAndFailClosed(t *testing.T) {
p, _ := powerFixture()
for _, output := range []string{`s "yes"`, `s "challenge"`, `s "no"`, ""} {
p.run = func(_ context.Context, m string) ([]byte, error) {
if m != "CanPowerOff" {
t.Fatal(m)
}
return []byte(output), nil
}
state := p.Snapshot(context.Background()).(map[string]any)
if state["available"] != (output == `s "yes"`) {
t.Fatal(state)
}
}
p.run = func(context.Context, string) ([]byte, error) { return nil, errors.New("denied") }
if p.Snapshot(context.Background()).(map[string]any)["available"] != false {
t.Fatal("failed open")
}
}
func TestPowerFailureIsReportedAndNotRetried(t *testing.T) {
p, c := powerFixture()
done := make(chan bool)
p.run = func(context.Context, string) ([]byte, error) { defer close(done); return nil, errors.New("inhibited") }
p.Accept(context.Background(), "owner", rawPower(c), nil)
p.Accept(context.Background(), "owner", nil, rawPower(c.ID))
<-done
deadline := time.Now().Add(time.Second)
for time.Now().Before(deadline) {
p.mu.Lock()
state := p.result.State
p.mu.Unlock()
if state == "failed" {
return
}
time.Sleep(time.Millisecond)
}
t.Fatal("failure not reported")
}