carlos / platform Public

Clone
git clone https://amadan.net/carlos/platform

Plain git — no account needed to clone.

Download

Download this file

1package activator
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "slices"
8 "strings"
9 "sync"
10 "testing"
11 "time"
12
13 "github.com/carlosframework/platform/internal/registry"
14)
15
16// execLog is a BeforeExec hook that records host@build, the backend's spawn
17// count when it was asked (so a test can tell the record came before the
18// spawn), and the build-state location the context carried. fail, when
19// set, says which builds it refuses.
20type execLog struct {
21 mu sync.Mutex
22 calls []string
23 at []int
24 locs []BuildStateLocation
25 spawns func() int
26 fail func(build string) bool
27}
28
29func (l *execLog) hook(ctx context.Context, host, build string) error {
30 n := -1
31 if l.spawns != nil {
32 n = l.spawns()
33 }
34 loc, _ := BuildStateLocationFrom(ctx)
35 l.mu.Lock()
36 defer l.mu.Unlock()
37 l.calls = append(l.calls, host+"@"+build)
38 l.at = append(l.at, n)
39 l.locs = append(l.locs, loc)
40 if l.fail != nil && l.fail(build) {
41 return errors.New("bucket refused the build state")
42 }
43 return nil
44}
45
46func (l *execLog) seen() ([]string, []int, []BuildStateLocation) {
47 l.mu.Lock()
48 defer l.mu.Unlock()
49 return append([]string(nil), l.calls...), append([]int(nil), l.at...), append([]BuildStateLocation(nil), l.locs...)
50}
51
52func failAll(string) bool { return true }
53
54// --- the hook itself ---
55
56// Ruling R-EXEC-NOVERSION: an identity outside the version store has no
57// build a build state could name. With the hook set it is refused; with no
58// hook (a box with no replica bucket) it runs as today.
59func TestAnUnrecordableBuildIsRefused(t *testing.T) {
60 a := &Service{cfg: Config{Bucket: "b"}}
61 if err := a.recordBuild(context.Background(), "one.example.com", ""); err != nil {
62 t.Fatalf("a nil hook refused: %v", err)
63 }
64 var l execLog
65 a.BeforeExec = l.hook
66 err := a.recordBuild(context.Background(), "one.example.com", "")
67 if !errors.Is(err, errBuildStateUnwritten) {
68 t.Fatalf("err = %v, want errBuildStateUnwritten", err)
69 }
70 if calls, _, _ := l.seen(); len(calls) != 0 {
71 t.Fatalf("the hook was asked to record no build: %v", calls)
72 }
73}
74
75// The unclaimed lease's location rides to the hook, so the agent writes
76// beside this lease's lock.json; a location the caller already attached
77// (the claimed path, Task 5c) is kept. A hook error is wrapped so every
78// classifier reads it as a refusal.
79func TestTheHookIsToldWhereTheLeaseIs(t *testing.T) {
80 a := &Service{cfg: Config{Bucket: "hib", Prefix: "inst"}}
81 var l execLog
82 a.BeforeExec = l.hook
83 if err := a.recordBuild(context.Background(), "one.example.com", "v1"); err != nil {
84 t.Fatal(err)
85 }
86 claimed := BuildStateLocation{Bucket: "data", Prefix: "instances/one.example.com/inc1"}
87 if err := a.recordBuild(WithBuildStateLocation(context.Background(), claimed), "one.example.com", "v1"); err != nil {
88 t.Fatal(err)
89 }
90 calls, _, locs := l.seen()
91 if len(calls) != 2 || calls[0] != "one.example.com@v1" {
92 t.Fatalf("calls = %v", calls)
93 }
94 if want := (BuildStateLocation{Bucket: "hib", Prefix: HibernatePrefix("inst", "one.example.com")}); locs[0] != want {
95 t.Fatalf("location = %+v, want the hibernate lease's %+v", locs[0], want)
96 }
97 if locs[1] != claimed {
98 t.Fatalf("location = %+v, want the caller's %+v kept", locs[1], claimed)
99 }
100 l.fail = failAll
101 err := a.recordBuild(context.Background(), "one.example.com", "v1")
102 if !errors.Is(err, errBuildStateUnwritten) || !strings.Contains(err.Error(), "bucket refused") {
103 t.Fatalf("err = %v, want errBuildStateUnwritten carrying the cause", err)
104 }
105}
106
107// A wake's own record (Task 5b) is pending until its first exec (amadan
108// #272): a call for that build writes nothing, the exec seam writes it
109// once, and another build is written at once. A record of another build
110// supersedes the pending one, which the exec seam then never writes.
111func TestARecordedBuildIsNotWrittenTwice(t *testing.T) {
112 rt := registry.Route{Host: "one.example.com"}
113 a := &Service{cfg: Config{Bucket: "b"}}
114 var l execLog
115 a.BeforeExec = l.hook
116 ctx := wakeRecord(a, rt.Host, "v1")
117 if err := a.recordBuild(ctx, rt.Host, "v1"); err != nil {
118 t.Fatal(err)
119 }
120 if calls, _, _ := l.seen(); len(calls) != 0 {
121 t.Fatalf("calls = %v before any exec, want none", calls)
122 }
123 for range 2 {
124 if _, err := runPendingRecord(ctx); err != nil {
125 t.Fatal(err)
126 }
127 }
128 if err := a.recordBuild(ctx, rt.Host, "v2"); err != nil {
129 t.Fatal(err)
130 }
131 if calls, _, _ := l.seen(); !slices.Equal(calls, []string{"one.example.com@v1", "one.example.com@v2"}) {
132 t.Fatalf("calls = %v, want v1 once at the exec, then the fallback's v2", calls)
133 }
134
135 var s execLog
136 a.BeforeExec = s.hook
137 ctx = wakeRecord(a, rt.Host, "v1")
138 if err := a.recordBuild(ctx, rt.Host, "v2"); err != nil {
139 t.Fatal(err)
140 }
141 if _, err := runPendingRecord(ctx); err != nil {
142 t.Fatal(err)
143 }
144 if calls, _, _ := s.seen(); !slices.Equal(calls, []string{"one.example.com@v2"}) {
145 t.Fatalf("calls = %v, want only v2: the superseded v1 is never written", calls)
146 }
147
148 // A write that fails refuses every exec of the wake, and is not retried.
149 f := execLog{fail: failAll}
150 a.BeforeExec = f.hook
151 ctx = wakeRecord(a, rt.Host, "v1")
152 for range 2 {
153 if _, err := runPendingRecord(ctx); !errors.Is(err, errBuildStateUnwritten) {
154 t.Fatalf("err = %v, want errBuildStateUnwritten", err)
155 }
156 }
157 if calls, _, _ := f.seen(); len(calls) != 1 {
158 t.Fatalf("calls = %v, want one attempt", calls)
159 }
160}
161
162// wakeRecord is the context settleWakeIdentity returns for a wake of host
163// that settled build: its record pending.
164func wakeRecord(a *Service, host, build string) context.Context {
165 return withPendingRecord(context.Background(), build, func() error { return a.recordBuild(context.Background(), host, build) }, nil)
166}
167
168// Ruling R-WAKEWORDS: a member never sees the internal text.
169func TestMemberSeesFencedForAnUnwrittenBuildState(t *testing.T) {
170 err := fmt.Errorf("start one.example.com: %w", fmt.Errorf("%w: s3: access denied", errBuildStateUnwritten))
171 if got, want := memberSafeWakeReason(err), memberSafeWakeReason(ErrFenced); got != want {
172 t.Fatalf("member reads %q, want the fence's %q", got, want)
173 }
174}
175
176// A refused record is never a failure of the build, whichever classifier
177// reads it.
178func TestAnUnwrittenBuildStateIsARefusal(t *testing.T) {
179 err := fmt.Errorf("spawn: %w", fmt.Errorf("%w: s3: access denied", errBuildStateUnwritten))
180 if got := classifyStep(nil, err); got != stepStale {
181 t.Fatalf("classifyStep = %v, want stepStale", got)
182 }
183 if got := verdictOf(err); got != gateNoOwnership {
184 t.Fatalf("verdictOf = %v, want a refusal", got)
185 }
186}
187
188// --- every chokepoint that execs a captured identity (anchors-exec §1) ---
189
190// #11: a hold swap's pinned wake records the attempt's build before its
191// exec; a refused record abandons the attempt with nothing exec'd.
192func TestBeforeExecRunsBeforeAHoldSwap(t *testing.T) {
193 t.Parallel()
194 f := newSwapFixture(t)
195 l := &execLog{spawns: func() int { n, _, _ := f.b.calls(); return n }}
196 f.a.BeforeExec = l.hook
197 res := f.a.Swap(context.Background(), f.attempt(ModeHold), f.newest)
198 if res.Outcome != SwapDone {
199 t.Fatalf("Swap = %+v", res)
200 }
201 calls, at, locs := l.seen()
202 if len(calls) != 1 || calls[0] != f.host+"@v2" || at[0] != 0 {
203 t.Fatalf("records %v at spawn counts %v, want %s@v2 before the exec", calls, at, f.host)
204 }
205 if locs[0] != (BuildStateLocation{Bucket: "test-bucket", Prefix: HibernatePrefix("", f.host)}) {
206 t.Fatalf("location = %+v", locs[0])
207 }
208 if gens, _, _ := f.b.calls(); gens != 1 {
209 t.Fatalf("StartStaged calls = %d, want 1", gens)
210 }
211
212 f = newSwapFixture(t)
213 f.a.BeforeExec = (&execLog{fail: failAll}).hook
214 res = f.a.Swap(context.Background(), f.attempt(ModeHold), f.newest)
215 if res.Outcome != SwapAbandoned || !strings.Contains(res.Reason, errBuildStateUnwritten.Error()) {
216 t.Fatalf("Swap = %+v, want abandoned for the unwritten build state", res)
217 }
218 if gens, _, _ := f.b.calls(); gens != 0 {
219 t.Fatalf("StartStaged calls = %d: a build ran unrecorded", gens)
220 }
221}
222
223// #12: an overlap successor records its build before its exec; a refused
224// record is SwapAbandoned, never SwapFailed (which the scheduler writes as
225// the build's failure), and the incumbent keeps serving.
226func TestBeforeExecRunsBeforeAnOverlapSuccessor(t *testing.T) {
227 t.Parallel()
228 f := newSwapFixture(t)
229 l := &execLog{spawns: func() int { n, _, _ := f.b.calls(); return n }}
230 f.a.BeforeExec = l.hook
231 res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest)
232 if res.Outcome != SwapDone {
233 t.Fatalf("Swap = %+v", res)
234 }
235 if calls, at, _ := l.seen(); len(calls) != 1 || calls[0] != f.host+"@v2" || at[0] != 0 {
236 t.Fatalf("records %v at spawn counts %v, want %s@v2 before the exec", calls, at, f.host)
237 }
238
239 f = newSwapFixture(t)
240 f.a.BeforeExec = (&execLog{fail: failAll}).hook
241 res = f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest)
242 if res.Outcome != SwapAbandoned || !strings.Contains(res.Reason, errBuildStateUnwritten.Error()) {
243 t.Fatalf("Swap = %+v, want abandoned (never failed) for the unwritten build state", res)
244 }
245 if gens, _, _ := f.b.calls(); gens != 0 {
246 t.Fatalf("StartStaged calls = %d: a build ran unrecorded", gens)
247 }
248 if got := f.appSocket(t); got != f.incumbent.Socket {
249 t.Fatalf("AppSocket = %q, want the incumbent's", got)
250 }
251 if _, raises, restores := f.b.calls(); raises != restores {
252 t.Fatalf("raises %d restores %d: the parent limit was not restored", raises, restores)
253 }
254}
255
256// #13: a planned boot records B before its exec; a refused record execs
257// nothing and records nothing against B.
258func TestBeforeExecRunsBeforeAPlannedBoot(t *testing.T) {
259 t.Parallel()
260 dir := t.TempDir()
261 next := stagedID(t, dir, "v2")
262 a, b, _ := planActivator(t, WakePlan{Boot: next, Mode: ModeOverlap})
263 l := &execLog{spawns: func() int { return len(b.started()) }}
264 a.BeforeExec = l.hook
265 done, err := a.beginRequest(context.Background(), testRoute("one.example.com"))
266 if err != nil {
267 t.Fatalf("the wake: %v", err)
268 }
269 done()
270 if calls, at, _ := l.seen(); len(calls) != 1 || calls[0] != "one.example.com@v2" || at[0] != 0 {
271 t.Fatalf("records %v at spawn counts %v, want one.example.com@v2 before the exec", calls, at)
272 }
273
274 dir = t.TempDir()
275 good, next := stagedID(t, dir, "v1"), stagedID(t, dir, "v2")
276 a, b, evs := planActivator(t, WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true, Fallback: &good})
277 a.BeforeExec = (&execLog{fail: failAll}).hook
278 _, err = a.beginRequest(context.Background(), testRoute("one.example.com"))
279 if !errors.Is(err, errBuildStateUnwritten) {
280 t.Fatalf("err = %v, want errBuildStateUnwritten", err)
281 }
282 if gens := b.started(); len(gens) != 0 {
283 t.Fatalf("spawned %+v: a build ran unrecorded", gens)
284 }
285 time.Sleep(50 * time.Millisecond)
286 if k := evs.kinds(); len(k) != 0 {
287 t.Fatalf("events %v: a build that never ran was recorded", k)
288 }
289}
290
291// #15: the fallback is a different build touching the data, so it records
292// again before its own exec. A refused record starts no good build; B's own
293// failure (it did fail) stays its own, and nothing falls back.
294func TestBeforeExecRunsBeforeAPlannedFallback(t *testing.T) {
295 t.Parallel()
296 dir := t.TempDir()
297 good, next := stagedID(t, dir, "v1"), stagedID(t, dir, "v2")
298 a, b, evs := planActivator(t, WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true, Fallback: &good})
299 a.genHealth = func(_ context.Context, g Gen) error {
300 if g.Build == "v2" {
301 return errors.New("GET / answered 500")
302 }
303 return nil
304 }
305 l := &execLog{spawns: func() int { return len(b.started()) }}
306 a.BeforeExec = l.hook
307 done, err := a.beginRequest(context.Background(), testRoute("one.example.com"))
308 if err != nil {
309 t.Fatalf("the wake: %v", err)
310 }
311 done()
312 calls, at, _ := l.seen()
313 if len(calls) != 2 || calls[0] != "one.example.com@v2" || calls[1] != "one.example.com@v1" || at[0] != 0 || at[1] != 1 {
314 t.Fatalf("records %v at spawn counts %v, want v2 before B's exec, then v1 before the fallback's", calls, at)
315 }
316 evs.wait(t, GenFellBack)
317
318 a, b, evs = planActivator(t, WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true, Fallback: &good})
319 a.genHealth = func(context.Context, Gen) error { return errors.New("GET / answered 500") }
320 a.BeforeExec = (&execLog{fail: func(build string) bool { return build == "v1" }}).hook
321 // The wake's error is B's failure (spawnPlanned wraps it); the
322 // fallback's refusal is its detail.
323 if _, err := a.beginRequest(context.Background(), testRoute("one.example.com")); err == nil || !strings.Contains(err.Error(), errBuildStateUnwritten.Error()) {
324 t.Fatalf("err = %v, want B's failure with the fallback's unwritten build state", err)
325 }
326 if gens := b.started(); len(gens) != 1 || gens[0].Build != "v2" {
327 t.Fatalf("spawned %+v, want B alone", gens)
328 }
329 if ev := evs.wait(t, GenFailed); ev.Failed.Version != "v2" {
330 t.Fatalf("failure event = %+v, want B's own", ev)
331 }
332 time.Sleep(50 * time.Millisecond)
333 for _, k := range evs.kinds() {
334 if k == GenFellBack {
335 t.Fatalf("events %v: a fallback that never ran was reported", evs.kinds())
336 }
337 }
338}
339
340// #5: a worker wake records the identity it is about to exec, after its
341// publication; a refused record execs nothing and fails the wake.
342func TestBeforeExecRunsBeforeAWorkerWake(t *testing.T) {
343 t.Parallel()
344 a, b, _, _, _ := stagedActivator(t)
345 host := "bot.x.internal"
346 l := &execLog{spawns: b.workerStarts}
347 a.BeforeExec = l.hook
348 if err := a.WakeWorker(alwaysOnWorkerRoute(host)); err != nil {
349 t.Fatalf("WakeWorker: %v", err)
350 }
351 calls, at, locs := l.seen()
352 if len(calls) != 1 || calls[0] != host+"@v1" || at[0] != 0 {
353 t.Fatalf("records %v at spawn counts %v, want %s@v1 before the exec", calls, at, host)
354 }
355 if locs[0] != (BuildStateLocation{Bucket: "test-bucket", Prefix: HibernatePrefix("", host)}) {
356 t.Fatalf("location = %+v, want the worker's own lease", locs[0])
357 }
358
359 a, b, _, _, _ = stagedActivator(t)
360 a.BeforeExec = (&execLog{fail: failAll}).hook
361 if err := a.WakeWorker(alwaysOnWorkerRoute(host)); !errors.Is(err, errBuildStateUnwritten) {
362 t.Fatalf("WakeWorker = %v, want errBuildStateUnwritten", err)
363 }
364 if n := b.workerStarts(); n != 0 {
365 t.Fatalf("%d worker children: a build ran unrecorded", n)
366 }
367}
368
369// #7: a crash restart records the captured build before it respawns it. A
370// refused record is a refusal: nothing exec'd, no "failed to respawn"
371// member error event, and the sweep asks again.
372func TestBeforeExecRunsBeforeAWorkerRecycle(t *testing.T) {
373 t.Parallel()
374 a, b, clk, _, _ := stagedActivator(t)
375 sink := &lockedSink{}
376 a.Logs = sink
377 host := "bot.x.internal"
378 l := &execLog{spawns: b.workerStarts}
379 a.BeforeExec = l.hook
380 if err := a.WakeWorker(alwaysOnWorkerRoute(host)); err != nil {
381 t.Fatalf("WakeWorker: %v", err)
382 }
383 b.lastWorker().kill()
384 a.sweepOnce()
385 waitForRestart(t, a, b.fakeBackend, host, 2)
386 calls, at, _ := l.seen()
387 if len(calls) != 2 || calls[1] != host+"@v1" || at[1] != 1 {
388 t.Fatalf("records %v at spawn counts %v, want the recycle's %s@v1 before its exec", calls, at, host)
389 }
390
391 l.mu.Lock()
392 l.fail = failAll
393 l.mu.Unlock()
394 b.lastWorker().kill()
395 clk.advance(sidecarRestartMax + time.Second)
396 a.sweepOnce()
397 waitForSpawnCalls(t, a, b, host, 3)
398 if n := b.workerStarts(); n != 2 {
399 t.Fatalf("%d worker children: a build ran unrecorded", n)
400 }
401 sink.mu.Lock()
402 defer sink.mu.Unlock()
403 for _, ev := range sink.events {
404 if ev.level == "error" {
405 t.Fatalf("member event %+v: a refused record read as a failed respawn", ev)
406 }
407 }
408}
409
410// #10: ReplaceWorker's attempt records its build before the exec; a refused
411// record is abandonment, never a failure of the build.
412func TestBeforeExecRunsBeforeReplaceWorker(t *testing.T) {
413 shrinkFirstWake(t, 55*time.Second, 25*time.Second, 100*time.Millisecond)
414 a, b, _, _, _ := stagedActivator(t)
415 host := "bot.x.internal"
416 l := &execLog{spawns: b.workerStarts}
417 a.BeforeExec = l.hook
418 if err := a.WakeWorker(alwaysOnWorkerRoute(host)); err != nil {
419 t.Fatal(err)
420 }
421 res := a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeOverlap, fakeIdentity("v2")), nil, one)
422 if res.Outcome != SwapDone {
423 t.Fatalf("ReplaceWorker = %+v", res)
424 }
425 if calls, at, _ := l.seen(); len(calls) != 2 || calls[1] != host+"@v2" || at[1] != 1 {
426 t.Fatalf("records %v at spawn counts %v, want %s@v2 before the attempt's exec", calls, at, host)
427 }
428
429 a, b, _, _, _ = stagedActivator(t)
430 l = &execLog{fail: func(build string) bool { return build == "v2" }}
431 a.BeforeExec = l.hook
432 if err := a.WakeWorker(alwaysOnWorkerRoute(host)); err != nil {
433 t.Fatal(err)
434 }
435 res = a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeOverlap, fakeIdentity("v2")), nil, one)
436 if res.Outcome != SwapAbandoned || !strings.Contains(res.Reason, errBuildStateUnwritten.Error()) {
437 t.Fatalf("ReplaceWorker = %+v, want abandoned: an unrecorded build never ran", res)
438 }
439 waitFor(t, "the respawns to finish", func() bool { return !a.entryRespawning(host) })
440 // Every child had a recorded build before it, and v2 never served.
441 calls, _, _ := l.seen()
442 recorded := 0
443 for _, c := range calls {
444 if c != host+"@v2" {
445 recorded++
446 }
447 }
448 if !slices.Contains(calls, host+"@v2") || b.workerStarts() != recorded {
449 t.Fatalf("records %v, %d worker children: a child ran without its build recorded", calls, b.workerStarts())
450 }
451 if got := a.entryServing(host); got.Version == "v2" {
452 t.Fatalf("serving %+v: v2 ran unrecorded", got)
453 }
454 // Fix round 1: nothing of v2 ran, so the replaced v1 is restored at
455 // once, with no sweep: the worker is not left down until the next
456 // crash restart.
457 if got, w := a.entryServing(host), b.lastWorker(); got != fakeIdentity("v1") || b.workerStarts() != 2 || w == nil || w.Exited() {
458 t.Fatalf("serving %+v with %d children (last exited: %v); want v1 restored and running without a sweep", got, b.workerStarts(), w != nil && w.Exited())
459 }
460}
461