carlos / platform Public

region HA P1a Task 5: lease owner format and box identity

Every lock a box's agent writes names the box:
box/v1;ref=<ref>;iid=<instance id>;pid=<pid> (hafresh.OwnerFor, strict
ParseOwner). agentEntry sets it with lease.SetSelf after the
group-reference wait, on every box whatever CARLOS_REGION_HA says.
The instance id is one IMDS read within 2 s; when it misses, the agent
asks again every minute (haSelfRetry). Processes that never call
SetSelf keep litestream's host:pid owner.

locktest.NewLockFixture is an in-process S3 endpoint for lock tests
(ETags, conditional PUT and DELETE, ListObjectsV2, request log, faults
on the n-th request of a verb, a hook before writes). It imports nothing
from the platform, so package lease's own tests can use it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 39a8fe42532ed110c7d58da89f72e64398f8c485 parent 149b4fd
13 files changed, +888 −7
  • internal/hafresh/owner.go +90 −0
  • internal/hafresh/owner_test.go +56 −0
  • internal/host/agent.go +12 −3
  • internal/host/agententry.go +12 −2
  • internal/host/agententry_test.go +2 −1
  • internal/host/haself.go +99 −0
  • internal/host/haself_test.go +93 −0
  • internal/lease/createlease.go +1 −1
  • internal/lease/lease.go +1 −0
  • internal/lease/locktest/fixture.go +332 −0
  • internal/lease/locktest/fixture_test.go +90 −0
  • internal/lease/self.go +43 −0
  • internal/lease/self_test.go +57 −0

CI failed — run details

diff --git a/internal/hafresh/owner.go b/internal/hafresh/owner.go
new file mode 100644
index 000000000..516fe1ab1
--- /dev/null
+++ b/internal/hafresh/owner.go
@@ -0,0 +1,90 @@
+// Package hafresh holds region HA's lock vocabulary: who owns a lease
+// (the owner string a box writes into lock.json) and, in later tasks, the
+// release marker and the decisions read from a lock.
+package hafresh
+
+import (
+ "strconv"
+ "strings"
+)
+
+// Self is this box's identity as a lease owner: its reference (the label
+// it publishes metrics under) and its cloud instance id, "" until known.
+type Self struct{ Ref, IID string }
+
+// Owner is a parsed owner string.
+type Owner struct {
+ Ref, IID string
+ PID int
+ HA bool
+}
+
+const ownerPrefix = "box/v1;"
+
+// OwnerFor is the owner string a box writes into a lock:
+// box/v1;ref=<ref>;iid=<instance id>;pid=<pid>, with ;ha=1 on an HA
+// lock. iid= is left out while the instance id is unknown.
+func OwnerFor(s Self, pid int, ha bool) string {
+ var b strings.Builder
+ b.WriteString(ownerPrefix + "ref=" + s.Ref)
+ if s.IID != "" {
+ b.WriteString(";iid=" + s.IID)
+ }
+ b.WriteString(";pid=" + strconv.Itoa(pid))
+ if ha {
+ b.WriteString(";ha=1")
+ }
+ return b.String()
+}
+
+// ParseOwner reads an owner string OwnerFor wrote, strictly: ref, iid
+// (optional), pid and ha (optional, only "1"), in that order, each with a
+// non-empty value, pid a positive decimal with no sign or leading zero,
+// nothing else. Any other string (a legacy host:pid owner, a tombstone's
+// moved:<id>, a release marker's owner) is not a box owner: ok is false.
+func ParseOwner(s string) (Owner, bool) {
+ rest, ok := strings.CutPrefix(s, ownerPrefix)
+ if !ok {
+ return Owner{}, false
+ }
+ fields := strings.Split(rest, ";")
+ var o Owner
+ next := func(name string) (string, bool) {
+ if len(fields) == 0 {
+ return "", false
+ }
+ k, v, found := strings.Cut(fields[0], "=")
+ if !found || k != name || v == "" || strings.Contains(v, "=") {
+ return "", false
+ }
+ fields = fields[1:]
+ return v, true
+ }
+ if o.Ref, ok = next("ref"); !ok {
+ return Owner{}, false
+ }
+ if len(fields) > 0 && strings.HasPrefix(fields[0], "iid=") {
+ if o.IID, ok = next("iid"); !ok {
+ return Owner{}, false
+ }
+ }
+ pid, ok := next("pid")
+ if !ok {
+ return Owner{}, false
+ }
+ n, err := strconv.Atoi(pid)
+ if err != nil || n <= 0 || strconv.Itoa(n) != pid {
+ return Owner{}, false
+ }
+ o.PID = n
+ if len(fields) > 0 {
+ if v, ok := next("ha"); !ok || v != "1" {
+ return Owner{}, false
+ }
+ o.HA = true
+ }
+ if len(fields) != 0 {
+ return Owner{}, false
+ }
+ return o, true
+}
diff --git a/internal/hafresh/owner_test.go b/internal/hafresh/owner_test.go
new file mode 100644
index 000000000..49750575b
--- /dev/null
+++ b/internal/hafresh/owner_test.go
@@ -0,0 +1,56 @@
+package hafresh_test
+
+import (
+ "testing"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+)
+
+func TestOwnerRoundTrip(t *testing.T) {
+ s := hafresh.OwnerFor(hafresh.Self{Ref: "g-0123456789abcdef0123", IID: "i-0abc"}, 4242, true)
+ if s != "box/v1;ref=g-0123456789abcdef0123;iid=i-0abc;pid=4242;ha=1" {
+ t.Fatal(s)
+ }
+ if o, ok := hafresh.ParseOwner(s); !ok || o.IID != "i-0abc" || o.PID != 4242 || !o.HA {
+ t.Fatalf("%+v", o)
+ }
+ for _, bad := range []string{"ip-10-0-0-1:77", "moved:mv_1", "box/v1;ref=a;pid=1;extra=2", "box/v1;iid=i-1;ref=a;pid=1"} {
+ if _, ok := hafresh.ParseOwner(bad); ok {
+ t.Errorf("parsed %q", bad)
+ }
+ }
+ if hafresh.OwnerFor(hafresh.Self{Ref: "ie-box"}, 1, false) != "box/v1;ref=ie-box;pid=1" {
+ t.Fatal("empty iid kept")
+ }
+}
+
+// The strict reading beyond the plan's cases: every field has a value,
+// pid is a plain positive decimal, ha is only "1", nothing repeats.
+func TestParseOwnerIsStrict(t *testing.T) {
+ good := map[string]hafresh.Owner{
+ "box/v1;ref=ie-box;pid=1": {Ref: "ie-box", PID: 1},
+ "box/v1;ref=ie-box;iid=i-1;pid=77": {Ref: "ie-box", IID: "i-1", PID: 77},
+ "box/v1;ref=ie-box;pid=9;ha=1": {Ref: "ie-box", PID: 9, HA: true},
+ "box/v1;ref=ie-box;iid=i-1;pid=9;ha=1": {Ref: "ie-box", IID: "i-1", PID: 9, HA: true},
+ }
+ for s, want := range good {
+ if o, ok := hafresh.ParseOwner(s); !ok || o != want {
+ t.Errorf("%q: %+v %v, want %+v", s, o, ok, want)
+ }
+ if hafresh.OwnerFor(hafresh.Self{Ref: want.Ref, IID: want.IID}, want.PID, want.HA) != s {
+ t.Errorf("%q does not round-trip", s)
+ }
+ }
+ for _, bad := range []string{
+ "", "box/v1", "box/v1;", "box/v2;ref=a;pid=1", "box/v1;ref=;pid=1", "box/v1;ref=a;iid=;pid=1",
+ "box/v1;ref=a", "box/v1;pid=1", "box/v1;ref=a;pid=0", "box/v1;ref=a;pid=-1", "box/v1;ref=a;pid=+1",
+ "box/v1;ref=a;pid=01", "box/v1;ref=a;pid=x", "box/v1;ref=a;pid=1;ha=0", "box/v1;ref=a;pid=1;ha=",
+ "box/v1;ref=a;pid=1;ha=1;ha=1", "box/v1;ref=a;ref=b;pid=1", "box/v1;ref=a;pid=1;iid=i-1",
+ "box/v1;ref=a;pid=1;", "box/v1;ref=a;;pid=1", "box/v1;ref=a=b;pid=1", "box/v1;ref;pid=1",
+ "released/v1;ref=a;iid=i-1",
+ } {
+ if o, ok := hafresh.ParseOwner(bad); ok {
+ t.Errorf("parsed %q as %+v", bad, o)
+ }
+ }
+}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 34e832ff6..b21e2b246 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -188,6 +188,7 @@ import (
"github.com/carlosframework/platform/internal/edge"
"github.com/carlosframework/platform/internal/edgesfile"
"github.com/carlosframework/platform/internal/fleetapi"
+ "github.com/carlosframework/platform/internal/hafresh"
"github.com/carlosframework/platform/internal/hostwrite"
"github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/instancefs"
@@ -219,10 +220,18 @@ func dataDir() string {
//
// Before it starts, a box its region's group launched resolves its group
// reference, whatever the switches say: the loops runAgent starts read
-// the box's label once and keep it (agentEntry, agententry.go).
+// the box's label once and keep it (agentEntry, agententry.go). Then it
+// names the box as the owner of the lease locks it writes; an instance id
+// IMDS did not answer within 2 seconds is asked for again every minute.
func RunAgent(args []string) {
- agentEntry(os.Getenv, resolveGroupBoxReference, groupReferenceBackoff, log.Printf,
- func() { runAgent(args, productionClaimFactory) })
+ var self hafresh.Self
+ identity := func() hafresh.Self { self = haSelfNow(os.Getenv, haIMDSClient); return self }
+ agentEntry(os.Getenv, resolveGroupBoxReference, groupReferenceBackoff, log.Printf, identity, func() {
+ if self.IID == "" {
+ go haSelfRetry(context.Background(), os.Getenv, haIMDSClient, time.Minute, lease.SetSelf)
+ }
+ runAgent(args, productionClaimFactory)
+ })
}
func runAgent(args []string, buildClaims ClaimFactory) {
diff --git a/internal/host/agententry.go b/internal/host/agententry.go
index c3945a5b9..16e269563 100644
--- a/internal/host/agententry.go
+++ b/internal/host/agententry.go
@@ -6,6 +6,9 @@ import (
"os/signal"
"syscall"
"time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
)
// groupReferenceBackoff is how long agentEntry waits after the n-th
@@ -26,9 +29,13 @@ func groupReferenceBackoff(n int) time.Duration {
// the registry snapshot, metrics, usage, the layout box, the moves pass)
// read the label once and keep it for the process. It asks IMDS again
// with backoff, logging each failure's cause, until it answers or the
-// process is told to stop. Any other box resolves nothing. Then it starts
+// process is told to stop. Any other box resolves nothing. Then, on every
+// box, whatever CARLOS_REGION_HA says, it names the box every lease lock
+// this process writes belongs to (lease.SetSelf with identity's answer,
+// read after the wait so a group box's reference is resolved), and starts
// the agent (run).
-func agentEntry(getenv func(string) string, resolve func() (string, error), backoff func(int) time.Duration, logf func(string, ...any), run func()) {
+func agentEntry(getenv func(string) string, resolve func() (string, error), backoff func(int) time.Duration,
+ logf func(string, ...any), identity func() hafresh.Self, run func()) {
if groupReferenced(getenv) {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
ok := awaitGroupReference(ctx, resolve, backoff, logf)
@@ -37,6 +44,9 @@ func agentEntry(getenv func(string) string, resolve func() (string, error), back
return
}
}
+ self := identity()
+ lease.SetSelf(self)
+ logf("agent: lease locks name this box %s", hafresh.OwnerFor(self, os.Getpid(), false))
run()
}
diff --git a/internal/host/agententry_test.go b/internal/host/agententry_test.go
index a63f37cc9..976cb41c6 100644
--- a/internal/host/agententry_test.go
+++ b/internal/host/agententry_test.go
@@ -8,6 +8,7 @@ import (
"testing"
"time"
+ "github.com/carlosframework/platform/internal/hafresh"
"github.com/carlosframework/platform/internal/hostactors"
"github.com/carlosframework/platform/internal/hostenv"
"github.com/carlosframework/platform/internal/status"
@@ -43,7 +44,7 @@ func TestAGroupBoxResolvesItsReferenceBeforeTheAgentStarts(t *testing.T) {
logf := func(format string, args ...any) { lines = append(lines, fmt.Sprintf(format, args...)) }
ranAt, label := -1, ""
run := func() { ranAt = asked; label = metricsBoxLabel(getenv, "machine-1") }
- agentEntry(getenv, resolveGroupBoxReference, quick, logf, run)
+ agentEntry(getenv, resolveGroupBoxReference, quick, logf, func() hafresh.Self { return hafresh.Self{Ref: "test-box"} }, run)
want, ref := 0, status.Label("machine-1")
if tc.marked {
want, ref = 3, hostactors.GroupBoxReference("123456789012", "i-0a61f580df1acfa65")
diff --git a/internal/host/haself.go b/internal/host/haself.go
new file mode 100644
index 000000000..bb9f73dca
--- /dev/null
+++ b/internal/host/haself.go
@@ -0,0 +1,99 @@
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+)
+
+// haIMDSClient is the client the box's lease identity reads IMDS with. A
+// read is bounded by haIdentityRead, so a box off EC2 starts at most that
+// late.
+var haIMDSClient = &http.Client{Timeout: haIdentityRead}
+
+// haSelfNow is this box's identity as a lease owner (lease.SetSelf): its
+// reference is the label it publishes metrics under, and its instance id
+// comes from one identity-document read, given 2 seconds, "" when that
+// read fails.
+// agentEntry calls it after the group-reference wait, so a group box's
+// label is its resolved group reference.
+func haSelfNow(getenv func(string) string, client *http.Client) hafresh.Self {
+ iid, _ := readInstanceID(client, imdsBase)
+ return hafresh.Self{Ref: metricsBoxLabel(getenv, readMachineID()), IID: iid}
+}
+
+// haSelfRetry asks again, every tick, for an instance id the startup read
+// missed, and hands the identity to set once it has one. It returns then,
+// or when ctx ends.
+func haSelfRetry(ctx context.Context, getenv func(string) string, client *http.Client, every time.Duration, set func(hafresh.Self)) {
+ t := time.NewTicker(every)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ }
+ if s := haSelfNow(getenv, client); s.IID != "" {
+ set(s)
+ return
+ }
+ }
+}
+
+// haIdentityRead is the whole of one instance-id read: token and document.
+const haIdentityRead = 2 * time.Second
+
+// readInstanceID reads the instance id from the identity document (IMDSv2),
+// the token and the document together within haIdentityRead.
+func readInstanceID(client *http.Client, base string) (string, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), haIdentityRead)
+ defer cancel()
+ get := func(method, path string, hdr map[string]string) ([]byte, error) {
+ req, err := http.NewRequestWithContext(ctx, method, base+path, nil)
+ if err != nil {
+ return nil, err
+ }
+ for k, v := range hdr {
+ req.Header.Set(k, v)
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+ body, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
+ if err != nil {
+ return nil, err
+ }
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("IMDS %s answered %d", path, resp.StatusCode)
+ }
+ return body, nil
+ }
+ tok, err := get(http.MethodPut, "/latest/api/token", map[string]string{"X-aws-ec2-metadata-token-ttl-seconds": "60"})
+ if err != nil {
+ return "", fmt.Errorf("IMDS token: %w", err)
+ }
+ token := strings.TrimSpace(string(tok))
+ if token == "" {
+ return "", fmt.Errorf("IMDS token: empty")
+ }
+ doc, err := get(http.MethodGet, imdsIdentityDocument, map[string]string{"X-aws-ec2-metadata-token": token})
+ if err != nil {
+ return "", err
+ }
+ var d struct {
+ InstanceID string `json:"instanceId"`
+ }
+ if err := json.Unmarshal(doc, &d); err != nil {
+ return "", fmt.Errorf("IMDS identity document: %w", err)
+ }
+ return strings.TrimSpace(d.InstanceID), nil
+}
diff --git a/internal/host/haself_test.go b/internal/host/haself_test.go
new file mode 100644
index 000000000..1b422d63a
--- /dev/null
+++ b/internal/host/haself_test.go
@@ -0,0 +1,93 @@
+package host
+
+import (
+ "context"
+ "net/http"
+ "slices"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/lease/locktest"
+)
+
+// r2.10: the owner is set by agentEntry itself, before the agent starts,
+// on a box with no switches set; deleting the SetSelf call in agentEntry
+// fails this. The self set first stands for one left by an earlier test.
+func TestAgentEntrySetsOwnerBeforeRun(t *testing.T) {
+ ctx := context.Background()
+ fx := locktest.NewLockFixture(t)
+ lease.SetSelf(hafresh.Self{Ref: "stale"})
+ var owner string
+ agentEntry(envOf(nil), nil, groupReferenceBackoff, t.Logf, func() hafresh.Self { return hafresh.Self{Ref: "ie-box", IID: "i-0abc"} }, func() {
+ h, err := lease.Acquire(ctx, fx.Bucket, "instances/h", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ owner = fx.LockOwner("instances/h")
+ h.Release(ctx)
+ })
+ if o, ok := hafresh.ParseOwner(owner); !ok || o.Ref != "ie-box" || o.IID != "i-0abc" {
+ t.Fatalf("%q", owner)
+ }
+}
+
+// The box's reference is its metrics label; its instance id comes from one
+// identity-document read, "" when that read fails.
+func TestHASelfNowNamesTheBox(t *testing.T) {
+ f := &fakeIMDS{doc: `{"accountId":"123456789012","instanceId":"i-0a61f580df1acfa65"}`}
+ getenv := envOf(map[string]string{"CARLOS_FLEET": "pi", "CARLOS_FLEET_BOX": "pi-box"})
+ want := metricsBoxLabel(getenv, readMachineID())
+ if got := haSelfNow(getenv, imdsClient(f)); got != (hafresh.Self{Ref: want, IID: "i-0a61f580df1acfa65"}) ||
+ !slices.Equal(f.calls, []string{"PUT /latest/api/token", "GET " + imdsIdentityDocument}) {
+ t.Fatalf("%+v after %q, want ref %q", got, f.calls, want)
+ }
+ f.status = http.StatusInternalServerError
+ if got := haSelfNow(getenv, imdsClient(f)); got != (hafresh.Self{Ref: want}) {
+ t.Fatalf("IMDS failing: %+v", got)
+ }
+}
+
+// failingFor answers 500 to the first n identity-document reads.
+type failingFor struct {
+ *fakeIMDS
+ n int
+}
+
+func (f *failingFor) RoundTrip(r *http.Request) (*http.Response, error) {
+ if r.URL.Path == imdsIdentityDocument {
+ if f.n--; f.n >= 0 {
+ f.status = http.StatusInternalServerError
+ } else {
+ f.status = 0
+ }
+ }
+ return f.fakeIMDS.RoundTrip(r)
+}
+
+// An instance id the startup read missed is asked for again on each tick
+// until it answers, then set once, with the reference; the retry ends
+// there, or when its context does.
+func TestHASelfRetrySetsALateInstanceID(t *testing.T) {
+ f := &failingFor{fakeIMDS: &fakeIMDS{doc: `{"instanceId":"i-0abc"}`}, n: 2}
+ getenv := envOf(map[string]string{"CARLOS_FLEET": "pi", "CARLOS_FLEET_BOX": "pi-box"})
+ var set []hafresh.Self
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ haSelfRetry(context.Background(), getenv, &http.Client{Transport: f}, time.Millisecond, func(s hafresh.Self) { set = append(set, s) })
+ }()
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the retry never ended")
+ }
+ if want := (hafresh.Self{Ref: metricsBoxLabel(getenv, readMachineID()), IID: "i-0abc"}); len(set) != 1 || set[0] != want || len(f.calls) != 6 {
+ t.Fatalf("set %+v after %d requests, want once %+v after 3 reads", set, len(f.calls), want)
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ haSelfRetry(ctx, getenv, imdsClient(&fakeIMDS{status: 500}), time.Hour, func(hafresh.Self) { t.Fatal("set with no instance id") })
+}
diff --git a/internal/lease/createlease.go b/internal/lease/createlease.go
index 71aa2a1d4..2394a4196 100644
--- a/internal/lease/createlease.go
+++ b/internal/lease/createlease.go
@@ -22,7 +22,7 @@ var errLockPresent = errors.New("lease: a lock is present")
// createLease is litestream's AcquireLease for the common case, the lock
// absent (a release deletes it), in one round trip instead of two. It
// writes what AcquireLease writes for an absent lock: generation 1, the
-// leaser's owner, now plus its TTL, the same JSON and content type, and the
+// leaser's owner (currentOwner, which AcquireTTL set), now plus its TTL, the same JSON and content type, and the
// same create-only condition (If-None-Match: *). So the lock it leaves, and
// what a reader of it decides, are AcquireLease's. A 412 means a lock is
// there, and errLockPresent hands the decision back to AcquireLease (the
diff --git a/internal/lease/lease.go b/internal/lease/lease.go
index b926b7e78..8b844f415 100644
--- a/internal/lease/lease.go
+++ b/internal/lease/lease.go
@@ -188,6 +188,7 @@ func AcquireTTL(ctx context.Context, bucket, prefix, region string, ttl time.Dur
leaser.Bucket = bucket
leaser.Path = prefix // lock lives at <prefix>/lock.json, colocated with the replica
leaser.TTL = ttl
+ leaser.Owner = currentOwner(false) // the box, once agentEntry named it (self.go)
started := time.Now()
lease, err := createLease(ctx, client, leaser)
diff --git a/internal/lease/locktest/fixture.go b/internal/lease/locktest/fixture.go
new file mode 100644
index 000000000..dce1527f0
--- /dev/null
+++ b/internal/lease/locktest/fixture.go
@@ -0,0 +1,332 @@
+// Package locktest is an in-process S3 endpoint for lease tests: one
+// bucket of plain (unversioned) objects, served path-style over HTTP on
+// 127.0.0.1, with ETags, conditional PUT and DELETE (If-Match,
+// If-None-Match: *), ListObjectsV2, a request log, fault injection and a
+// hook before each write.
+//
+// It imports nothing from the platform, so package lease's own tests, as
+// well as anyone else's, can use it without an import cycle (leasetest
+// imports lease, so lease's in-package tests cannot import leasetest).
+package locktest
+
+import (
+ "crypto/md5"
+ "encoding/hex"
+ "encoding/json"
+ "encoding/xml"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// FixtureBucket is the one bucket a LockFixture serves.
+const FixtureBucket = "locks"
+
+type object struct {
+ body []byte
+ etag string // quoted, as S3 sends it
+ modified time.Time
+}
+
+// LockFixture is the endpoint and its state. Its methods are safe to call
+// from any goroutine, hooks included.
+type LockFixture struct {
+ Bucket string // the bucket to pass to lease.Acquire
+ URL string // the endpoint, also in CARLOS_S3_ENDPOINT
+
+ mu sync.Mutex
+ objects map[string]object
+ log []string
+ seen map[string]int // verb -> requests served so far
+ failAt map[string]map[int]int // verb -> request number -> status
+ beforeWrite func(method, key string)
+}
+
+// NewLockFixture starts the endpoint for the test's life and points the
+// AWS SDK and the lease package at it: static test credentials, no shared
+// config or IMDS, and CARLOS_S3_ENDPOINT. It uses t.Setenv, so the test
+// cannot run in parallel.
+func NewLockFixture(t testing.TB) *LockFixture {
+ t.Helper()
+ f := &LockFixture{Bucket: FixtureBucket, objects: map[string]object{}, seen: map[string]int{}, failAt: map[string]map[int]int{}}
+ srv := httptest.NewServer(http.HandlerFunc(f.serve)) // 127.0.0.1 only
+ t.Cleanup(srv.Close)
+ f.URL = srv.URL
+ for k, v := range map[string]string{
+ "AWS_ACCESS_KEY_ID": "test-key", "AWS_SECRET_ACCESS_KEY": "test-secret", "AWS_SESSION_TOKEN": "", "AWS_PROFILE": "",
+ "AWS_EC2_METADATA_DISABLED": "true", "AWS_CONFIG_FILE": "/nonexistent", "AWS_SHARED_CREDENTIALS_FILE": "/nonexistent",
+ "CARLOS_S3_ENDPOINT": srv.URL,
+ } {
+ t.Setenv(k, v)
+ }
+ return f
+}
+
+// lockKey is where lease keeps a prefix's lock.
+func lockKey(prefix string) string {
+ if prefix == "" {
+ return "lock.json"
+ }
+ return prefix + "/lock.json"
+}
+
+// PutLock stores body as prefix's lock.json, unconditionally and without
+// a log entry: the test's own setup, not a request.
+func (f *LockFixture) PutLock(prefix string, body []byte) { f.PutObject(lockKey(prefix), body) }
+
+// PutObject stores body at key, as PutLock does.
+func (f *LockFixture) PutObject(key string, body []byte) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.storeLocked(key, body)
+}
+
+// LockBody is prefix's lock.json as stored now, nil when there is none.
+func (f *LockFixture) LockBody(prefix string) []byte {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ o, ok := f.objects[lockKey(prefix)]
+ if !ok {
+ return nil
+ }
+ return append([]byte(nil), o.body...)
+}
+
+// LockOwner is the "owner" field of prefix's lock.json, "" when there is
+// no lock or it is not JSON.
+func (f *LockFixture) LockOwner(prefix string) string {
+ var l struct {
+ Owner string `json:"owner"`
+ }
+ _ = json.Unmarshal(f.LockBody(prefix), &l)
+ return l.Owner
+}
+
+// Requests is every request served, in order: "GET key", "HEAD key",
+// "PUT key", "DELETE key" or "LIST prefix". A request a fault failed is
+// listed too. The SDK retries 5xx answers by itself, so a retried request
+// appears once per attempt.
+func (f *LockFixture) Requests() []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]string(nil), f.log...)
+}
+
+// FailNext fails the next request of verb ("GET", "HEAD", "PUT", "DELETE"
+// or "LIST") with status, before it touches any object.
+func (f *LockFixture) FailNext(verb string, status int) { f.FailNth(verb, 1, status) }
+
+// FailNth fails the n-th request of verb from now (n from 1) with status.
+func (f *LockFixture) FailNth(verb string, n int, status int) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.failAt[verb] == nil {
+ f.failAt[verb] = map[int]int{}
+ }
+ f.failAt[verb][f.seen[verb]+n] = status
+}
+
+// BeforeWrite runs hook before each PUT or DELETE is applied, after it is
+// logged and before its condition is checked, with no lock held: a hook
+// may change the store (PutLock) to stage a race.
+func (f *LockFixture) BeforeWrite(hook func(method, key string)) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.beforeWrite = hook
+}
+
+func (f *LockFixture) storeLocked(key string, body []byte) object {
+ sum := md5.Sum(body)
+ o := object{body: append([]byte(nil), body...), etag: `"` + hex.EncodeToString(sum[:]) + `"`, modified: time.Now().UTC()}
+ f.objects[key] = o
+ return o
+}
+
+func s3error(w http.ResponseWriter, status int, code string) {
+ w.Header().Set("Content-Type", "application/xml")
+ w.WriteHeader(status)
+ io.WriteString(w, "<Error><Code>"+code+"</Code><Message>"+code+"</Message></Error>")
+}
+
+func codeFor(status int) string {
+ switch status {
+ case http.StatusPreconditionFailed:
+ return "PreconditionFailed"
+ case http.StatusNotFound:
+ return "NoSuchKey"
+ case http.StatusForbidden:
+ return "AccessDenied"
+ case http.StatusConflict:
+ return "ConditionalRequestConflict"
+ case http.StatusServiceUnavailable:
+ return "SlowDown"
+ default:
+ return "InternalError"
+ }
+}
+
+func etagMatches(o object, header string) bool {
+ return strings.Trim(o.etag, `"`) == strings.Trim(header, `"`)
+}
+
+func (f *LockFixture) serve(w http.ResponseWriter, r *http.Request) {
+ bucket, rawKey, _ := strings.Cut(strings.TrimPrefix(r.URL.EscapedPath(), "/"), "/")
+ key, err := url.PathUnescape(rawKey)
+ if err != nil {
+ s3error(w, http.StatusBadRequest, "InvalidURI")
+ return
+ }
+ q := r.URL.Query()
+ verb, subject := r.Method, key
+ if r.Method == http.MethodGet && key == "" {
+ verb, subject = "LIST", q.Get("prefix")
+ }
+ var body []byte
+ if r.Method == http.MethodPut {
+ if body, err = io.ReadAll(r.Body); err != nil {
+ s3error(w, http.StatusBadRequest, "IncompleteBody")
+ return
+ }
+ }
+
+ f.mu.Lock()
+ f.log = append(f.log, verb+" "+subject)
+ f.seen[verb]++
+ status, failing := f.failAt[verb][f.seen[verb]]
+ delete(f.failAt[verb], f.seen[verb])
+ hook := f.beforeWrite
+ f.mu.Unlock()
+ if failing {
+ s3error(w, status, codeFor(status))
+ return
+ }
+ if bucket != f.Bucket {
+ s3error(w, http.StatusNotFound, "NoSuchBucket")
+ return
+ }
+ if hook != nil && (r.Method == http.MethodPut || r.Method == http.MethodDelete) {
+ hook(r.Method, key)
+ }
+
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ cur, exists := f.objects[key]
+ switch {
+ case verb == "LIST":
+ f.listLocked(w, q)
+ case (r.Method == http.MethodGet || r.Method == http.MethodHead) && key != "":
+ if !exists {
+ s3error(w, http.StatusNotFound, "NoSuchKey")
+ return
+ }
+ w.Header().Set("ETag", cur.etag)
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Last-Modified", cur.modified.Format(http.TimeFormat))
+ w.Header().Set("Content-Length", strconv.Itoa(len(cur.body)))
+ if r.Method == http.MethodGet {
+ w.Write(cur.body)
+ }
+ case r.Method == http.MethodPut && key != "":
+ // S3's conditional writes: If-None-Match: * refuses a present
+ // key with 412; If-Match answers 404 for an absent key and 412
+ // for another ETag.
+ if r.Header.Get("If-None-Match") == "*" && exists {
+ s3error(w, http.StatusPreconditionFailed, "PreconditionFailed")
+ return
+ }
+ if m := r.Header.Get("If-Match"); m != "" {
+ if !exists {
+ s3error(w, http.StatusNotFound, "NoSuchKey")
+ return
+ }
+ if !etagMatches(cur, m) {
+ s3error(w, http.StatusPreconditionFailed, "PreconditionFailed")
+ return
+ }
+ }
+ o := f.storeLocked(key, body)
+ w.Header().Set("ETag", o.etag)
+ case r.Method == http.MethodDelete && key != "":
+ if m := r.Header.Get("If-Match"); m != "" {
+ if !exists {
+ s3error(w, http.StatusNotFound, "NoSuchKey")
+ return
+ }
+ if !etagMatches(cur, m) {
+ s3error(w, http.StatusPreconditionFailed, "PreconditionFailed")
+ return
+ }
+ }
+ delete(f.objects, key)
+ w.WriteHeader(http.StatusNoContent)
+ default:
+ s3error(w, http.StatusNotImplemented, "NotImplemented")
+ }
+}
+
+type listContents struct {
+ Key string
+ LastModified string
+ ETag string
+ Size int
+}
+
+type listResult struct {
+ XMLName xml.Name `xml:"ListBucketResult"`
+ Name string
+ Prefix string
+ MaxKeys int
+ KeyCount int
+ IsTruncated bool
+ NextContinuationToken string `xml:",omitempty"`
+ Contents []listContents
+}
+
+// listLocked is ListObjectsV2: keys under prefix in order, at most
+// max-keys (default 1000), resuming after continuation-token or
+// start-after.
+func (f *LockFixture) listLocked(w http.ResponseWriter, q url.Values) {
+ prefix := q.Get("prefix")
+ max := 1000
+ if s := q.Get("max-keys"); s != "" {
+ n, err := strconv.Atoi(s)
+ if err != nil || n < 0 {
+ s3error(w, http.StatusBadRequest, "InvalidArgument")
+ return
+ }
+ max = n
+ }
+ after := q.Get("start-after")
+ if c := q.Get("continuation-token"); c != "" {
+ after = c
+ }
+ var keys []string
+ for k := range f.objects {
+ if strings.HasPrefix(k, prefix) && k > after {
+ keys = append(keys, k)
+ }
+ }
+ sort.Strings(keys)
+ res := listResult{Name: f.Bucket, Prefix: prefix, MaxKeys: max}
+ if len(keys) > max {
+ keys, res.IsTruncated = keys[:max], true
+ if max > 0 {
+ res.NextContinuationToken = keys[max-1]
+ }
+ }
+ for _, k := range keys {
+ 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)
+ w.Header().Set("Content-Type", "application/xml")
+ io.WriteString(w, xml.Header)
+ xml.NewEncoder(w).Encode(res)
+}
diff --git a/internal/lease/locktest/fixture_test.go b/internal/lease/locktest/fixture_test.go
new file mode 100644
index 000000000..cd3b6e7a4
--- /dev/null
+++ b/internal/lease/locktest/fixture_test.go
@@ -0,0 +1,90 @@
+package locktest
+
+import (
+ "io"
+ "net/http"
+ "slices"
+ "strings"
+ "testing"
+)
+
+func do(t *testing.T, f *LockFixture, method, path string, hdr map[string]string, body string) (int, string, http.Header) {
+ t.Helper()
+ req, err := http.NewRequest(method, f.URL+path, strings.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for k, v := range hdr {
+ req.Header.Set(k, v)
+ }
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ b, _ := io.ReadAll(resp.Body)
+ return resp.StatusCode, string(b), resp.Header
+}
+
+// The conditional writes S3 answers, the log, a fault on the n-th request
+// of a verb, the write hook and ListObjectsV2's max-keys.
+func TestLockFixtureSpeaksConditionalS3(t *testing.T) {
+ f := NewLockFixture(t)
+ lock := "/locks/instances/h/lock.json"
+ if st, _, _ := do(t, f, "GET", lock, nil, ""); st != 404 {
+ t.Fatalf("absent GET %d", st)
+ }
+ st, _, h := do(t, f, "PUT", lock, map[string]string{"If-None-Match": "*"}, `{"owner":"a"}`)
+ if st != 200 || h.Get("ETag") == "" {
+ t.Fatalf("create %d %q", st, h.Get("ETag"))
+ }
+ etag := h.Get("ETag")
+ if st, _, _ := do(t, f, "PUT", lock, map[string]string{"If-None-Match": "*"}, `{"owner":"b"}`); st != 412 {
+ t.Fatalf("second create %d", st)
+ }
+ if st, _, _ := do(t, f, "PUT", lock, map[string]string{"If-Match": `"nope"`}, `{"owner":"b"}`); st != 412 {
+ t.Fatalf("stale If-Match %d", st)
+ }
+ if st, _, _ := do(t, f, "PUT", "/locks/other", map[string]string{"If-Match": etag}, `x`); st != 404 {
+ t.Fatalf("If-Match on an absent key %d", st)
+ }
+ if st, body, h := do(t, f, "GET", lock, nil, ""); st != 200 || body != `{"owner":"a"}` || h.Get("ETag") != etag {
+ t.Fatalf("GET %d %q %q", st, body, h.Get("ETag"))
+ }
+ var hooked []string
+ f.BeforeWrite(func(m, k string) { hooked = append(hooked, m+" "+k) })
+ if st, _, _ := do(t, f, "PUT", lock, map[string]string{"If-Match": strings.Trim(etag, `"`)}, `{"owner":"c"}`); st != 200 || f.LockOwner("instances/h") != "c" {
+ t.Fatalf("If-Match %d owner %q", st, f.LockOwner("instances/h"))
+ }
+ f.PutObject("instances/h/files/0/manifest.json", []byte(`{}`))
+ f.FailNth("PUT", 2, 503)
+ if st, _, _ := do(t, f, "PUT", "/locks/a", nil, `1`); st != 200 {
+ t.Fatalf("first PUT after FailNth(2) %d", st)
+ }
+ if st, _, _ := do(t, f, "PUT", "/locks/b", nil, `1`); st != 503 {
+ t.Fatalf("second PUT after FailNth(2) %d", st)
+ }
+ if st, body, _ := do(t, f, "GET", "/locks?list-type=2&prefix=instances/h/&max-keys=1", nil, ""); st != 200 ||
+ !strings.Contains(body, "<Key>instances/h/files/0/manifest.json</Key>") || strings.Contains(body, "lock.json") || !strings.Contains(body, "<IsTruncated>true</IsTruncated>") {
+ t.Fatalf("LIST %d %s", st, body)
+ }
+ f.FailNext("DELETE", 500)
+ if st, _, _ := do(t, f, "DELETE", lock, nil, ""); st != 500 || f.LockBody("instances/h") == nil {
+ t.Fatalf("failed DELETE %d", st)
+ }
+ if st, _, _ := do(t, f, "DELETE", lock, map[string]string{"If-Match": etag}, ""); st != 412 {
+ t.Fatalf("stale DELETE %d", st)
+ }
+ if st, _, _ := do(t, f, "DELETE", lock, nil, ""); st != 204 || f.LockBody("instances/h") != nil {
+ t.Fatalf("DELETE %d", st)
+ }
+ want := []string{"GET instances/h/lock.json", "PUT instances/h/lock.json", "PUT instances/h/lock.json", "PUT instances/h/lock.json",
+ "PUT other", "GET instances/h/lock.json", "PUT instances/h/lock.json", "PUT a", "PUT b", "LIST instances/h/",
+ "DELETE instances/h/lock.json", "DELETE instances/h/lock.json", "DELETE instances/h/lock.json"}
+ if got := f.Requests(); !slices.Equal(got, want) {
+ t.Fatalf("log\n%q\nwant\n%q", got, want)
+ }
+ if want := []string{"PUT instances/h/lock.json", "PUT a", "DELETE instances/h/lock.json", "DELETE instances/h/lock.json"}; !slices.Equal(hooked, want) {
+ t.Fatalf("hooked %q, want %q", hooked, want)
+ }
+}
diff --git a/internal/lease/self.go b/internal/lease/self.go
new file mode 100644
index 000000000..4334a953e
--- /dev/null
+++ b/internal/lease/self.go
@@ -0,0 +1,43 @@
+package lease
+
+import (
+ "fmt"
+ "os"
+ "sync/atomic"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+)
+
+// self is the box this process acquires leases for, nil until SetSelf.
+var self atomic.Pointer[hafresh.Self]
+
+// SetSelf names the box every lock this process writes from now on
+// belongs to. The agent calls it once at startup (agentEntry), and again
+// when an instance id it could not read then arrives. Safe to call at any
+// time from any goroutine; a lease already held keeps the owner it was
+// acquired with.
+func SetSelf(s hafresh.Self) { self.Store(&s) }
+
+// currentOwner is the owner a lock written now carries: the box format
+// (hafresh.OwnerFor) once SetSelf has named the box. Before that, and in
+// any process other than the agent (the console, a CLI), a legacy lock
+// keeps litestream's own host:pid owner, since only the agent knows the
+// box's reference. An HA owner is always the box format.
+func currentOwner(ha bool) string {
+ s := self.Load()
+ if s == nil {
+ if !ha {
+ return legacyOwner()
+ }
+ s = &hafresh.Self{}
+ }
+ return hafresh.OwnerFor(*s, os.Getpid(), ha)
+}
+
+// legacyOwner is what litestream's NewLeaser names a lease's owner.
+func legacyOwner() string {
+ if h, _ := os.Hostname(); h != "" {
+ return fmt.Sprintf("%s:%d", h, os.Getpid())
+ }
+ return fmt.Sprintf("pid-%d", os.Getpid())
+}
diff --git a/internal/lease/self_test.go b/internal/lease/self_test.go
new file mode 100644
index 000000000..0ae7f7e0d
--- /dev/null
+++ b/internal/lease/self_test.go
@@ -0,0 +1,57 @@
+package lease
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease/locktest"
+)
+
+// A lock this process writes names the box SetSelf last set, through both
+// of the acquire's writes (the create of an absent lock and the takeover
+// of an expired one), and a later SetSelf (the instance id arriving) is
+// what the next acquire writes. With no self set (a process other than
+// the agent) the owner stays litestream's host:pid.
+func TestAcquireWritesTheBoxOwner(t *testing.T) {
+ ctx := context.Background()
+ fx := locktest.NewLockFixture(t)
+ t.Cleanup(func() { self.Store(nil) })
+
+ self.Store(nil)
+ h, err := Acquire(ctx, fx.Bucket, "instances/legacy", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ host, _ := os.Hostname()
+ if got := fx.LockOwner("instances/legacy"); got != fmt.Sprintf("%s:%d", host, os.Getpid()) {
+ t.Fatalf("no self: owner %q", got)
+ }
+ h.Release(ctx)
+
+ SetSelf(hafresh.Self{Ref: "ie-box"})
+ h, err = Acquire(ctx, fx.Bucket, "instances/h", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, want := fx.LockOwner("instances/h"), fmt.Sprintf("box/v1;ref=ie-box;pid=%d", os.Getpid()); got != want {
+ t.Fatalf("created lock owner %q, want %q", got, want)
+ }
+ h.Release(ctx)
+
+ SetSelf(hafresh.Self{Ref: "ie-box", IID: "i-0abc"})
+ fx.PutLock("instances/h", []byte(`{"generation":4,"expires_at":"2020-01-01T00:00:00Z","owner":"ip-10-0-0-1:77"}`))
+ h, err = Acquire(ctx, fx.Bucket, "instances/h", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer h.Release(ctx)
+ if got, want := fx.LockOwner("instances/h"), fmt.Sprintf("box/v1;ref=ie-box;iid=i-0abc;pid=%d", os.Getpid()); got != want {
+ t.Fatalf("taken-over lock owner %q, want %q", got, want)
+ }
+ if got := currentOwner(true); got != fmt.Sprintf("box/v1;ref=ie-box;iid=i-0abc;pid=%d;ha=1", os.Getpid()) {
+ t.Fatalf("HA owner %q", got)
+ }
+}