lease: a holder paused past 30 s gives its lease up unrenewed
G2 drill 2 (2026-11-05): the HA holder's edge was SIGSTOPped and missed its renewal; the group replaced the box. systemd's stop sent SIGTERM and SIGCONT, and the resumed process's overdue ticker renewed the lock before the shutdown reached it, moving expiry 23:47:48Z -> 23:54:40Z. The replacement waited that out: first 200 at t0+1064 s against 825.5 s. The renewer now samples its own liveness (watch, every limit/6) and checkLocked latches ErrPaused (an ErrLost) when the gap since the last sample exceeds 30 s, the load balancer's exclusion bound. Every check makes the test first, the renewal's included, so an overdue tick cannot renew ahead of the sampler. The lock keeps its last live expiry; the takeover rule (proof AND expiry) is unchanged. On at production terms (TTL >= 3 min), off for the short test TTLs. RED/GREEN: TestPausedHolderDoesNotRenewOnResume SIGSTOPs a real child holder past its renewal and resumes it with SIGTERM+SIGCONT; before the fix it renewed 1 ms after SIGCONT. Root-runner witness TestRootPausedHolderStopWitness does the same at the production TTL against real S3 under a systemd unit stopped by systemctl stop.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+541
−10
internal/lease/health.go+99 −10internal/lease/pause_rootrunner_linux_test.go+181 −0internal/lease/pause_test.go+89 −0internal/lease/pause_unix_test.go+172 −0
diff --git a/internal/lease/health.go b/internal/lease/health.go| index 4b3b9193a..284252c96 100644 |
| --- a/internal/lease/health.go |
| +++ b/internal/lease/health.go |
| @@ -3,6 +3,8 @@ package lease |
| import ( |
| "context" |
| "errors" |
| + "fmt" |
| + "log" |
| "sync" |
| "time" |
| @@ -14,8 +16,51 @@ var ( |
| ErrLost = errors.New("lease safety deadline elapsed") |
| ErrSpent = errors.New("lease handle is spent") |
| ErrBusy = errors.New("lease operation already running") |
| + // ErrPaused is ErrLost (errors.Is) reached early: the process went |
| + // longer than the pause limit without running, so it renews no more. |
| + ErrPaused = fmt.Errorf("lease given up, this process was paused for longer than the pause limit: %w", ErrLost) |
| ) |
| +// pauseLimit is how long a holder may go without running before it gives |
| +// its lease up instead of renewing it. G2 drill 2 (2026-11-05) is why: the |
| +// holder's edge was SIGSTOPped, missed its renewal, and the load balancer |
| +// and the group replaced the box. systemd's stop sends SIGTERM and then |
| +// SIGCONT, and the moment the process ran again its overdue renewal fired, |
| +// before the shutdown reached the lease. The lock's expiry moved a whole |
| +// TTL past the bound the takeover is planned around, and the replacement |
| +// waited it out. The conditional write kept a single writer; it was the |
| +// outage that grew. |
| +// |
| +// A renewal is a claim that the holder is alive. After a pause that claim |
| +// is stale: the box has been out of the load balancer for most of it (its |
| +// health checks fail within about 30 s) and is presumed to be being |
| +// replaced. So the renewer samples its own liveness (watch, below) and |
| +// latches ErrPaused when the gap since the last sample exceeds this limit. |
| +// The lock keeps the expiry its last live renewal wrote, so a takeover |
| +// (proof AND expiry, unchanged) waits no longer than it would for a hard |
| +// crash at the moment the pause began. |
| +// |
| +// 30 s is the load balancer's exclusion bound. A healthy process never |
| +// goes that long without a timer running; a holder that does is not |
| +// serving anyway, and standing down costs it a re-wake on its next |
| +// request. |
| +const pauseLimit = 30 * time.Second |
| + |
| +// pauseLimitForTTL is the pause limit for a lease of term ttl: pauseLimit |
| +// at production terms, off (0) below six of them, where only tests run |
| +// (their short TTLs would make a scheduling hiccup on a loaded CI worker |
| +// look like a pause). Tests that want pause detection set their own. |
| +func pauseLimitForTTL(ttl time.Duration) time.Duration { |
| + if ttl < 6*pauseLimit { |
| + return 0 |
| + } |
| + return pauseLimit |
| +} |
| + |
| +// pauseLimitFor is pauseLimitForTTL; a test seam for the child process |
| +// TestPausedHolderDoesNotRenewOnResume runs, which has a short TTL. |
| +var pauseLimitFor = pauseLimitForTTL |
| + |
| const terminationMargin = 5 * time.Second |
| // RenewMargin is the margin Held.SafeUntil subtracts from the lease's |
| @@ -33,13 +78,18 @@ func marginForTTL(ttl time.Duration) time.Duration { |
| } |
| type renewer struct { |
| - ctx context.Context |
| - leaser *lss3.Leaser |
| - mu sync.Mutex |
| - lease *litestream.Lease |
| - err error |
| - until time.Time |
| - margin time.Duration |
| + ctx context.Context |
| + leaser *lss3.Leaser |
| + mu sync.Mutex |
| + lease *litestream.Lease |
| + err error |
| + until time.Time |
| + margin time.Duration |
| + // pause is the pause limit (0 = off) and seen the last time this |
| + // process was observed running (checkLocked); watch samples at least |
| + // every pause/pauseSamples while pause is on. |
| + pause time.Duration |
| + seen time.Time |
| stopped bool |
| cancel context.CancelFunc |
| done chan struct{} |
| @@ -48,9 +98,17 @@ type renewer struct { |
| lost chan struct{} |
| } |
| +// pauseSamples is how many liveness samples watch takes per pause limit. |
| +const pauseSamples = 6 |
| + |
| func startRenewer(leaser *lss3.Leaser, lease *litestream.Lease, started time.Time, margin time.Duration) *renewer { |
| + return startRenewerPause(leaser, lease, started, margin, pauseLimitFor(leaser.TTL)) |
| +} |
| + |
| +// startRenewerPause is startRenewer with the pause limit given (0 = off). |
| +func startRenewerPause(leaser *lss3.Leaser, lease *litestream.Lease, started time.Time, margin, pause time.Duration) *renewer { |
| ctx, cancel := context.WithCancel(context.Background()) |
| - rn := &renewer{ctx: ctx, leaser: leaser, lease: lease, until: started.Add(leaser.TTL - margin), margin: margin, cancel: cancel, done: make(chan struct{}), watchDone: make(chan struct{}), changed: make(chan struct{}, 1), lost: make(chan struct{})} |
| + rn := &renewer{ctx: ctx, leaser: leaser, lease: lease, until: started.Add(leaser.TTL - margin), margin: margin, pause: pause, seen: time.Now(), cancel: cancel, done: make(chan struct{}), watchDone: make(chan struct{}), changed: make(chan struct{}, 1), lost: make(chan struct{})} |
| go rn.watch(ctx) |
| go rn.renew(ctx) |
| return rn |
| @@ -72,11 +130,33 @@ func (rn *renewer) checkLocked() error { |
| if rn.stopped { |
| return ErrSpent |
| } |
| - if !time.Now().Before(rn.until) { |
| + now := time.Now() |
| + // The pause check comes first and every caller makes it, the renewal |
| + // included: after a resume, whichever goroutine runs first finds the |
| + // gap, so an overdue tick cannot renew ahead of the sampler. Only a |
| + // check that finds no gap counts as a new sample. |
| + if rn.pause > 0 && now.Sub(rn.seen) > rn.pause { |
| + log.Printf("lease: %s: this process did not run for %s (pause limit %s): giving the lease up unrenewed; it expires %s", rn.leaser.Path, |
| + now.Sub(rn.seen).Round(time.Millisecond), rn.pause, rn.expiresLocked()) |
| + rn.loseLocked(ErrPaused) |
| + return rn.err |
| + } |
| + if !now.Before(rn.until) { |
| rn.loseLocked(ErrLost) |
| } |
| + if rn.err == nil { |
| + rn.seen = now |
| + } |
| return rn.err |
| } |
| + |
| +// expiresLocked names the expiry the lock keeps, for the journal. |
| +func (rn *renewer) expiresLocked() string { |
| + if rn.lease == nil || rn.lease.ExpiresAt.IsZero() { |
| + return "at its last renewal's expiry" |
| + } |
| + return "at " + rn.lease.ExpiresAt.UTC().Format(time.RFC3339) |
| +} |
| func (rn *renewer) Err() error { |
| rn.mu.Lock() |
| defer rn.mu.Unlock() |
| @@ -98,7 +178,11 @@ func (rn *renewer) watch(ctx context.Context) { |
| rn.cancel() |
| return |
| } |
| - timer := time.NewTimer(time.Until(until)) |
| + wait := time.Until(until) |
| + if sample := rn.pause / pauseSamples; rn.pause > 0 && wait > sample { |
| + wait = sample |
| + } |
| + timer := time.NewTimer(wait) |
| select { |
| case <-ctx.Done(): |
| timer.Stop() |
| @@ -130,6 +214,11 @@ func (rn *renewer) renew(ctx context.Context) { |
| rn.cancel() |
| return |
| } |
| + // The check above refused a paused process. A pause landing |
| + // between it and RenewLease does no harm: RenewLease stamps |
| + // ExpiresAt from time.Now() before it sends, so a renewal held |
| + // up by a pause carries a pre-pause expiry, and the check after |
| + // it latches the loss. |
| started := time.Now() |
| renewed, err := rn.leaser.RenewLease(ctx, cur) |
| rn.mu.Lock() |
diff --git a/internal/lease/pause_rootrunner_linux_test.go b/internal/lease/pause_rootrunner_linux_test.go| new file mode 100644 |
| index 000000000..ded42decf |
| --- /dev/null |
| +++ b/internal/lease/pause_rootrunner_linux_test.go |
| @@ -0,0 +1,181 @@ |
| +//go:build linux && rootrunner |
| + |
| +package lease |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "os" |
| + "os/exec" |
| + "os/signal" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/config" |
| + s3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/benbjohnson/litestream" |
| +) |
| + |
| +// The root runner's role may Get and Put under this prefix and nothing |
| +// else, so the witness's lock object is left in place (one small object |
| +// per run, under the runner's own prefix). |
| +const ( |
| + witnessBucket = "carlos-dev-640012953448" |
| + witnessRegion = "eu-west-1" |
| + witnessChild = "CARLOS_LEASE_PAUSE_WITNESS_PREFIX" |
| +) |
| + |
| +// TestRootPausedHolderStopWitness replays G2 drill 2 with production |
| +// wiring: the production AcquireTTL at the production LeaseTTL and pause |
| +// limit, against real S3, in a real systemd unit. The holder is SIGSTOPped |
| +// right after it acquires, kept stopped past its first renewal (TTL/3) |
| +// but well inside its safe deadline, and then stopped by `systemctl stop`, |
| +// which sends SIGTERM and SIGCONT exactly as the box's shutdown did. The |
| +// holder must not renew on resume: the lock object in S3 keeps the ETag |
| +// and expiry its acquire wrote, and the holder's own journal says it gave |
| +// the lease up as paused. |
| +func TestRootPausedHolderStopWitness(t *testing.T) { |
| + if prefix := os.Getenv(witnessChild); prefix != "" { |
| + pausedWitnessChild(prefix) |
| + return |
| + } |
| + if os.Geteuid() != 0 { |
| + t.Fatal("the witness needs root (systemd-run)") |
| + } |
| + if pauseLimitFor(LeaseTTL) != pauseLimit || pauseLimit >= LeaseTTL/3 { |
| + t.Fatalf("production pause limit %s against renewal every %s: the witness assumes a limit shorter than the renewal interval", pauseLimitFor(LeaseTTL), LeaseTTL/3) |
| + } |
| + self, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var b [6]byte |
| + rand.Read(b[:]) |
| + run := hex.EncodeToString(b[:]) |
| + prefix := "root-runner/lease-pause-witness/" + run |
| + unit := "carlos-lease-pause-witness-" + run |
| + ctx := context.Background() |
| + cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(witnessRegion)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + client := s3.NewFromConfig(cfg) |
| + readLock := func() (string, litestream.Lease) { |
| + t.Helper() |
| + out, err := client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(witnessBucket), Key: aws.String(prefix + "/lock.json")}) |
| + if err != nil { |
| + t.Fatalf("read the lock: %v", err) |
| + } |
| + defer out.Body.Close() |
| + raw, _ := io.ReadAll(out.Body) |
| + var l litestream.Lease |
| + if err := json.Unmarshal(raw, &l); err != nil { |
| + t.Fatalf("lock body %q: %v", raw, err) |
| + } |
| + return aws.ToString(out.ETag), l |
| + } |
| + |
| + start := exec.Command("systemd-run", "--unit="+unit, "--collect", "--quiet", |
| + "--setenv="+witnessChild+"="+prefix, |
| + self, "-test.run=^TestRootPausedHolderStopWitness$", "-test.v") |
| + if out, err := start.CombinedOutput(); err != nil { |
| + t.Fatalf("systemd-run: %v: %s", err, out) |
| + } |
| + defer exec.Command("systemctl", "kill", "--signal=SIGKILL", unit).Run() |
| + journal := func() string { |
| + out, _ := exec.Command("journalctl", "-u", unit, "-o", "cat", "--no-pager").CombinedOutput() |
| + return string(out) |
| + } |
| + mainPID := func() int { |
| + out, err := exec.Command("systemctl", "show", "-P", "MainPID", unit).Output() |
| + if err != nil { |
| + t.Fatalf("MainPID: %v", err) |
| + } |
| + var pid int |
| + fmt.Sscanf(strings.TrimSpace(string(out)), "%d", &pid) |
| + return pid |
| + } |
| + waitFor := func(what string, limit time.Duration) { |
| + t.Helper() |
| + for deadline := time.Now().Add(limit); !strings.Contains(journal(), what); time.Sleep(200 * time.Millisecond) { |
| + if time.Now().After(deadline) { |
| + t.Fatalf("no %q in the unit's journal:\n%s", what, journal()) |
| + } |
| + } |
| + } |
| + waitFor("witness held", time.Minute) |
| + pid := mainPID() |
| + if err := syscall.Kill(pid, syscall.SIGSTOP); err != nil { |
| + t.Fatal(err) |
| + } |
| + stoppedAt := time.Now() |
| + etag0, lock0 := readLock() |
| + t.Logf("held: pid %d, lock etag %s, expires %s; stopped at %s", pid, etag0, lock0.ExpiresAt.UTC().Format(time.RFC3339Nano), stoppedAt.UTC().Format(time.RFC3339)) |
| + // Past the first renewal (TTL/3 after the acquire), well inside the |
| + // safe deadline (TTL - margin): drill 2 was 112 s overdue. |
| + hold := LeaseTTL/3 + 60*time.Second |
| + time.Sleep(hold) |
| + if e, _ := readLock(); e != etag0 { |
| + t.Fatal("the lock changed while the holder was stopped") |
| + } |
| + stop := exec.Command("systemctl", "stop", unit) |
| + resumedAt := time.Now() |
| + if out, err := stop.CombinedOutput(); err != nil { |
| + t.Fatalf("systemctl stop: %v: %s", err, out) |
| + } |
| + t.Logf("systemctl stop returned after %s", time.Since(resumedAt).Round(time.Millisecond)) |
| + j := journal() |
| + t.Logf("unit journal:\n%s", j) |
| + etag1, lock1 := readLock() |
| + if etag1 != etag0 || !lock1.ExpiresAt.Equal(lock0.ExpiresAt) { |
| + t.Fatalf("the resumed holder renewed: etag %s -> %s, expiry %s -> %s", etag0, etag1, |
| + lock0.ExpiresAt.UTC().Format(time.RFC3339Nano), lock1.ExpiresAt.UTC().Format(time.RFC3339Nano)) |
| + } |
| + for _, want := range []string{ |
| + "giving the lease up unrenewed", |
| + "witness SIGTERM", |
| + "witness verdict lost=true paused=true", |
| + } { |
| + if !strings.Contains(j, want) { |
| + t.Fatalf("the unit's journal has no %q", want) |
| + } |
| + } |
| + t.Logf("PASS: stopped %s (renewal due after %s, pause limit %s); no renewal after SIGTERM+SIGCONT; lock expiry unchanged at %s", |
| + resumedAt.Sub(stoppedAt).Round(time.Second), LeaseTTL/3, pauseLimit, lock1.ExpiresAt.UTC().Format(time.RFC3339Nano)) |
| +} |
| + |
| +// pausedWitnessChild holds the lease in the unit and reports, on SIGTERM, |
| +// what its handle says. It never releases: the parent reads the lock the |
| +// stop left behind. |
| +func pausedWitnessChild(prefix string) { |
| + term := make(chan os.Signal, 1) |
| + signal.Notify(term, syscall.SIGTERM) |
| + h, err := Acquire(context.Background(), witnessBucket, prefix, witnessRegion) |
| + if err != nil { |
| + fmt.Println("witness acquire failed:", err) |
| + os.Exit(1) |
| + } |
| + fmt.Println("witness held") |
| + <-term |
| + fmt.Println("witness SIGTERM") |
| + // The edge's shutdown takes this long and more before it reaches a |
| + // lease; the renewer must already have stood down. |
| + time.Sleep(2 * time.Second) |
| + err = h.Err() |
| + lost := false |
| + select { |
| + case <-h.Lost(): |
| + lost = true |
| + default: |
| + } |
| + fmt.Printf("witness verdict lost=%t paused=%t err=%v\n", lost, errors.Is(err, ErrPaused), err) |
| + os.Exit(0) |
| +} |
diff --git a/internal/lease/pause_test.go b/internal/lease/pause_test.go| new file mode 100644 |
| index 000000000..383b65436 |
| --- /dev/null |
| +++ b/internal/lease/pause_test.go |
| @@ -0,0 +1,89 @@ |
| +package lease |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "testing" |
| + "time" |
| + |
| + lss3 "github.com/benbjohnson/litestream/s3" |
| +) |
| + |
| +func TestPauseLimitForTTL(t *testing.T) { |
| + for _, c := range []struct { |
| + ttl, want time.Duration |
| + }{ |
| + {LeaseTTL, pauseLimit}, |
| + {45 * time.Minute, pauseLimit}, // the moves staging term |
| + {time.Hour, pauseLimit}, |
| + {3 * time.Minute, pauseLimit}, |
| + {3*time.Minute - time.Nanosecond, 0}, |
| + {3 * time.Second, 0}, |
| + } { |
| + if got := pauseLimitForTTL(c.ttl); got != c.want { |
| + t.Errorf("pauseLimitForTTL(%s) = %s, want %s", c.ttl, got, c.want) |
| + } |
| + } |
| + if pauseLimit != 30*time.Second { |
| + t.Fatalf("pause limit %s: the load balancer's 30 s exclusion bound is the reasoning; change both together", pauseLimit) |
| + } |
| +} |
| + |
| +func pauseRenewer(t *testing.T, backend *lockStore, ttl, pause time.Duration) *renewer { |
| + t.Helper() |
| + leaser := lss3.NewLeaser() |
| + leaser.SetClient(backend) |
| + leaser.TTL = ttl |
| + started := time.Now() |
| + lock, e := leaser.AcquireLease(context.Background()) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + rn := startRenewerPause(leaser, lock, started, ttl/10, pause) |
| + t.Cleanup(func() { leaser.ReleaseLease(context.Background(), rn.stop()) }) |
| + return rn |
| +} |
| + |
| +// A gap since the last liveness sample longer than the limit latches |
| +// ErrPaused (which is ErrLost) at the next check, whoever makes it, and |
| +// no renewal follows. The gap is made by moving the last sample back, |
| +// which is what a stopped process sees on resume. |
| +func TestPauseGapLatchesLossWithoutRenewing(t *testing.T) { |
| + backend := &lockStore{} |
| + rn := pauseRenewer(t, backend, 3*time.Second, 300*time.Millisecond) |
| + puts, _ := backend.counts() |
| + rn.mu.Lock() |
| + rn.seen = time.Now().Add(-time.Second) |
| + rn.mu.Unlock() |
| + err := rn.Err() |
| + if !errors.Is(err, ErrPaused) || !errors.Is(err, ErrLost) { |
| + t.Fatalf("a gap past the pause limit: %v, want ErrPaused (an ErrLost)", err) |
| + } |
| + await(t, rn.lost) |
| + await(t, rn.done) |
| + // A full renewal interval later, still nothing written. |
| + time.Sleep(time.Second + 100*time.Millisecond) |
| + if now, _ := backend.counts(); now != puts { |
| + t.Fatalf("%d renewal(s) after the pause latched", now-puts) |
| + } |
| + if _, e := rn.SafeUntil(); !errors.Is(e, ErrPaused) { |
| + t.Fatalf("SafeUntil after the pause: %v", e) |
| + } |
| +} |
| + |
| +// With the limit on, a holder that keeps running keeps renewing. The |
| +// limit here is shorter than the renewal interval, as in production (30 s |
| +// against 5 min), so the renewal's own checks cannot keep the holder |
| +// alive: only watch's sampling between renewals does. |
| +func TestPauseLimitKeepsAHealthyHolder(t *testing.T) { |
| + backend := &lockStore{} |
| + rn := pauseRenewer(t, backend, 3*time.Second, 600*time.Millisecond) |
| + start, _ := backend.counts() |
| + time.Sleep(2500 * time.Millisecond) // two and a half renewal intervals |
| + if e := rn.Err(); e != nil { |
| + t.Fatalf("healthy holder lost its lease: %v", e) |
| + } |
| + if now, _ := backend.counts(); now-start < 2 { |
| + t.Fatalf("only %d renewal(s) in two and a half intervals", now-start) |
| + } |
| +} |
diff --git a/internal/lease/pause_unix_test.go b/internal/lease/pause_unix_test.go| new file mode 100644 |
| index 000000000..c30ed9ed0 |
| --- /dev/null |
| +++ b/internal/lease/pause_unix_test.go |
| @@ -0,0 +1,172 @@ |
| +//go:build unix |
| + |
| +package lease |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http/httptest" |
| + "os" |
| + "os/exec" |
| + "os/signal" |
| + "strings" |
| + "sync" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + s3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| +) |
| + |
| +// pauseHelperEnv carries the fake store's URL to the child process |
| +// TestPausedHolderDoesNotRenewOnResume re-executes this test binary as. |
| +const pauseHelperEnv = "CARLOS_LEASE_PAUSE_HELPER" |
| + |
| +// TestPausedHolderDoesNotRenewOnResume is G2 drill 2 in one test binary |
| +// (2026-11-05): a holder whose process is SIGSTOPped past its renewal |
| +// time, then sent SIGTERM and SIGCONT together (what systemd's stop does |
| +// to a stopped unit), must not renew on resume. Before the fix the |
| +// overdue ticker fired the moment the process ran again and the PUT |
| +// pushed the lock's expiry a whole TTL past the outage bound. |
| +// |
| +// The holder runs in a child process so the kernel really stops it: no |
| +// goroutine of the renewer can run while it is stopped, exactly as on the |
| +// box. The fake S3 store lives in this process and records every renewal |
| +// (If-Match PUT) with the time it landed. |
| +func TestPausedHolderDoesNotRenewOnResume(t *testing.T) { |
| + if url := os.Getenv(pauseHelperEnv); url != "" { |
| + pausedHolderChild(url) |
| + return |
| + } |
| + var mu sync.Mutex |
| + var renewals []time.Time |
| + backend := &lockStore{beforePut: func(ctx context.Context, p *s3.PutObjectInput) error { |
| + if p.IfMatch != nil { |
| + mu.Lock() |
| + renewals = append(renewals, time.Now()) |
| + mu.Unlock() |
| + } |
| + return nil |
| + }} |
| + srv := httptest.NewServer(backend) |
| + defer srv.Close() |
| + |
| + cmd := exec.Command(os.Args[0], "-test.run=^TestPausedHolderDoesNotRenewOnResume$") |
| + cmd.Env = append(os.Environ(), pauseHelperEnv+"="+srv.URL) |
| + cmd.Stderr = os.Stderr |
| + out, err := cmd.StdoutPipe() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := cmd.Start(); err != nil { |
| + t.Fatal(err) |
| + } |
| + defer cmd.Process.Kill() |
| + lines := make(chan string, 16) |
| + go func() { |
| + sc := bufio.NewScanner(out) |
| + for sc.Scan() { |
| + lines <- sc.Text() |
| + } |
| + close(lines) |
| + }() |
| + expect := func(prefix string) string { |
| + t.Helper() |
| + for { |
| + select { |
| + case l, ok := <-lines: |
| + if !ok { |
| + t.Fatalf("child exited before %q", prefix) |
| + } |
| + if strings.HasPrefix(l, prefix) { |
| + return l |
| + } |
| + case <-time.After(10 * time.Second): |
| + t.Fatalf("timed out waiting for %q", prefix) |
| + } |
| + } |
| + } |
| + expect("held") |
| + renewalCount := func() int { mu.Lock(); defer mu.Unlock(); return len(renewals) } |
| + // Stop the holder just after a renewal, so its next one falls due |
| + // while it is stopped. |
| + for deadline := time.Now().Add(5 * time.Second); renewalCount() == 0; { |
| + if time.Now().After(deadline) { |
| + t.Fatal("the holder never renewed before the pause") |
| + } |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| + if err := cmd.Process.Signal(syscall.SIGSTOP); err != nil { |
| + t.Fatal(err) |
| + } |
| + stoppedAt := time.Now() |
| + before := renewalCount() |
| + // pauseChildTTL/3 is the renewal interval: stopped for 1.5 of them, |
| + // the next renewal is overdue at resume while the lease is still valid |
| + // (well inside SafeUntil), which is drill 2's shape. |
| + time.Sleep(pauseChildTTL / 2) |
| + _ = cmd.Process.Signal(syscall.SIGTERM) |
| + if err := cmd.Process.Signal(syscall.SIGCONT); err != nil { |
| + t.Fatal(err) |
| + } |
| + resumedAt := time.Now() |
| + if renewalCount() != before { |
| + t.Fatal("a renewal landed while the holder was stopped") |
| + } |
| + verdict := expect("verdict") |
| + // One full renewal interval after resume: long enough for an overdue |
| + // tick and the next scheduled one. |
| + time.Sleep(pauseChildTTL/3 + 100*time.Millisecond) |
| + mu.Lock() |
| + after := append([]time.Time(nil), renewals[before:]...) |
| + mu.Unlock() |
| + t.Logf("stopped %s; %s", resumedAt.Sub(stoppedAt).Round(time.Millisecond), verdict) |
| + if len(after) != 0 { |
| + t.Fatalf("the resumed holder renewed %d time(s), first %s after SIGCONT: a paused holder extended its lease", len(after), after[0].Sub(resumedAt).Round(time.Millisecond)) |
| + } |
| + if !strings.Contains(verdict, "lost=true") || !strings.Contains(verdict, "paused=true") { |
| + t.Fatalf("the resumed holder did not stand down as paused: %s", verdict) |
| + } |
| +} |
| + |
| +// pauseChildTTL is short so the test runs in seconds; pauseChildLimit is |
| +// the pause the child tolerates, well under the 0.5 TTL stop above. |
| +const ( |
| + pauseChildTTL = 3 * time.Second |
| + pauseChildLimit = 400 * time.Millisecond |
| +) |
| + |
| +// pausedHolderChild is the child: it holds a lease through the production |
| +// AcquireTTL against the parent's store, then reports what its handle |
| +// says once SIGTERM arrives (delivered with the SIGCONT that resumes it). |
| +func pausedHolderChild(url string) { |
| + os.Setenv("AWS_ACCESS_KEY_ID", "test-key") |
| + os.Setenv("AWS_SECRET_ACCESS_KEY", "test-secret") |
| + os.Setenv("AWS_EC2_METADATA_DISABLED", "true") |
| + os.Setenv("CARLOS_S3_ENDPOINT", url) |
| + pauseLimitFor = func(time.Duration) time.Duration { return pauseChildLimit } |
| + term := make(chan os.Signal, 1) |
| + signal.Notify(term, syscall.SIGTERM) |
| + h, err := AcquireTTL(context.Background(), "test-bucket", "one.example", "test-region", pauseChildTTL) |
| + if err != nil { |
| + fmt.Println("error", err) |
| + os.Exit(1) |
| + } |
| + fmt.Println("held") |
| + <-term |
| + // A shutdown takes a moment before it reaches the lease; the renewer |
| + // must already have stood down by then, without help from the signal. |
| + time.Sleep(50 * time.Millisecond) |
| + err = h.Err() |
| + lost := false |
| + select { |
| + case <-h.Lost(): |
| + lost = true |
| + default: |
| + } |
| + fmt.Printf("verdict lost=%t paused=%t err=%v\n", lost, errors.Is(err, ErrPaused), err) |
| + // Stay up (as a draining edge would) until the parent kills us. |
| + time.Sleep(time.Minute) |
| +} |