carlos / platform Public

ha: decouple departure recovery from queue and inventory readiness

Bind proof takeovers to the host record lifetime. Retry initialization while replay and identity observation run independently. Normalize validated hints into durable per-iid pending rows, preserve retry/page state, and isolate discovery failures. Keep suspicion checks Describe-first and distinguish rate-limited failure notices.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 828c82f230468fba5ea59546d1f006f5d8a51f9d parent ad93b78
13 files changed, +973 −162
  • internal/activator/hawake.go +21 −0
  • internal/awsterminations/queue.go +24 −13
  • internal/hadeparture/consumer.go +58 −28
  • internal/hadeparture/consumer_test.go +66 −16
  • internal/host/hadeparture_identity.go +95 −14
  • internal/host/hadeparture_identity_test.go +39 −2
  • internal/host/hadepartures.go +80 −36
  • internal/host/hadepartures_wiring.go +42 −42
  • internal/host/hadepartures_wiring_test.go +361 −1
  • internal/provision/departure_inventory.go +4 −5
  • internal/provision/departure_inventory_test.go +20 −0
  • internal/registry/ha_journal.go +94 −5
  • internal/registry/ha_journal_test.go +69 −0
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go
index 8a781cbd9..1a786069f 100644
--- a/internal/activator/hawake.go
+++ b/internal/activator/hawake.go
@@ -115,6 +115,27 @@ func (b *ExecBackend) IsHA(ctx context.Context, rt registry.Route) (bool, error)
return ha, err
}
+func (b *ExecBackend) TerminationLifetime(ctx context.Context, host string) (string, error) {
+ if b.Registry == nil {
+ return "", errors.New("ha_registry_missing")
+ }
+ rt, err := b.Registry.Get(host)
+ if err != nil {
+ return "", err
+ }
+ if rt == nil {
+ return "", errors.New("ha_route_missing")
+ }
+ e, ha, err := b.isHA(ctx, *rt)
+ if err != nil {
+ return "", err
+ }
+ if !ha || e.ID == "" {
+ return "", errors.New("ha_lifetime_missing")
+ }
+ return e.ID, nil
+}
+
// haContained is the containment admission (r3.2): nil only for a row in
// the nested layout, not unit-backed, on a box whose nested gate passes
// (the control channel configured and NestedOK). An HA host never runs
diff --git a/internal/awsterminations/queue.go b/internal/awsterminations/queue.go
index f73c74cae..3b9e2b307 100644
--- a/internal/awsterminations/queue.go
+++ b/internal/awsterminations/queue.go
@@ -34,10 +34,30 @@ type Queue struct {
// New retains method values, so linking the adapter does not retain every SQS
// method. The caller supplies the combined five-second initialization context.
func New(ctx context.Context, cfg aws.Config, rawURL string, self boxid.Cloud) (*Queue, error) {
- u, err := url.Parse(rawURL)
- if err != nil || !self.Complete() || !accountPattern.MatchString(self.Account) || !iidPattern.MatchString(self.InstanceID) || cfg.Region != self.Region {
+ expected, err := queueARN(rawURL, self)
+ if err != nil || cfg.Region != self.Region {
return nil, ErrQueueIdentity
}
+ cfg.RetryMaxAttempts = 1
+ client := sqs.NewFromConfig(cfg)
+ attrs, err := client.GetQueueAttributes(ctx, &sqs.GetQueueAttributesInput{QueueUrl: aws.String(rawURL), AttributeNames: []types.QueueAttributeName{types.QueueAttributeNameQueueArn}})
+ if err != nil {
+ return nil, err
+ }
+ if attrs == nil || attrs.Attributes["QueueArn"] != expected {
+ return nil, ErrQueueIdentity
+ }
+ return &Queue{url: rawURL, receive: client.ReceiveMessage, delete: client.DeleteMessage}, nil
+}
+func ValidateURL(rawURL string, self boxid.Cloud) error {
+ _, err := queueARN(rawURL, self)
+ return err
+}
+func queueARN(rawURL string, self boxid.Cloud) (string, error) {
+ u, err := url.Parse(rawURL)
+ if err != nil || !self.Complete() || !accountPattern.MatchString(self.Account) || !iidPattern.MatchString(self.InstanceID) {
+ return "", ErrQueueIdentity
+ }
suffix, partition := "amazonaws.com", "aws"
if strings.HasPrefix(self.Region, "cn-") {
suffix = "amazonaws.com.cn"
@@ -47,18 +67,9 @@ func New(ctx context.Context, cfg aws.Config, rawURL string, self boxid.Cloud) (
}
parts := strings.Split(u.Path, "/")
if u.Scheme != "https" || u.Host != "sqs."+self.Region+"."+suffix || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.RawPath != "" || len(parts) != 3 || parts[1] != self.Account || !queuePattern.MatchString(parts[2]) {
- return nil, ErrQueueIdentity
- }
- cfg.RetryMaxAttempts = 1
- client := sqs.NewFromConfig(cfg)
- attrs, err := client.GetQueueAttributes(ctx, &sqs.GetQueueAttributesInput{QueueUrl: aws.String(rawURL), AttributeNames: []types.QueueAttributeName{types.QueueAttributeNameQueueArn}})
- if err != nil {
- return nil, err
+ return "", ErrQueueIdentity
}
- if attrs == nil || attrs.Attributes["QueueArn"] != "arn:"+partition+":sqs:"+self.Region+":"+self.Account+":"+parts[2] {
- return nil, ErrQueueIdentity
- }
- return &Queue{url: rawURL, receive: client.ReceiveMessage, delete: client.DeleteMessage}, nil
+ return "arn:" + partition + ":sqs:" + self.Region + ":" + self.Account + ":" + parts[2], nil
}
func (q *Queue) Receive(ctx context.Context, wait time.Duration) ([]hadeparture.Message, error) {
if wait != hadeparture.LongPoll {
diff --git a/internal/hadeparture/consumer.go b/internal/hadeparture/consumer.go
index bcfa65dc6..71aab3bc2 100644
--- a/internal/hadeparture/consumer.go
+++ b/internal/hadeparture/consumer.go
@@ -21,6 +21,8 @@ func (e *InitError) Unwrap() error { return e.Err }
type Consumer struct {
OnRetry func()
+ OnInitRetry func(string)
+ OnRecordRetry func()
OnStopped func()
initialize func(context.Context) error
record func(context.Context, Message) error
@@ -77,31 +79,10 @@ func (c *Consumer) Start(parent context.Context, makeQueue func(context.Context)
c.ctx, c.cancel = context.WithCancel(parent)
ctx := c.ctx
c.mu.Unlock()
- initCtx, cancel := context.WithTimeout(ctx, InitializeTimeout)
- defer cancel()
- fail := func(stage string, err error) (Lifecycle, error) {
+ if c.initialize == nil || c.record == nil || makeQueue == nil {
c.cancel()
close(c.done)
- return c, &InitError{stage, err}
- }
- if c.initialize == nil || c.record == nil || makeQueue == nil {
- return fail("dependencies", errors.New("ha_consumer_dependency_missing"))
- }
- if err := c.initialize(initCtx); err != nil {
- return fail("journal", err)
- }
- if err := initCtx.Err(); err != nil {
- return fail("journal", err)
- }
- q, err := makeQueue(initCtx)
- if err != nil {
- return fail("queue", err)
- }
- if err = initCtx.Err(); err != nil {
- return fail("queue", err)
- }
- if q == nil {
- return fail("queue", errors.New("ha_consumer_queue_missing"))
+ return c, &InitError{"dependencies", errors.New("ha_consumer_dependency_missing")}
}
c.running.Store(true)
go func() {
@@ -109,10 +90,54 @@ func (c *Consumer) Start(parent context.Context, makeQueue func(context.Context)
defer c.running.Store(false)
defer c.cancel()
var workers sync.WaitGroup
- if c.work != nil {
- workers.Go(func() { defer c.cancel(); _ = c.work(ctx) })
+ journalReady := false
+ failures := 0
+ var q Queue
+ for ctx.Err() == nil {
+ initCtx, cancel := context.WithTimeout(ctx, InitializeTimeout)
+ stage := "journal"
+ var err error
+ if !journalReady {
+ err = c.initialize(initCtx)
+ if err == nil {
+ err = initCtx.Err()
+ }
+ if err == nil {
+ journalReady = true
+ if c.work != nil {
+ workers.Go(func() { defer c.cancel(); _ = c.work(ctx) })
+ }
+ }
+ }
+ if err == nil {
+ stage = "queue"
+ q, err = makeQueue(initCtx)
+ if err == nil {
+ err = initCtx.Err()
+ }
+ if err == nil && q == nil {
+ err = errors.New("ha_consumer_queue_missing")
+ }
+ }
+ cancel()
+ if err == nil {
+ break
+ }
+ q = nil
+ if ctx.Err() != nil {
+ break
+ }
+ if c.OnInitRetry != nil {
+ c.OnInitRetry(stage)
+ }
+ if c.wait(ctx, retryDelay(failures)) != nil {
+ break
+ }
+ failures++
+ }
+ if q != nil && ctx.Err() == nil {
+ c.receive(ctx, q)
}
- c.receive(ctx, q)
c.cancel()
workers.Wait()
if c.OnStopped != nil {
@@ -131,6 +156,7 @@ func (c *Consumer) receive(ctx context.Context, q Queue) {
if err == nil {
err = request.Err()
}
+ receiveFailed := err != nil
if err == nil {
for _, m := range messages {
// A handle belongs only to this receive. The journal never sees it.
@@ -148,8 +174,12 @@ func (c *Consumer) receive(ctx context.Context, q Queue) {
return
}
if err != nil {
- if c.OnRetry != nil {
- c.OnRetry()
+ if receiveFailed {
+ if c.OnRetry != nil {
+ c.OnRetry()
+ }
+ } else if c.OnRecordRetry != nil {
+ c.OnRecordRetry()
}
if c.wait(ctx, retryDelay(failures)) != nil {
return
diff --git a/internal/hadeparture/consumer_test.go b/internal/hadeparture/consumer_test.go
index b331f6088..484d0fa00 100644
--- a/internal/hadeparture/consumer_test.go
+++ b/internal/hadeparture/consumer_test.go
@@ -141,22 +141,6 @@ func TestTerminationConsumerLifecycle(t *testing.T) {
}
_ = life.Stop(context.Background())
})
- for _, stage := range []string{"init", "client"} {
- t.Run(stage, func(t *testing.T) {
- c := testConsumer()
- bad := errors.New("unavailable")
- if stage == "init" {
- c.initialize = func(context.Context) error { return bad }
- }
- life, err := c.Start(context.Background(), func(context.Context) (Queue, error) { return nil, bad })
- var ie *InitError
- if !errors.As(err, &ie) || life.Running() {
- t.Fatalf("%v", err)
- }
- assertOpen(t, life.Started())
- waitClosed(t, life.Done())
- })
- }
t.Run("parent cancels receive", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
c := testConsumer()
@@ -272,3 +256,69 @@ func TestTerminationConsumerStoppedNoticeJoinsWork(t *testing.T) {
waitClosed(t, notice)
waitClosed(t, l.Done())
}
+
+func TestTerminationConsumerInitializationRetries(t *testing.T) {
+ for _, stage := range []string{"journal", "queue"} {
+ t.Run(stage, func(t *testing.T) {
+ c := testConsumer()
+ var calls atomic.Int32
+ entered := make(chan struct{})
+ c.work = func(ctx context.Context) error { close(entered); <-ctx.Done(); return ctx.Err() }
+ failure := func() error {
+ if calls.Add(1) < 8 {
+ return errors.New("outage")
+ }
+ return nil
+ }
+ var waits []time.Duration
+ c.wait = func(ctx context.Context, d time.Duration) error { waits = append(waits, d); return ctx.Err() }
+ if stage == "journal" {
+ c.initialize = func(context.Context) error { return failure() }
+ }
+ q := &testQueue{receive: func(context.Context, time.Duration) ([]Message, error) { return nil, nil }}
+ life, err := c.Start(t.Context(), func(context.Context) (Queue, error) {
+ if stage == "queue" {
+ if err := failure(); err != nil {
+ return nil, err
+ }
+ }
+ return q, nil
+ })
+ if err != nil {
+ t.Fatalf("retryable failure ended lifecycle: %v", err)
+ }
+ waitClosed(t, entered)
+ waitClosed(t, life.Started())
+ _ = life.Stop(context.Background())
+ if calls.Load() != 8 {
+ t.Fatal(calls.Load())
+ }
+ for i, seconds := range []time.Duration{1, 2, 4, 8, 16, 30, 30} {
+ if waits[i] < seconds*time.Second*8/10 || waits[i] > seconds*time.Second {
+ t.Fatal(waits)
+ }
+ }
+ })
+ }
+}
+
+func TestTerminationConsumerRecordErrorSignal(t *testing.T) {
+ c := testConsumer()
+ var queueErrors, recordErrors atomic.Int32
+ c.OnRetry = func() { queueErrors.Add(1) }
+ c.OnRecordRetry = func() { recordErrors.Add(1) }
+ c.record = func(context.Context, Message) error { return errors.New("journal") }
+ notified := make(chan struct{})
+ c.wait = func(ctx context.Context, _ time.Duration) error { close(notified); <-ctx.Done(); return ctx.Err() }
+ q := &testQueue{receive: func(context.Context, time.Duration) ([]Message, error) { return []Message{{ID: "one"}}, nil }}
+ l, e := c.Start(t.Context(), func(context.Context) (Queue, error) { return q, nil })
+ if e != nil {
+ t.Fatal(e)
+ }
+ waitClosed(t, notified)
+ assertOpen(t, l.Started())
+ _ = l.Stop(context.Background())
+ if queueErrors.Load() != 0 || recordErrors.Load() != 1 {
+ t.Fatal(queueErrors.Load(), recordErrors.Load())
+ }
+}
diff --git a/internal/host/hadeparture_identity.go b/internal/host/hadeparture_identity.go
index 123106c29..8d4c1f23b 100644
--- a/internal/host/hadeparture_identity.go
+++ b/internal/host/hadeparture_identity.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"strings"
+ "sync"
"time"
"github.com/carlosframework/platform/internal/boxid"
@@ -18,12 +19,54 @@ import (
var errDepartureIdentity = errors.New("ha_departure_identity_unbound")
type departureIdentities struct {
- Registry *registry.Registry
- Store release.Store
- Verifier boxid.Verifier
- Fixed map[string]string
- Region string
- Now func() time.Time
+ Registry *registry.Registry
+ Store release.Store
+ OpenStore func(context.Context) (release.Store, error)
+ storeMu sync.Mutex
+ opening chan struct{}
+ Verifier boxid.Verifier
+ Fixed map[string]string
+ Region string
+ Now func() time.Time
+}
+
+func (r *departureIdentities) store(ctx context.Context) (release.Store, error) {
+ for {
+ r.storeMu.Lock()
+ if r.Store != nil {
+ s := r.Store
+ r.storeMu.Unlock()
+ return s, nil
+ }
+ if wait := r.opening; wait != nil {
+ r.storeMu.Unlock()
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-wait:
+ continue
+ }
+ }
+ if r.OpenStore == nil {
+ r.storeMu.Unlock()
+ return nil, errDepartureIdentity
+ }
+ r.opening = make(chan struct{})
+ r.storeMu.Unlock()
+ s, err := r.OpenStore(ctx)
+ if err == nil && s == nil {
+ err = errDepartureIdentity
+ }
+ r.storeMu.Lock()
+ if err == nil {
+ r.Store = s
+ }
+ close(r.opening)
+ r.opening = nil
+ r.storeMu.Unlock()
+ return s, err
+ }
+
}
func (r *departureIdentities) now() time.Time {
@@ -110,7 +153,11 @@ func (r *departureIdentities) Observe(ctx context.Context, o hadeparture.BoxObse
return o, err
}
if !ok {
- raw, e := boxid.Load(ctx, r.Store, o.Box.Ref)
+ store, e := r.store(ctx)
+ if e != nil {
+ return o, e
+ }
+ raw, e := boxid.Load(ctx, store, o.Box.Ref)
if e != nil {
return o, e
}
@@ -148,7 +195,11 @@ func (r *departureIdentities) Walk(ctx context.Context) (bool, time.Time, error)
if w.StartedAt.IsZero() {
w.StartedAt = r.now()
}
- l, ok := r.Store.(release.PageLister)
+ store, err := r.store(ctx)
+ if err != nil {
+ return false, w.StartedAt, err
+ }
+ l, ok := store.(release.PageLister)
if !ok {
return false, w.StartedAt, errDepartureIdentity
}
@@ -168,29 +219,44 @@ func (r *departureIdentities) Walk(ctx context.Context) (bool, time.Time, error)
key := w.Keys[w.Offset]
w.Offset++
if key <= w.Cursor || !strings.HasPrefix(key, boxid.Prefix) || !strings.HasSuffix(key, ".json") {
- w.Failed = true
+ w.Blocked = append(w.Blocked, "ref:"+strings.TrimSuffix(strings.TrimPrefix(key, boxid.Prefix), ".json"))
continue
}
ref := strings.TrimSuffix(strings.TrimPrefix(key, boxid.Prefix), ".json")
if !boxid.ValidBox(ref) {
- w.Failed = true
+ w.Blocked = append(w.Blocked, "ref:"+strings.TrimSuffix(strings.TrimPrefix(key, boxid.Prefix), ".json"))
continue
}
_, known, e := r.Resolve(ctx, ref, "")
if e != nil {
- w.Failed = true
+ w.Blocked = append(w.Blocked, "ref:"+strings.TrimSuffix(strings.TrimPrefix(key, boxid.Prefix), ".json"))
continue
}
if known {
continue
}
gets++
- raw, e := boxid.Load(ctx, r.Store, ref)
+ raw, e := boxid.Load(ctx, store, ref)
if e == nil {
_, e = r.verify(ctx, ref, raw)
}
if e != nil {
- w.Failed = true
+ w.Blocked = append(w.Blocked, "ref:"+ref)
+ var rec boxid.Record
+ var doc struct {
+ IID string `json:"instanceId"`
+ }
+ candidate := false
+ if len(raw) <= 64*1024 && json.Unmarshal(raw, &rec) == nil {
+ data, _ := base64.StdEncoding.DecodeString(rec.IdentityDocument)
+ if json.Unmarshal(data, &doc) == nil && len(doc.IID) >= 10 && len(doc.IID) <= 19 {
+ w.Blocked = append(w.Blocked, "iid:"+doc.IID)
+ candidate = true
+ }
+ }
+ if !candidate && r.Fixed[ref] == "" && !(strings.HasPrefix(ref, "g-") && len(ref) == 22) {
+ w.Blocked = append(w.Blocked, "unbound:"+ref)
+ }
}
}
pageDone := w.Offset == len(w.Keys)
@@ -198,7 +264,7 @@ func (r *departureIdentities) Walk(ctx context.Context) (bool, time.Time, error)
complete := finished && !w.Failed
at := w.StartedAt
if finished {
- w = registry.HAIdentityWalk{}
+ w = registry.HAIdentityWalk{LastBlocked: w.Blocked}
} else if pageDone {
w.Cursor = w.Keys[len(w.Keys)-1]
w.Keys = nil
@@ -209,3 +275,18 @@ func (r *departureIdentities) Walk(ctx context.Context) (bool, time.Time, error)
}
return complete, at, nil
}
+
+func (r *departureIdentities) walkBlocks(blocked []string, iid string) bool {
+ for _, b := range blocked {
+ if strings.HasPrefix(b, "unbound:") {
+ return true
+ }
+ if b == "iid:"+iid || b == "ref:"+groupReferenceOf(r.Verifier.Account, iid) {
+ return true
+ }
+ if ref, ok := strings.CutPrefix(b, "ref:"); ok && r.Fixed[ref] == iid {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/host/hadeparture_identity_test.go b/internal/host/hadeparture_identity_test.go
index d2a5fafa1..e511a5890 100644
--- a/internal/host/hadeparture_identity_test.go
+++ b/internal/host/hadeparture_identity_test.go
@@ -92,8 +92,45 @@ func TestDepartureUnknownIdentityBudget(t *testing.T) {
}
for n := 0; n < 2; n++ {
done, _, _ = repo.Walk(ctx)
- if done {
- t.Fatal("malformed record certified unrelated")
+ if n == 1 && !done {
+ t.Fatal("malformed record blocked every iid")
}
}
}
+
+func TestDepartureWalkFailureIsolation(t *testing.T) {
+ a, _, _ := departureArmFixture(t)
+ store, err := a.OpenStore(t.Context())
+ if err != nil {
+ t.Fatal(err)
+ }
+ repo := &departureIdentities{Registry: a.Registry, Store: store, Verifier: a.Verifier, Region: a.Self.Scope.CloudRegion}
+ // The signed fixed identity has no configured binding. It blocks its own iid.
+ complete, _, err := repo.Walk(t.Context())
+ if err != nil || !complete {
+ t.Fatal("unbound fixed ref blocked walk", complete, err)
+ }
+ w, err := a.Registry.LoadHAIdentityWalk(t.Context())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !repo.walkBlocks(w.LastBlocked, "i-1123456789abcdef0") || repo.walkBlocks(w.LastBlocked, "i-2123456789abcdef0") {
+ t.Fatal("fixed binding failure spilled across iids", w)
+ }
+ // A malformed record blocks its independently configured iid only.
+ repo.Fixed = map[string]string{"broken": "i-3123456789abcdef0"}
+ if _, err = store.Put(t.Context(), boxid.Key("broken"), []byte(`{}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ complete, _, err = repo.Walk(t.Context())
+ if err != nil || !complete {
+ t.Fatal(complete, err)
+ }
+ w, err = a.Registry.LoadHAIdentityWalk(t.Context())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !repo.walkBlocks(w.LastBlocked, "i-3123456789abcdef0") || repo.walkBlocks(w.LastBlocked, "i-2123456789abcdef0") {
+ t.Fatal("malformed record blocks unrelated iid", w)
+ }
+}
diff --git a/internal/host/hadepartures.go b/internal/host/hadepartures.go
index c89dfef16..cd0c4a0b4 100644
--- a/internal/host/hadepartures.go
+++ b/internal/host/hadepartures.go
@@ -65,8 +65,9 @@ type DepartureConfig struct {
Now func() time.Time
Logf func(string, ...any)
// Pending is the B4 scan-page entry. A nil entry retains all work.
- Pending func(context.Context, registry.HADeparture, provision.InventorySnapshot) error
- Page func(context.Context, registry.HADeparture, []provision.DepartureHost) error
+ Pending func(context.Context, registry.HADeparture, provision.InventorySnapshot) error
+ Page func(context.Context, registry.HADeparture, []provision.DepartureHost) error
+ PageIdentity func(context.Context, registry.HAPendingTermination, string) error
}
type Controller struct {
cfg DepartureConfig
@@ -77,6 +78,7 @@ type Controller struct {
peerOffset int
evidence map[string]bool
suspects map[string]bool
+ notices map[string]time.Time
}
func NewController(cfg DepartureConfig) (*Controller, error) {
@@ -85,12 +87,30 @@ func NewController(cfg DepartureConfig) (*Controller, error) {
}
c := &Controller{cfg: cfg, wake: make(chan struct{}, 1), evidence: map[string]bool{}}
c.consumer = hadeparture.NewConsumer(func(ctx context.Context) error { _, err := cfg.Registry.TerminationInbox(ctx, c.now(), 1); return err }, c.record, c.work)
- c.consumer.OnRetry = func() { c.logf("Termination recovery is retrying after a queue error.") }
+ c.consumer.OnRetry = func() { c.notice("receive", "Termination recovery is retrying after a queue error.") }
+ c.consumer.OnInitRetry = func(stage string) { c.notice("init", "Termination recovery has not started: %s.", stage) }
+ c.consumer.OnRecordRetry = func() { c.notice("record", "ha_departure_retry code=record") }
c.consumer.OnStopped = func() {
c.logf("Termination recovery has stopped. Pending recovery will resume when the box starts again.")
}
return c, nil
}
+func (c *Controller) notice(code, format string, args ...any) {
+ c.mu.Lock()
+ if c.notices == nil {
+ c.notices = map[string]time.Time{}
+ }
+ now := c.now()
+ last, ok := c.notices[code]
+ if ok && now.Sub(last) < time.Hour {
+ c.mu.Unlock()
+ return
+ }
+ c.notices[code] = now
+ c.mu.Unlock()
+ c.logf(format, args...)
+}
+
func departureCloud(b hadeparture.Box) boxid.Cloud {
return boxid.Cloud{Provider: "aws", Account: b.Account, Region: b.Scope.CloudRegion, InstanceID: b.InstanceID}
}
@@ -116,10 +136,11 @@ func (c *Controller) Start(ctx context.Context, makeQueue func(context.Context)
return life, nil
}
func (c *Controller) record(ctx context.Context, m hadeparture.Message) error {
- if _, err := awsterminations.Hint(m.Body, departureCloud(c.cfg.Self)); err != nil {
+ iid, err := awsterminations.Hint(m.Body, departureCloud(c.cfg.Self))
+ if err != nil {
return nil
}
- return c.cfg.Registry.RecordTermination(ctx, m.ID, m.Body, c.now())
+ return c.cfg.Registry.ParkTermination(ctx, registry.HAPendingTermination{Account: c.cfg.Self.Account, Region: c.cfg.Self.Scope.CloudRegion, IID: iid, ReceivedAt: c.now()}, "")
}
func departureID(bucket string, b hadeparture.Box) string {
raw, _ := json.Marshal([]string{bucket, b.Account, b.Scope.CloudRegion, b.Ref, b.InstanceID, b.RecordSHA256})
@@ -203,12 +224,7 @@ func (c *Controller) Tick(_ context.Context, v hadeparture.DepartureView) error
return nil
}
func (c *Controller) work(ctx context.Context) error {
- select {
- case <-ctx.Done():
- return ctx.Err()
- case <-c.consumer.Started():
- }
- c.logf("Termination recovery is running.")
+ started := c.consumer.Started()
timer := time.NewTicker(30 * time.Second)
defer timer.Stop()
lastStep := time.Time{}
@@ -217,12 +233,15 @@ func (c *Controller) work(ctx context.Context) error {
if time.Since(lastStep) >= 30*time.Second {
lastStep = time.Now()
if err := c.step(ctx); err != nil && ctx.Err() == nil {
- c.logf("ha_departure_retry code=journal")
+ c.notice("journal", "ha_departure_retry code=journal")
}
}
select {
case <-ctx.Done():
return ctx.Err()
+ case <-started:
+ c.logf("Termination recovery is running.")
+ started = nil
case <-timer.C:
case <-c.wake:
}
@@ -251,7 +270,7 @@ func (c *Controller) step(ctx context.Context) error {
o, known, e := c.cfg.Identities.Resolve(ctx, ref, "")
if e == nil && known {
if due, e := c.cfg.Registry.ClaimHAConfirmation(ctx, ref, c.now()); e == nil && due {
- _ = c.Enqueue(ctx, o)
+ _, _ = c.cfg.Confirmer.Terminated(ctx, o.Box.InstanceID)
}
}
}
@@ -272,17 +291,17 @@ func (c *Controller) step(ctx context.Context) error {
}
if v.Self.Known && !v.Self.PlacementNull && v.Self.Box.Scope == c.cfg.Self.Scope && c.now().Sub(o.PublishedAt) > 15*time.Minute {
if due, err := c.cfg.Registry.ClaimHAConfirmation(ctx, bound.Box.Ref, c.now()); err == nil && due {
- _ = c.Enqueue(ctx, bound)
+ _, _ = c.cfg.Confirmer.Terminated(ctx, bound.Box.InstanceID)
}
}
}
c.peerOffset = (c.peerOffset + min(32, len(observations))) % len(observations)
}
- rows, err := c.cfg.Registry.TerminationInbox(ctx, c.now(), 32)
+ rows, err := c.cfg.Registry.TerminationInbox(ctx, time.Unix(0, 1<<63-1), 32)
if err != nil {
return err
}
- unknown := false
+ // Normalize old inboxes in bounded pages, including rows whose retry is later.
for _, row := range rows {
iid, e := awsterminations.Hint(row.Body, departureCloud(c.cfg.Self))
if e != nil {
@@ -291,37 +310,62 @@ func (c *Controller) step(ctx context.Context) error {
}
continue
}
- o, known, e := c.cfg.Identities.Resolve(ctx, "", iid)
- if e == nil && !known {
+ if e = c.cfg.Registry.ParkTermination(ctx, registry.HAPendingTermination{Account: c.cfg.Self.Account, Region: c.cfg.Self.Scope.CloudRegion, IID: iid, ReceivedAt: row.ReceivedAt}, row.Key); e != nil {
+ return e
+ }
+ }
+ hints, err := c.cfg.Registry.PendingTerminations(ctx, c.now(), 32)
+ if err != nil {
+ return err
+ }
+ unknown := false
+ for _, h := range hints {
+ _, known, e := c.cfg.Identities.Resolve(ctx, "", h.IID)
+ if e != nil || !known {
unknown = true
- if e = c.cfg.Registry.RetryTermination(ctx, row.Key, c.now().Add(30*time.Second), "identity_walk"); e != nil {
+ }
+ }
+ complete := false
+ var started time.Time
+ var blocked []string
+ if unknown {
+ complete, started, err = c.cfg.Identities.Walk(ctx)
+ if err == nil && complete {
+ w, e := c.cfg.Registry.LoadHAIdentityWalk(ctx)
+ if e != nil {
return e
}
- continue
+ blocked = w.LastBlocked
}
- if e == nil {
- e = c.enqueue(ctx, o, row.Key)
+ }
+ for _, h := range hints {
+ o, known, e := c.cfg.Identities.Resolve(ctx, "", h.IID)
+ code := "identity_unbound"
+ if e == nil && known {
+ e = c.enqueue(ctx, o, "")
+ code = "evidence"
}
- if e != nil {
- if e = c.cfg.Registry.RetryTermination(ctx, row.Key, c.now().Add(30*time.Second), "evidence"); e != nil {
+ if e == nil && known {
+ if e = c.cfg.Registry.RemovePendingTermination(ctx, h); e != nil {
return e
}
+ continue
}
- }
- if unknown {
- complete, started, e := c.cfg.Identities.Walk(ctx)
+ if e == nil && !known && complete && !h.ReceivedAt.After(started) && !c.cfg.Identities.walkBlocks(blocked, h.IID) {
+ if e = c.cfg.Registry.RemovePendingTermination(ctx, h); e != nil {
+ return e
+ }
+ continue
+ }
+ page, e := c.cfg.Registry.RetryPendingTermination(ctx, h, c.now(), code)
if e != nil {
return e
}
- for _, row := range rows {
- iid, e := awsterminations.Hint(row.Body, departureCloud(c.cfg.Self))
- if e != nil {
- continue
- }
- _, known, e := c.cfg.Identities.Resolve(ctx, "", iid)
- if e == nil && !known && complete && !row.ReceivedAt.After(started) {
- if e = c.cfg.Registry.RejectTermination(ctx, row.Key); e != nil {
- return e
+ if page {
+ c.logf("ha_departure_pending code=%s iid=%s", code, h.IID)
+ if c.cfg.PageIdentity != nil {
+ if e = c.cfg.PageIdentity(ctx, h, code); e != nil {
+ c.logf("ha_departure_page code=failed")
}
}
}
diff --git a/internal/host/hadepartures_wiring.go b/internal/host/hadepartures_wiring.go
index 0771e2e2b..2714ee069 100644
--- a/internal/host/hadepartures_wiring.go
+++ b/internal/host/hadepartures_wiring.go
@@ -7,7 +7,6 @@ import (
"log"
"strconv"
"strings"
- "time"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/carlosframework/platform/internal/activator"
@@ -47,7 +46,6 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
if !enabled {
return nil, nil, nil
}
- started := time.Now()
fail := func(stage string, err error) (*Controller, hadeparture.Lifecycle, error) {
log.Printf("Termination recovery has not started: %s.", stage)
return nil, nil, &hadeparture.InitError{Stage: stage, Err: err}
@@ -55,9 +53,6 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
if a.Registry == nil || a.Service == nil || a.Backend == nil || a.Confirmer == nil || a.Inventory == nil || a.OpenStore == nil {
return fail("dependencies", errDepartureScope)
}
- if a.Getenv(departureQueueEnv) == "" && a.MakeQueue == nil {
- return fail("queue_setting", errDepartureScope)
- }
if a.Self.Ref == "" {
self := lease.CurrentSelf()
a.Self = hadeparture.Box{Ref: self.Ref, InstanceID: self.IID, Account: self.Account, Scope: hadeparture.Scope{CloudRegion: self.Region, Placement: a.Getenv("CARLOS_REGION"), DataBucket: a.Backend.Cfg.Bucket, SecretsKeyFP: edgesFileSecretsFP(a.Getenv)}}
@@ -82,29 +77,37 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
}
a.Verifier = boxid.Verifier{Account: a.Self.Account, Certs: certs}
}
- initCtx, cancel := context.WithDeadline(ctx, started.Add(hadeparture.InitializeTimeout))
- defer cancel()
- store, err := a.OpenStore(initCtx)
- if err != nil {
- return fail("store", err)
- }
- repo := &departureIdentities{Registry: a.Registry, Store: store, Verifier: a.Verifier, Fixed: fixed, Region: a.Self.Scope.CloudRegion}
+ repo := &departureIdentities{Registry: a.Registry, OpenStore: a.OpenStore, Verifier: a.Verifier, Fixed: fixed, Region: a.Self.Scope.CloudRegion}
cache := &termfence.ProofCache{}
if a.ProofStore == nil {
- data, err := release.NewS3StoreIn(initCtx, a.Self.Scope.DataBucket, a.Self.Scope.CloudRegion)
- if err != nil {
- return fail("data_store", err)
- }
- a.ProofStore = func(_ context.Context, bucket, region string) (termfence.ProofStore, error) {
+ gate := make(chan struct{}, 1)
+ var api termfence.ProofStore
+ a.ProofStore = func(ctx context.Context, bucket, region string) (termfence.ProofStore, error) {
if bucket != a.Self.Scope.DataBucket || region != a.Self.Scope.CloudRegion {
return nil, errDepartureScope
}
- return termfence.NewProofStore(data.Client), nil
+ select {
+ case gate <- struct{}{}:
+ defer func() { <-gate }()
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ if api != nil {
+ return api, nil
+ }
+ data, err := release.NewS3StoreIn(ctx, bucket, region)
+ if err != nil {
+ return nil, err
+ }
+ api = termfence.NewProofStore(data.Client)
+ return api, nil
}
}
c, err := NewController(DepartureConfig{Registry: a.Registry, Identities: repo, Confirmer: a.Confirmer, Cache: cache, ProofStore: a.ProofStore, Self: a.Self, DeploymentBucket: a.Getenv("CARLOS_DEPLOYMENT_BUCKET"), Inventory: func() provision.InventorySnapshot { return departureInventorySnapshot(a.Inventory) }, Policy: func() LocalPolicy {
return LocalPolicy{Scope: a.Self.Scope, Pools: provision.ParseBoxPools(a.Getenv("CARLOS_POOLS"))}
- }, Invalidate: a.Service.InvalidateDutyHolder, Page: func(ctx context.Context, d registry.HADeparture, hosts []provision.DepartureHost) error {
+ }, Invalidate: a.Service.InvalidateDutyHolder, PageIdentity: func(ctx context.Context, h registry.HAPendingTermination, code string) error {
+ return PageOperator(ctx, alerting.LevelWarning, "ha_departure_pending", fmt.Sprintf("code=%s account=%s region=%s iid=%s", code, h.Account, h.Region, h.IID))
+ }, Page: func(ctx context.Context, d registry.HADeparture, hosts []provision.DepartureHost) error {
var messages []string
for _, h := range hosts {
messages = append(messages, fmt.Sprintf("Duties for sidecar %s cannot be recovered by this version. Keep the departure records. The departure stays open. Upgrading alone will not recover the sidecar.", h.Host))
@@ -114,9 +117,14 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
if err != nil {
return fail("controller", err)
}
+ var queueError error
makeQueue := a.MakeQueue
if makeQueue == nil {
+ queueError = awsterminations.ValidateURL(a.Getenv(departureQueueEnv), departureCloud(a.Self))
makeQueue = func(ctx context.Context) (hadeparture.Queue, error) {
+ if queueError != nil {
+ return nil, queueError
+ }
cfg, err := rootaws.LoadDefaultConfig(ctx, awsconfig.WithRegion(a.Self.Scope.CloudRegion), awsconfig.WithRetryMaxAttempts(1))
if err != nil {
return nil, err
@@ -125,21 +133,15 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
}
}
queue := func(ctx context.Context) (hadeparture.Queue, error) {
- bounded, cancel := context.WithDeadline(ctx, started.Add(hadeparture.InitializeTimeout))
- defer cancel()
- return makeQueue(bounded)
- }
- if err = initCtx.Err(); err != nil {
- return fail("deadline", err)
+ if _, err := repo.store(ctx); err != nil {
+ return nil, err
+ }
+ if _, err := a.ProofStore(ctx, a.Self.Scope.DataBucket, a.Self.Scope.CloudRegion); err != nil {
+ return nil, err
+ }
+ return makeQueue(ctx)
}
- // Install before workers start; a failed Start restores the prior callback.
- previous := a.Confirmer.OnConfirmed
a.Confirmer.OnConfirmed = c.confirmed
- life, err := c.Start(ctx, queue)
- if err != nil {
- a.Confirmer.OnConfirmed = previous
- return nil, life, err
- }
a.Backend.TerminationProofs = &lease.TerminationProofAdapter{Cache: cache, Confirmer: a.Confirmer, Resolve: repo.Proof, Lifetime: func(ctx context.Context, bucket, prefix, region string) (string, error) {
if bucket != a.Backend.Cfg.Bucket || region != a.Backend.Cfg.Region {
return "", errDepartureScope
@@ -152,22 +154,20 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
if activator.HibernatePrefix(a.Backend.Cfg.Prefix, host) != prefix || !provision.ValidHostShape(host) {
return "", errDepartureScope
}
- snapshot := departureInventorySnapshot(a.Inventory)
- if !snapshot.Complete {
- return "", errDepartureIdentity
- }
- for _, h := range snapshot.Records {
- if h.Host == host && h.HA && h.Placement == a.Self.Scope.Placement && h.Lifetime != "" {
- return h.Lifetime, nil
- }
- }
- return "", errDepartureIdentity
+ return a.Backend.TerminationLifetime(ctx, host)
}}
a.Service.AdoptionIdentity = func(ctx context.Context, ref, iid string) (bool, error) {
o, known, err := repo.Resolve(ctx, ref, iid)
return known && o.Known && !o.PlacementNull && o.Box.Account == a.Self.Account && o.Box.Scope == a.Self.Scope, err
}
a.Service.OnDepartureSuspect = c.Suspect
+ life, err := c.Start(ctx, queue)
+ if err != nil {
+ return c, life, err
+ }
+ if queueError != nil {
+ return c, life, &hadeparture.InitError{Stage: "queue_setting", Err: queueError}
+ }
return c, life, nil
}
diff --git a/internal/host/hadepartures_wiring_test.go b/internal/host/hadepartures_wiring_test.go
index cb4ebf3c1..2ed9e2ce2 100644
--- a/internal/host/hadepartures_wiring_test.go
+++ b/internal/host/hadepartures_wiring_test.go
@@ -2,12 +2,15 @@ package host
import (
"context"
+ "encoding/json"
"errors"
+ "fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
+ "sync/atomic"
"testing"
"time"
@@ -19,6 +22,9 @@ import (
"github.com/carlosframework/platform/internal/boxid"
"github.com/carlosframework/platform/internal/boxid/boxidtest"
"github.com/carlosframework/platform/internal/hadeparture"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/lease/locktest"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
@@ -198,10 +204,364 @@ func TestTerminationEventEvidence(t *testing.T) {
if err = c.step(t.Context()); err != nil {
t.Fatal(err)
}
- rows, err := a.Registry.TerminationInbox(t.Context(), time.Now().Add(time.Hour), 32)
+ rows, err := a.Registry.PendingTerminations(t.Context(), time.Now().Add(time.Hour), 32)
if err != nil || len(rows) != 1 || scans != 0 || p.puts != 0 {
t.Fatalf("unproven event inbox=%d scans=%d puts=%d err=%v", len(rows), scans, p.puts, err)
}
})
}
}
+
+func TestTerminationProductionLifetimeIncompleteInventory(t *testing.T) {
+ oldSelf := lease.CurrentSelf()
+ t.Cleanup(func() { lease.SetSelf(oldSelf) })
+ fx := locktest.NewLockFixture(t)
+ a, _, _ := departureArmFixture(t)
+ a.Self.Scope.DataBucket = fx.Bucket
+ a.Backend.Cfg.Bucket = fx.Bucket
+ a.Backend.Registry = a.Registry
+ a.Backend.Cfg.Record = func(context.Context, registry.Route) (activator.RecordFacts, error) {
+ return activator.RecordFacts{LifetimeEntry: provision.LifetimeEntry{ID: "life", HA: true}}, nil
+ }
+ a.ProofStore = nil
+ lease.SetSelf(hafresh.Self{Ref: a.Self.Ref, IID: a.Self.InstanceID, Account: a.Self.Account, Region: a.Self.Scope.CloudRegion})
+ if err := lease.SetObligationDir(t.TempDir()); err != nil {
+ t.Fatal(err)
+ }
+ if err := a.Registry.Upsert(registry.Route{Host: "shop.example.com", Kind: "instance", Provisioned: true, HA: true}); err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ c, l, err := armHADepartures(ctx, a)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer l.Stop(context.Background())
+ o, err := c.cfg.Identities.Observe(ctx, hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: "dead", Scope: a.Self.Scope}, EdgesKey: "control/edges/dead.json", EdgesETag: "exact"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = c.Enqueue(ctx, o); err != nil {
+ t.Fatal(err)
+ }
+ // The proof was persisted. A fresh cache must recover without EC2.
+ if err = l.Stop(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ a.Backend.TerminationProofs.Cache = &termfence.ProofCache{}
+ a.Confirmer = &termfence.Confirmer{Self: func() boxid.Cloud { return departureCloud(a.Self) }, API: func(context.Context, string) (termfence.EC2, error) { return nil, errors.New("forgotten") }, OnConfirmed: c.confirmed}
+ a.Backend.TerminationProofs.Confirmer = a.Confirmer
+ c.cfg.Confirmer = a.Confirmer
+ c.cfg.Cache = a.Backend.TerminationProofs.Cache
+ for _, life := range []string{"wrong", "life"} {
+ body, _ := json.Marshal(hafresh.Lock{Generation: 1, Owner: hafresh.OwnerFor(hafresh.Self{Ref: "dead", IID: o.Box.InstanceID}, 1, true), ExpiresAt: time.Now().Add(-time.Hour)})
+ fx.PutLock("instances/shop.example.com", body)
+ held, e := lease.AcquireHA(lease.WithTerminationProof(ctx, a.Backend.TerminationProofs), fx.Bucket, "instances/shop.example.com", a.Self.Scope.CloudRegion, hafresh.Marker{Lifetime: life}, hafresh.Proofs{})
+ if life == "wrong" {
+ if e == nil {
+ _ = held.Release(ctx)
+ t.Fatal("lifetime mismatch authorized")
+ }
+ continue
+ }
+ if e != nil {
+ t.Fatalf("incomplete inventory blocked proof takeover: %v", e)
+ }
+ _ = held.Release(ctx)
+ }
+}
+
+func TestTerminationArmWithoutQueue(t *testing.T) {
+ a, _, _ := departureArmFixture(t)
+ a.MakeQueue = nil
+ c, l, err := armHADepartures(t.Context(), a)
+ if err == nil {
+ t.Fatal("missing static queue error")
+ }
+ if l != nil {
+ defer l.Stop(context.Background())
+ }
+ if c == nil || a.Backend.TerminationProofs == nil || a.Service.AdoptionIdentity == nil || a.Service.OnDepartureSuspect == nil {
+ t.Fatal("queue configuration disabled proof/adoption")
+ }
+}
+
+func terminationHint(iid string) []byte {
+ return []byte(fmt.Sprintf(`{"version":"0","id":"event","source":"aws.ec2","detail-type":"EC2 Instance State-change Notification","account":"111122223333","region":"eu-west-1","detail":{"instance-id":%q,"state":"terminated"}}`, iid))
+}
+func TestTerminationInboxCapRestart(t *testing.T) {
+ a, _, _ := departureArmFixture(t)
+ at := time.Now().Add(-time.Hour)
+ for n := 0; n < hadeparture.MaxInboxRows; n++ {
+ if err := a.Registry.RecordTermination(t.Context(), fmt.Sprint(n), terminationHint(fmt.Sprintf("i-%017x", n+1)), at); err != nil {
+ t.Fatal(err)
+ }
+ }
+ path := a.Registry.Path()
+ a.Registry.Close()
+ reg, err := registry.Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ a.Registry = reg
+ a.MakeQueue = func(context.Context) (hadeparture.Queue, error) {
+ return &departureRedeliveryQueue{body: terminationHint("i-1123456789abcdef0")}, nil
+ }
+ c, l, err := armHADepartures(t.Context(), a)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer l.Stop(context.Background())
+ if err = c.record(t.Context(), hadeparture.Message{ID: "real", Body: terminationHint("i-1123456789abcdef0")}); err != nil {
+ t.Fatalf("cap stopped recording: %v", err)
+ }
+ // Queue startup must not prevent observation or the draining of old inboxes.
+ c.Tick(t.Context(), hadeparture.DepartureView{Peers: []hadeparture.BoxObservation{{Known: true, Box: hadeparture.Box{Ref: "dead", Scope: a.Self.Scope}, EdgesKey: "control/edges/dead.json", EdgesETag: "exact"}}})
+ deadline := time.Now().Add(35 * time.Second)
+ for time.Now().Before(deadline) {
+ if _, ok, _ := c.cfg.Identities.Resolve(t.Context(), "dead", ""); ok {
+ select {
+ case <-l.Started():
+ return
+ default:
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ t.Fatal("queue failure stopped identity observation")
+}
+func TestTerminationUnknownRowsReleaseInbox(t *testing.T) {
+ a, _, _ := departureArmFixture(t)
+ repo := &departureIdentities{Registry: a.Registry, OpenStore: a.OpenStore, Verifier: a.Verifier, Fixed: map[string]string{}, Region: "eu-west-1"}
+ c, err := NewController(DepartureConfig{Registry: a.Registry, Identities: repo, Confirmer: a.Confirmer, Cache: &termfence.ProofCache{}, ProofStore: a.ProofStore, Self: a.Self, DeploymentBucket: "deployment", Inventory: a.Inventory.Snapshot, Policy: func() LocalPolicy { return LocalPolicy{Scope: a.Self.Scope} }})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = c.record(t.Context(), hadeparture.Message{ID: "unknown", Body: terminationHint("i-1123456789abcdef0")}); err != nil {
+ t.Fatal(err)
+ }
+ if err = c.step(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ rows, err := a.Registry.TerminationInbox(t.Context(), time.Now().Add(time.Hour), 32)
+ if err != nil || len(rows) != 0 {
+ t.Fatalf("unresolved row holds inbox slot: %d %v", len(rows), err)
+ }
+}
+
+func TestTerminationSuspicionDescribeBeforeProof(t *testing.T) {
+ a, p, _ := departureArmFixture(t)
+ a.Confirmer.API = func(context.Context, string) (termfence.EC2, error) {
+ return describeInstances(func(_ context.Context, in *ec2.DescribeInstancesInput, _ ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) {
+ return &ec2.DescribeInstancesOutput{Reservations: []ec2types.Reservation{{OwnerId: aws.String(a.Self.Account), Instances: []ec2types.Instance{{InstanceId: aws.String(in.InstanceIds[0]), State: &ec2types.InstanceState{Name: ec2types.InstanceStateNameRunning}}}}}}, nil
+ }), nil
+ }
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ c, l, err := armHADepartures(ctx, a)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = l.Stop(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ o, err := c.cfg.Identities.Observe(t.Context(), hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: "dead", Scope: a.Self.Scope}, PublishedAt: time.Now().Add(-time.Hour), EdgesKey: "control/edges/dead.json", EdgesETag: "exact"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ c.Suspect("dead")
+ if err = c.step(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.gets != 0 || p.puts != 0 {
+ t.Fatalf("live suspicion touched proofs: GET=%d PUT=%d", p.gets, p.puts)
+ }
+ _ = o
+}
+func TestTerminationRetryNotices(t *testing.T) {
+ a, _, _ := departureArmFixture(t)
+ repo := &departureIdentities{Registry: a.Registry, OpenStore: a.OpenStore, Verifier: a.Verifier, Region: a.Self.Scope.CloudRegion}
+ var logs []string
+ c, err := NewController(DepartureConfig{Registry: a.Registry, Identities: repo, Confirmer: a.Confirmer, Cache: &termfence.ProofCache{}, Self: a.Self, DeploymentBucket: "deployment", Inventory: a.Inventory.Snapshot, Policy: func() LocalPolicy { return LocalPolicy{} }, Logf: func(f string, args ...any) { logs = append(logs, fmt.Sprintf(f, args...)) }})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for n := 0; n < 10; n++ {
+ c.consumer.OnRetry()
+ }
+ if len(logs) != 1 {
+ t.Fatalf("C6 repeated %d times", len(logs))
+ }
+ if c.consumer.OnRecordRetry == nil {
+ t.Fatal("journal errors have no separate signal")
+ }
+ for n := 0; n < 10; n++ {
+ c.consumer.OnRecordRetry()
+ }
+ if len(logs) != 2 || logs[1] != "ha_departure_retry code=record" {
+ t.Fatal(logs)
+ }
+}
+
+func TestTerminationArmRetriesStores(t *testing.T) {
+ for _, stage := range []string{"deployment", "data", "queue"} {
+ t.Run(stage, func(t *testing.T) {
+ a, _, _ := departureArmFixture(t)
+ var calls atomic.Int32
+ fail := func() error {
+ if calls.Add(1) == 1 {
+ return errors.New("temporary")
+ }
+ return nil
+ }
+ switch stage {
+ case "deployment":
+ old := a.OpenStore
+ a.OpenStore = func(ctx context.Context) (release.Store, error) {
+ if e := fail(); e != nil {
+ return nil, e
+ }
+ return old(ctx)
+ }
+ case "data":
+ old := a.ProofStore
+ a.ProofStore = func(ctx context.Context, b, r string) (termfence.ProofStore, error) {
+ if e := fail(); e != nil {
+ return nil, e
+ }
+ return old(ctx, b, r)
+ }
+ case "queue":
+ old := a.MakeQueue
+ a.MakeQueue = func(ctx context.Context) (hadeparture.Queue, error) {
+ if e := fail(); e != nil {
+ return nil, e
+ }
+ return old(ctx)
+ }
+ }
+ c, l, e := armHADepartures(t.Context(), a)
+ if e != nil {
+ t.Fatalf("transient %s ended arm: %v", stage, e)
+ }
+ defer l.Stop(context.Background())
+ if c == nil || a.Backend.TerminationProofs == nil || a.Service.AdoptionIdentity == nil {
+ t.Fatal("not armed")
+ }
+ select {
+ case <-l.Started():
+ case <-time.After(3 * time.Second):
+ t.Fatal("startup did not retry")
+ }
+ })
+ }
+}
+func TestTerminationArmRejectsQueueURLKeepsProof(t *testing.T) {
+ a, _, _ := departureArmFixture(t)
+ old := a.Getenv
+ a.Getenv = func(k string) string {
+ if k == departureQueueEnv {
+ return "https://sqs.eu-west-1.amazonaws.com/999999999999/wrong"
+ }
+ return old(k)
+ }
+ a.MakeQueue = nil
+ _, l, err := armHADepartures(t.Context(), a)
+ if l != nil {
+ defer l.Stop(context.Background())
+ }
+ var ie *hadeparture.InitError
+ if !errors.As(err, &ie) {
+ t.Fatal("URL mismatch must be a static error", err)
+ }
+ if a.Backend.TerminationProofs == nil || a.Service.AdoptionIdentity == nil {
+ t.Fatal("static queue error disabled proof")
+ }
+}
+
+type departureRedeliveryQueue struct {
+ body []byte
+ calls atomic.Int32
+}
+
+func (q *departureRedeliveryQueue) Receive(ctx context.Context, _ time.Duration) ([]hadeparture.Message, error) {
+ if q.calls.Add(1) == 1 {
+ return []hadeparture.Message{{ID: "redelivered", Body: q.body}}, nil
+ }
+ <-ctx.Done()
+ return nil, ctx.Err()
+}
+func (q *departureRedeliveryQueue) Delete(context.Context, string) error { return nil }
+func TestTerminationWorkerIndependentOfQueue(t *testing.T) {
+ for _, mode := range []string{"initialization", "receive"} {
+ t.Run(mode, func(t *testing.T) {
+ a, _, _ := departureArmFixture(t)
+ repo := &departureIdentities{Registry: a.Registry, OpenStore: a.OpenStore, Verifier: a.Verifier, Fixed: map[string]string{"dead": "i-1123456789abcdef0"}, Region: a.Self.Scope.CloudRegion}
+ c, err := NewController(DepartureConfig{Registry: a.Registry, Identities: repo, Confirmer: a.Confirmer, Cache: &termfence.ProofCache{}, Self: a.Self, DeploymentBucket: "deployment", Inventory: a.Inventory.Snapshot, Policy: func() LocalPolicy { return LocalPolicy{} }})
+ if err != nil {
+ t.Fatal(err)
+ }
+ c.Tick(t.Context(), hadeparture.DepartureView{Peers: []hadeparture.BoxObservation{{Known: true, Box: hadeparture.Box{Ref: "dead", Scope: a.Self.Scope}, EdgesKey: "control/edges/dead.json", EdgesETag: "exact"}}})
+ l, err := c.Start(t.Context(), func(context.Context) (hadeparture.Queue, error) {
+ if mode == "initialization" {
+ return nil, errors.New("offline")
+ }
+ return &departureFailQueue{}, nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer l.Stop(context.Background())
+ deadline := time.Now().Add(time.Second)
+ for time.Now().Before(deadline) {
+ if o, ok, _ := repo.Resolve(t.Context(), "dead", ""); ok && o.Known {
+ select {
+ case <-l.Started():
+ t.Fatal("failure acknowledged startup")
+ default:
+ return
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ t.Fatal("queue outage prevented observation")
+ })
+ }
+}
+
+type departureFailQueue struct{}
+
+func (*departureFailQueue) Receive(context.Context, time.Duration) ([]hadeparture.Message, error) {
+ return nil, errors.New("offline")
+}
+func (*departureFailQueue) Delete(context.Context, string) error { return nil }
+
+func TestTerminationUnreadIdentityRetainsPending(t *testing.T) {
+ a, _, _ := departureArmFixture(t)
+ store, err := a.OpenStore(t.Context())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = store.Put(t.Context(), boxid.Key("unconfigured"), []byte(`{}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ repo := &departureIdentities{Registry: a.Registry, Store: store, Verifier: a.Verifier, Region: a.Self.Scope.CloudRegion}
+ c, err := NewController(DepartureConfig{Registry: a.Registry, Identities: repo, Confirmer: a.Confirmer, Cache: &termfence.ProofCache{}, Self: a.Self, DeploymentBucket: "deployment", Inventory: a.Inventory.Snapshot, Policy: func() LocalPolicy { return LocalPolicy{} }})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = c.record(t.Context(), hadeparture.Message{ID: "unknown", Body: terminationHint("i-2123456789abcdef0")}); err != nil {
+ t.Fatal(err)
+ }
+ if err = c.step(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ hints, err := a.Registry.PendingTerminations(t.Context(), time.Now().Add(time.Hour), 32)
+ if err != nil || len(hints) != 1 {
+ t.Fatal("an unidentifiable record cannot certify unrelated", hints, err)
+ }
+}
diff --git a/internal/provision/departure_inventory.go b/internal/provision/departure_inventory.go
index a1f862317..54541c69a 100644
--- a/internal/provision/departure_inventory.go
+++ b/internal/provision/departure_inventory.go
@@ -36,6 +36,7 @@ type DeparturePass struct {
families map[string][]DepartureHost
complete map[string]bool
sourceComplete bool
+ snapshot InventorySnapshot
}
func (i *DepartureInventory) Snapshot() InventorySnapshot {
@@ -49,11 +50,8 @@ func (i *DepartureInventory) Begin(generation string, walk, source time.Time, co
i.mu.Lock()
defer i.mu.Unlock()
i.serial++
- i.snapshot.Generation = generation
- i.snapshot.WalkStartedAt = walk
- i.snapshot.SourceReadStartedAt = source
- i.snapshot.Complete = false
- return &DeparturePass{inventory: i, serial: i.serial, families: map[string][]DepartureHost{}, complete: map[string]bool{}, sourceComplete: complete}
+ return &DeparturePass{inventory: i, serial: i.serial, families: map[string][]DepartureHost{}, complete: map[string]bool{}, sourceComplete: complete, snapshot: InventorySnapshot{Generation: generation, WalkStartedAt: walk, SourceReadStartedAt: source}}
+
}
func (p *DeparturePass) family(kind string, hosts []DepartureHost, complete bool) {
if p == nil {
@@ -95,6 +93,7 @@ func (p *DeparturePass) family(kind string, hosts []DepartureHost, complete bool
}
return 0
})
+ i.snapshot = p.snapshot
i.snapshot.Records = all
i.snapshot.Complete = good
}
diff --git a/internal/provision/departure_inventory_test.go b/internal/provision/departure_inventory_test.go
index bb037ab28..3fa8216e0 100644
--- a/internal/provision/departure_inventory_test.go
+++ b/internal/provision/departure_inventory_test.go
@@ -97,3 +97,23 @@ func TestDepartureInventorySourceRefresh(t *testing.T) {
t.Fatalf("fresh inventory %+v", snap)
}
}
+
+func TestDepartureInventoryPublishesAtPassEnd(t *testing.T) {
+ inv := &DepartureInventory{}
+ at := time.Now()
+ p := inv.Begin("one", at, at, true)
+ p.family("instance", []DepartureHost{{Host: "shop.example.com", HA: true, Lifetime: "life"}}, true)
+ p.family("sidecar", nil, true)
+ p = inv.Begin("two", at.Add(time.Second), at.Add(time.Second), true)
+ if s := inv.Snapshot(); !s.Complete || s.Generation != "one" {
+ t.Fatalf("Begin unpublished last snapshot: %+v", s)
+ }
+ p.family("instance", nil, false)
+ if s := inv.Snapshot(); !s.Complete || s.Generation != "one" {
+ t.Fatal("partial publication", s)
+ }
+ p.family("sidecar", nil, true)
+ if s := inv.Snapshot(); s.Complete || s.Generation != "two" || len(s.Records) != 1 {
+ t.Fatal("publication", s)
+ }
+}
diff --git a/internal/registry/ha_journal.go b/internal/registry/ha_journal.go
index eafe25af4..a246809b3 100644
--- a/internal/registry/ha_journal.go
+++ b/internal/registry/ha_journal.go
@@ -20,6 +20,11 @@ type HATerminationInbox struct {
ReceivedAt, NextAttempt time.Time
LastError string
}
+type HAPendingTermination struct {
+ Account, Region, IID string
+ ReceivedAt, NextAttempt, LastPage time.Time
+ LastError string
+}
type HADeparture struct {
hadeparture.Departure
ProofKey, ProofDigest, Phase, InventoryGeneration, LastError string
@@ -31,11 +36,12 @@ type HABoxIdentity struct {
Observation hadeparture.BoxObservation
}
type HAIdentityWalk struct {
- Cursor string
- Keys []string
- Offset int
- Failed bool
- StartedAt time.Time
+ Cursor string
+ Keys []string
+ Offset int
+ Failed bool
+ StartedAt time.Time
+ Blocked, LastBlocked []string
}
type haJournalRequest struct {
@@ -47,9 +53,11 @@ type haJournalRequest struct {
Departure HADeparture
Identity HABoxIdentity
Walk HAIdentityWalk
+ Hint HAPendingTermination
}
type haJournalResponse struct {
Inbox []HATerminationInbox
+ Hints []HAPendingTermination
Departures []HADeparture
Identity HABoxIdentity
Walk HAIdentityWalk
@@ -59,6 +67,7 @@ type haJournalResponse struct {
func (r *Registry) migrateHAJournal() error {
_, err := r.sql.Exec(`
CREATE TABLE IF NOT EXISTS ha_termination_inbox(key TEXT PRIMARY KEY,message_id TEXT NOT NULL,body BLOB NOT NULL CHECK(length(body)<=65536),received INTEGER NOT NULL,next_attempt INTEGER NOT NULL,last_error TEXT NOT NULL DEFAULT '');
+ CREATE TABLE IF NOT EXISTS ha_pending_terminations(account TEXT NOT NULL,region TEXT NOT NULL,iid TEXT NOT NULL,received INTEGER NOT NULL,next_attempt INTEGER NOT NULL,last_page INTEGER NOT NULL DEFAULT 0,last_error TEXT NOT NULL DEFAULT '',PRIMARY KEY(account,region,iid));
CREATE TABLE IF NOT EXISTS ha_departures(id TEXT PRIMARY KEY,body BLOB NOT NULL,phase TEXT NOT NULL DEFAULT 'pending',next_attempt INTEGER NOT NULL,last_page INTEGER NOT NULL DEFAULT 0,last_error TEXT NOT NULL DEFAULT '');
CREATE TABLE IF NOT EXISTS ha_box_identities(ref TEXT PRIMARY KEY,iid TEXT NOT NULL UNIQUE,body BLOB NOT NULL);
CREATE TABLE IF NOT EXISTS ha_confirmation_retries(ref TEXT PRIMARY KEY,next_attempt INTEGER NOT NULL,attempts INTEGER NOT NULL);
@@ -78,6 +87,23 @@ func journalDate(n int64) time.Time {
}
return time.Unix(0, n).UTC()
}
+func (r *Registry) ParkTermination(ctx context.Context, hint HAPendingTermination, inbox string) error {
+ _, err := r.haJournal(ctx, haJournalRequest{Op: "park", Hint: hint, Key: inbox})
+ return err
+}
+func (r *Registry) PendingTerminations(ctx context.Context, at time.Time, limit int) ([]HAPendingTermination, error) {
+ out, err := r.haJournal(ctx, haJournalRequest{Op: "hints", At: at, Limit: limit})
+ return out.Hints, err
+}
+func (r *Registry) RemovePendingTermination(ctx context.Context, h HAPendingTermination) error {
+ _, err := r.haJournal(ctx, haJournalRequest{Op: "remove_hint", Hint: h})
+ return err
+}
+func (r *Registry) RetryPendingTermination(ctx context.Context, h HAPendingTermination, at time.Time, code string) (bool, error) {
+ out, err := r.haJournal(ctx, haJournalRequest{Op: "retry_hint", Hint: h, At: at, Code: code})
+ return out.Found, err
+}
+
func (r *Registry) RecordTermination(ctx context.Context, id string, body []byte, at time.Time) error {
_, err := r.haJournal(ctx, haJournalRequest{Op: "record", ID: id, Body: body, At: at})
return err
@@ -137,6 +163,69 @@ func (r *Registry) haJournal(ctx context.Context, q haJournalRequest) (out haJou
return resp.HAJournal, e
}
switch q.Op {
+ case "park":
+ h := q.Hint
+ if len(h.Account) != 12 || len(h.Region) == 0 || len(h.Region) > 32 || len(h.IID) > 32 || len(h.IID) < 3 || h.ReceivedAt.IsZero() {
+ return out, ErrHAJournal
+ }
+ tx, e := r.beginClaimTransaction(ctx, true)
+ if e != nil {
+ return out, e
+ }
+ defer tx.Rollback()
+ if _, e = tx.ExecContext(ctx, `INSERT INTO ha_pending_terminations(account,region,iid,received,next_attempt) VALUES(?,?,?,?,?) ON CONFLICT(account,region,iid) DO UPDATE SET received=max(received,excluded.received)`, h.Account, h.Region, h.IID, journalTime(h.ReceivedAt), journalTime(h.ReceivedAt)); e != nil {
+ return out, e
+ }
+ if q.Key != "" {
+ if _, e = tx.ExecContext(ctx, `DELETE FROM ha_termination_inbox WHERE key=?`, q.Key); e != nil {
+ return out, e
+ }
+ }
+ err = tx.Commit()
+ case "hints":
+ if q.Limit < 1 || q.Limit > 32 {
+ return out, ErrHAJournal
+ }
+ rows, e := r.sql.QueryContext(ctx, `SELECT account,region,iid,received,next_attempt,last_page,last_error FROM ha_pending_terminations WHERE next_attempt<=? ORDER BY next_attempt,received,account,region,iid LIMIT ?`, journalTime(q.At), q.Limit)
+ if e != nil {
+ return out, e
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var h HAPendingTermination
+ var at, next, page int64
+ if e = rows.Scan(&h.Account, &h.Region, &h.IID, &at, &next, &page, &h.LastError); e != nil {
+ return out, e
+ }
+ h.ReceivedAt = journalDate(at)
+ h.NextAttempt = journalDate(next)
+ h.LastPage = journalDate(page)
+ out.Hints = append(out.Hints, h)
+ }
+ err = rows.Err()
+ case "remove_hint":
+ h := q.Hint
+ _, err = r.sql.ExecContext(ctx, `DELETE FROM ha_pending_terminations WHERE account=? AND region=? AND iid=? AND received<=?`, h.Account, h.Region, h.IID, journalTime(h.ReceivedAt))
+ case "retry_hint":
+ h := q.Hint
+ tx, e := r.beginClaimTransaction(ctx, true)
+ if e != nil {
+ return out, e
+ }
+ defer tx.Rollback()
+ res, e := tx.ExecContext(ctx, `UPDATE ha_pending_terminations SET last_page=? WHERE account=? AND region=? AND iid=? AND (last_page=0 OR last_page<=?)`, journalTime(q.At), h.Account, h.Region, h.IID, journalTime(q.At.Add(-time.Hour)))
+ if e != nil {
+ return out, e
+ }
+ n, e := res.RowsAffected()
+ if e != nil {
+ return out, e
+ }
+ out.Found = n == 1
+ if _, e = tx.ExecContext(ctx, `UPDATE ha_pending_terminations SET next_attempt=?,last_error=? WHERE account=? AND region=? AND iid=?`, journalTime(q.At.Add(30*time.Second)), q.Code, h.Account, h.Region, h.IID); e != nil {
+ return out, e
+ }
+ err = tx.Commit()
case "reobserve":
tx, e := r.beginClaimTransaction(ctx, true)
if e != nil {
diff --git a/internal/registry/ha_journal_test.go b/internal/registry/ha_journal_test.go
index 8189b35ae..92381cfab 100644
--- a/internal/registry/ha_journal_test.go
+++ b/internal/registry/ha_journal_test.go
@@ -159,3 +159,72 @@ func TestDepartureResumeRequiresFreshEvidence(t *testing.T) {
t.Fatalf("resume %+v %v", rows, err)
}
}
+
+func TestTerminationPendingDurability(t *testing.T) {
+ for _, remote := range []bool{false, true} {
+ t.Run(fmt.Sprint(remote), func(t *testing.T) {
+ var r *Registry
+ var path string
+ if remote {
+ r, path = remoteTestRegistry(t)
+ } else {
+ r, path = adoptRegistry(t)
+ }
+ ctx := t.Context()
+ at := time.Now().UTC()
+ if err := r.RecordTermination(ctx, "old", []byte("old body"), at); err != nil {
+ t.Fatal(err)
+ }
+ rows, err := r.TerminationInbox(ctx, at, 1)
+ if err != nil || len(rows) != 1 {
+ t.Fatal(rows, err)
+ }
+ h := HAPendingTermination{Account: "111122223333", Region: "eu-west-1", IID: "i-1123456789abcdef0", ReceivedAt: at}
+ if err = r.ParkTermination(ctx, h, rows[0].Key); err != nil {
+ t.Fatal(err)
+ }
+ if rows, err = r.TerminationInbox(ctx, at, 1); err != nil || len(rows) != 0 {
+ t.Fatal(rows, err)
+ }
+ if page, e := r.RetryPendingTermination(ctx, h, at, "identity_unbound"); e != nil || !page {
+ t.Fatal(page, e)
+ }
+ h.ReceivedAt = at.Add(time.Second)
+ if err = r.ParkTermination(ctx, h, ""); err != nil {
+ t.Fatal(err)
+ }
+ r.Close()
+ r, err = Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer r.Close()
+ hints, err := r.PendingTerminations(ctx, at.Add(time.Minute), 32)
+ if err != nil || len(hints) != 1 || hints[0].LastError != "identity_unbound" || !hints[0].LastPage.Equal(at) || !hints[0].ReceivedAt.Equal(h.ReceivedAt) {
+ t.Fatal(hints, err)
+ }
+ if page, e := r.RetryPendingTermination(ctx, h, at.Add(time.Minute), "identity_unbound"); e != nil || page {
+ t.Fatal("hourly page", page, e)
+ }
+ old := h
+ old.ReceivedAt = at
+ if err = r.RemovePendingTermination(ctx, old); err != nil {
+ t.Fatal(err)
+ }
+ hints, err = r.PendingTerminations(ctx, at.Add(time.Hour), 32)
+ if err != nil || len(hints) != 1 {
+ t.Fatal("new event deleted by old walk", hints, err)
+ }
+ if page, e := r.RetryPendingTermination(ctx, h, at.Add(time.Hour), "identity_unbound"); e != nil || !page {
+ t.Fatal("next hourly page", page, e)
+ }
+ if err = r.RemovePendingTermination(ctx, h); err != nil {
+ t.Fatal(err)
+ }
+ hints, err = r.PendingTerminations(ctx, at.Add(2*time.Hour), 32)
+ if err != nil || len(hints) != 0 {
+ t.Fatal(hints, err)
+ }
+ })
+ }
+}