carlos / platform Public

region HA: the two-box planned handover witness against MinIO

Two real activators (ExecBackend, the HA lease, litestream and the files
store against MinIO) and three real edges in one process. The drain is
the production verb over the drain socket and the real driver; A's start
gate is the group admission reading the verb's fence.

TestHeldHandoverTwoBoxMinio: the drain moves an awake HA host from A to B
through BeginMove, the stop and its clean marker, the take and
SetMoveTaken. A direct request and a replayable hop POST (48 KiB) that
cross the move are delivered once on B; a hop with an unknown-length body
gets 503 Retry-After: 10 at once; a non-HA host is released, never taken.
The report is ok and the store calls of the drain are counted and bounded.
After the drain the fence refuses a start on A; drain --cancel lifts it.

TestHeldHandoverLostLeaseMinio: the store refuses A's marker mid-move; a
later request gets F-A's 503 at once, the held one today's answer, and B
starts nothing.

Both skip without CARLOS_MINIO_TEST; .amadan/ci.d/30-minio-contract runs
them as the scoped user and requires both PASS lines.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 9ec7c79c8004c6b4d0d56af2a29adf41c0b739af parent 1a1c585
2 files changed, +1,282 −0
  • .amadan/ci.d/30-minio-contract +32 −0
  • internal/host/hadrain_twobox_minio_linux_test.go +1,250 −0
diff --git a/.amadan/ci.d/30-minio-contract b/.amadan/ci.d/30-minio-contract
index 119ce0034..b2e70769c 100755
--- a/.amadan/ci.d/30-minio-contract
+++ b/.amadan/ci.d/30-minio-contract
@@ -480,4 +480,36 @@ if ! grep -q '^--- PASS: TestDBForwardMinio (' "$out4"; then
exit 1
fi
+# The planned handover witnesses (region HA §25.10, held-requests Task 8):
+# two real activators and three real edges in one process, the HA lease,
+# litestream replication and the files store against this MinIO, as the
+# scoped user over the same bucket. Each run uses its own key prefix and
+# host names. TMPDIR is short because the instances' unix sockets live
+# beneath it. Same rule as above: both PASS lines must appear, because the
+# tests skip without CARLOS_MINIO_TEST.
+out5=$rundir/test-handover.log
+mkdir -p "$rundir/g"
+set +e
+CARLOS_MINIO_TEST=1 TMPDIR="$rundir/g" \
+ MINIO_ENDPOINT="http://127.0.0.1:$port" \
+ MINIO_SCOPED_KEY=scopeduser \
+ MINIO_SCOPED_SECRET=scopedsecret1 \
+ MINIO_BUCKET=contract-bucket \
+ go test ./internal/host/ -run 'TestHeldHandover.*Minio' -count=1 -v >"$out5" 2>&1
+test_status=$?
+set -e
+cat "$out5"
+if [ "$test_status" -ne 0 ]; then
+ exit "$test_status"
+fi
+for name in TestHeldHandoverTwoBoxMinio TestHeldHandoverLostLeaseMinio; do
+ if ! grep -q "^--- PASS: $name (" "$out5"; then
+ echo >&2
+ echo "the handover witness $name did not PASS: it was skipped, filtered out, or renamed." >&2
+ echo "It skips unless CARLOS_MINIO_TEST=1. Check the env block above and that" >&2
+ echo "$name still exists in internal/host." >&2
+ exit 1
+ fi
+done
+
echo "minio contract: PASS"
diff --git a/internal/host/hadrain_twobox_minio_linux_test.go b/internal/host/hadrain_twobox_minio_linux_test.go
new file mode 100644
index 000000000..35230db28
--- /dev/null
+++ b/internal/host/hadrain_twobox_minio_linux_test.go
@@ -0,0 +1,1250 @@
+//go:build linux
+
+package host
+
+import (
+ "bytes"
+ "context"
+ "crypto/ecdh"
+ "crypto/ecdsa"
+ "crypto/ed25519"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/tls"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "database/sql"
+ "encoding/hex"
+ "encoding/json"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "io"
+ "math/big"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httputil"
+ "net/url"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+ "unsafe"
+
+ "golang.org/x/crypto/acme/autocert"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/groupadmission"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The planned handover end to end (region HA §25.10's integration witness,
+// Task 8 of the held-requests plan). Three boxes in one process, each a
+// real Edge behind its own TLS listener on a loopback address, over one
+// deployment store:
+//
+// - annie (A) and betty (B) serve the HA pool: each has a real
+// activator.Service over a real ExecBackend, whose HA lease is the
+// production lease against a real S3 server (MinIO), with litestream
+// replication, the files store and the escrow key;
+// - carol (C) serves another pool and only forwards: a first box.
+//
+// The drain is the production one: the group-maintenance drain verb over
+// the real drain socket, the drain driver (hadrain.go), A's drain state
+// published through the real edges-file writer, acknowledgements over the
+// signed control path, BeginMove, the stop and its marker, the signed take
+// to B, B's DecideAcquire over A's marker and restore of A's replica,
+// SetMoveTaken, drained, and the connection drain. A's start gate is the
+// real group admission reading the fence the verb installs.
+//
+// What is modelled: the HA acquire's identity is the process's one
+// (lease.SetSelf), so the test sets it to the box that acquires next;
+// root's control channel (a unit "starts" by binding the
+// app's socket in-process; it is the instance-control seam the activator
+// tests use), the unit and cgroup observers behind their seams, and the
+// app itself, which records every request it sees. The drain driver is
+// handed the real Service behind an observer that only records the calls
+// and signals the test; every call goes through.
+//
+// It runs only against a real MinIO (CARLOS_MINIO_TEST=1 and the MINIO_*
+// variables), which .amadan/ci.d/30-minio-contract stands up in CI.
+
+//go:linkname drainWitnessBackhaulPort github.com/carlosframework/platform/internal/edge.backhaulPort
+var drainWitnessBackhaulPort string
+
+const (
+ dwRegion = "us-east-1"
+ dwPool = "ha"
+ dwTxn = "t8-witness"
+ dwAccount = "111122223333"
+)
+
+// dwS3 is the S3 server the lease, replication and files store dial
+// (CARLOS_S3_ENDPOINT): a proxy in front of MinIO that logs every request
+// and can refuse writes to chosen keys.
+type dwS3 struct {
+ mu sync.Mutex
+ log []string
+ refuse func(method, path string) bool
+}
+
+func (s *dwS3) since(n int) []string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return append([]string(nil), s.log[n:]...)
+}
+
+func (s *dwS3) mark() int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return len(s.log)
+}
+
+func (s *dwS3) setRefuse(f func(method, path string) bool) {
+ s.mu.Lock()
+ s.refuse = f
+ s.mu.Unlock()
+}
+
+// dwStore is the deployment store, counting what it is asked.
+type dwStore struct {
+ release.Store
+ mu sync.Mutex
+ ops []string
+}
+
+func (d *dwStore) note(op, key string) {
+ d.mu.Lock()
+ d.ops = append(d.ops, op+" "+key)
+ d.mu.Unlock()
+}
+func (d *dwStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ d.note("GET", key)
+ return d.Store.Get(ctx, key)
+}
+func (d *dwStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ d.note("PUT", key)
+ return d.Store.Put(ctx, key, body, ifMatch)
+}
+func (d *dwStore) List(ctx context.Context, prefix string) ([]string, error) {
+ d.note("LIST", prefix)
+ return d.Store.List(ctx, prefix)
+}
+func (d *dwStore) mark() int {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return len(d.ops)
+}
+func (d *dwStore) since(n int) []string {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return append([]string(nil), d.ops[n:]...)
+}
+
+// dwApp is one host's app on one box: every request it sees, by id.
+type dwApp struct {
+ box string
+ mu sync.Mutex
+ seen []string
+ slow chan struct{}
+ srv *http.Server
+ // entered is signalled when a /slow request is inside the app.
+ entered chan struct{}
+}
+
+func (a *dwApp) handler(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ id := r.Header.Get("X-Witness-Id")
+ if id == "" {
+ id = r.Method + " " + r.URL.Path
+ }
+ a.mu.Lock()
+ a.seen = append(a.seen, id)
+ slow := a.slow
+ a.mu.Unlock()
+ if r.URL.Path == "/slow" && slow != nil {
+ select {
+ case a.entered <- struct{}{}:
+ default:
+ }
+ <-slow
+ }
+ fmt.Fprintf(w, "%s|%s|%d", a.box, id, len(body))
+}
+
+func (a *dwApp) count(id string) int {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ n := 0
+ for _, s := range a.seen {
+ if s == id {
+ n++
+ }
+ }
+ return n
+}
+
+// dwControl is root's instance-control channel for one box: a start binds
+// the host's app on its socket (after the database exists, as a booting
+// app leaves it); a stop closes it.
+type dwControl struct {
+ t *testing.T
+ box *dwBox
+ mu sync.Mutex
+ starts map[string]int
+ units map[string]bool
+}
+
+func (c *dwControl) unitHost(host string) string { return host }
+
+func (c *dwControl) start(host string) (string, error) {
+ c.mu.Lock()
+ c.starts[host]++
+ c.units[host] = true
+ c.mu.Unlock()
+ rt, err := c.box.reg.Get(host)
+ if err != nil || rt == nil {
+ return "", fmt.Errorf("no route for %s", host)
+ }
+ if err := dwEnsureDB(rt.DBPath); err != nil {
+ return "", err
+ }
+ app := c.box.app(host)
+ _ = os.Remove(rt.Socket)
+ if err := os.MkdirAll(filepath.Dir(rt.Socket), 0o755); err != nil {
+ return "", err
+ }
+ ln, err := net.Listen("unix", rt.Socket)
+ if err != nil {
+ return "", err
+ }
+ srv := &http.Server{Handler: http.HandlerFunc(app.handler)}
+ app.mu.Lock()
+ app.srv = srv
+ app.mu.Unlock()
+ go srv.Serve(ln)
+ return "inv-" + host, nil
+}
+
+func (c *dwControl) stop(host string) {
+ c.mu.Lock()
+ c.units[host] = false
+ c.mu.Unlock()
+ app := c.box.app(host)
+ app.mu.Lock()
+ srv := app.srv
+ app.srv = nil
+ app.mu.Unlock()
+ if srv != nil {
+ _ = srv.Close()
+ }
+}
+
+func (c *dwControl) startCount(host string) int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.starts[host]
+}
+
+func (c *dwControl) Start(_ context.Context, host string, _ instancectl.Role, _ int64) (string, error) {
+ return c.start(host)
+}
+func (c *dwControl) StartExe(_ context.Context, host string, _ instancectl.Role, _ int64, _ instancectl.StagedExe) (string, error) {
+ return c.start(host)
+}
+func (c *dwControl) Seed(context.Context, string, int64) (instancectl.SeedResponse, error) {
+ return instancectl.SeedResponse{}, nil
+}
+func (c *dwControl) SeedExe(context.Context, string, int64, instancectl.StagedExe) (instancectl.SeedResponse, error) {
+ return instancectl.SeedResponse{}, nil
+}
+func (c *dwControl) Cmd(context.Context, string, int64) (string, error) {
+ return "", errors.New("no cmd units here")
+}
+func (c *dwControl) CmdStatus(context.Context, string, string) (instancectl.CmdStatus, error) {
+ return instancectl.CmdStatus{}, errors.New("no cmd units here")
+}
+func (c *dwControl) Stop(_ context.Context, host string, _ instancectl.Role) error {
+ c.stop(host)
+ return nil
+}
+func (c *dwControl) Reset(context.Context, string, instancectl.Role) error { return nil }
+func (c *dwControl) Sweep(context.Context) (instancectl.SweepResponse, error) {
+ return instancectl.SweepResponse{}, nil
+}
+func (c *dwControl) Ready(context.Context) error { return nil }
+
+// unitState and cgroupEvents are the observers' seams: a unit is active
+// while its app runs.
+func (c *dwControl) unitState(_ context.Context, unit string) (string, string, error) {
+ unit = strings.ReplaceAll(unit, `\x2d`, "-")
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ for host, up := range c.units {
+ if up && strings.Contains(unit, provision.InstanceID(host)) {
+ return "active", "inv-" + host, nil
+ }
+ }
+ return "inactive", "", nil
+}
+
+func (c *dwControl) cgroupEvents(slice, unit string) (bool, bool, error) {
+ slice, unit = strings.ReplaceAll(slice, `\x2d`, "-"), strings.ReplaceAll(unit, `\x2d`, "-")
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ for host, up := range c.units {
+ if strings.Contains(slice+unit, provision.InstanceID(host)) {
+ return true, up, nil
+ }
+ }
+ return false, false, nil
+}
+
+func dwEnsureDB(path string) error {
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ return err
+ }
+ db, err := sql.Open("sqlite", path)
+ if err != nil {
+ return err
+ }
+ defer db.Close()
+ _, err = db.Exec("create table if not exists t(x)")
+ return err
+}
+
+// dwBox is one box of the scene.
+type dwBox struct {
+ name, ip string
+ self hafresh.Self
+ reg *registry.Registry
+ ctl *dwControl
+ eb *activator.ExecBackend
+ svc *activator.Service
+ e *edge.Edge
+ srv *httptest.Server
+ drain *haDrainState
+ ident edgesFile
+ last []byte
+ pubMu sync.Mutex
+ appsMu sync.Mutex
+ apps map[string]*dwApp
+ client *http.Client
+}
+
+func (x *dwBox) app(host string) *dwApp {
+ x.appsMu.Lock()
+ defer x.appsMu.Unlock()
+ a := x.apps[host]
+ if a == nil {
+ a = &dwApp{box: x.name, entered: make(chan struct{}, 1)}
+ x.apps[host] = a
+ }
+ return a
+}
+
+// dwScene is the deployment.
+type dwScene struct {
+ t *testing.T
+ s3 *dwS3
+ store *dwStore
+ bucket string
+ prefix string
+ host string // the HA host that moves
+ plain string // a host on A that is not HA
+ rec provision.Record
+ plainRec provision.Record
+ escrow *ecdh.PrivateKey
+ roots *x509.CertPool
+ cert tls.Certificate
+ port string
+ a, b, c *dwBox
+}
+
+func dwNeed(t *testing.T, name string) string {
+ t.Helper()
+ v := os.Getenv(name)
+ if v == "" {
+ t.Fatalf("%s is not set", name)
+ }
+ return v
+}
+
+func newDWScene(t *testing.T) *dwScene {
+ t.Helper()
+ if os.Getenv("CARLOS_MINIO_TEST") != "1" {
+ t.Skip("set CARLOS_MINIO_TEST=1 (with a running MinIO and the MINIO_* env vars) to run the two-box handover witness; see .amadan/ci.d/30-minio-contract")
+ }
+ endpoint, key, secret := dwNeed(t, "MINIO_ENDPOINT"), dwNeed(t, "MINIO_SCOPED_KEY"), dwNeed(t, "MINIO_SCOPED_SECRET")
+ s := &dwScene{t: t, s3: &dwS3{}, bucket: dwNeed(t, "MINIO_BUCKET")}
+ var rnd [4]byte
+ if _, err := rand.Read(rnd[:]); err != nil {
+ t.Fatal(err)
+ }
+ tag := hex.EncodeToString(rnd[:])
+ s.prefix = "t8-" + tag
+ s.host = "shop-" + tag + ".example.test"
+ s.plain = "plain-" + tag + ".example.test"
+
+ // The S3 proxy, in front of MinIO. The Host header is passed through
+ // unchanged, so the client's signature (over the proxy's address) is
+ // what MinIO checks.
+ target, err := url.Parse(endpoint)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rp := httputil.NewSingleHostReverseProxy(target)
+ proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ line := r.Method + " " + r.URL.Path
+ if r.URL.RawQuery != "" && r.Method == http.MethodGet && strings.Contains(r.URL.RawQuery, "list-type") {
+ line = "LIST " + r.URL.Path + "?" + r.URL.Query().Get("prefix")
+ }
+ s.s3.mu.Lock()
+ s.s3.log = append(s.s3.log, line)
+ refuse := s.s3.refuse
+ s.s3.mu.Unlock()
+ if refuse != nil && refuse(r.Method, r.URL.Path) {
+ w.Header().Set("Content-Type", "application/xml")
+ w.WriteHeader(http.StatusServiceUnavailable)
+ io.WriteString(w, `<?xml version="1.0" encoding="UTF-8"?><Error><Code>ServiceUnavailable</Code><Message>witness: refused</Message></Error>`)
+ return
+ }
+ rp.ServeHTTP(w, r)
+ }))
+ t.Cleanup(proxy.Close)
+ t.Setenv("AWS_ACCESS_KEY_ID", key)
+ t.Setenv("AWS_SECRET_ACCESS_KEY", secret)
+ t.Setenv("AWS_SESSION_TOKEN", "")
+ t.Setenv("AWS_REGION", dwRegion)
+ t.Setenv("AWS_EC2_METADATA_DISABLED", "true")
+ t.Setenv("AWS_CONFIG_FILE", filepath.Join(t.TempDir(), "absent"))
+ t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(t.TempDir(), "absent"))
+ t.Setenv("CARLOS_S3_ENDPOINT", proxy.URL)
+ t.Setenv("CARLOS_REGION_HA", "true")
+ t.Setenv("CARLOS_RATE_LIMIT", "observe")
+ t.Setenv("CARLOS_POOLS", dwPool)
+
+ t.Cleanup(lease.ProcessStateForTest())
+ if err := lease.SetObligationDir(t.TempDir()); err != nil {
+ t.Fatal(err)
+ }
+
+ s.store = &dwStore{Store: release.NewDirStore(t.TempDir())}
+ if err := edge.MintMeshKey(t.Context(), s.store); err != nil {
+ t.Fatal(err)
+ }
+ s.escrow, err = ecdh.P256().GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ created := time.Date(2026, 11, 9, 9, 0, 0, 0, time.UTC)
+ s.rec = provision.Record{Schema: 1, Host: s.host, App: "shop", Account: domains.Sqid(2), Channel: "stable", CreatedAt: created, HA: true, Pool: dwPool}
+ s.plainRec = provision.Record{Schema: 1, Host: s.plain, App: "plain", Account: domains.Sqid(2), Channel: "stable", CreatedAt: created, Pool: dwPool}
+ s.tls(t)
+
+ s.a = s.box(t, "annie", "127.0.0.21", true)
+ s.b = s.box(t, "betty", "127.0.0.22", true)
+ s.c = s.box(t, "carol", "127.0.0.23", false)
+ for _, x := range []*dwBox{s.a, s.b, s.c} {
+ s.publish(t, x)
+ }
+ for _, x := range []*dwBox{s.a, s.b, s.c} {
+ if x.e.ArmHomeMap() == nil {
+ t.Fatalf("%s: no home map", x.name)
+ }
+ }
+ // A's edges loop: it publishes the drain state when it changes, as
+ // the agent's loop does (edgesFileWriteClaims via the drain source).
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ tick := time.NewTicker(50 * time.Millisecond)
+ defer tick.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-tick.C:
+ if s.a.drain.needsPublish() {
+ s.publish(t, s.a)
+ }
+ }
+ }
+ }()
+ t.Cleanup(func() { cancel(); <-done })
+ return s
+}
+
+// tls makes the scene's CA and one leaf every box presents, publishes the
+// leaf to control/certs/ as the issuer would (every edge's mirror then
+// holds it, which is what names a peer on the control path), and points
+// the edges' backhaul at the scene's port and trust.
+func (s *dwScene) tls(t *testing.T) {
+ t.Helper()
+ caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ca := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "witness CA"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(2 * time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature}
+ caDER, err := x509.CreateCertificate(rand.Reader, ca, ca, &caKey.PublicKey, caKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ caCert, _ := x509.ParseCertificate(caDER)
+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ leaf := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: s.host}, DNSNames: []string{s.host, s.plain}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(2 * time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}
+ leafDER, err := x509.CreateCertificate(rand.Reader, leaf, caCert, &key.PublicKey, caKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ s.cert = tls.Certificate{Certificate: [][]byte{leafDER, caDER}, PrivateKey: key}
+ s.roots = x509.NewCertPool()
+ s.roots.AddCert(caCert)
+ keyDER, err := x509.MarshalECPrivateKey(key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var pemBody bytes.Buffer
+ _ = pem.Encode(&pemBody, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})
+ for _, der := range s.cert.Certificate {
+ _ = pem.Encode(&pemBody, &pem.Block{Type: "CERTIFICATE", Bytes: der})
+ }
+ for _, name := range []string{s.host, s.plain} {
+ if _, err := s.store.Put(t.Context(), "control/certs/"+name, pemBody.Bytes(), ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ oldRoots, oldPort := startupBackhaulRoots, drainWitnessBackhaulPort
+ startupBackhaulRoots = s.roots
+ t.Cleanup(func() { startupBackhaulRoots, drainWitnessBackhaulPort = oldRoots, oldPort })
+}
+
+//go:linkname drainWitnessCertMirror github.com/carlosframework/platform/internal/edge.(*Edge).newCertMirror
+func drainWitnessCertMirror(*edge.Edge, autocert.Cache) unsafe.Pointer
+
+//go:linkname drainWitnessCertRefresh github.com/carlosframework/platform/internal/edge.(*certMirror).Refresh
+func drainWitnessCertRefresh(unsafe.Pointer, context.Context) error
+
+// box builds one box. ha boxes serve the HA pool through a real
+// ExecBackend; the other serves pool "other" and forwards.
+func (s *dwScene) box(t *testing.T, name, ip string, ha bool) *dwBox {
+ t.Helper()
+ x := &dwBox{name: name, ip: ip, apps: map[string]*dwApp{}, drain: newHADrainState()}
+ x.self = hafresh.Self{Ref: name, IID: "i-" + name, Account: dwAccount, Region: dwRegion}
+ root, err := os.MkdirTemp("", "dw")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(root) })
+ x.reg, err = registry.Open(filepath.Join(root, "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { x.reg.Close() })
+ pools := []string{dwPool}
+ if !ha {
+ pools = []string{"other"}
+ }
+ served := (provision.ReconcileConfig{Pools: pools}).ServedPools
+ self := x.self
+ records := map[string]provision.Record{s.host: s.rec, s.plain: s.plainRec}
+ cfg := activator.Config{Bucket: s.bucket, Region: dwRegion, Prefix: s.prefix, Idle: time.Hour,
+ Self: func() hafresh.Self { return self },
+ Record: func(_ context.Context, rt registry.Route) (activator.RecordFacts, error) {
+ rec, ok := records[rt.Host]
+ if !ok {
+ return activator.RecordFacts{}, os.ErrNotExist
+ }
+ return activator.RecordFactsOf(rec)
+ }}
+ x.ctl = &dwControl{t: t, box: x, starts: map[string]int{}, units: map[string]bool{}}
+ b := &activator.ExecBackend{Cfg: cfg, ServedPools: served, Registry: x.reg,
+ OptDir: filepath.Join(root, "opt"), DataDir: filepath.Join(root, "data"), RunDirOverride: filepath.Join(root, "run"),
+ Control: x.ctl, UnitState: x.ctl.unitState, CgroupEvents: x.ctl.cgroupEvents, ObservePoll: 20 * time.Millisecond,
+ StartupSwept: func() bool { return true }, EscrowKey: s.escrow, Lifetimes: &provision.LifetimeIndex{},
+ LeaseIdentity: &self,
+ }
+ b.Lifetimes.Merge(records)
+ if ha {
+ fs, err := lease.NewFilesStore(t.Context(), s.bucket, dwRegion)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b.FilesStore = fs
+ }
+ for _, d := range []string{b.DataDir, filepath.Join(b.OptDir, "live"), filepath.Join(b.OptDir, "versions", "v1")} {
+ if err := os.MkdirAll(d, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ bin := filepath.Join(b.OptDir, "versions", "v1", "app")
+ if err := os.WriteFile(bin, []byte("#!/bin/sh\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ route := func(rec provision.Record) registry.Route {
+ rt := registry.Route{Host: rec.Host, Kind: "instance", Hibernate: true, HA: rec.HA, Provisioned: true, Status: "ready",
+ App: rec.App, Account: rec.Account, Pool: rec.Pool,
+ DBPath: provision.NestedDBPath(b.DataDir, rec.Host),
+ Socket: filepath.Join(b.RunDirOverride, "instances", provision.InstanceID(rec.Host), "app.sock")}
+ if !ha {
+ rt.Socket = "/unused"
+ }
+ return rt
+ }
+ hosts := []provision.Record{s.rec}
+ if name == "annie" {
+ hosts = append(hosts, s.plainRec)
+ }
+ for _, rec := range hosts {
+ if err := x.reg.Upsert(route(rec)); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(bin, filepath.Join(b.OptDir, "live", rec.Host)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ x.eb = b
+ x.svc = activator.New(cfg, b, x.reg)
+ t.Cleanup(func() {
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ x.svc.Shutdown(ctx)
+ })
+ x.e, err = edge.New(x.reg, x.svc)
+ if err != nil {
+ t.Fatal(err)
+ }
+ edge.WithBoxLabel(name)(x.e)
+ x.e.EnableStatic(s.store, ed25519.NewKeyFromSeed(make([]byte, 32)).Public().(ed25519.PublicKey), "")
+ // The cert mirror, armed as RunWithActivatorReady arms it, with one
+ // synchronous refresh.
+ if m := drainWitnessCertMirror(x.e, autocert.DirCache(filepath.Join(root, "certs"))); m == nil {
+ t.Fatalf("%s: no cert mirror", name)
+ } else if err := drainWitnessCertRefresh(m, t.Context()); err != nil {
+ t.Fatalf("%s: cert mirror: %v", name, err)
+ }
+ // The HA ingress projection (haingress.go), fed the HA row as the
+ // records pass would publish it.
+ ingress := &haIngressProjection{}
+ if row, err := x.reg.Get(s.host); err != nil || row == nil {
+ t.Fatalf("%s: no HA row: %v", name, err)
+ } else {
+ ingress.publish(map[string]registry.Route{s.host: *row}, nil)
+ }
+ x.e.SetHAIngressLookup(ingress.lookup)
+ x.svc.SetHeldWakeHook(x.e.HeldWake)
+ x.svc.SetDrainingSource(x.drain.IsDraining)
+ x.svc.SetPeerDrainView(x.e.PeerDraining)
+ x.e.SetPeerDrainedHook(x.svc.DropHoldersNaming)
+
+ // The TLS listener: every box on its own loopback address, all on one
+ // port, which is the backhaul's.
+ port := s.port
+ if port == "" {
+ port = "0"
+ }
+ ln, err := net.Listen("tcp", net.JoinHostPort(ip, port))
+ if err != nil {
+ t.Skipf("no loopback address %s to listen on: %v", ip, err)
+ }
+ if s.port == "" {
+ _, s.port, _ = net.SplitHostPort(ln.Addr().String())
+ drainWitnessBackhaulPort = s.port
+ }
+ x.srv = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { x.e.ServeHTTP(w, r) }))
+ x.srv.Listener.Close()
+ x.srv.Listener = ln
+ x.srv.TLS = &tls.Config{Certificates: []tls.Certificate{s.cert}}
+ x.srv.StartTLS()
+ t.Cleanup(x.srv.Close)
+ addr := ln.Addr().String()
+ x.client = &http.Client{Timeout: 90 * time.Second, Transport: &http.Transport{
+ DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, network, addr)
+ },
+ TLSClientConfig: &tls.Config{RootCAs: s.roots},
+ }}
+ t.Cleanup(x.client.CloseIdleConnections)
+
+ yes, no := true, false
+ x.ident = edgesFile{ServedPools: served(), Box: name, Region: dwRegion, Placement: "ie", DataBucket: s.bucket, SecretsKeyFP: "shared",
+ HibernationConfigured: true, Capabilities: []string{capRegionHA1}, BoxRole: "serve", Admitted: &yes, Drained: &no,
+ Headroom: &edgeHeadroom{MemFreeMiB: 3000, MemTotalMiB: 4000, DiskFreeMiB: 3000, DiskTotalMiB: 4000}}
+ if name == "annie" {
+ // The roomiest, so the first wake is placed on A.
+ x.ident.Headroom = &edgeHeadroom{MemFreeMiB: 3900, MemTotalMiB: 4000, DiskFreeMiB: 3900, DiskTotalMiB: 4000}
+ }
+ return x
+}
+
+// publish writes x's edges file through the real writer, carrying its
+// drain state as the edges loop does.
+func (s *dwScene) publish(t *testing.T, x *dwBox) {
+ x.pubMu.Lock()
+ defer x.pubMu.Unlock()
+ ident := x.ident
+ ident.Draining, ident.HADrained, ident.HADrain = x.drain.want()
+ ident.DrainSource, ident.DrainPublishRequired = x.drain, x.drain.needsPublish()
+ if err := edgesFileWrite(context.Background(), s.store, x.reg, ident, x.ip, &x.last, true); err != nil {
+ t.Errorf("%s: edges file: %v", x.name, err)
+ }
+}
+
+// dwReply is one client request's answer.
+type dwReply struct {
+ status int
+ header http.Header
+ body string
+ err error
+ elapsed time.Duration
+}
+
+func (r dwReply) String() string {
+ return fmt.Sprintf("%d %q (Retry-After %q, holder %q, %v, err %v)", r.status, r.body, r.header.Get("Retry-After"), r.header.Get("X-Carlos-Holder"), r.elapsed.Round(time.Millisecond), r.err)
+}
+
+// do sends one client request to x's door for host.
+func (s *dwScene) do(x *dwBox, method, host, path, id string, body io.Reader, length int64) dwReply {
+ req, err := http.NewRequest(method, "https://"+host+path, body)
+ if err != nil {
+ return dwReply{err: err}
+ }
+ req.ContentLength = length
+ if id != "" {
+ req.Header.Set("X-Witness-Id", id)
+ }
+ start := time.Now()
+ resp, err := x.client.Do(req)
+ if err != nil {
+ return dwReply{err: err, elapsed: time.Since(start)}
+ }
+ defer resp.Body.Close()
+ b, err := io.ReadAll(resp.Body)
+ return dwReply{status: resp.StatusCode, header: resp.Header, body: string(b), err: err, elapsed: time.Since(start)}
+}
+
+// lock is the host's lock as MinIO holds it.
+func (s *dwScene) lock(t *testing.T, host string) hafresh.Lock {
+ t.Helper()
+ store, err := release.NewS3StoreIn(t.Context(), s.bucket, dwRegion)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, _, err := store.Get(t.Context(), activator.HibernatePrefix(s.prefix, host)+"/lock.json")
+ if err != nil {
+ t.Fatalf("lock of %s: %v", host, err)
+ }
+ var l hafresh.Lock
+ if err := json.Unmarshal(body, &l); err != nil {
+ t.Fatalf("lock of %s: %v (%s)", host, err, body)
+ }
+ return l
+}
+
+// dwObserver is the drain driver's activator: the real Service, with the
+// move calls recorded in order and BeginMove signalled. Every call goes
+// through unchanged.
+type dwObserver struct {
+ *activator.Service
+ mu sync.Mutex
+ calls []string
+ began chan string
+ releases []activator.DrainRelease
+}
+
+func (o *dwObserver) note(s string) {
+ o.mu.Lock()
+ o.calls = append(o.calls, s)
+ o.mu.Unlock()
+}
+
+func (o *dwObserver) BeginMove(host string) error {
+ err := o.Service.BeginMove(host)
+ o.note(fmt.Sprintf("begin %s %v", host, err))
+ if err == nil {
+ o.began <- host
+ }
+ return err
+}
+
+func (o *dwObserver) SetMoveReleasing(host string) error {
+ err := o.Service.SetMoveReleasing(host)
+ o.note(fmt.Sprintf("releasing %s %v", host, err))
+ return err
+}
+
+func (o *dwObserver) DrainStop(ctx context.Context, host string) (activator.DrainRelease, error) {
+ r, err := o.Service.DrainStop(ctx, host)
+ o.mu.Lock()
+ o.releases = append(o.releases, r)
+ o.mu.Unlock()
+ o.note(fmt.Sprintf("stop %s marker=%v clean=%v %v", host, r.Marker, r.Clean, err))
+ return r, err
+}
+
+func (o *dwObserver) SetMoveTaken(host, holder string, gen int64) error {
+ err := o.Service.SetMoveTaken(host, holder, gen)
+ o.note(fmt.Sprintf("taken %s %s %v", host, holder, err))
+ return err
+}
+
+func (o *dwObserver) SetMoveLeft(host, reason string) {
+ o.Service.SetMoveLeft(host, reason)
+ o.note(fmt.Sprintf("left %s %s", host, reason))
+}
+
+func (o *dwObserver) EndDrainMoves() {
+ o.Service.EndDrainMoves()
+ o.note("end-moves")
+}
+
+func (o *dwObserver) log() []string {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ return append([]string(nil), o.calls...)
+}
+
+// drainOn wires A's drain: its group admission reading the verb's fence,
+// the driver over the observer, and the verb over the real socket.
+func (s *dwScene) drainOn(t *testing.T) (*groupMaintenanceCommand, fenceLocation, *dwObserver) {
+ cmd, l, obs, _ := s.drainDriverOn(t)
+ return cmd, l, obs
+}
+
+func (s *dwScene) drainDriverOn(t *testing.T) (*groupMaintenanceCommand, fenceLocation, *dwObserver, *drainDriver) {
+ t.Helper()
+ obs := &dwObserver{Service: s.a.svc, began: make(chan string, 8)}
+ d := newDrainDriver(obs, s.a.e, s.a.drain, nil)
+ cmd, l := verbDrain(t, d)
+ d.fence = l.read
+ prev := startFenced
+ startFenced = l.fenced
+ t.Cleanup(func() { startFenced = prev })
+ adm := readyGroupAdmission(t)
+ adm.observe(groupadmission.Facts{TerminationStarted: true})
+ adm.tick(t.Context())
+ if !adm.startAllowed() {
+ t.Fatal("A's admission is not open")
+ }
+ if opt := wireAgentAdmission(adm, s.a.svc, s.a.eb, nil); opt != nil {
+ opt(s.a.e)
+ }
+ return cmd, l, obs, d
+}
+
+func dwSummary(lines []string) map[string]int {
+ out := map[string]int{}
+ for _, l := range lines {
+ f := strings.Fields(l)
+ if len(f) < 2 {
+ continue
+ }
+ kind, p := f[0], f[1]
+ switch {
+ case strings.HasSuffix(p, "/lock.json"):
+ kind += " lock"
+ case strings.Contains(p, "/files/"):
+ kind += " files"
+ case strings.HasPrefix(p, "control/edges/"):
+ kind += " edges"
+ case strings.HasPrefix(p, "control/"):
+ kind += " control"
+ case strings.HasSuffix(p, ".ltx") || strings.HasSuffix(p, "/generations/") || strings.HasSuffix(strings.TrimRight(p, "/"), "/000") || dwLevel(p):
+ kind += " replica"
+ default:
+ kind += " other"
+ }
+ out[kind]++
+ }
+ return out
+}
+
+// dwLevel is whether p names a litestream level directory (.../0000/).
+func dwLevel(p string) bool {
+ p = strings.TrimSuffix(p, "/")
+ i := strings.LastIndexByte(p, '/')
+ if i < 0 || len(p)-i-1 != 4 {
+ return false
+ }
+ for _, c := range p[i+1:] {
+ if c < '0' || c > '9' {
+ return false
+ }
+ }
+ return true
+}
+
+func dwSorted(m map[string]int) string {
+ keys := make([]string, 0, len(m))
+ for k := range m {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ var b strings.Builder
+ for _, k := range keys {
+ fmt.Fprintf(&b, "%s=%d ", k, m[k])
+ }
+ return strings.TrimSpace(b.String())
+}
+
+// TestHeldHandoverTwoBoxMinio is the planned handover witness: a drain on
+// A moves an awake HA host to B, and the requests that cross the move are
+// held and delivered once on B, redirected and replayed once, or refused
+// at once, as §25.5 and §25.8 say.
+func TestHeldHandoverTwoBoxMinio(t *testing.T) {
+ s := newDWScene(t)
+ cmd, fence, obs := s.drainOn(t)
+ A, B, C := s.a, s.b, s.c
+
+ // The host wakes on A from a client request: A takes the lease from
+ // an absent lock through DecideAcquire. The HA acquire reads the
+ // process's one identity (lease.SetSelf), so this process names the
+ // box that acquires next: A now, B from the drain on (A acquires
+ // nothing while it drains).
+ lease.SetSelf(A.self)
+ if r := s.do(A, "GET", s.host, "/", "warm", nil, 0); r.status != 200 || !strings.HasPrefix(r.body, "annie|warm") {
+ t.Fatalf("warm on A: %v", r)
+ }
+ if l := s.lock(t, s.host); !strings.Contains(l.Owner, "ref=annie") {
+ t.Fatalf("lock after the wake: %+v", l)
+ }
+ // A plain (not HA) host awake on A too: the drain releases it and
+ // never takes it.
+ if r := s.do(A, "GET", s.plain, "/", "plain-warm", nil, 0); r.status != 200 {
+ t.Fatalf("plain on A: %v", r)
+ }
+ // C reaches the host through A (its lock read names A).
+ if r := s.do(C, "GET", s.host, "/", "via-c", nil, 0); r.status != 200 || !strings.HasPrefix(r.body, "annie|via-c") {
+ t.Fatalf("C's request before the move: %v", r)
+ }
+
+ // A slow request inside A's app keeps the move in its in-flight
+ // drain, so the requests below arrive while the host is held.
+ app := A.app(s.host)
+ app.mu.Lock()
+ app.slow = make(chan struct{})
+ app.mu.Unlock()
+ slow := make(chan dwReply, 1)
+ go func() { slow <- s.do(A, "GET", s.host, "/slow", "slow", nil, 0) }()
+ select {
+ case <-app.entered:
+ case <-time.After(30 * time.Second):
+ t.Fatal("the slow request never reached A's app")
+ }
+
+ lease.SetSelf(B.self)
+ s3Before, storeBefore := s.s3.mark(), s.store.mark()
+ drainStart := time.Now()
+ type verbOut struct {
+ rep *drainReport
+ err error
+ }
+ verb := make(chan verbOut, 1)
+ go func() {
+ rep, err := runDrainVerb(t, cmd, "drain", dwTxn)
+ verb <- verbOut{rep, err}
+ }()
+ select {
+ case h := <-obs.began:
+ if h != s.host {
+ t.Fatalf("first move %q, want %q", h, s.host)
+ }
+ case v := <-verb:
+ t.Fatalf("the drain ended before any move: %+v %v\ncalls: %v", v.rep, v.err, obs.log())
+ case <-time.After(3 * time.Minute):
+ t.Fatalf("no move began; calls: %v", obs.log())
+ }
+ if f := fence.read(); f.Transaction != dwTxn {
+ t.Fatalf("the fence at the move: %+v", f)
+ }
+
+ // While the host is held: a direct client request to A, a replayable
+ // hop POST through C (a known length under 64 KiB), and a hop C cannot
+ // replay (a body of unknown length).
+ var wg sync.WaitGroup
+ var direct, replay, chunked dwReply
+ small := bytes.Repeat([]byte("p"), 48<<10)
+ wg.Add(3)
+ go func() {
+ defer wg.Done()
+ direct = s.do(A, "POST", s.host, "/direct", "direct-1", strings.NewReader("direct body"), 11)
+ }()
+ go func() {
+ defer wg.Done()
+ replay = s.do(C, "POST", s.host, "/replay", "hop-2", bytes.NewReader(small), int64(len(small)))
+ }()
+ go func() {
+ defer wg.Done()
+ chunked = s.do(C, "POST", s.host, "/chunked", "hop-3", io.MultiReader(strings.NewReader("chunk")), -1)
+ }()
+ // The non-replayable hop is answered at once, while the host is still
+ // held (the slow request is still in A's app).
+ deadline := time.Now().Add(20 * time.Second)
+ for time.Now().Before(deadline) && A.svc.DrainHoldStatsNow().RefusedAtOnce == 0 {
+ time.Sleep(20 * time.Millisecond)
+ }
+ if A.svc.DrainHoldStatsNow().RefusedAtOnce == 0 {
+ t.Fatalf("the non-replayable hop was not refused at once; calls %v", obs.log())
+ }
+ time.Sleep(300 * time.Millisecond) // the direct request and the replayable hop reach their holds
+ app.mu.Lock()
+ close(app.slow)
+ app.slow = nil
+ app.mu.Unlock()
+ if r := <-slow; r.status != 200 || !strings.HasPrefix(r.body, "annie|slow") {
+ t.Fatalf("the slow request: %v", r)
+ }
+ wg.Wait()
+ v := <-verb
+ drainTook := time.Since(drainStart)
+ s3Drain, storeDrain := s.s3.since(s3Before), s.store.since(storeBefore)
+
+ if v.err != nil || v.rep == nil || v.rep.Result != "ok" {
+ t.Fatalf("drain: %+v %v\ncalls: %v", v.rep, v.err, obs.log())
+ }
+ t.Logf("drain report: %+v", *v.rep)
+ t.Logf("driver calls: %v", obs.log())
+ for _, l := range s3Drain {
+ t.Logf("S3 during the drain: %s", l)
+ }
+ t.Logf("drain took %v; S3 calls %d (%s); deployment store calls %d (%s)", drainTook.Round(time.Millisecond), len(s3Drain), dwSorted(dwSummary(s3Drain)), len(storeDrain), dwSorted(dwSummary(storeDrain)))
+
+ // The store budget of one drain (§25.10): two edges mutations (the
+ // drain state, then drained); two acknowledgement rounds, each one
+ // fold (one LIST and a GET per edges file) on each of the two peers;
+ // for the host moved, the marker PUT and the successor's acquire
+ // (GET and PUT), plus at most one coalesced lock read for a
+ // redirect; the plain host's legacy release; and the restore's reads,
+ // which the host's next wake would make anyway. Nothing else polls.
+ s3Sum, storeSum := dwSummary(s3Drain), dwSummary(storeDrain)
+ if storeSum["PUT edges"] != 2 || storeSum["LIST edges"] != 4 || storeSum["GET edges"] > 16 || len(storeDrain) != storeSum["PUT edges"]+storeSum["LIST edges"]+storeSum["GET edges"] {
+ t.Fatalf("deployment store calls during the drain: %v", storeDrain)
+ }
+ if s3Sum["PUT lock"] != 2 || s3Sum["GET lock"] > 3 || s3Sum["DELETE lock"] != 1 || s3Sum["PUT files"] != 0 || s3Sum["other"]+s3Sum["GET other"]+s3Sum["PUT other"]+s3Sum["LIST other"] != 0 {
+ t.Fatalf("S3 calls during the drain: %s\n%s", dwSorted(s3Sum), strings.Join(s3Drain, "\n"))
+ }
+
+ // The sequence: BeginMove, the stop with its clean marker, the take
+ // naming B, SetMoveTaken, and the redirects dropped only at the end.
+ calls := strings.Join(obs.log(), "\n")
+ for _, want := range []string{"begin " + s.host + " <nil>", "releasing " + s.host + " <nil>", "stop " + s.host + " marker=true clean=true <nil>", "taken " + s.host + " betty <nil>", "end-moves"} {
+ if !strings.Contains(calls, want) {
+ t.Fatalf("driver calls lack %q:\n%s", want, calls)
+ }
+ }
+ if strings.Contains(calls, "left ") {
+ t.Fatalf("a move failed:\n%s", calls)
+ }
+ if len(v.rep.Moved) != 1 || v.rep.Moved[0].Host != s.host || v.rep.Moved[0].Holder != "betty" || v.rep.Moved[0].Confirmed != "take" || v.rep.Moved[0].Gen < 2 {
+ t.Fatalf("moved: %+v", v.rep.Moved)
+ }
+ var plainReleased bool
+ for _, r := range v.rep.Released {
+ if r.Host == s.plain && r.Marker && r.Clean {
+ plainReleased = true
+ }
+ if r.Host == s.host {
+ t.Fatalf("the HA host was released, not taken: %+v", r)
+ }
+ }
+ if !plainReleased || len(v.rep.Unclean) != 0 || len(v.rep.Left) != 0 {
+ t.Fatalf("released %+v unclean %v left %+v", v.rep.Released, v.rep.Unclean, v.rep.Left)
+ }
+ if B.ctl.startCount(s.plain) != 0 {
+ t.Fatal("the plain host was started on B")
+ }
+ if l := s.lock(t, s.host); !strings.Contains(l.Owner, "ref=betty") {
+ t.Fatalf("lock after the move: %+v", l)
+ }
+
+ // The direct request: held, then delivered once, on B.
+ if direct.status != 200 || !strings.HasPrefix(direct.body, "betty|direct-1|11") {
+ t.Fatalf("direct request: %v", direct)
+ }
+ // The replayable hop: A's handover answer, then C's one replay to B.
+ if replay.status != 200 || replay.body != fmt.Sprintf("betty|hop-2|%d", len(small)) {
+ t.Fatalf("replayable hop: %v", replay)
+ }
+ // The non-replayable hop: today's answer at once.
+ if chunked.status != http.StatusServiceUnavailable || chunked.header.Get("Retry-After") != "10" {
+ t.Fatalf("non-replayable hop: %v", chunked)
+ }
+ for id, want := range map[string][2]int{"direct-1": {0, 1}, "hop-2": {0, 1}, "hop-3": {0, 0}} {
+ if a, b := A.app(s.host).count(id), B.app(s.host).count(id); a != want[0] || b != want[1] {
+ t.Fatalf("%s reached A's app %d and B's %d times, want %d and %d", id, a, b, want[0], want[1])
+ }
+ }
+ if B.ctl.startCount(s.host) != 1 {
+ t.Fatalf("B started the host %d times, want 1", B.ctl.startCount(s.host))
+ }
+
+ // After the drain: the fence stays. A's door answers every new
+ // request at the connection drain's barrier (today's 503 with
+ // Retry-After: 10, nothing forwarded or started).
+ if f := fence.read(); !f.Present || f.Transaction != dwTxn {
+ t.Fatalf("fence after the drain: %+v", f)
+ }
+ starts := A.ctl.startCount(s.plain)
+ if r := s.do(A, "GET", s.plain, "/", "plain-after", nil, 0); r.status != http.StatusServiceUnavailable || r.header.Get("Retry-After") != "10" {
+ t.Fatalf("a request at the drained A's door: %v", r)
+ }
+ // Behind the barrier, the activator's own request path (what the edge
+ // hands a request to) meets the start gate: the fence refuses the
+ // start with today's admission answer, and nothing starts.
+ plainRT, err := A.reg.Get(s.plain)
+ if err != nil || plainRT == nil {
+ t.Fatal(plainRT, err)
+ }
+ if A.eb.TenantStartAllowed(*plainRT) {
+ t.Fatal("the fenced A allows a tenant start")
+ }
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest("GET", "https://"+s.plain+"/", nil)
+ A.svc.ServeHTTP(rec, req, *plainRT, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ t.Error("the fenced A proxied a request to the plain host")
+ }))
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("a start on the fenced A: %d %q", rec.Code, rec.Body.String())
+ }
+ t.Logf("the fenced A's start gate answers %d %q (Retry-After %q)", rec.Code, rec.Body.String(), rec.Header().Get("Retry-After"))
+ if A.ctl.startCount(s.plain) != starts || A.app(s.plain).count("plain-after") != 0 {
+ t.Fatal("the fenced A started the plain host")
+ }
+ // drain --cancel (the real verb) ends the drain and lifts the fence;
+ // then A starts the plain host again.
+ if _, err := runDrainVerb(t, cmd, "drain-cancel", dwTxn); err != nil {
+ t.Fatalf("drain --cancel: %v", err)
+ }
+ if f := fence.read(); f.Present {
+ t.Fatalf("fence after the cancel: %+v", f)
+ }
+ if r := s.do(A, "GET", s.plain, "/", "plain-cancelled", nil, 0); r.status != 200 || !strings.HasPrefix(r.body, "annie|plain-cancelled") {
+ t.Fatalf("the plain host after the cancel: %v", r)
+ }
+ // The moved host is served on B, through A's door too.
+ if r := s.do(B, "GET", s.host, "/", "after-b", nil, 0); r.status != 200 || !strings.HasPrefix(r.body, "betty|after-b") {
+ t.Fatalf("B after the move: %v", r)
+ }
+}
+
+// TestHeldHandoverLostLeaseMinio is F-A during a move (§25.2, §25.5 step
+// 1): A holds the host for its move, then loses the lease mid-move. Here
+// the loss is the store refusing A's marker write for the host, which
+// leaves A an owed release and latches the activator's loss exactly as a
+// failed renewal does (a renewal runs every 5 minutes at the production
+// TTL, too slow for a test). A request that arrives after the loss gets
+// F-A's answer at once (503, Retry-After: 10, holder none), never reaches
+// an app, and nothing is taken: B starts nothing.
+func TestHeldHandoverLostLeaseMinio(t *testing.T) {
+ s := newDWScene(t)
+ cmd, _, obs, driver := s.drainDriverOn(t)
+ A, B := s.a, s.b
+ lease.SetSelf(A.self)
+ if r := s.do(A, "GET", s.host, "/", "warm", nil, 0); r.status != 200 || !strings.HasPrefix(r.body, "annie|warm") {
+ t.Fatalf("warm on A: %v", r)
+ }
+ app := A.app(s.host)
+ app.mu.Lock()
+ app.slow = make(chan struct{})
+ app.mu.Unlock()
+ slow := make(chan dwReply, 1)
+ go func() { slow <- s.do(A, "GET", s.host, "/slow", "slow", nil, 0) }()
+ select {
+ case <-app.entered:
+ case <-time.After(30 * time.Second):
+ t.Fatal("the slow request never reached A's app")
+ }
+ lease.SetSelf(B.self)
+ verb := make(chan error, 1)
+ go func() {
+ _, err := runDrainVerb(t, cmd, "drain", dwTxn)
+ verb <- err
+ }()
+ select {
+ case <-obs.began:
+ case err := <-verb:
+ t.Fatalf("the drain ended before any move: %v; calls %v", err, obs.log())
+ case <-time.After(3 * time.Minute):
+ t.Fatalf("no move began; calls: %v", obs.log())
+ }
+ // A request held while the host moves: the failed move gives it
+ // today's answer.
+ held := make(chan dwReply, 1)
+ go func() { held <- s.do(A, "GET", s.host, "/held", "held", nil, 0) }()
+ time.Sleep(300 * time.Millisecond)
+ lockKey := "/" + s.bucket + "/" + activator.HibernatePrefix(s.prefix, s.host) + "/lock.json"
+ s.s3.setRefuse(func(method, path string) bool { return method == http.MethodPut && path == lockKey })
+ t.Cleanup(func() { s.s3.setRefuse(nil) })
+ app.mu.Lock()
+ close(app.slow)
+ app.slow = nil
+ app.mu.Unlock()
+ if r := <-slow; r.status != 200 {
+ t.Fatalf("the slow request: %v", r)
+ }
+ // Wait for the stop's outcome: no marker.
+ deadline := time.Now().Add(2 * time.Minute)
+ for time.Now().Before(deadline) && !strings.Contains(strings.Join(obs.log(), "\n"), "stop "+s.host+" marker=false") {
+ time.Sleep(50 * time.Millisecond)
+ }
+ calls := strings.Join(obs.log(), "\n")
+ if !strings.Contains(calls, "stop "+s.host+" marker=false") {
+ t.Fatalf("the stop wrote a marker the store refused:\n%s", calls)
+ }
+ r := s.do(A, "POST", s.host, "/after-loss", "after-loss", strings.NewReader("x"), 1)
+ if r.status != http.StatusServiceUnavailable || r.header.Get("Retry-After") != "10" || r.header.Get("X-Carlos-Holder") != "none" || r.elapsed > 2*time.Second {
+ t.Fatalf("a request after the loss: %v, want F-A's 503 at once", r)
+ }
+ if A.app(s.host).count("after-loss") != 0 || B.app(s.host).count("after-loss") != 0 || B.ctl.startCount(s.host) != 0 {
+ t.Fatal("a request after the loss reached an app, or B started the host")
+ }
+ if h := <-held; h.status != http.StatusServiceUnavailable || h.header.Get("Retry-After") != "10" || A.app(s.host).count("held") != 0 || B.app(s.host).count("held") != 0 {
+ t.Fatalf("the request held across the failed move: %v", h)
+ }
+ // The answer is the loss latch's: A owes the release, and its forward
+ // decision for the host is the refusal F-A gives.
+ if q := A.svc.DrainQuietNow(); q.Owed == 0 {
+ t.Fatalf("no owed release after the refused marker: %+v", q)
+ }
+ rt, err := A.reg.Get(s.host)
+ if err != nil || rt == nil {
+ t.Fatal(rt, err)
+ }
+ if d := A.svc.ForwardTarget(t.Context(), *rt, nil); !d.Unavailable {
+ t.Fatalf("A's forward decision after the loss: %+v, want unavailable", d)
+ }
+ if strings.Contains(calls, "taken ") || !strings.Contains(calls, "left "+s.host) {
+ t.Fatalf("the move was not left:\n%s", calls)
+ }
+ t.Logf("driver calls: %v", obs.log())
+ t.Logf("a request after the loss: %v", r)
+ // The drain cannot report ok (an owed release names A); cancel it.
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ defer cancel()
+ if err := driver.cancel(ctx, dwTxn); err != nil {
+ t.Fatalf("cancel: %v", err)
+ }
+ select {
+ case err := <-verb:
+ if err == nil {
+ t.Fatal("the drain succeeded with a lost lease")
+ }
+ case <-time.After(time.Minute):
+ t.Fatal("the drain verb did not return after the cancel")
+ }
+}