| new file mode 100644 |
| index 000000000..6b536417a |
| --- /dev/null |
| +++ b/internal/host/fleettwobox_e2e_test.go |
| @@ -0,0 +1,1035 @@ |
| +//go:build linux |
| + |
| +package host |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/benbjohnson/litestream" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/console" |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/lease/leasetest" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| + "github.com/carlosframework/platform/internal/version" |
| +) |
| + |
| +// The real two-box fleet (managed fleets 1b, Task 7; spec "1b addendum"). |
| +// TestTwoBoxFleetEndToEnd in internal/edge models the lease; these tests |
| +// take it for real: one fake S3 (leasetest.NewS3Server) holding fleet pi's |
| +// one data bucket, two boxes pi-1 and pi-2 with their own data directories, |
| +// registries, real activator.ExecBackends and their own lease identities, |
| +// and the console in process over the one deployment store. Production |
| +// code throughout: |
| +// |
| +// - the console's doors (fleet create, add box, place, instance create, |
| +// drain, detach) over HTTP with an operator's CLI token, and its |
| +// relabel worker's pass (Server.RunFleetRelabelPass) at explicit times; |
| +// - each box's reconcile (BoxProvisionConfig from the box's own |
| +// environment, reconcileSerializedWith), and the hub's, whose forward |
| +// rows carry the label; |
| +// - ExecBackend.Acquire and Restore (the lease take, the start rule, the |
| +// set-aside and the restore from the fleet bucket), the lease's renewal |
| +// and release, litestream replication (Lease.Replicate, Rep.Close); |
| +// - the heartbeat's drain facts (drainReport over a Service on the |
| +// backend) and the binding a wake publishes (fleetBindingHook). |
| +// |
| +// What is modelled, and why: |
| +// - the activator's orchestration around the backend: a wake is Acquire, |
| +// Restore, the app opening its database, Replicate (doWake's order); |
| +// a stop is Rep.Close (the final sync and the release); the edge's |
| +// reload retiring a host whose row is gone is a stop after reconcile |
| +// (RetireExcept). Spawning a child needs a version store, cgroups and |
| +// a binary; the start decisions this test is about are all the |
| +// backend's. |
| +// - the app: the test reads and writes the instance's database at the |
| +// row's DBPath while it is awake, as the app would. |
| +// - the heartbeat is composed as statusTick composes it |
| +// (status.CollectBox, the box's label, status.WriteBox under |
| +// fleets/pi/), with a chosen time so the console's clock can be driven; |
| +// - a partition is the box's view of the deployment store refusing every |
| +// request (records, heartbeats); its data bucket, and so its lease |
| +// renewal, still answers; |
| +// - a dead agent is Replicator.Abandon: renewal and replication stop, |
| +// nothing is released, the lock lapses on its TTL. |
| +// |
| +// Every lease is fleetTTL long (ExecBackend.LeaseTTL), so an expiry fits |
| +// in a test; the activator's own start rules do not read the TTL. |
| + |
| +const ( |
| + fleetName = "pi" |
| + fleetBucket = "pi-fleet-data" |
| + fleetRegion = "eu-west-1" |
| + fleetPrefix = "instances" |
| + fleetTTL = 6 * time.Second |
| + fleetAddr = "ops@example.com" |
| + fleetA = "a.example.com" |
| + fleetB = "b.example.com" |
| +) |
| + |
| +// cutStore is a box's view of the deployment store: while cut, every |
| +// request fails, as a box partitioned from the store sees it. |
| +type cutStore struct { |
| + release.Store |
| + cut atomic.Bool |
| +} |
| + |
| +var errPartitioned = errors.New("partitioned: the deployment store is unreachable from this box") |
| + |
| +func (c *cutStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if c.cut.Load() { |
| + return nil, "", errPartitioned |
| + } |
| + return c.Store.Get(ctx, key) |
| +} |
| + |
| +func (c *cutStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + if c.cut.Load() { |
| + return "", errPartitioned |
| + } |
| + return c.Store.Put(ctx, key, body, ifMatch) |
| +} |
| + |
| +func (c *cutStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + if c.cut.Load() { |
| + return nil, errPartitioned |
| + } |
| + return c.Store.List(ctx, prefix) |
| +} |
| + |
| +func (c *cutStore) ListDirs(ctx context.Context, prefix string) ([]string, error) { |
| + if c.cut.Load() { |
| + return nil, errPartitioned |
| + } |
| + return c.Store.ListDirs(ctx, prefix) |
| +} |
| + |
| +func (c *cutStore) Delete(ctx context.Context, key string) error { |
| + if c.cut.Load() { |
| + return errPartitioned |
| + } |
| + return c.Store.Delete(ctx, key) |
| +} |
| + |
| +// fleetWorld is the deployment: the console, the hub's registry, the fleet |
| +// bucket and the two boxes. |
| +type fleetWorld struct { |
| + t *testing.T |
| + s3 *leasetest.VersionedBucket |
| + store release.Store // the deployment store |
| + srv *console.Server |
| + base string // the console's URL |
| + token string |
| + acct string |
| + hub *registry.Registry |
| + // regPath is the console's registry file. |
| + regPath string |
| + // now is the console's and the heartbeats' clock: it starts at the wall |
| + // clock and only moves forward, by advance. |
| + now time.Time |
| + pi1, pi2 *fleetBox |
| +} |
| + |
| +// fleetBox is one box of fleet pi. |
| +type fleetBox struct { |
| + w *fleetWorld |
| + label string |
| + self hafresh.Self |
| + dd string |
| + reg *registry.Registry |
| + store *cutStore |
| + eb *activator.ExecBackend |
| + svc *activator.Service // the heartbeat's drain facts (DrainFacts) |
| + awake map[string]activator.Rep |
| +} |
| + |
| +// fleetOpts shapes the fixture: rel is the release every box reports. |
| +type fleetOpts struct{ rel string } |
| + |
| +func newFleetWorld(t *testing.T, opts fleetOpts) *fleetWorld { |
| + t.Helper() |
| + ctx := context.Background() |
| + if opts.rel == "" { |
| + opts.rel = release.FleetBoxLabelFloor |
| + } |
| + t.Setenv("CARLOS_HOST_CLAIM", "") |
| + // The console runs the label floor (gate d). |
| + prevBuild := version.Build |
| + version.Build = release.FleetBoxLabelFloor |
| + t.Cleanup(func() { version.Build = prevBuild }) |
| + |
| + // The fleet's data bucket over the S3 wire protocol, on loopback. |
| + fake := leasetest.NewVersionedBucket() |
| + fake.AddBucket(fleetBucket) |
| + h, _ := leasetest.NewS3Server(fake) |
| + s3srv := httptest.NewServer(h) |
| + t.Cleanup(s3srv.Close) |
| + t.Setenv("AWS_ACCESS_KEY_ID", "test-key") |
| + t.Setenv("AWS_SECRET_ACCESS_KEY", "test-secret") |
| + t.Setenv("AWS_SESSION_TOKEN", "") |
| + 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", s3srv.URL) |
| + |
| + store := release.NewDirStore(t.TempDir()) |
| + keyB64, _, err := appconfig.GenerateKey() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + priv, err := appconfig.ParsePrivateKey(keyB64, "test key") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + seed, pubB64, err := release.GenerateKey() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + relPriv, err := release.ParseSigningKey(seed, "test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + relPub, err := release.ParsePublicKey(pubB64, "test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // The console, an operator and its CLI token, shop in the ops account. |
| + dir := t.TempDir() |
| + cst, err := console.Open(filepath.Join(dir, "console.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { cst.Close() }) |
| + var srv *console.Server |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv.ServeHTTP(w, r) })) |
| + t.Cleanup(ts.Close) |
| + if srv, err = console.NewServer(console.Config{Origin: ts.URL, Keymail: "http://keymail.invalid", |
| + Registry: filepath.Join(dir, "registry.db"), Releases: store, ReleasePub: relPub, Key: relPriv, AppScheme: "http", |
| + HomeRegion: "ie", SecretsPub: base64.StdEncoding.EncodeToString(priv.PublicKey().Bytes())}, cst); err != nil { |
| + t.Fatal(err) |
| + } |
| + now := time.Now() |
| + if err := cst.AddMember(console.OpsAccountID, fleetAddr, console.RoleOwner, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := cst.SetOperator(fleetAddr, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := cst.CreateAppIn(console.OpsAccountID, "shop", fleetAddr, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + userCode, deviceCode, err := cst.NewCLIAuth("ops@laptop", "127.0.0.1", now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := cst.ApproveCLIAuth(userCode, fleetAddr, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, token, _, err := cst.PollCLIAuth(deviceCode, now) |
| + if err != nil || token == "" { |
| + t.Fatalf("no CLI token: %v", err) |
| + } |
| + acct := release.OpsAccount |
| + if _, _, err := store.Get(ctx, domains.AccountManifestKey(acct)); errors.Is(err, os.ErrNotExist) { |
| + manifest, _ := json.Marshal(map[string]any{"id": console.OpsAccountID, "sqid": acct, "name": "ops", "created_at": now}) |
| + if _, err := store.Put(ctx, domains.AccountManifestKey(acct), manifest, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := provision.PutManifest(ctx, store, acct, "shop", provision.Manifest{Schema: 1, App: "shop", Domain: "example.com", Channel: "edge"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := &fleetWorld{t: t, s3: fake, store: store, srv: srv, base: ts.URL, token: token, acct: acct, now: now, |
| + regPath: filepath.Join(dir, "registry.db")} |
| + |
| + // Fleet pi with its data bucket, its two boxes, and shop placed on it, |
| + // all through the doors. |
| + w.mustDo(http.MethodPost, "/api/cli/fleets/"+acct+"/new", `{"name":"pi","bucket":"`+fleetBucket+`"}`, http.StatusOK) |
| + for _, label := range []string{"pi-1", "pi-2"} { |
| + w.mustDo(http.MethodPost, "/api/cli/fleets/"+acct+"/pi/boxes", `{"label":"`+label+`"}`, http.StatusOK) |
| + } |
| + w.mustDo(http.MethodPost, "/api/cli/apps/"+acct+"/shop/place", `{"target":"fleet/pi"}`, http.StatusOK) |
| + |
| + // The hub: its own registry, with the fleets table it serves forward |
| + // rows by. |
| + hub, err := registry.Open(filepath.Join(t.TempDir(), "hub.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { hub.Close() }) |
| + if err := hub.UpsertFleet(registry.Fleet{Name: fleetName, Account: acct, Bucket: fleetBucket}); err != nil { |
| + t.Fatal(err) |
| + } |
| + w.hub = hub |
| + |
| + w.pi1 = w.newBox("pi-1") |
| + w.pi2 = w.newBox("pi-2") |
| + for _, b := range []*fleetBox{w.pi1, w.pi2} { |
| + b.heartbeatRel(w.now, opts.rel) |
| + } |
| + return w |
| +} |
| + |
| +func (w *fleetWorld) newBox(label string) *fleetBox { |
| + t := w.t |
| + t.Helper() |
| + b := &fleetBox{w: w, label: label, dd: t.TempDir(), store: &cutStore{Store: w.store}, awake: map[string]activator.Rep{}, |
| + self: hafresh.Self{Ref: label, IID: "i-" + label, Account: "123456789012", Region: fleetRegion, Boot: "boot-" + label}} |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + b.reg = reg |
| + b.start() |
| + t.Cleanup(func() { |
| + for host, rep := range b.awake { |
| + if r, ok := rep.(*lease.Replicator); ok { |
| + r.Abandon(context.Background()) |
| + } |
| + delete(b.awake, host) |
| + } |
| + }) |
| + return b |
| +} |
| + |
| +// start is the box's agent starting: a fresh backend and activator over |
| +// the box's data directory and registry, nothing awake. |
| +func (b *fleetBox) start() { |
| + cfg := activator.Config{Bucket: fleetBucket, Region: fleetRegion, Prefix: fleetPrefix} |
| + id := b.self |
| + b.eb = &activator.ExecBackend{Cfg: cfg, DataDir: b.dd, OptDir: b.w.t.TempDir(), LeaseIdentity: &id, LeaseTTL: fleetTTL} |
| + b.svc = activator.New(cfg, b.eb, b.reg) |
| + b.awake = map[string]activator.Rep{} |
| +} |
| + |
| +// getenv is the box's agent environment. |
| +func (b *fleetBox) getenv(k string) string { |
| + switch k { |
| + case "CARLOS_REGION": |
| + return registry.PlacementTarget(fleetName) |
| + case "CARLOS_FLEET": |
| + return fleetName |
| + case "CARLOS_FLEET_BOX": |
| + return b.label |
| + case "CARLOS_DATA_DIR": |
| + return b.dd |
| + case "CARLOS_HIBERNATE_BUCKET": |
| + return fleetBucket |
| + } |
| + return "" |
| +} |
| + |
| +// reconcile is one instances pass on the box, configured as the agent |
| +// configures it from its environment, then the edge reload's retire: a |
| +// host awake here whose row is gone is stopped. |
| +func (b *fleetBox) reconcile() error { |
| + b.w.t.Helper() |
| + cfg := BoxProvisionConfig(b.reg, b.getenv, nil, nil) |
| + cfg.Lifetimes = &provision.LifetimeIndex{} // the box's own process's index |
| + cfg.Layout = flatLayout |
| + if cfg.FleetBox != b.label { |
| + b.w.t.Fatalf("%s: the pass config names box %q", b.label, cfg.FleetBox) |
| + } |
| + err := reconcileSerializedWith(context.Background(), b.store, b.reg, cfg, nil) |
| + for host := range b.awake { |
| + if rt, gerr := b.reg.Get(host); gerr == nil && rt == nil { |
| + if serr := b.stop(host); serr != nil { |
| + b.w.t.Fatalf("%s: retire %s: %v", b.label, host, serr) |
| + } |
| + } |
| + } |
| + return err |
| +} |
| + |
| +func (b *fleetBox) mustReconcile() { |
| + b.w.t.Helper() |
| + if err := b.reconcile(); err != nil { |
| + b.w.t.Fatalf("%s: reconcile: %v", b.label, err) |
| + } |
| +} |
| + |
| +func (b *fleetBox) row(host string) *registry.Route { |
| + b.w.t.Helper() |
| + rt, err := b.reg.Get(host) |
| + if err != nil { |
| + b.w.t.Fatal(err) |
| + } |
| + return rt |
| +} |
| + |
| +func (b *fleetBox) hosts() []string { |
| + b.w.t.Helper() |
| + routes, err := b.reg.List() |
| + if err != nil { |
| + b.w.t.Fatal(err) |
| + } |
| + var out []string |
| + for _, rt := range routes { |
| + out = append(out, rt.Host) |
| + } |
| + return out |
| +} |
| + |
| +// wake is the activator's wake of host on this box, in doWake's order: |
| +// the lease, the restore, the app opening its database, replication. On |
| +// success the box publishes its binding, as the wake hook does. |
| +func (b *fleetBox) wake(host string) error { |
| + b.w.t.Helper() |
| + ctx := context.Background() |
| + rt := b.row(host) |
| + if rt == nil { |
| + return fmt.Errorf("%s: no row for %s", b.label, host) |
| + } |
| + l, err := b.eb.Acquire(ctx, *rt) |
| + if err != nil { |
| + return err |
| + } |
| + if _, err := b.eb.Restore(ctx, *rt); err != nil { |
| + _ = l.Release(ctx) |
| + return err |
| + } |
| + db, err := sql.Open("sqlite", rt.DBPath) |
| + if err != nil { |
| + _ = l.Release(ctx) |
| + return err |
| + } |
| + for _, q := range []string{`PRAGMA journal_mode=WAL`, `CREATE TABLE IF NOT EXISTS kv (k TEXT PRIMARY KEY, v TEXT)`} { |
| + if _, err := db.Exec(q); err != nil { |
| + db.Close() |
| + _ = l.Release(ctx) |
| + return err |
| + } |
| + } |
| + if err := db.Close(); err != nil { |
| + _ = l.Release(ctx) |
| + return err |
| + } |
| + rep, err := l.Replicate(ctx, rt.DBPath, 0) |
| + if err != nil { |
| + _ = l.Release(ctx) |
| + return err |
| + } |
| + b.awake[host] = rep |
| + fleetBindingHook(b.store, fleetName, b.label)(*rt) |
| + return nil |
| +} |
| + |
| +func (b *fleetBox) mustWake(host string) { |
| + b.w.t.Helper() |
| + if err := b.wake(host); err != nil { |
| + b.w.t.Fatalf("%s: wake %s: %v", b.label, host, err) |
| + } |
| +} |
| + |
| +// stop is the activator's stop: the final sync and the lease's release. |
| +func (b *fleetBox) stop(host string) error { |
| + rep, ok := b.awake[host] |
| + if !ok { |
| + return fmt.Errorf("%s: %s is not awake", b.label, host) |
| + } |
| + delete(b.awake, host) |
| + return rep.Close(context.Background()) |
| +} |
| + |
| +func (b *fleetBox) mustStop(host string) { |
| + b.w.t.Helper() |
| + if err := b.stop(host); err != nil { |
| + b.w.t.Fatalf("%s: stop %s: %v", b.label, host, err) |
| + } |
| +} |
| + |
| +// crash is the box's agent dying with host awake: no final sync, no |
| +// release. |
| +func (b *fleetBox) crash() { |
| + for host, rep := range b.awake { |
| + rep.(*lease.Replicator).Abandon(context.Background()) |
| + delete(b.awake, host) |
| + } |
| +} |
| + |
| +// dbPath is the database of host's row here. |
| +func (b *fleetBox) dbPath(host string) string { |
| + b.w.t.Helper() |
| + if rt := b.row(host); rt != nil && rt.DBPath != "" { |
| + return rt.DBPath |
| + } |
| + return provision.DefaultDBPath(b.dd, host) |
| +} |
| + |
| +// write is the app on this box setting the instance's value, then waiting |
| +// for the replica to have it. |
| +func (b *fleetBox) write(host, v string) { |
| + t := b.w.t |
| + t.Helper() |
| + rep, ok := b.awake[host] |
| + if !ok { |
| + t.Fatalf("%s: write %s: not awake", b.label, host) |
| + } |
| + db, err := sql.Open("sqlite", b.dbPath(host)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := db.Exec(`INSERT INTO kv (k, v) VALUES ('n', ?) ON CONFLICT (k) DO UPDATE SET v = excluded.v`, v); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := db.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := rep.(*lease.Replicator).SyncAndWait(context.Background()); err != nil { |
| + t.Fatalf("%s: sync %s: %v", b.label, host, err) |
| + } |
| +} |
| + |
| +// read is the app on this box reading the instance's value ("" for none). |
| +func (b *fleetBox) read(host string) string { |
| + t := b.w.t |
| + t.Helper() |
| + if _, ok := b.awake[host]; !ok { |
| + t.Fatalf("%s: read %s: not awake", b.label, host) |
| + } |
| + db, err := sql.Open("sqlite", b.dbPath(host)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + var v string |
| + err = db.QueryRow(`SELECT v FROM kv WHERE k = 'n'`).Scan(&v) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return "" |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return v |
| +} |
| + |
| +// setAside is the host's set-aside entries on this box. |
| +func (b *fleetBox) setAside(host string) []string { |
| + b.w.t.Helper() |
| + ents, err := os.ReadDir(filepath.Join(b.dd, ".superseded", host)) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return nil |
| + } |
| + if err != nil { |
| + b.w.t.Fatal(err) |
| + } |
| + var out []string |
| + for _, e := range ents { |
| + out = append(out, e.Name()) |
| + } |
| + return out |
| +} |
| + |
| +// heartbeat writes the box's heartbeat composed at at, at the label floor. |
| +func (b *fleetBox) heartbeat(at time.Time) status.Box { |
| + return b.heartbeatRel(at, release.FleetBoxLabelFloor) |
| +} |
| + |
| +// heartbeatRel is statusTick's composition with a chosen time and |
| +// release: the box's routes, the drain facts, its label, written under |
| +// fleets/pi/. |
| +func (b *fleetBox) heartbeatRel(at time.Time, rel string) status.Box { |
| + t := b.w.t |
| + t.Helper() |
| + routes, err := b.reg.List() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p := status.Probes{MachineID: "machine-" + b.label, Release: rel} |
| + drainReport(&p, b.svc, b.dd) |
| + box := status.CollectBox(routes, p, at) |
| + box.Label = b.label |
| + if err := status.WriteBox(context.Background(), release.NewPrefixStore(b.store, "fleets/"+fleetName+"/"), box); err != nil { |
| + t.Fatalf("%s: heartbeat: %v", b.label, err) |
| + } |
| + return box |
| +} |
| + |
| +// lock is the lock of host in the fleet bucket: its owner's box ref and |
| +// its expiry, ok false when there is none. |
| +func (w *fleetWorld) lock(host string) (ref string, expires time.Time, ok bool) { |
| + w.t.Helper() |
| + body, ok := w.s3.Current(fleetBucket, fleetPrefix+"/"+host+"/lock.json") |
| + if !ok { |
| + return "", time.Time{}, false |
| + } |
| + var l litestream.Lease |
| + if err := json.Unmarshal(body, &l); err != nil { |
| + w.t.Fatal(err) |
| + } |
| + o, parsed := hafresh.ParseOwner(l.Owner) |
| + if !parsed { |
| + w.t.Fatalf("lock of %s names %q, not a box", host, l.Owner) |
| + } |
| + return o.Ref, l.ExpiresAt, true |
| +} |
| + |
| +func (w *fleetWorld) wantLock(host, box string) time.Time { |
| + w.t.Helper() |
| + ref, exp, ok := w.lock(host) |
| + if !ok || ref != box { |
| + w.t.Fatalf("lock of %s: box %q (present %v), want %s", host, ref, ok, box) |
| + } |
| + return exp |
| +} |
| + |
| +func (w *fleetWorld) wantNoLock(host string) { |
| + w.t.Helper() |
| + if ref, _, ok := w.lock(host); ok { |
| + w.t.Fatalf("lock of %s still names %s", host, ref) |
| + } |
| +} |
| + |
| +func (w *fleetWorld) do(method, path, body string) (int, string) { |
| + w.t.Helper() |
| + req, err := http.NewRequest(method, w.base+path, strings.NewReader(body)) |
| + if err != nil { |
| + w.t.Fatal(err) |
| + } |
| + req.Header.Set("Authorization", "Bearer "+w.token) |
| + req.Header.Set("Content-Type", "application/json") |
| + res, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + w.t.Fatal(err) |
| + } |
| + defer res.Body.Close() |
| + raw, _ := io.ReadAll(res.Body) |
| + return res.StatusCode, string(raw) |
| +} |
| + |
| +func (w *fleetWorld) mustDo(method, path, body string, want int) string { |
| + w.t.Helper() |
| + code, out := w.do(method, path, body) |
| + if code != want { |
| + w.t.Fatalf("%s %s = %d %s, want %d", method, path, code, out, want) |
| + } |
| + return out |
| +} |
| + |
| +// create is `carlos instances create` of shop at host. |
| +func (w *fleetWorld) create(host string) provision.Record { |
| + w.t.Helper() |
| + w.mustDo(http.MethodPost, "/api/cli/apps/"+w.acct+"/shop/instances", `{"host":"`+host+`"}`, http.StatusCreated) |
| + return w.record(host) |
| +} |
| + |
| +func (w *fleetWorld) record(host string) provision.Record { |
| + w.t.Helper() |
| + rec, err := provision.GetRecord(context.Background(), w.store, w.acct, "shop", host) |
| + if err != nil { |
| + w.t.Fatal(err) |
| + } |
| + return *rec |
| +} |
| + |
| +func (w *fleetWorld) wantRecord(host, box string, moved bool) provision.Record { |
| + w.t.Helper() |
| + rec := w.record(host) |
| + if rec.FleetBox != box || rec.FleetBoxMoved != moved || (box != "" && rec.FleetBoxAt == "") { |
| + w.t.Fatalf("record %s: box %q at %q moved %v; want box %q moved %v", host, rec.FleetBox, rec.FleetBoxAt, rec.FleetBoxMoved, box, moved) |
| + } |
| + return rec |
| +} |
| + |
| +// relabel is one pass of the console's relabel worker at the world's clock. |
| +func (w *fleetWorld) relabel() { |
| + w.t.Helper() |
| + if err := w.srv.RunFleetRelabelPass(context.Background(), w.now); err != nil { |
| + w.t.Fatalf("relabel pass: %v", err) |
| + } |
| +} |
| + |
| +func (w *fleetWorld) advance(d time.Duration) { w.now = w.now.Add(d) } |
| + |
| +// forwards runs the hub's instances pass and answers each forward row's |
| +// box. |
| +func (w *fleetWorld) forwards() map[string]string { |
| + w.t.Helper() |
| + env := map[string]string{"CARLOS_TUNNEL_HOST": "tunnel.example.com", "CARLOS_DATA_DIR": w.t.TempDir()} |
| + getenv := func(k string) string { return env[k] } |
| + cfg := BoxProvisionConfig(w.hub, getenv, nil, nil) |
| + cfg.Lifetimes = &provision.LifetimeIndex{} |
| + cfg.Layout = flatLayout |
| + if cfg.FleetOwners == nil { |
| + w.t.Fatal("the hub's pass is not armed for forward rows") |
| + } |
| + if err := reconcileSerializedWith(context.Background(), w.store, w.hub, cfg, nil); err != nil { |
| + w.t.Fatalf("hub reconcile: %v", err) |
| + } |
| + routes, err := w.hub.List() |
| + if err != nil { |
| + w.t.Fatal(err) |
| + } |
| + out := map[string]string{} |
| + for _, rt := range routes { |
| + if rt.IsForward() { |
| + out[rt.Host] = rt.FleetBox |
| + } |
| + } |
| + return out |
| +} |
| + |
| +func (w *fleetWorld) wantForwards(want map[string]string) { |
| + w.t.Helper() |
| + got := w.forwards() |
| + if len(got) != len(want) { |
| + w.t.Fatalf("forward rows %v, want %v", got, want) |
| + } |
| + for h, b := range want { |
| + if got[h] != b { |
| + w.t.Fatalf("forward rows %v, want %v", got, want) |
| + } |
| + } |
| +} |
| + |
| +// boxRow is fleet pi's console registry row for label, read on a fresh |
| +// handle. |
| +func (w *fleetWorld) boxRow(label string) registry.FleetBox { |
| + w.t.Helper() |
| + boxes, err := w.fleetBoxes() |
| + if err != nil { |
| + w.t.Fatal(err) |
| + } |
| + for _, b := range boxes { |
| + if b.Label == label { |
| + return b |
| + } |
| + } |
| + w.t.Fatalf("no box %s", label) |
| + return registry.FleetBox{} |
| +} |
| + |
| +func (w *fleetWorld) fleetBoxes() ([]registry.FleetBox, error) { |
| + reg, err := registry.Open(w.regPath) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer reg.Close() |
| + return reg.ListFleetBoxes(fleetName) |
| +} |
| + |
| +func wantOnly(t *testing.T, b *fleetBox, hosts ...string) { |
| + t.Helper() |
| + got := b.hosts() |
| + if len(got) != len(hosts) { |
| + t.Fatalf("%s holds rows %v, want %v", b.label, got, hosts) |
| + } |
| + for i := range hosts { |
| + if got[i] != hosts[i] { |
| + t.Fatalf("%s holds rows %v, want %v", b.label, got, hosts) |
| + } |
| + } |
| +} |
| + |
| +// waitUntil polls ok every 100ms until it holds or limit passes. |
| +func waitUntil(t *testing.T, limit time.Duration, what string, ok func() bool) { |
| + t.Helper() |
| + deadline := time.Now().Add(limit) |
| + for !ok() { |
| + if time.Now().After(deadline) { |
| + t.Fatalf("after %s: %s", limit, what) |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + } |
| +} |
| + |
| +// TestTwoBoxFleetEndToEnd_Real is the scenario's main line: spread at |
| +// create, each box minting and locking only its own, a partitioned box |
| +// that keeps renewing while its instance moves, the move once it heals, a |
| +// drain back, and no stale read after A, then B, then A. |
| +func TestTwoBoxFleetEndToEnd_Real(t *testing.T) { |
| + w := newFleetWorld(t, fleetOpts{}) |
| + pi1, pi2 := w.pi1, w.pi2 |
| + |
| + // (1) Two instances land one per box (the fewest records, ties by |
| + // label), and the hub's forward rows name them. |
| + w.create(fleetA) |
| + w.wantRecord(fleetA, "pi-1", false) |
| + w.create(fleetB) |
| + w.wantRecord(fleetB, "pi-2", false) |
| + w.wantForwards(map[string]string{fleetA: "pi-1", fleetB: "pi-2"}) |
| + |
| + // (2) Each box mints only its own, and each lock names its box. |
| + pi1.mustReconcile() |
| + pi2.mustReconcile() |
| + wantOnly(t, pi1, fleetA) |
| + wantOnly(t, pi2, fleetB) |
| + pi1.mustWake(fleetA) |
| + pi2.mustWake(fleetB) |
| + w.wantLock(fleetA, "pi-1") |
| + w.wantLock(fleetB, "pi-2") |
| + if err := pi2.wake(fleetA); err == nil || !strings.Contains(err.Error(), "no row") { |
| + t.Fatalf("pi-2 woke a, which is pi-1's: %v", err) |
| + } |
| + |
| + // (3) a on pi-1 writes 1; b on pi-2 writes b1 and sleeps. |
| + pi1.write(fleetA, "1") |
| + pi2.write(fleetB, "b1") |
| + pi2.mustStop(fleetB) |
| + w.wantNoLock(fleetB) |
| + pi1.heartbeat(w.now) |
| + pi2.heartbeat(w.now) |
| + |
| + // pi-1 is partitioned from the deployment store. Its heartbeat stops; |
| + // its lease, on the data bucket, keeps renewing. Past the lost-box |
| + // horizon the relabel moves a to pi-2, the one fresh box. |
| + pi1.store.cut.Store(true) |
| + w.advance(25 * time.Minute) |
| + pi2.heartbeat(w.now) |
| + w.relabel() |
| + moved := w.wantRecord(fleetA, "pi-2", true) |
| + w.wantRecord(fleetB, "pi-2", false) |
| + w.wantForwards(map[string]string{fleetA: "pi-2", fleetB: "pi-2"}) |
| + |
| + // pi-1 cannot read the relabel: it keeps a's row, awake. |
| + if err := pi1.reconcile(); err == nil { |
| + t.Fatal("pi-1's pass read the store through the partition") |
| + } |
| + wantOnly(t, pi1, fleetA) |
| + // pi-2 mints a and waits: the lease is pi-1's, and pi-1 renews it past |
| + // the expiry it had when pi-2 first asked. |
| + pi2.mustReconcile() |
| + wantOnly(t, pi2, fleetA, fleetB) |
| + if rt := pi2.row(fleetA); rt.Assigned != moved.FleetBoxAt || !rt.Moved { |
| + t.Fatalf("pi-2's row of a: assigned %q moved %v, want %q moved", rt.Assigned, rt.Moved, moved.FleetBoxAt) |
| + } |
| + first := w.wantLock(fleetA, "pi-1") |
| + if err := pi2.wake(fleetA); err == nil || !strings.Contains(err.Error(), "lease held") { |
| + t.Fatalf("pi-2 woke a under pi-1's lease: %v", err) |
| + } |
| + waitUntil(t, 3*fleetTTL, "pi-1 renewed a's lease past its first expiry", func() bool { |
| + _, exp, ok := w.lock(fleetA) |
| + return ok && exp.After(first) && time.Now().After(first) |
| + }) |
| + if err := pi2.wake(fleetA); err == nil || !strings.Contains(err.Error(), "lease held") { |
| + t.Fatalf("pi-2 woke a under pi-1's renewed lease: %v", err) |
| + } |
| + w.wantLock(fleetA, "pi-1") |
| + if _, err := os.Stat(pi2.dbPath(fleetA)); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("pi-2 has a copy of a while waiting: %v", err) |
| + } |
| + |
| + // Heal: pi-1 reads the relabel, drops the row, stops a (its final sync) |
| + // and releases the lease. |
| + pi1.store.cut.Store(false) |
| + pi1.mustReconcile() |
| + wantOnly(t, pi1) |
| + if len(pi1.awake) != 0 { |
| + t.Fatalf("pi-1 still has %d awake", len(pi1.awake)) |
| + } |
| + w.wantNoLock(fleetA) |
| + pi1.heartbeat(w.now) |
| + // pi-2 takes the lease, restores, reads 1, writes 2. |
| + pi2.mustWake(fleetA) |
| + w.wantLock(fleetA, "pi-2") |
| + if got := pi2.read(fleetA); got != "1" { |
| + t.Fatalf("pi-2 read %q from a after the move, want 1", got) |
| + } |
| + pi2.write(fleetA, "2") |
| + |
| + // (4) Drain pi-2: a and b move to pi-1. pi-2 stays attached until its |
| + // heartbeat says it holds nothing. |
| + w.mustDo(http.MethodPost, "/api/cli/fleets/"+w.acct+"/pi/boxes/pi-2/drain", `{}`, http.StatusOK) |
| + w.wantRecord(fleetA, "pi-1", true) |
| + w.wantRecord(fleetB, "pi-1", true) |
| + w.wantForwards(map[string]string{fleetA: "pi-1", fleetB: "pi-1"}) |
| + row := w.boxRow("pi-2") |
| + if row.DrainingSince == 0 || row.Status != "active" { |
| + t.Fatalf("pi-2 after the drain: %+v, want active and draining", row) |
| + } |
| + since := time.Unix(0, row.DrainingSince) |
| + w.advance(time.Minute) |
| + if hb := pi2.heartbeat(w.now); hb.LeasesHeld != 1 { |
| + t.Fatalf("pi-2 reports %d leases held, want 1 (a)", hb.LeasesHeld) |
| + } |
| + w.mustDo(http.MethodPost, "/api/cli/fleets/"+w.acct+"/pi/boxes/pi-2/detach", `{}`, http.StatusConflict) |
| + pi2.mustReconcile() |
| + wantOnly(t, pi2) |
| + w.wantNoLock(fleetA) |
| + at := w.now.Add(3 * time.Minute) |
| + if since.Add(3 * time.Minute).After(at) { |
| + at = since.Add(3 * time.Minute) |
| + } |
| + w.now = at |
| + if hb := pi2.heartbeat(w.now); hb.LeasesHeld != 0 || hb.ReplicationFailures != 0 || hb.Routes.Resident+hb.Routes.Hibernating != 0 { |
| + t.Fatalf("drained pi-2 reports %+v routes, %d leases, %d failures", hb.Routes, hb.LeasesHeld, hb.ReplicationFailures) |
| + } |
| + w.mustDo(http.MethodPost, "/api/cli/fleets/"+w.acct+"/pi/boxes/pi-2/detach", `{}`, http.StatusOK) |
| + |
| + // pi-1 wakes a under the new assignment: its old copy (written under |
| + // the first) is set aside, the bucket's restored, and it reads 2, not |
| + // the 1 it left behind. |
| + pi1.mustReconcile() |
| + wantOnly(t, pi1, fleetA, fleetB) |
| + if n := len(pi1.setAside(fleetA)); n != 0 { |
| + t.Fatalf("pi-1 set aside %d copies of a before the wake", n) |
| + } |
| + pi1.mustWake(fleetA) |
| + if got := pi1.read(fleetA); got != "2" { |
| + t.Fatalf("pi-1 read %q from a after A, B, A; want 2", got) |
| + } |
| + if n := len(pi1.setAside(fleetA)); n != 1 { |
| + t.Fatalf("pi-1 set aside %d copies of a, want 1 (the copy kept under the first assignment)", n) |
| + } |
| + w.wantLock(fleetA, "pi-1") |
| + // b, never on pi-1 before, restores the copy pi-2 left. |
| + pi1.mustWake(fleetB) |
| + if got := pi1.read(fleetB); got != "b1" { |
| + t.Fatalf("pi-1 read %q from b, want b1", got) |
| + } |
| + if n := len(pi1.setAside(fleetB)); n != 0 { |
| + t.Fatalf("pi-1 set aside %d copies of b, which it never had", n) |
| + } |
| + pi1.mustStop(fleetA) |
| + pi1.mustStop(fleetB) |
| +} |
| + |
| +// TestTwoBoxFleetEndToEnd_RealFirstLabelling is step 5: a fleet whose |
| +// instances were created and served unlabelled (its boxes below the label |
| +// floor) is labelled once every box is on the floor, each record to the |
| +// box its binding names. Nothing moves and nothing is lost: each box sets |
| +// its copy aside once and restores the same data. |
| +func TestTwoBoxFleetEndToEnd_RealFirstLabelling(t *testing.T) { |
| + w := newFleetWorld(t, fleetOpts{rel: "v0.32.9"}) |
| + pi1, pi2 := w.pi1, w.pi2 |
| + w.create(fleetA) |
| + w.wantRecord(fleetA, "", false) |
| + w.create(fleetB) |
| + w.wantRecord(fleetB, "", false) |
| + |
| + // Unlabelled, as on main: both boxes mint both, the lease picks the |
| + // writer, and the winning wake publishes its binding. |
| + pi1.mustReconcile() |
| + pi2.mustReconcile() |
| + wantOnly(t, pi1, fleetA, fleetB) |
| + wantOnly(t, pi2, fleetA, fleetB) |
| + pi1.mustWake(fleetA) |
| + pi1.write(fleetA, "1") |
| + pi1.mustStop(fleetA) |
| + pi2.mustWake(fleetB) |
| + pi2.write(fleetB, "b1") |
| + pi2.mustStop(fleetB) |
| + |
| + // While the boxes run an older release the pass labels nothing. |
| + pi1.heartbeatRel(w.now, "v0.32.9") |
| + pi2.heartbeatRel(w.now, "v0.32.9") |
| + w.relabel() |
| + w.wantRecord(fleetA, "", false) |
| + w.wantRecord(fleetB, "", false) |
| + |
| + // Both boxes reach the floor: the first labelling follows the bindings. |
| + w.advance(time.Minute) |
| + pi1.heartbeat(w.now) |
| + pi2.heartbeat(w.now) |
| + w.relabel() |
| + w.wantRecord(fleetA, "pi-1", false) |
| + w.wantRecord(fleetB, "pi-2", false) |
| + w.wantForwards(map[string]string{fleetA: "pi-1", fleetB: "pi-2"}) |
| + |
| + pi1.mustReconcile() |
| + pi2.mustReconcile() |
| + wantOnly(t, pi1, fleetA) |
| + wantOnly(t, pi2, fleetB) |
| + for _, c := range []struct { |
| + b *fleetBox |
| + host, val string |
| + }{{pi1, fleetA, "1"}, {pi2, fleetB, "b1"}} { |
| + c.b.mustWake(c.host) |
| + if got := c.b.read(c.host); got != c.val { |
| + t.Fatalf("%s read %q from %s after the first labelling, want %s", c.b.label, got, c.host, c.val) |
| + } |
| + if n := len(c.b.setAside(c.host)); n != 1 { |
| + t.Fatalf("%s set aside %d copies of %s, want 1", c.b.label, n, c.host) |
| + } |
| + w.wantLock(c.host, c.b.label) |
| + c.b.write(c.host, c.val+"+") |
| + c.b.mustStop(c.host) |
| + // The next wake keeps the copy: it was kept under this assignment. |
| + c.b.mustWake(c.host) |
| + if got := c.b.read(c.host); got != c.val+"+" { |
| + t.Fatalf("%s read %q from %s on a warm wake, want %s+", c.b.label, got, c.host, c.val) |
| + } |
| + if n := len(c.b.setAside(c.host)); n != 1 { |
| + t.Fatalf("%s set aside %d copies of %s after a warm wake, want still 1", c.b.label, n, c.host) |
| + } |
| + c.b.mustStop(c.host) |
| + } |
| +} |
| + |
| +// TestTwoBoxFleetEndToEnd_RealLostBox is step 6: pi-1's agent dies with a |
| +// awake, without releasing. Its records move once it has been silent past |
| +// the lost-box horizon, and pi-2 takes the lease when it lapses (the short |
| +// TTL), restores and serves. When pi-1 comes back it drops a. |
| +func TestTwoBoxFleetEndToEnd_RealLostBox(t *testing.T) { |
| + w := newFleetWorld(t, fleetOpts{}) |
| + pi1, pi2 := w.pi1, w.pi2 |
| + w.create(fleetA) |
| + w.wantRecord(fleetA, "pi-1", false) |
| + pi1.mustReconcile() |
| + pi2.mustReconcile() |
| + wantOnly(t, pi1, fleetA) |
| + wantOnly(t, pi2) |
| + pi1.mustWake(fleetA) |
| + pi1.write(fleetA, "1") |
| + pi1.heartbeat(w.now) |
| + pi2.heartbeat(w.now) |
| + |
| + pi1.crash() |
| + expires := w.wantLock(fleetA, "pi-1") |
| + w.advance(25 * time.Minute) |
| + pi2.heartbeat(w.now) |
| + w.relabel() |
| + w.wantRecord(fleetA, "pi-2", true) |
| + pi2.mustReconcile() |
| + wantOnly(t, pi2, fleetA) |
| + if time.Now().Before(expires) { |
| + if err := pi2.wake(fleetA); err == nil || !strings.Contains(err.Error(), "lease held") { |
| + t.Fatalf("pi-2 woke a before pi-1's lease lapsed: %v", err) |
| + } |
| + } |
| + for deadline := time.Now().Add(3 * fleetTTL); ; time.Sleep(100 * time.Millisecond) { |
| + err := pi2.wake(fleetA) |
| + if err == nil { |
| + break |
| + } |
| + if !strings.Contains(err.Error(), "lease held") || time.Now().After(deadline) { |
| + t.Fatalf("pi-2's wake of a, %s after pi-1's lease was due to lapse: %v", time.Since(expires).Round(time.Millisecond), err) |
| + } |
| + } |
| + w.wantLock(fleetA, "pi-2") |
| + if got := pi2.read(fleetA); got != "1" { |
| + t.Fatalf("pi-2 read %q from a after the failover, want 1", got) |
| + } |
| + pi2.write(fleetA, "2") |
| + |
| + // pi-1 comes back: a new agent over the same disk. Its pass no longer |
| + // admits a and drops the row; it never takes the lease. |
| + pi1.start() |
| + pi1.mustReconcile() |
| + wantOnly(t, pi1) |
| + w.wantLock(fleetA, "pi-2") |
| + pi2.mustStop(fleetA) |
| +} |