carlos / platform Public

host: gate departure listings on the configured lock prefix

Validate every inventory key before using a directory listing as absence
proof. List host directories and allow 128 reads after a successful list
so dense inventories retire promptly while fallback scans stay bounded.

Keep listing results in memory and relist after blocked retries or restart.
Cover custom-prefix deletion safety, dense churn, and both read budgets.
Co-Authored-By: GPT-6 Astra <noreply@openai.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 2a7ed4d0917b5e27be5023dbd784465a20b67ade parent 43d4d03
9 files changed, +305 −77
  • internal/host/hadepartures.go +2 −0
  • internal/host/hadepartures_g3_test.go +15 −6
  • internal/host/hadepartures_listing_test.go +157 −13
  • internal/host/hadepartures_scan.go +60 −18
  • internal/host/hadepartures_scan_test.go +31 −18
  • internal/lease/ha.go +6 −10
  • internal/lease/ha_list_test.go +11 −5
  • internal/lease/locktest/fixture.go +23 −4
  • internal/registry/ha_scan.go +0 −3

Intent

Attributed to this commit: 29.6 g CO₂e (3,775,511 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-g3-fixes, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/host/hadepartures.go b/internal/host/hadepartures.go
index 7f564847f..61f539664 100644
--- a/internal/host/hadepartures.go
+++ b/internal/host/hadepartures.go
@@ -100,6 +100,8 @@ type Controller struct {
evidence map[string]bool
suspects map[string]bool
notices map[string]time.Time
+
+ lockListings map[string]departureLockListing
}
func NewController(cfg DepartureConfig) (*Controller, error) {
diff --git a/internal/host/hadepartures_g3_test.go b/internal/host/hadepartures_g3_test.go
index a7e428fbf..25f9ec272 100644
--- a/internal/host/hadepartures_g3_test.go
+++ b/internal/host/hadepartures_g3_test.go
@@ -40,7 +40,7 @@ type g3Departure struct {
signer *boxidtest.Signer
}
-func newG3Departure(t *testing.T, n int) *g3Departure {
+func newG3Departure(t *testing.T, n int, prefixes ...string) *g3Departure {
t.Helper()
t.Cleanup(lease.ProcessStateForTest())
previous := metricsDepartures.Load()
@@ -49,6 +49,9 @@ func newG3Departure(t *testing.T, n int) *g3Departure {
x.now, x.expiry = x.start, x.start.Add(15*time.Minute)
x.a, _, _ = departureArmFixtureBucket(t, x.fx.Bucket)
a := &x.a
+ if len(prefixes) > 0 {
+ a.Backend.Cfg.Prefix = prefixes[0]
+ }
a.Backend.Registry = a.Registry
a.Backend.DataDir = filepath.Join(t.TempDir(), "data")
a.Backend.RunDirOverride = filepath.Join(t.TempDir(), "run")
@@ -104,7 +107,7 @@ func newG3Departure(t *testing.T, n int) *g3Departure {
if err = lease.SetObligationDir(t.TempDir()); err != nil {
t.Fatal(err)
}
- pub, err := hostfiles.Open(t.Context(), files, "instances/"+rec.Host+"/files/0/")
+ pub, err := hostfiles.Open(t.Context(), files, activator.HibernatePrefix(a.Backend.Cfg.Prefix, rec.Host)+"/files/0/")
if err != nil {
t.Fatal(err)
}
@@ -162,7 +165,7 @@ func (x *g3Departure) putLock(t *testing.T, b hadeparture.Box, gen int64, expiry
if err != nil {
t.Fatal(err)
}
- x.fx.PutLock("instances/"+x.records[0].Host, raw)
+ x.fx.PutLock(activator.HibernatePrefix(x.a.Backend.Cfg.Prefix, x.records[0].Host), raw)
}
func (x *g3Departure) writeEdges(t *testing.T) {
t.Helper()
@@ -320,7 +323,13 @@ func TestDepartureG3Simulation(t *testing.T) {
rng := rand.New(rand.NewSource(seed))
n := 1 + rng.Intn(300)
x := newScanRig(t, n)
- listing := &listedScanReader{scanReader: x.locks}
+ root := []string{"", "instances", "fleet"}[rng.Intn(3)]
+ listing := listedRig(x, root)
+ for _, h := range x.inv.Records {
+ if rng.Intn(3) == 0 {
+ listing.extra = append(listing.extra, h.Host)
+ }
+ }
if seed%7 == 0 {
listing.err = errors.New("AccessDenied")
}
@@ -740,7 +749,7 @@ func TestDepartureG3MissingPendingRecord(t *testing.T) {
}
func TestDepartureG3RollbackCheckpoint(t *testing.T) {
- x := newG3Departure(t, 100)
+ x := newG3Departure(t, 300)
for _, rec := range x.records[1:] {
x.fx.PutLock("instances/"+rec.Host, x.fx.LockBody("instances/"+x.records[0].Host))
}
@@ -764,7 +773,7 @@ func TestDepartureG3RollbackCheckpoint(t *testing.T) {
t.Fatal(err)
}
scan, err := x.a.Registry.DepartureScan(t.Context(), x.id)
- if err != nil || len(scan.Visited) != 63 {
+ if err != nil || len(scan.Visited) != 255 {
t.Fatalf("checkpoint: visits=%d %v", len(scan.Visited), err)
}
raw, err = json.Marshal(scan)
diff --git a/internal/host/hadepartures_listing_test.go b/internal/host/hadepartures_listing_test.go
index e4863b40b..4b962dc5b 100644
--- a/internal/host/hadepartures_listing_test.go
+++ b/internal/host/hadepartures_listing_test.go
@@ -2,14 +2,17 @@ package host
import (
"context"
+ "encoding/json"
"errors"
"fmt"
"net/http"
"os"
+ "path"
"strings"
"testing"
"time"
+ "github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/boxid"
"github.com/carlosframework/platform/internal/hadeparture"
"github.com/carlosframework/platform/internal/hafresh"
@@ -21,27 +24,41 @@ type listedScanReader struct {
lists int
err error
omit bool
+ extra []string
}
-func (r *listedScanReader) ListLocks(context.Context, string) (map[string]bool, error) {
+func (r *listedScanReader) ListLocks(_ context.Context, _, root string) (map[string]bool, error) {
r.lists++
keys := map[string]bool{}
if !r.omit {
for key := range r.views {
- keys[key] = true
+ keys[root+"/"+key] = true
}
}
+ for _, host := range r.extra {
+ keys[root+"/"+host] = true
+ }
return keys, r.err
}
+func (r *listedScanReader) ReadLock(ctx context.Context, bucket, prefix string) (hafresh.View, error) {
+ return r.scanReader.ReadLock(ctx, bucket, path.Base(prefix))
+}
+
+func listedRig(x *scanRig, root string) *listedScanReader {
+ x.c.cfg.Prefix = func(host string) string { return activator.HibernatePrefix(root, host) }
+ r := &listedScanReader{scanReader: x.locks}
+ x.c.cfg.NewReader = func(context.Context, string) (DepartureLockReader, error) { return r, nil }
+ return r
+}
+
func TestDepartureLockListingPages(t *testing.T) {
x := newScanRig(t, 260)
- for _, h := range x.inv.Records[32:259] {
+ for _, h := range x.inv.Records[128:259] {
delete(x.locks.views, h.Host)
}
- l := &listedScanReader{scanReader: x.locks}
- x.c.cfg.NewReader = func(context.Context, string) (DepartureLockReader, error) { return l, nil }
- for i, want := range []int{32, 33, 65, 66} {
+ l := listedRig(x, "instances")
+ for i, want := range []int{128, 129, 257, 258} {
x.pass(t)
if x.locks.reads != want || l.lists != i/2+1 {
t.Fatalf("page %d: reads=%d lists=%d", i, x.locks.reads, l.lists)
@@ -63,8 +80,7 @@ func TestDepartureLockListing(t *testing.T) {
if mode == "empty" {
delete(x.locks.views, x.inv.Records[0].Host)
}
- l := &listedScanReader{scanReader: x.locks}
- x.c.cfg.NewReader = func(context.Context, string) (DepartureLockReader, error) { return l, nil }
+ l := listedRig(x, "instances")
logs := 0
x.c.cfg.Logf = func(format string, _ ...any) {
if strings.Contains(format, "lock_list_fallback") {
@@ -103,7 +119,7 @@ func TestDepartureLockListing(t *testing.T) {
}
switch mode {
case "failed":
- if x.locks.reads != 520 || l.lists != 2 || logs != 1 {
+ if x.locks.reads != 520 || l.lists != 2 || logs != 2 {
t.Fatalf("fallback reads=%d lists=%d logs=%d", x.locks.reads, l.lists, logs)
}
case "empty":
@@ -124,12 +140,19 @@ func TestDepartureLockListing(t *testing.T) {
}
func TestDepartureG3FiveMinutes(t *testing.T) {
- for _, released := range []bool{false, true} {
- t.Run(fmt.Sprintf("released=%v", released), func(t *testing.T) {
+ for _, tc := range []struct {
+ released bool
+ live int
+ }{{false, 0}, {true, 0}, {false, 80}, {true, 80}} {
+ released := tc.released
+ t.Run(fmt.Sprintf("released=%v/live=%d", released, tc.live), func(t *testing.T) {
x := newG3Departure(t, 260)
for i := 1; i < len(x.records); i++ {
rec := x.records[i]
rec.HA = false
+ if i <= tc.live {
+ rec.Region = ""
+ }
_, tag, err := x.store.Get(t.Context(), provision.RecordKey(rec.Account, rec.App, rec.Host))
if err != nil {
t.Fatal(err)
@@ -146,6 +169,18 @@ func TestDepartureG3FiveMinutes(t *testing.T) {
raw, _ := hafresh.MarkerBody(5, hafresh.Marker{V: 1, Box: x.dead.Ref, IID: x.dead.InstanceID, Lifetime: entry.ID})
x.fx.PutLock("instances/"+x.records[0].Host, raw)
}
+ for i := 1; i <= tc.live; i++ {
+ rec := x.records[i]
+ lock := hafresh.Lock{Generation: 5, Owner: hafresh.OwnerFor(hafresh.Self{Ref: x.peer.Ref, IID: x.peer.InstanceID}, 1, true), ExpiresAt: x.start.Add(time.Hour)}
+ if i%2 == 0 {
+ entry, _ := provision.LifetimeEntryOf(rec)
+ lock.Release = &hafresh.Marker{V: 1, Box: x.peer.Ref, IID: x.peer.InstanceID, Lifetime: entry.ID}
+ lock.Owner = hafresh.MarkerOwner(*lock.Release)
+ lock.ExpiresAt = time.Unix(0, 0)
+ }
+ raw, _ := json.Marshal(lock)
+ x.fx.PutLock("instances/"+rec.Host, raw)
+ }
ids := []string{x.id}
keys := []string{x.edgesKey}
for i := 3; i <= 4; i++ {
@@ -238,7 +273,7 @@ func TestDepartureG3FiveMinutes(t *testing.T) {
unrelatedReads++
}
}
- if lists != 6 || unrelatedReads != 0 {
+ if lists != 6 || unrelatedReads != 6*tc.live {
t.Fatalf("lists=%d unrelated lock reads=%d", lists, unrelatedReads)
}
timer, err := x.a.Registry.GetTimer(x.records[0].Host, "reminder")
@@ -270,7 +305,7 @@ func TestDepartureG3ListingDenied(t *testing.T) {
}
x.now = x.row(t).NextAttempt
}
- if x.row(t).Phase != "complete" || logs != 1 || x.pages != 0 {
+ if x.row(t).Phase != "complete" || logs != 2 || x.pages != 0 {
t.Fatalf("fallback: phase=%s logs=%d pages=%d", x.row(t).Phase, logs, x.pages)
}
reads := 0
@@ -283,3 +318,112 @@ func TestDepartureG3ListingDenied(t *testing.T) {
t.Fatal("fallback did not walk complete inventory twice", reads)
}
}
+
+func TestDepartureG3PrefixSafety(t *testing.T) {
+ for _, root := range []string{"fleet", ""} {
+ for _, released := range []bool{false, true} {
+ t.Run(fmt.Sprintf("root=%s/released=%v", root, released), func(t *testing.T) {
+ x := newG3Departure(t, 65, root)
+ if released {
+ entry, _ := provision.LifetimeEntryOf(x.records[0])
+ raw, _ := hafresh.MarkerBody(5, hafresh.Marker{V: 1, Box: x.dead.Ref, IID: x.dead.InstanceID, Lifetime: entry.ID})
+ x.fx.PutLock(x.c.cfg.Prefix(x.records[0].Host), raw)
+ }
+ logs := 0
+ x.c.cfg.Logf = func(format string, _ ...any) {
+ if strings.Contains(format, "lock_list_fallback") {
+ logs++
+ }
+ }
+ for range 12 {
+ if err := x.c.step(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ _, _, edgeErr := x.store.Get(t.Context(), x.edgesKey)
+ if errors.Is(edgeErr, os.ErrNotExist) {
+ timer, err := x.a.Registry.GetTimer(x.records[0].Host, "reminder")
+ if err != nil || timer == nil || timer.Registration != "original" {
+ t.Fatal("deleted before adoption", timer, err)
+ }
+ if !released && !x.now.After(x.expiry) {
+ t.Fatal("deleted before expiry")
+ }
+ break
+ }
+ if edgeErr != nil {
+ t.Fatal(edgeErr)
+ }
+ x.now = x.row(t).NextAttempt
+ }
+ if x.row(t).Phase != "complete" {
+ t.Fatal("did not complete", x.row(t))
+ }
+ lists := 0
+ for _, req := range x.fx.Requests() {
+ if req == "LIST "+root+"/" {
+ lists++
+ }
+ }
+ if root == "" && (lists != 0 || logs < 2) || root != "" && (lists < 2 || logs != 0) {
+ t.Fatalf("prefix gate: lists=%d fallbacks=%d", lists, logs)
+ }
+ })
+ }
+ }
+}
+
+func TestDepartureLockListingPrefixMismatch(t *testing.T) {
+ x := newScanRig(t, 260)
+ l := listedRig(x, "fleet")
+ prefix := x.c.cfg.Prefix
+ x.c.cfg.Prefix = func(host string) string {
+ if host == x.inv.Records[259].Host {
+ return "other/" + host
+ }
+ return prefix(host)
+ }
+ logs := 0
+ x.c.cfg.Logf = func(format string, _ ...any) {
+ if strings.Contains(format, "lock_list_fallback") {
+ logs++
+ }
+ }
+ for range 18 {
+ x.pass(t)
+ }
+ if l.lists != 0 || logs != 2 || x.imports != 260 || x.locks.reads != 520 {
+ t.Fatalf("mismatch: lists=%d logs=%d imports=%d reads=%d", l.lists, logs, x.imports, x.locks.reads)
+ }
+}
+
+func TestDepartureLockListingResume(t *testing.T) {
+ for _, restart := range []bool{false, true} {
+ t.Run(fmt.Sprintf("restart=%v", restart), func(t *testing.T) {
+ x := newScanRig(t, 260)
+ l := listedRig(x, "fleet")
+ if !restart {
+ x.locks.err = errors.New("unavailable")
+ }
+ x.pass(t)
+ if l.lists != 1 {
+ t.Fatal(l.lists)
+ }
+ if restart {
+ x.c = &Controller{cfg: x.c.cfg, evidence: x.c.evidence}
+ }
+ x.locks.err = nil
+ x.pass(t)
+ if l.lists != 2 {
+ t.Fatal("resumed without relisting", l.lists)
+ }
+ scan, err := x.r.DepartureScan(t.Context(), x.d.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, err := json.Marshal(scan)
+ if err != nil || strings.Contains(string(raw), "LockPrefixes") || strings.Contains(string(raw), "LocksListed") {
+ t.Fatal("listing persisted", string(raw), err)
+ }
+ })
+ }
+}
diff --git a/internal/host/hadepartures_scan.go b/internal/host/hadepartures_scan.go
index d8d821069..990828a87 100644
--- a/internal/host/hadepartures_scan.go
+++ b/internal/host/hadepartures_scan.go
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"os"
+ "path"
"strconv"
"strings"
"time"
@@ -27,7 +28,7 @@ type DepartureLockReader interface {
}
type departureLockLister interface {
- ListLocks(context.Context, string) (map[string]bool, error)
+ ListLocks(context.Context, string, string) (map[string]bool, error)
}
var errDeparturePending = errors.New("ha_departure_pending")
@@ -141,7 +142,7 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
s.Waiting = 0
s.NotBefore = time.Time{}
s.Visited = map[string]registry.HADepartureVisit{}
- s.LockPrefixes, s.LocksListed = nil, false
+ delete(c.lockListings, d.ID)
if s.Hosts == nil {
s.Hosts = map[string]registry.HADepartureHostScan{}
}
@@ -158,19 +159,13 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
if err != nil {
return false, errors.Join(err, c.retryScan(ctx, d, nil, "reader", true))
}
- if !s.LocksListed {
- s.LocksListed = true
- if lister, ok := reader.(departureLockLister); ok {
- call, cancel := context.WithTimeout(ctx, 5*time.Second)
- prefixes, err := lister.ListLocks(call, d.Box.Scope.DataBucket)
- cancel()
- if err == nil {
- s.LockPrefixes = prefixes
- } else if !s.LockListAlerted {
- c.logf("ha_departure_lock_list_fallback departure=%s bucket=%s error=%v", d.ID, d.Box.Scope.DataBucket, err)
- s.LockListAlerted = true
- }
- }
+ if d.LastError == "blocked" {
+ delete(c.lockListings, d.ID)
+ }
+ prefixes := c.departureLockPrefixes(ctx, d, inv, reader)
+ limit := 32
+ if prefixes != nil {
+ limit = 128
}
blockers := []provision.DepartureHost{}
count := 0
@@ -182,8 +177,8 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
_, previouslySeen := s.Hosts[h.Host]
// After termination proof, the dead member cannot create another lock.
// Keep reading known duties even if their lock disappears from the list.
- absent := s.LockPrefixes != nil && !s.LockPrefixes[c.cfg.Prefix(h.Host)] && !previouslySeen
- if count == 32 && !absent || ctx.Err() != nil {
+ absent := prefixes != nil && !prefixes[c.cfg.Prefix(h.Host)] && !previouslySeen
+ if count == limit && !absent || ctx.Err() != nil {
break
}
if !absent {
@@ -361,18 +356,65 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
s.Waiting = 0
s.NotBefore = time.Time{}
s.Visited = map[string]registry.HADepartureVisit{}
- s.LockPrefixes, s.LocksListed = nil, false
+ delete(c.lockListings, d.ID)
}
}
if err = c.cfg.Registry.SaveDepartureScan(ctx, d.ID, phase, s); err != nil {
return true, errors.Join(err, c.retryScan(ctx, d, nil, "journal", true))
}
if phase == "authority_complete" {
+ delete(c.lockListings, d.ID)
return true, c.complete(ctx, d.ID)
}
return true, c.retryScanAt(ctx, d, blockers, "scan", blocked, next)
}
+type departureLockListing struct {
+ root string
+ prefixes map[string]bool
+}
+
+// Check every current record before using absence from the listing, including
+// records added between pages. The cache belongs to this walk under scanMu.
+func (c *Controller) departureLockPrefixes(ctx context.Context, d registry.HADeparture, inv provision.InventorySnapshot, reader DepartureLockReader) map[string]bool {
+ lister, ok := reader.(departureLockLister)
+ if !ok {
+ return nil
+ }
+ root := path.Dir(c.cfg.Prefix("ha-departure-prefix-probe.invalid"))
+ valid := root != "" && root != "."
+ for _, h := range inv.Records {
+ if c.cfg.Prefix(h.Host) != root+"/"+h.Host {
+ valid = false
+ break
+ }
+ }
+ if !valid {
+ root = ""
+ }
+ if cached, ok := c.lockListings[d.ID]; ok && cached.root == root {
+ return cached.prefixes
+ }
+ var prefixes map[string]bool
+ var err error
+ if root == "" {
+ err = errors.New("prefix_shape")
+ } else {
+ call, cancel := context.WithTimeout(ctx, 15*time.Second)
+ prefixes, err = lister.ListLocks(call, d.Box.Scope.DataBucket, root)
+ cancel()
+ }
+ if err != nil {
+ prefixes = nil
+ c.logf("ha_departure_lock_list_fallback departure=%s bucket=%s error=%v", d.ID, d.Box.Scope.DataBucket, err)
+ }
+ if c.lockListings == nil {
+ c.lockListings = map[string]departureLockListing{}
+ }
+ c.lockListings[d.ID] = departureLockListing{root: root, prefixes: prefixes}
+ return prefixes
+}
+
// departureScanCoverage drops removed and changed revisions, retaining all other
// visits. Counts describe only the current inventory, including catch-up reads.
func departureScanCoverage(s *registry.HADepartureScan, inv provision.InventorySnapshot) bool {
diff --git a/internal/host/hadepartures_scan_test.go b/internal/host/hadepartures_scan_test.go
index c95022fdc..1db86ebdc 100644
--- a/internal/host/hadepartures_scan_test.go
+++ b/internal/host/hadepartures_scan_test.go
@@ -341,22 +341,35 @@ func TestDepartureDeletionRace(t *testing.T) {
}
}
func TestDepartureRequestBudget(t *testing.T) {
- x := newScanRig(t, 65)
- constructs := 0
- x.c.cfg.NewReader = func(context.Context, string) (DepartureLockReader, error) { constructs++; return x.locks, nil }
- for range 6 {
- before := x.locks.reads
- x.pass(t)
- if x.locks.reads-before > 32 {
- t.Fatal("page exceeded", x.locks.reads-before)
- }
- }
- if x.locks.reads != 130 || constructs != 6 || x.imports != 65 {
- t.Fatal(x.locks.reads, constructs, x.imports)
- }
- x.pass(t)
- if constructs != 6 {
- t.Fatal("idle opened reader")
+ for _, listed := range []bool{false, true} {
+ t.Run(fmt.Sprintf("listed=%v", listed), func(t *testing.T) {
+ limit := 32
+ if listed {
+ limit = 128
+ }
+ n := 2*limit + 1
+ x := newScanRig(t, n)
+ var reader DepartureLockReader = x.locks
+ if listed {
+ reader = listedRig(x, "instances")
+ }
+ constructs := 0
+ x.c.cfg.NewReader = func(context.Context, string) (DepartureLockReader, error) { constructs++; return reader, nil }
+ for range 6 {
+ before := x.locks.reads
+ x.pass(t)
+ if x.locks.reads-before > limit {
+ t.Fatal("page exceeded", x.locks.reads-before, limit)
+ }
+ }
+ if x.locks.reads != 2*n || constructs != 6 || x.imports != n {
+ t.Fatal(x.locks.reads, constructs, x.imports)
+ }
+ x.pass(t)
+ if constructs != 6 {
+ t.Fatal("idle opened reader")
+ }
+ })
}
}
func TestDepartureFairScheduling(t *testing.T) {
@@ -671,7 +684,7 @@ func TestDepartureProductionImporter(t *testing.T) {
constructors++
return reader(ctx, region)
}
- for page, want := range []struct{ gets, puts, lists int }{{193, 64, 1}, {6, 2, 0}, {32, 0, 1}, {1, 0, 0}} {
+ for page, want := range []struct{ gets, puts, lists int }{{199, 66, 1}, {33, 0, 1}} {
before := len(fx.Requests())
if _, err = c.ScanPass(t.Context()); err != nil {
t.Fatal(err)
@@ -693,7 +706,7 @@ func TestDepartureProductionImporter(t *testing.T) {
}
now = now.Add(31 * time.Second)
}
- if constructors != 4 {
+ if constructors != 2 {
t.Fatal("scan reader clients", constructors)
}
diff --git a/internal/lease/ha.go b/internal/lease/ha.go
index eb5ffcf33..665105510 100644
--- a/internal/lease/ha.go
+++ b/internal/lease/ha.go
@@ -215,22 +215,18 @@ func (r *LockReader) ReadLock(ctx context.Context, bucket, prefix string) (hafre
return readView(ctx, r.client, bucket, key)
}
-// ListLocks returns instance prefixes with a lock in this bucket. A partial
-// listing is never evidence of absence, so any page failure discards the set.
-func (r *LockReader) ListLocks(ctx context.Context, bucket string) (map[string]bool, error) {
+// ListLocks returns host directories, including those with only non-lock objects.
+// Any failed page discards the set; a partial list cannot prove absence.
+func (r *LockReader) ListLocks(ctx context.Context, bucket, root string) (map[string]bool, error) {
locks := map[string]bool{}
- pager := awss3.NewListObjectsV2Paginator(r.lister, &awss3.ListObjectsV2Input{Bucket: aws.String(bucket), Prefix: aws.String("instances/")})
+ pager := awss3.NewListObjectsV2Paginator(r.lister, &awss3.ListObjectsV2Input{Bucket: aws.String(bucket), Prefix: aws.String(root + "/"), Delimiter: aws.String("/")})
for pager.HasMorePages() {
page, err := pager.NextPage(ctx)
if err != nil {
return nil, err
}
- for _, object := range page.Contents {
- key := aws.ToString(object.Key)
- host := strings.TrimSuffix(strings.TrimPrefix(key, "instances/"), "/lock.json")
- if host != "" && !strings.Contains(host, "/") && key == "instances/"+host+"/lock.json" {
- locks["instances/"+host] = true
- }
+ for _, dir := range page.CommonPrefixes {
+ locks[strings.TrimSuffix(aws.ToString(dir.Prefix), "/")] = true
}
}
return locks, nil
diff --git a/internal/lease/ha_list_test.go b/internal/lease/ha_list_test.go
index 1dd3436ce..74f537400 100644
--- a/internal/lease/ha_list_test.go
+++ b/internal/lease/ha_list_test.go
@@ -14,11 +14,14 @@ func TestListDepartureLocks(t *testing.T) {
t.Run(fmt.Sprint(failPage), func(t *testing.T) {
f := locktest.NewLockFixture(t)
for i := range 1001 {
- f.PutLock(fmt.Sprintf("instances/h-%04d.example.com", i), []byte("lock"))
+ f.PutLock(fmt.Sprintf("fleet/h-%04d.example.com", i), []byte("lock"))
}
- for _, key := range []string{"instances/h/files/0/lock.json", "instances/h/lock.json.bak", "instances/lock.json", "other/h/lock.json"} {
+ for _, key := range []string{"fleet/h/files/0/lock.json", "fleet/h/lock.json.bak", "fleet/lock.json", "other/h/lock.json"} {
f.PutObject(key, []byte("unrelated"))
}
+ for i := range 2000 {
+ f.PutObject(fmt.Sprintf("fleet/h/files/%d", i), []byte("data"))
+ }
r, err := lease.NewLockReader(t.Context(), "eu-west-1")
if err != nil {
t.Fatal(err)
@@ -26,21 +29,24 @@ func TestListDepartureLocks(t *testing.T) {
if failPage != 0 {
f.FailNth("LIST", failPage, http.StatusForbidden)
}
- keys, err := r.ListLocks(t.Context(), f.Bucket)
+ keys, err := r.ListLocks(t.Context(), f.Bucket, "fleet")
if failPage != 0 {
if err == nil || keys != nil {
t.Fatalf("partial listing escaped: keys=%d err=%v", len(keys), err)
}
return
}
- if err != nil || len(keys) != 1001 {
+ if err != nil || len(keys) != 1002 {
t.Fatalf("listing keys=%d err=%v", len(keys), err)
}
for i := range 1001 {
- if !keys[fmt.Sprintf("instances/h-%04d.example.com", i)] {
+ if !keys[fmt.Sprintf("fleet/h-%04d.example.com", i)] {
t.Fatal("missing lock", i)
}
}
+ if !keys["fleet/h"] {
+ t.Fatal("non-lock directory omitted")
+ }
if len(f.Requests()) != 2 {
t.Fatal("pagination", f.Requests())
}
diff --git a/internal/lease/locktest/fixture.go b/internal/lease/locktest/fixture.go
index e9ff25a84..96b3d4094 100644
--- a/internal/lease/locktest/fixture.go
+++ b/internal/lease/locktest/fixture.go
@@ -331,6 +331,7 @@ type listResult struct {
IsTruncated bool
NextContinuationToken string `xml:",omitempty"`
Contents []listContents
+ CommonPrefixes []struct{ Prefix string }
}
// listLocked is ListObjectsV2: keys under prefix in order, at most
@@ -351,12 +352,26 @@ func (f *LockFixture) listLocked(w http.ResponseWriter, q url.Values) {
if c := q.Get("continuation-token"); c != "" {
after = c
}
- var keys []string
+ entries := map[string]bool{}
for k := range f.objects {
- if strings.HasPrefix(k, prefix) && k > after {
- keys = append(keys, k)
+ if !strings.HasPrefix(k, prefix) {
+ continue
+ }
+ dir := false
+ if delimiter := q.Get("delimiter"); delimiter != "" {
+ if i := strings.Index(strings.TrimPrefix(k, prefix), delimiter); i >= 0 {
+ k = k[:len(prefix)+i+len(delimiter)]
+ dir = true
+ }
+ }
+ if k > after {
+ entries[k] = dir
}
}
+ var keys []string
+ for k := range entries {
+ keys = append(keys, k)
+ }
sort.Strings(keys)
res := listResult{Name: f.Bucket, Prefix: prefix, MaxKeys: max}
if len(keys) > max {
@@ -366,10 +381,14 @@ func (f *LockFixture) listLocked(w http.ResponseWriter, q url.Values) {
}
}
for _, k := range keys {
+ if entries[k] {
+ res.CommonPrefixes = append(res.CommonPrefixes, struct{ Prefix string }{k})
+ continue
+ }
o := f.objects[k]
res.Contents = append(res.Contents, listContents{Key: k, LastModified: o.modified.Format(time.RFC3339), ETag: o.etag, Size: len(o.body)})
}
- res.KeyCount = len(res.Contents)
+ res.KeyCount = len(res.Contents) + len(res.CommonPrefixes)
w.Header().Set("Content-Type", "application/xml")
io.WriteString(w, xml.Header)
xml.NewEncoder(w).Encode(res)
diff --git a/internal/registry/ha_scan.go b/internal/registry/ha_scan.go
index 855834e80..8f2523914 100644
--- a/internal/registry/ha_scan.go
+++ b/internal/registry/ha_scan.go
@@ -32,9 +32,6 @@ type HADepartureScan struct {
Waiting int
NotBefore time.Time
Visited map[string]HADepartureVisit
- LockPrefixes map[string]bool
- LocksListed bool
- LockListAlerted bool
Hosts map[string]HADepartureHostScan
DeleteUncertain bool
EdgesETag string