region-ha p1b-1: the HA wake takes a terminated holder's host once its lease expired
The activator hands hafresh.Proofs.OwnerTerminated to the HA acquire (ExecBackend.OwnerTerminated, nil: no takeover). A confirmed termination is logged; a failed describe refuses the wake and is logged at most once a minute per host. The lease's acquire log names the winning round's rule (first wake, clean marker, unclean marker, same-box takeover, holder terminated). The agent builds one termfence.Confirmer whose identity is the lease's, read at each call, with an EC2 client built through rootaws and kept as a single method value.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+460
−17
internal/activator/backend_exec.go+7 −0internal/activator/hasamebox.go+6 −5internal/activator/hatakeover.go+70 −0internal/activator/hatakeover_test.go+170 −0internal/activator/hawake.go+1 −1internal/host/agent.go+4 −0internal/host/hatakeover.go+49 −0internal/host/hatakeover_wiring_test.go+57 −0internal/lease/ha.go+24 −11internal/lease/ha_test.go+72 −0
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index d97a017e8..7efa860b1 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -337,6 +337,13 @@ type ExecBackend struct { |
| // Nil: never proven, and every same-box takeover of an expired HA lock |
| // is refused. |
| StartupSwept func() bool |
| + // OwnerTerminated asks EC2 whether another box's instance is confirmed |
| + // terminated (termfence.Confirmer.Terminated), the proof that hands an |
| + // HA host whose lease expired to a surviving box (hatakeover.go). Nil: |
| + // no takeover, and another box's expired HA lock is always refused. |
| + OwnerTerminated func(ctx context.Context, iid string) (bool, error) |
| + // takeover is the takeover proof's log throttle (hatakeover.go). |
| + takeover takeoverState |
| // sameBox is the same-box recovery's state (hasamebox.go): the hosts |
| // this process has acquired (acquiredHere). |
| sameBox sameBoxState |
diff --git a/internal/activator/hasamebox.go b/internal/activator/hasamebox.go| index e084b9a6d..fbb69bb99 100644 |
| --- a/internal/activator/hasamebox.go |
| +++ b/internal/activator/hasamebox.go |
| @@ -17,11 +17,12 @@ import ( |
| // second writer on the same box after an agent crash). |
| // |
| // When the agent dies with an HA host awake, the host's lock stops |
| -// renewing. No other box ever takes an expired HA lock |
| -// (hafresh.ReasonOtherExpired), so the host comes back only on this box, |
| -// once the lock has expired (up to one lease TTL, lease.LeaseTTL, 15 |
| -// minutes, after the crash), and only on proof that nothing of the host |
| -// still runs here: hafresh.Proofs.SameBoxEmpty, which is sameBoxEmpty. |
| +// renewing. No other box takes an expired HA lock of a box that is not |
| +// confirmed terminated (hafresh.ReasonOtherExpired, hatakeover.go), and |
| +// this box is not, so the host comes back only on this box, once the lock |
| +// has expired (up to one lease TTL, lease.LeaseTTL, 15 minutes, after the |
| +// crash), and only on proof that nothing of the host still runs here: |
| +// hafresh.Proofs.SameBoxEmpty, which is sameBoxEmpty. |
| // |
| // The proof is root's existing stop-and-prove for nested units; P1a adds |
| // none. sameBoxEmpty answers true only when all of these hold: |
diff --git a/internal/activator/hatakeover.go b/internal/activator/hatakeover.go| new file mode 100644 |
| index 000000000..b0e7842ec |
| --- /dev/null |
| +++ b/internal/activator/hatakeover.go |
| @@ -0,0 +1,70 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "log" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// Region HA P1b-1, the takeover of a terminated holder's host. |
| +// |
| +// An HA lock that expired while another box held it is taken only when |
| +// that box's instance is confirmed terminated: hafresh.DecideAcquire asks |
| +// hafresh.Proofs.OwnerTerminated, which is ownerTerminated, only for an |
| +// expired lock of another box's non-empty instance id, so an unexpired |
| +// lock is held without asking (N-HA9). The answer is EC2's, in this box's |
| +// own account and region (termfence.Confirmer): a stopped, running or |
| +// unknown instance, another account or region, or a describe that failed, |
| +// refuses the wake and nothing is written. The host then stays down until |
| +// the holder comes back and releases it, or EC2 confirms it terminated. |
| + |
| +// ownerTerminated is the takeover proof for rt's acquire: nil (no |
| +// takeover) when OwnerTerminated is not wired. A confirmed termination is |
| +// logged; a failed describe is logged at most once a minute per host. |
| +func (b *ExecBackend) ownerTerminated(ctx context.Context, rt registry.Route) func(iid string) (bool, error) { |
| + if b.OwnerTerminated == nil { |
| + return nil |
| + } |
| + return func(iid string) (bool, error) { |
| + gone, err := b.OwnerTerminated(ctx, iid) |
| + if err != nil { |
| + b.takeover.alarm(rt.Host, iid, err) |
| + return false, err |
| + } |
| + if gone { |
| + log.Printf("activator: %s: the holder %s is terminated (EC2) and its lease expired; taking the host over", rt.Host, iid) |
| + } |
| + return gone, nil |
| + } |
| +} |
| + |
| +// takeoverAlarmEvery is how often one host's failed takeover proof is |
| +// logged again while its wakes keep failing. |
| +const takeoverAlarmEvery = sameBoxAlarmEvery |
| + |
| +// takeoverState is when each host's failed takeover proof was last logged. |
| +type takeoverState struct { |
| + mu sync.Mutex |
| + alarmed map[string]time.Time |
| +} |
| + |
| +// alarm logs a takeover refused because EC2 could not be asked, at most |
| +// once a minute per host (the twin of sameBoxState.alarm). |
| +func (s *takeoverState) alarm(host, iid string, why error) { |
| + s.mu.Lock() |
| + now := time.Now() |
| + last, seen := s.alarmed[host] |
| + if seen && now.Sub(last) < takeoverAlarmEvery { |
| + s.mu.Unlock() |
| + return |
| + } |
| + if s.alarmed == nil { |
| + s.alarmed = map[string]time.Time{} |
| + } |
| + s.alarmed[host] = now |
| + s.mu.Unlock() |
| + log.Printf("activator: ALERT %s: the takeover of %s's expired HA lock is refused: EC2 did not answer whether it is terminated: %v (the host stays down until EC2 confirms the holder terminated)", host, iid, why) |
| +} |
diff --git a/internal/activator/hatakeover_test.go b/internal/activator/hatakeover_test.go| new file mode 100644 |
| index 000000000..c6e7649bc |
| --- /dev/null |
| +++ b/internal/activator/hatakeover_test.go |
| @@ -0,0 +1,170 @@ |
| +package activator |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// Region HA P1b-1: a born-HA host whose holder box is terminated, and |
| +// whose lease has expired, is taken over by the first wake at a surviving |
| +// box. These run through the production Acquire against the lock fixture. |
| + |
| +// heldByB is box b's HA lease on the host, expiring at expires. |
| +const heldByB = "box/v1;ref=b;iid=i-b;pid=7;ha=1" |
| + |
| +// terminatedOracle is an OwnerTerminated that answers yes, no or err for |
| +// every id, and records the ids it was asked about. |
| +type terminatedOracle struct { |
| + mu sync.Mutex |
| + asked []string |
| + yes map[string]bool |
| + err error |
| +} |
| + |
| +func (o *terminatedOracle) terminated(_ context.Context, iid string) (bool, error) { |
| + o.mu.Lock() |
| + defer o.mu.Unlock() |
| + o.asked = append(o.asked, iid) |
| + if o.err != nil { |
| + return false, o.err |
| + } |
| + return o.yes[iid], nil |
| +} |
| + |
| +func (o *terminatedOracle) calls() []string { |
| + o.mu.Lock() |
| + defer o.mu.Unlock() |
| + return append([]string(nil), o.asked...) |
| +} |
| + |
| +// takeoverBackend is an HA backend whose host's lock is b's lease, |
| +// expiring at expires, with oracle (nil: none wired) as OwnerTerminated. |
| +func takeoverBackend(t *testing.T, expires time.Time, oracle *terminatedOracle) (*ExecBackend, registry.Route, []byte) { |
| + t.Helper() |
| + b, rt := haBackend(t, "shop.example.com") |
| + if oracle != nil { |
| + b.OwnerTerminated = oracle.terminated |
| + } |
| + if o, ok := hafresh.ParseOwner(heldByB); !ok || !o.HA || o.IID != "i-b" { |
| + t.Fatalf("fixture: %q does not parse as b's HA owner", heldByB) |
| + } |
| + body := leaseBody(t, heldByB, expires) |
| + putLockFor(t, b, rt, body) |
| + return b, rt, body |
| +} |
| + |
| +func lockBodyOf(b *ExecBackend, rt registry.Route) []byte { |
| + return haFixOf(b).fx.LockBody(b.Cfg.hibernatePrefix(rt.Host)) |
| +} |
| + |
| +func TestTakeoverOfATerminatedHolder(t *testing.T) { |
| + ctx := context.Background() |
| + logs := captureLog(t) |
| + oracle := &terminatedOracle{yes: map[string]bool{"i-b": true}} |
| + b, rt, _ := takeoverBackend(t, time.Now().Add(-time.Minute), oracle) |
| + l, err := b.Acquire(ctx, rt) |
| + if err != nil { |
| + t.Fatalf("the terminated holder's expired lock was not taken: %v", err) |
| + } |
| + releaseHALease(t, l) |
| + if got := oracle.calls(); len(got) != 1 || got[0] != "i-b" { |
| + t.Fatalf("OwnerTerminated asked about %v, want [i-b]", got) |
| + } |
| + v, err := hafresh.DecodeLock(lockBodyOf(b, rt), "x") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + o, ok := hafresh.ParseOwner(v.Lock.Owner) |
| + if !ok || !o.HA || o.Ref != "a" || o.IID != "i-a" || v.Lock.Generation != 10 || v.Lock.Release != nil { |
| + t.Fatalf("the taken lock is %+v, want this box's HA lease at generation 10", v.Lock) |
| + } |
| + if !strings.Contains(logs.String(), "HA lease acquired in") || !strings.Contains(logs.String(), "(holder terminated)") { |
| + t.Fatalf("the lease log does not say the holder was terminated:\n%s", logs) |
| + } |
| + if !strings.Contains(logs.String(), "activator: shop.example.com: the holder i-b is terminated (EC2) and its lease expired; taking the host over") { |
| + t.Fatalf("the activator did not log the takeover:\n%s", logs) |
| + } |
| + w, ok := b.haAcquired(rt.Host) |
| + if !ok || w.view.Absent || w.view.Lock.Release != nil || w.view.Lock.Owner != heldByB { |
| + t.Fatalf("the wake classified %+v, want b's expired lease and no marker", w.view) |
| + } |
| + if fresh, err := b.Restore(ctx, rt); err != nil || fresh { |
| + t.Fatalf("restore after the takeover: fresh %v, err %v", fresh, err) |
| + } |
| + if restoreCalls(b) != 1 { |
| + t.Fatalf("%d replica restores, want 1", restoreCalls(b)) |
| + } |
| + if !strings.Contains(logs.String(), "activator: shop.example.com: restored ("+hafresh.KeepNoMarker+")") { |
| + t.Fatalf("the restore's keep reason is not %s:\n%s", hafresh.KeepNoMarker, logs) |
| + } |
| +} |
| + |
| +// A terminated holder's lock is not taken before it expires (N-HA9): the |
| +// wake is held, the cloud is not asked, nothing is written. |
| +func TestTakeoverWaitsForExpiry(t *testing.T) { |
| + ctx := context.Background() |
| + oracle := &terminatedOracle{yes: map[string]bool{"i-b": true}} |
| + b, rt, body := takeoverBackend(t, time.Now().Add(10*time.Minute), oracle) |
| + _, err := b.Acquire(ctx, rt) |
| + var held *errLeaseHeld |
| + if !errors.As(err, &held) || held.holder != heldByB { |
| + t.Fatalf("an unexpired lock of a terminated holder: %v", err) |
| + } |
| + if got := oracle.calls(); len(got) != 0 { |
| + t.Fatalf("OwnerTerminated was asked about %v for an unexpired lock", got) |
| + } |
| + if lockWrites(t, b, rt) != 0 || !bytes.Equal(lockBodyOf(b, rt), body) { |
| + t.Fatal("the held wake wrote the lock") |
| + } |
| +} |
| + |
| +// A describe that fails proves nothing: the wake is refused, the lock |
| +// stays b's, and the refusal is logged once a minute, not once a wake. |
| +func TestTakeoverDescribeFailureKeepsHostDown(t *testing.T) { |
| + ctx := context.Background() |
| + logs := captureLog(t) |
| + oracle := &terminatedOracle{err: errors.New("RequestLimitExceeded")} |
| + b, rt, body := takeoverBackend(t, time.Now().Add(-time.Minute), oracle) |
| + for range 3 { |
| + _, err := b.Acquire(ctx, rt) |
| + var refused *errLeaseRefused |
| + if !errors.As(err, &refused) || !strings.Contains(refused.reason, hafresh.ReasonOtherExpired) { |
| + t.Fatalf("a failed describe: %v", err) |
| + } |
| + } |
| + if lockWrites(t, b, rt) != 0 || !bytes.Equal(lockBodyOf(b, rt), body) { |
| + t.Fatal("the refused wake wrote the lock") |
| + } |
| + if n := strings.Count(logs.String(), "RequestLimitExceeded (the host stays down"); n != 1 { |
| + t.Fatalf("the describe failure was logged %d times in three wakes, want 1:\n%s", n, logs) |
| + } |
| + if strings.Contains(logs.String(), "taking the host over") { |
| + t.Fatalf("a failed describe logged a takeover:\n%s", logs) |
| + } |
| +} |
| + |
| +// Without the oracle (P1a's wiring), another box's expired lock is never |
| +// taken. |
| +func TestNoTakeoverWithoutTheOracle(t *testing.T) { |
| + ctx := context.Background() |
| + b, rt, body := takeoverBackend(t, time.Now().Add(-time.Minute), nil) |
| + if b.ownerTerminated(ctx, rt) != nil { |
| + t.Fatal("a proof was built with no OwnerTerminated wired") |
| + } |
| + _, err := b.Acquire(ctx, rt) |
| + var refused *errLeaseRefused |
| + if !errors.As(err, &refused) || refused.reason != hafresh.ReasonOtherExpired { |
| + t.Fatalf("an expired lock of another box with no oracle: %v", err) |
| + } |
| + if lockWrites(t, b, rt) != 0 || !bytes.Equal(lockBodyOf(b, rt), body) { |
| + t.Fatal("the refused wake wrote the lock") |
| + } |
| +} |
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go| index a779944d0..b643dd40e 100644 |
| --- a/internal/activator/hawake.go |
| +++ b/internal/activator/hawake.go |
| @@ -314,7 +314,7 @@ func (b *ExecBackend) acquireClassified(ctx context.Context, rt registry.Route) |
| if err := b.haContained(rt); err != nil { |
| return nil, refusedUncontained(err) |
| } |
| - proofs := hafresh.Proofs{SameBoxEmpty: b.sameBoxEmpty(ctx, rt)} |
| + proofs := hafresh.Proofs{SameBoxEmpty: b.sameBoxEmpty(ctx, rt), OwnerTerminated: b.ownerTerminated(ctx, rt)} |
| held, err := acquireHALease(ctx, b.Cfg.Bucket, prefix, b.Cfg.Region, hafresh.Marker{Lifetime: entry.ID}, proofs) |
| if err != nil { |
| return nil, leaseError(err) |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 1dd4d6fad..8297dfac9 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -473,6 +473,10 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| eb.Lifetimes = boxLifetimes |
| eb.Registry = reg |
| eb.StartupSwept = seedSweptAtStart.Load |
| + // Region HA P1b-1: the takeover of a host whose holder box is |
| + // terminated and whose lease expired asks EC2 through one oracle. |
| + confirmer := haOwnerConfirmer() |
| + eb.OwnerTerminated = confirmer.Terminated |
| if fs, err := newProductionFilesStore(agentCtx, cfg.Bucket, cfg.Region); err != nil { |
| log.Printf("agent: region HA: files store: %v (every HA restore that needs it fails)", err) |
| } else { |
diff --git a/internal/host/hatakeover.go b/internal/host/hatakeover.go| new file mode 100644 |
| index 000000000..9430b06bb |
| --- /dev/null |
| +++ b/internal/host/hatakeover.go |
| @@ -0,0 +1,49 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + |
| + awsconfig "github.com/aws/aws-sdk-go-v2/config" |
| + "github.com/aws/aws-sdk-go-v2/service/ec2" |
| + |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/rootaws" |
| + "github.com/carlosframework/platform/internal/termfence" |
| +) |
| + |
| +// haOwnerConfirmer is the box's one termination oracle for Region HA |
| +// takeovers (activator.ExecBackend.OwnerTerminated): it asks EC2, in this |
| +// box's own account and region, whether another box's instance is |
| +// terminated. Its identity is the lease's, read at each call, because the |
| +// box's identity can arrive after the backend is built; until it is |
| +// complete every answer is an error and no client is built. Every box |
| +// gets one; only an HA host's wake ever asks it. |
| +func haOwnerConfirmer() *termfence.Confirmer { |
| + return &termfence.Confirmer{API: haTakeoverEC2, Self: haCloudSelf} |
| +} |
| + |
| +// haCloudSelf is the lease's identity as a cloud identity. |
| +func haCloudSelf() boxid.Cloud { |
| + s := lease.CurrentSelf() |
| + return boxid.Cloud{Provider: "aws", Account: s.Account, Region: s.Region, InstanceID: s.IID} |
| +} |
| + |
| +// haTakeoverEC2 builds the oracle's EC2 client for region, through root's |
| +// AWS loader. |
| +func haTakeoverEC2(ctx context.Context, region string) (termfence.EC2, error) { |
| + cfg, err := rootaws.LoadDefaultConfig(ctx, awsconfig.WithRegion(region)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return describeInstances(ec2.NewFromConfig(cfg).DescribeInstances), nil |
| +} |
| + |
| +// describeInstances is termfence.EC2 from one method value. A *ec2.Client |
| +// stored in an interface keeps every EC2 method in the binary (see |
| +// awsinv.factoryFor, discussion #275); a method value keeps one. |
| +type describeInstances func(context.Context, *ec2.DescribeInstancesInput, ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) |
| + |
| +func (f describeInstances) DescribeInstances(ctx context.Context, in *ec2.DescribeInstancesInput, opts ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) { |
| + return f(ctx, in, opts...) |
| +} |
diff --git a/internal/host/hatakeover_wiring_test.go b/internal/host/hatakeover_wiring_test.go| new file mode 100644 |
| index 000000000..2d8862483 |
| --- /dev/null |
| +++ b/internal/host/hatakeover_wiring_test.go |
| @@ -0,0 +1,57 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "os" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/termfence" |
| +) |
| + |
| +// RunAgent builds one termination oracle and hands it to the backend |
| +// before the Service starts (syntactic, like TestAgentWiresTheHAWake). |
| +func TestAgentWiresTheTakeoverOracle(t *testing.T) { |
| + src, err := os.ReadFile("agent.go") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + body := string(src) |
| + start := strings.Index(body, "Start: svc.Start,") |
| + built := strings.Index(body, "confirmer := haOwnerConfirmer()") |
| + wired := strings.Index(body, "eb.OwnerTerminated = confirmer.Terminated") |
| + if start < 0 || built < 0 || wired < built || wired > start { |
| + t.Fatalf("the takeover oracle is not built and wired before the Service starts (built %d, wired %d, start %d)", built, wired, start) |
| + } |
| + if strings.Count(body, "haOwnerConfirmer()") != 1 { |
| + t.Fatal("more than one termination oracle is built") |
| + } |
| +} |
| + |
| +// The oracle's identity is the lease's, read at each call: an identity |
| +// that arrives after the backend is built is the one it asks with, and |
| +// before it arrives every answer is an error, with no EC2 client built. |
| +func TestHAOwnerConfirmerReadsTheLateIdentity(t *testing.T) { |
| + t.Cleanup(lease.ProcessStateForTest()) |
| + c := haOwnerConfirmer() |
| + built := 0 |
| + c.API = func(context.Context, string) (termfence.EC2, error) { built++; return nil, os.ErrNotExist } |
| + lease.SetSelf(hafresh.Self{Ref: "a"}) |
| + if got := c.Self(); got.Complete() { |
| + t.Fatalf("an incomplete lease identity read as %+v", got) |
| + } |
| + if yes, err := c.Terminated(context.Background(), "i-b"); yes || err == nil || built != 0 { |
| + t.Fatalf("before the identity: %v, %v, %d clients built", yes, err, built) |
| + } |
| + lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"}) |
| + want := boxid.Cloud{Provider: "aws", Account: "111122223333", Region: "eu-west-1", InstanceID: "i-a"} |
| + if got := c.Self(); got != want { |
| + t.Fatalf("the oracle's identity is %+v, want %+v", got, want) |
| + } |
| + if got := haOwnerConfirmer(); got.API == nil { |
| + t.Fatal("no EC2 client builder") |
| + } |
| +} |
diff --git a/internal/lease/ha.go b/internal/lease/ha.go| index 8c4e32625..a72a42e15 100644 |
| --- a/internal/lease/ha.go |
| +++ b/internal/lease/ha.go |
| @@ -40,8 +40,10 @@ var ErrNoSelf = errors.New("lease: this box's identity (reference, instance id, |
| // 1. The lock is read with its ETag and classified (hafresh.DecideAcquire). |
| // 2. Absent: the prefix must be empty (PrefixEmpty), else *RefusedError |
| // "leftover data"; then a create, If-None-Match: *. |
| -// 3. A marker, or this box's expired lock with Proofs.SameBoxEmpty: a |
| -// take, If-Match the ETag classified, generation+1, the HA owner. |
| +// 3. A marker, this box's expired lock with Proofs.SameBoxEmpty, or |
| +// another box's expired lock with Proofs.OwnerTerminated: a take, |
| +// If-Match the ETag classified, generation+1, the HA owner. The log |
| +// names the rule that won. |
| // 4. Held: *HeldError. Refused: *RefusedError. Nothing written. |
| // 5. A lost condition re-reads and reclassifies, at most three rounds. |
| // |
| @@ -51,7 +53,8 @@ var ErrNoSelf = errors.New("lease: this box's identity (reference, instance id, |
| // id, lifetime) is kept for the handle's unclean releases; an empty box or |
| // instance id is this box's own. |
| // |
| -// The budget: a marker or same-box wake is 1 GET and 1 PUT; a first wake |
| +// The budget: a marker, same-box or takeover wake is 1 GET and 1 PUT (a |
| +// takeover's describe is the caller's, not S3's); a first wake |
| // 1 GET, 1 LIST (max-keys 1) and 1 PUT. |
| func AcquireHA(ctx context.Context, bucket, prefix, region string, base hafresh.Marker, p hafresh.Proofs) (*Held, error) { |
| return acquireHATTL(ctx, bucket, prefix, region, base, p, LeaseTTL) |
| @@ -88,8 +91,11 @@ func acquireHATTL(ctx context.Context, bucket, prefix, region string, base hafre |
| leaser.Path = loc |
| leaser.TTL = ttl |
| leaser.Owner = hafresh.OwnerFor(me, os.Getpid(), true) // renewals keep it |
| + // won is the last round's decision: the one whose write landed. |
| + var won hafresh.Decision |
| lease, view, started, err := classifyAndTake(ctx, client, bucket, key, leaser.Owner, ttl, func(v hafresh.View) error { |
| d := hafresh.DecideAcquire(v, me, time.Now(), p) |
| + won = d |
| switch d.Action { |
| case hafresh.ActCreate: |
| empty, err := prefixEmpty(ctx, client, bucket, loc) |
| @@ -127,20 +133,27 @@ func acquireHATTL(ctx context.Context, bucket, prefix, region string, base hafre |
| defer cancel() |
| return nil, errors.Join(fmt.Errorf("acquire HA lease: %w", err), releaseWithMarker(relCtx, leaser, region, cur, uncleanMarker(base, 0))) |
| } |
| - log.Printf("lease: %s: HA lease acquired in %s (%s)", prefix, time.Since(began).Round(time.Millisecond), viewWord(view)) |
| + log.Printf("lease: %s: HA lease acquired in %s (%s)", prefix, time.Since(began).Round(time.Millisecond), takeWord(won, view)) |
| return &Held{leaser: leaser, region: region, rn: rn, ha: true, view: view, base: base}, nil |
| } |
| -func viewWord(v hafresh.View) string { |
| - switch { |
| - case v.Absent: |
| +// takeWord names the rule that won the take, d, for the acquire's log: |
| +// the winning round's decision over v, the view it classified. |
| +func takeWord(d hafresh.Decision, v hafresh.View) string { |
| + switch d.Reason { |
| + case hafresh.ReasonAbsent: |
| return "first wake" |
| - case v.Lock.Release != nil && v.Lock.Release.Clean: |
| - return "clean marker" |
| - case v.Lock.Release != nil: |
| + case hafresh.ReasonMarker: |
| + if v.Lock.Release != nil && v.Lock.Release.Clean { |
| + return "clean marker" |
| + } |
| return "unclean marker" |
| + case hafresh.ReasonSameBox: |
| + return "same-box takeover" |
| + case hafresh.ReasonTerminated: |
| + return "holder terminated" |
| } |
| - return "same-box takeover" |
| + return d.Reason |
| } |
| // HA reports whether the handle holds an HA lease (AcquireHA). |
diff --git a/internal/lease/ha_test.go b/internal/lease/ha_test.go| index c87e8d8bf..fff0dde8a 100644 |
| --- a/internal/lease/ha_test.go |
| +++ b/internal/lease/ha_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "context" |
| "encoding/json" |
| "errors" |
| + "log" |
| "net/http" |
| "os" |
| "slices" |
| @@ -418,3 +419,74 @@ func TestAcquireHAWithAFailingObligationReadsNothing(t *testing.T) { |
| t.Fatal("the obligation was dropped") |
| } |
| } |
| + |
| +// lockedLog is the standard logger's output, for one test. |
| +type lockedLog struct { |
| + mu sync.Mutex |
| + b strings.Builder |
| +} |
| + |
| +func (l *lockedLog) Write(p []byte) (int, error) { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + return l.b.Write(p) |
| +} |
| + |
| +func (l *lockedLog) String() string { l.mu.Lock(); defer l.mu.Unlock(); return l.b.String() } |
| + |
| +func captureLog(t *testing.T) *lockedLog { |
| + t.Helper() |
| + l := &lockedLog{} |
| + prev, flags := log.Writer(), log.Flags() |
| + log.SetOutput(l) |
| + log.SetFlags(0) |
| + t.Cleanup(func() { log.SetOutput(prev); log.SetFlags(flags) }) |
| + return l |
| +} |
| + |
| +// The acquire's log names the rule that won the take: the decision of the |
| +// round whose write landed, not the first round's. |
| +func TestAcquireHALogsTheWinningRule(t *testing.T) { |
| + mine := hafresh.OwnerFor(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"}, 9, true) |
| + other := hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 7, true) |
| + clean, _ := hafresh.MarkerBody(3, hafresh.Marker{V: 1, Box: "b", IID: "i-b", Clean: true}) |
| + unclean, _ := hafresh.MarkerBody(3, hafresh.Marker{V: 1, Box: "b", IID: "i-b"}) |
| + proofs := hafresh.Proofs{ |
| + SameBoxEmpty: func() (bool, error) { return true, nil }, |
| + OwnerTerminated: func(iid string) (bool, error) { return iid == "i-b", nil }, |
| + } |
| + for _, c := range []struct { |
| + name string |
| + body []byte // nil: no lock |
| + change []byte // the lock as the first write finds it, nil: unchanged |
| + word string |
| + }{ |
| + {"absent", nil, nil, "first wake"}, |
| + {"clean marker", clean, nil, "clean marker"}, |
| + {"unclean marker", unclean, nil, "unclean marker"}, |
| + {"own expired", leaseBody(mine, time.Now().Add(-time.Hour)), nil, "same-box takeover"}, |
| + {"terminated holder", leaseBody(other, time.Now().Add(-time.Hour)), nil, "holder terminated"}, |
| + {"lost to a terminated holder", clean, leaseBody(other, time.Now().Add(-time.Hour)), "holder terminated"}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + haBox(t) |
| + logs := captureLog(t) |
| + fx := leasetest.NewLockFixture(t) |
| + if c.body != nil { |
| + fx.PutLock("instances/h", c.body) |
| + } |
| + if c.change != nil { |
| + var once sync.Once |
| + fx.BeforeWrite(func(string, string) { once.Do(func() { fx.PutLock("instances/h", c.change) }) }) |
| + } |
| + h, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, proofs) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer h.Release(ctx) |
| + if want := "(" + c.word + ")"; !strings.Contains(logs.String(), "HA lease acquired in") || !strings.Contains(logs.String(), want) { |
| + t.Fatalf("the acquire's log does not say %s:\n%s", want, logs) |
| + } |
| + }) |
| + } |
| +} |