| new file mode 100644 |
| index 000000000..896dce820 |
| --- /dev/null |
| +++ b/internal/console/managedfreshsim_test.go |
| @@ -0,0 +1,430 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "errors" |
| + "fmt" |
| + "math/rand/v2" |
| + "os" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// simClock is a controlled clock. A pending advance, armed by a goroutine |
| +// holding the fleet lock, takes effect after the next reading: that models a |
| +// relock wait that begins right after an observation dates its checks. |
| +type simClock struct { |
| + mu sync.Mutex |
| + t time.Time |
| + read chan struct{} // signalled after the next reading, when armed |
| + fallbacks int // relock waits that saw no reading first |
| +} |
| + |
| +func (c *simClock) now() time.Time { |
| + c.mu.Lock() |
| + t, read := c.t, c.read |
| + c.read = nil |
| + c.mu.Unlock() |
| + if read != nil { |
| + close(read) |
| + } |
| + return t |
| +} |
| +func (c *simClock) add(d time.Duration) { |
| + c.mu.Lock() |
| + c.t = c.t.Add(d) |
| + c.mu.Unlock() |
| +} |
| + |
| +// holdLockAfterNextReading takes the fleet lock now (the caller is inside an |
| +// unlocked call), and after the clock's next reading, or a short real-time |
| +// fallback, advances the clock by d and releases it: the worker's relock |
| +// waits d of clock time. |
| +func (c *simClock) holdLockAfterNextReading(s *Server, fleet string, d time.Duration) { |
| + unlock := s.lockFleet(fleet) |
| + read := make(chan struct{}) |
| + c.mu.Lock() |
| + c.read = read |
| + c.mu.Unlock() |
| + go func() { |
| + select { |
| + case <-read: |
| + case <-time.After(200 * time.Millisecond): |
| + c.mu.Lock() |
| + if c.read == read { |
| + c.read = nil |
| + } |
| + c.fallbacks++ |
| + c.mu.Unlock() |
| + } |
| + c.add(d) |
| + unlock() |
| + }() |
| +} |
| + |
| +// simMemStore is an in-memory release.Store with the DirStore's CAS |
| +// semantics ("" is create-only), so seeds do not pay for fsyncs. |
| +type simMemStore struct { |
| + mu sync.Mutex |
| + objects map[string][]byte |
| +} |
| + |
| +func simEtag(b []byte) string { sum := sha256.Sum256(b); return hex.EncodeToString(sum[:]) } |
| +func newSimMemStore(t *testing.T, from release.Store) *simMemStore { |
| + t.Helper() |
| + keys, err := from.List(context.Background(), "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + m := &simMemStore{objects: map[string][]byte{}} |
| + for _, k := range keys { |
| + raw, _, err := from.Get(context.Background(), k) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + m.objects[k] = raw |
| + } |
| + return m |
| +} |
| +func (m *simMemStore) Get(_ context.Context, key string) ([]byte, string, error) { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + raw, ok := m.objects[key] |
| + if !ok { |
| + return nil, "", fmt.Errorf("simstore: %s: %w", key, os.ErrNotExist) |
| + } |
| + return append([]byte(nil), raw...), simEtag(raw), nil |
| +} |
| +func (m *simMemStore) Put(_ context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + cur, ok := m.objects[key] |
| + if (ifMatch == "" && ok) || (ifMatch != "" && (!ok || simEtag(cur) != ifMatch)) { |
| + return "", fmt.Errorf("simstore: %s: %w", key, release.ErrCASConflict) |
| + } |
| + m.objects[key] = append([]byte(nil), body...) |
| + return simEtag(body), nil |
| +} |
| +func (m *simMemStore) List(_ context.Context, prefix string) ([]string, error) { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + var out []string |
| + for k := range m.objects { |
| + if strings.HasPrefix(k, prefix) { |
| + out = append(out, k) |
| + } |
| + } |
| + sort.Strings(out) |
| + return out, nil |
| +} |
| +func (m *simMemStore) ListDirs(_ context.Context, prefix string) ([]string, error) { |
| + if prefix != "" && !strings.HasSuffix(prefix, "/") { |
| + prefix += "/" |
| + } |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + seen := map[string]bool{} |
| + for k := range m.objects { |
| + if rest, ok := strings.CutPrefix(k, prefix); ok { |
| + if dir, _, nested := strings.Cut(rest, "/"); nested { |
| + seen[prefix+dir+"/"] = true |
| + } |
| + } |
| + } |
| + var out []string |
| + for d := range seen { |
| + out = append(out, d) |
| + } |
| + sort.Strings(out) |
| + return out, nil |
| +} |
| +func (m *simMemStore) Delete(_ context.Context, key string) error { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + delete(m.objects, key) |
| + return nil |
| +} |
| + |
| +type funcExtras func(context.Context, managedBox) (managedCheck, managedCheck, error) |
| + |
| +func (f funcExtras) Checks(ctx context.Context, b managedBox) (managedCheck, managedCheck, error) { |
| + return f(ctx, b) |
| +} |
| + |
| +// TestManagedPublicationFreshnessWitness: the checks are dated inside the |
| +// observation, before the fleet lock is taken back. A relock wait or a |
| +// restart that carries them past a minute grants nothing. |
| +func TestManagedPublicationFreshnessWitness(t *testing.T) { |
| + pass := managedCheck{State: "pass"} |
| + t.Run("relock", func(t *testing.T) { |
| + s, b, now := readyFixture(t) |
| + clock := &simClock{t: now} |
| + s.managedClock = clock.now |
| + st := countReadiness(s) |
| + calls := 0 |
| + s.managedExtra = funcExtras(func(context.Context, managedBox) (managedCheck, managedCheck, error) { |
| + calls++ |
| + if calls == 1 { |
| + // A member operation takes the lock while the observation |
| + // finishes; the worker's relock waits 70 s. |
| + clock.holdLockAfterNextReading(s, b.Fleet, 70*time.Second) |
| + return pass, pass, nil |
| + } |
| + return pass, managedCheck{State: "pending"}, nil |
| + }) |
| + b = workerStep(t, s, now) |
| + if st.puts != 0 || b.State != "publishing" || !b.ReadyAt.Equal(now) || !b.ReadinessCheckedAt.Equal(now.Add(70*time.Second)) { |
| + t.Fatalf("checks 70 s old after the relock authorized a PUT: puts=%d %+v", st.puts, b) |
| + } |
| + }) |
| + t.Run("restart", func(t *testing.T) { |
| + s, b, now := readyFixture(t) |
| + clock := &simClock{t: now} |
| + s.managedClock = clock.now |
| + st := countReadiness(s) |
| + st.failPut = true |
| + b = workerStep(t, s, now) |
| + st.failPut = false |
| + if st.puts != 1 || !b.ReadinessCheckedAt.Equal(now) { |
| + t.Fatalf("fixture: %+v", b) |
| + } |
| + // The process died after the stamp and before the PUT landed. |
| + s = restartManagedWorker(t, s) |
| + s.managedExtra = readyExtras{pass, managedCheck{State: "pending"}} |
| + clock.add(70 * time.Second) |
| + if b = workerStep(t, s, now.Add(70*time.Second)); st.puts != 1 || b.State != "publishing" { |
| + t.Fatalf("restart PUT on 70 s old checks: puts=%d %+v", st.puts, b) |
| + } |
| + }) |
| +} |
| + |
| +// freshnessSim drives one publishing box through seeded schedules and checks |
| +// the invariant at every ready-object PUT the store sees: the PUT's clock |
| +// reading is at most managedPublicationFreshFor after the completion of the |
| +// latest observation in which all six checks passed. |
| +type freshnessSim struct { |
| + t *testing.T |
| + rng *rand.Rand |
| + clock *simClock |
| + s *Server |
| + inner release.Store |
| + b managedBox |
| + logf func(string, ...any) |
| + lastPass time.Time |
| + puts int |
| + bad []string |
| +} |
| + |
| +func (m *freshnessSim) chance(p float64) bool { return m.rng.Float64() < p } |
| +func (m *freshnessSim) latency(max time.Duration) { |
| + d := time.Duration(m.rng.Int64N(int64(max))) |
| + if m.chance(0.05) { |
| + d += time.Duration(m.rng.Int64N(int64(2 * time.Minute))) // clock jump |
| + } |
| + m.clock.add(d) |
| +} |
| + |
| +// contend runs a member operation, or holds the fleet lock for a while, |
| +// during an unlocked call. |
| +func (m *freshnessSim) contend() { |
| + switch { |
| + case m.chance(0.1): |
| + _, _ = m.s.drainBox(context.Background(), m.b.Fleet, m.b.Label) |
| + case m.chance(0.1): |
| + unlock := m.s.lockFleet(m.b.Fleet) |
| + m.clock.add(time.Duration(m.rng.Int64N(int64(90 * time.Second)))) |
| + unlock() |
| + } |
| +} |
| + |
| +type freshnessSimStore struct { |
| + release.Store |
| + m *freshnessSim |
| +} |
| + |
| +func (st *freshnessSimStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + m := st.m |
| + switch { |
| + case strings.HasSuffix(key, "/ready.json"): |
| + m.latency(40 * time.Second) |
| + m.contend() |
| + if m.chance(0.1) { |
| + return nil, "", errors.New("unavailable") |
| + } |
| + case key == release.FleetOwnerKey(m.b.Account, m.b.Fleet): |
| + m.latency(20 * time.Second) |
| + if m.chance(0.05) { |
| + return nil, "", errors.New("unavailable") |
| + } |
| + raw, tag, err := st.Store.Get(ctx, key) |
| + if err == nil { |
| + // The owner record is the last check, read only once the other |
| + // five pass: all six pass as of this reading. |
| + m.lastPass = m.clock.now() |
| + m.logf("observation passed at %v", m.lastPass.Sub(m.b.LaunchStartedAt)) |
| + if m.chance(0.25) { |
| + m.clock.holdLockAfterNextReading(m.s, m.b.Fleet, time.Duration(m.rng.Int64N(int64(90*time.Second)))) |
| + } |
| + } |
| + return raw, tag, err |
| + default: |
| + m.latency(15 * time.Second) |
| + } |
| + return st.Store.Get(ctx, key) |
| +} |
| +func (st *freshnessSimStore) Put(ctx context.Context, key string, raw []byte, tag string) (string, error) { |
| + m := st.m |
| + if !strings.HasSuffix(key, "/ready.json") { |
| + return st.Store.Put(ctx, key, raw, tag) |
| + } |
| + at := m.clock.now() |
| + m.puts++ |
| + age := at.Sub(m.lastPass) |
| + m.logf("PUT at %v, checks %v old", at.Sub(m.b.LaunchStartedAt), age) |
| + if m.lastPass.IsZero() || age > managedPublicationFreshFor || tag != "" { |
| + m.bad = append(m.bad, fmt.Sprintf("PUT at %v on checks %v old (tag %q)", at.Sub(m.b.LaunchStartedAt), age, tag)) |
| + } |
| + m.latency(20 * time.Second) |
| + switch { |
| + case m.chance(0.6): |
| + return "", errors.New("unavailable") |
| + case m.chance(0.2): |
| + _, _ = st.Store.Put(ctx, key, raw, tag) |
| + return "", errors.New("lost response") |
| + } |
| + return st.Store.Put(ctx, key, raw, tag) |
| +} |
| + |
| +type freshnessSimRegistry struct { |
| + inner interface { |
| + GetFleetContext(context.Context, string) (*registry.Fleet, error) |
| + ListFleetBoxesContext(context.Context, string) ([]registry.FleetBox, error) |
| + } |
| + m *freshnessSim |
| +} |
| + |
| +func (r *freshnessSimRegistry) GetFleetContext(ctx context.Context, name string) (*registry.Fleet, error) { |
| + r.m.latency(10 * time.Second) |
| + if r.m.chance(0.08) { |
| + return nil, errors.New("registry unavailable") |
| + } |
| + return r.inner.GetFleetContext(ctx, name) |
| +} |
| +func (r *freshnessSimRegistry) ListFleetBoxesContext(ctx context.Context, name string) ([]registry.FleetBox, error) { |
| + r.m.latency(10 * time.Second) |
| + if r.m.chance(0.04) { |
| + return nil, errors.New("registry unavailable") |
| + } |
| + return r.inner.ListFleetBoxesContext(ctx, name) |
| +} |
| + |
| +// install wires the sim into a (possibly restarted) server. |
| +func (m *freshnessSim) install(s *Server) { |
| + m.s = s |
| + // Durability is not under test here; skip fsyncs to keep seeds cheap. |
| + if _, err := s.store.db.Exec(`PRAGMA synchronous=OFF`); err != nil { |
| + m.t.Fatal(err) |
| + } |
| + s.managedClock = m.clock.now |
| + s.cfg.Releases = &freshnessSimStore{Store: m.inner, m: m} |
| + inner := s.store.managedRegistry |
| + if wrapped, ok := inner.(*freshnessSimRegistry); ok { |
| + inner = wrapped.inner |
| + } |
| + s.store.managedRegistry = &freshnessSimRegistry{inner: inner, m: m} |
| + s.managedExtra = funcExtras(func(context.Context, managedBox) (managedCheck, managedCheck, error) { |
| + m.latency(20 * time.Second) |
| + router := managedCheck{State: "pass"} |
| + if m.chance(0.3) { |
| + router.State = "pending" |
| + } |
| + return managedCheck{State: "pass"}, router, nil |
| + }) |
| +} |
| + |
| +// TestManagedPublicationFreshnessSim randomizes observation duration, relock |
| +// waits, ready-object latency, clock jumps, member contention and restarts. |
| +// MANAGED_FRESHNESS_SEEDS sets the seed count (default 300); |
| +// MANAGED_FRESHNESS_SEED runs one seed and logs every step. |
| +func TestManagedPublicationFreshnessSim(t *testing.T) { |
| + seeds, first := 300, uint64(1) |
| + verbose := false |
| + if v := os.Getenv("MANAGED_FRESHNESS_SEEDS"); v != "" { |
| + n, err := strconv.Atoi(v) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + seeds = n |
| + } |
| + if v := os.Getenv("MANAGED_FRESHNESS_SEED"); v != "" { |
| + n, err := strconv.ParseUint(v, 10, 64) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + seeds, first, verbose = 1, n, true |
| + } |
| + s, _, now := readyFixture(t) |
| + base := workerBox(t, s) |
| + inner := newSimMemStore(t, s.cfg.Releases) |
| + reg, _ := openRegistry(s.cfg.Registry) |
| + puts, published, fallbacks, steps := 0, 0, 0, 0 |
| + for seed := first; seed < first+uint64(seeds); seed++ { |
| + m := &freshnessSim{t: t, rng: rand.New(rand.NewPCG(seed, seed^0x9e3779b97f4a7c15)), clock: &simClock{t: now}, inner: inner, b: base, logf: func(string, ...any) {}} |
| + if verbose { |
| + m.logf = t.Logf |
| + } |
| + // Reset the box, the ready object and the joining drain. |
| + if _, err := s.store.db.Exec(`UPDATE managed_boxes SET state=?,cloud_id=?,launch=?,enrol_used_at=0`, base.State, base.CloudID, []byte(base.storedLaunch)); err != nil { |
| + t.Fatal(err) |
| + } |
| + _ = inner.Delete(context.Background(), managedReadyKey(base)) |
| + if _, err := reg.SetFleetBoxDraining(base.Fleet, base.Label, base.EnrolDrainStart); err != nil { |
| + t.Fatal(err) |
| + } |
| + m.install(s) |
| + for step := 0; step < 40; step++ { |
| + if m.chance(0.8) { |
| + readyBeatIn(t, inner, base, status.Box{Label: base.Label, GeneratedAt: m.clock.now(), Metrics: &status.BoxMetrics{Release: "v0.34.0", RootfsReady: true}}) |
| + } |
| + if m.chance(0.1) { |
| + s = restartManagedWorker(t, s) |
| + m.install(s) |
| + m.logf("restart") |
| + } |
| + at := m.clock.now() |
| + steps++ |
| + err := s.stepManagedBox(context.Background(), workerBox(t, s), at) |
| + got := workerBox(t, s) |
| + m.logf("step %d at %v: %s err=%v checked=%v", step, at.Sub(base.LaunchStartedAt), got.State, err, got.ReadinessCheckedAt.Sub(base.LaunchStartedAt)) |
| + if got.State != "enrolled" && got.State != "publishing" { |
| + if got.State == "ready" { |
| + published++ |
| + } |
| + break |
| + } |
| + m.clock.add(time.Duration(1+m.rng.Int64N(30)) * time.Second) |
| + } |
| + puts += m.puts |
| + fallbacks += m.clock.fallbacks |
| + for _, bad := range m.bad { |
| + t.Errorf("seed %d: %s", seed, bad) |
| + } |
| + if t.Failed() { |
| + return |
| + } |
| + } |
| + t.Logf("freshness sim: %d seeds, %d steps, %d PUTs checked, %d boxes published, %d relock waits without a prior reading", seeds, steps, puts, published, fallbacks) |
| + if seeds >= 50 && (puts == 0 || published == 0) { |
| + t.Fatal("simulation never exercised publication") |
| + } |
| +} |