package session_test import ( "encoding/json" "errors" "testing" "testing/synctest" "time" "tangled.org/guid.foo/simmer/api/v1alpha1" "tangled.org/guid.foo/simmer/cluster" "tangled.org/guid.foo/simmer/dataplane" "tangled.org/guid.foo/simmer/internal/world" "tangled.org/guid.foo/simmer/session" ) const hookTemplate = `{"spec":{"containers":[{"name":"hook","image":"status:1","args":["post"]}]}}` // hooked puts the fixture's Mandate and its Duty triage with the hooks // named, before, after, or both, and answers the two. func hooked(t *testing.T, f *fixture, before, after bool) (*v1alpha1.Mandate, *v1alpha1.Duty) { t.Helper() hooks := &v1alpha1.Hooks{} if before { hooks.Before = json.RawMessage(hookTemplate) } if after { hooks.After = json.RawMessage(hookTemplate) } m := readyMandate() duty := world.When(m, "triage", "alerts", "firing") duty.Spec.Hooks = hooks f.w.Put(cluster.Mandates, m) f.w.Put(cluster.Duties, duty) synctest.Wait() return m, duty } func exists(f *fixture, job string) bool { _, ok := world.Get[cluster.Job](f.w, cluster.Jobs, "telemetry", job) return ok } func TestABeforeHookRunsAndTheTurnStartsWhenItEnds(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) hooked(t, f, true, false) f.pass(t, room, false) waiting := f.session() f.end(t, "ops-a-1-before", false) f.pass(t, room, false) if !exists(f, "ops-a-1-before") || waiting.Status.Phase != v1alpha1.PhaseRunning || waiting.Status.WaitingOn != v1alpha1.WaitingOnHook || waiting.Status.Turns[0].StartedAt != nil { t.Errorf("status = %+v, want the before hook running and the turn not started", waiting.Status) } s := f.session() if !exists(f, "ops-a-1") || s.Status.WaitingOn != v1alpha1.WaitingOnJob || s.Status.Turns[0].Before.Outcome != v1alpha1.OutcomeFailed { t.Errorf("status = %+v, want turn 1 running after its before hook failed", s.Status) } }) } func TestABeforeHookTakesTheTurnsSlot(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) m, _ := hooked(t, f, true, false) m.Spec.Sessions.MaxActive = 1 f.w.Put(cluster.Mandates, m) b := world.Session("telemetry", "ops-b", "ops", "triage") b.Status.Keys = []string{"b"} f.w.Put(cluster.Sessions, b) _ = f.store.Deliver(dataplane.SessionRef{Namespace: "telemetry", Name: "ops-b"}, dataplane.Event{ID: "b1"}) time.Sleep(time.Second) synctest.Wait() f.pass(t, room, false) f.pass(t, room, false) if got := sessionB(f).Status.WaitingOn; got != v1alpha1.WaitingOnCapacity || exists(f, "ops-b-1-before") { t.Errorf("ops-b waits on %s, want capacity while ops-a's before hook holds the one slot", got) } }) } // afterTurn runs turn 1 with an after hook to its end, and delivers a // second event while it runs. func afterTurn(t *testing.T, f *fixture, succeeded bool) { t.Helper() f.pass(t, room, false) _, _ = f.store.Take(f.ref, 1) _ = f.store.Deliver(f.ref, dataplane.Event{ID: "b", Signal: "alerts"}) f.end(t, "ops-a-1", succeeded) f.pass(t, room, false) } func TestAnAfterHookRunsWhenTheTurnEndsAndTheNextTurnWaitsForIt(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) hooked(t, f, false, true) afterTurn(t, f, true) waiting := f.session() kept, _ := f.store.Kept(f.ref, 1) f.pass(t, room, false) f.end(t, "ops-a-1-after", true) f.pass(t, room, false) if !exists(f, "ops-a-1-after") || waiting.Status.WaitingOn != v1alpha1.WaitingOnHook || waiting.Status.Phase != v1alpha1.PhaseWaiting || waiting.Status.TurnCount != 1 { t.Errorf("status = %+v, want the after hook running and no second turn", waiting.Status) } if len(kept) != 1 || kept[0].ID != "a" { t.Errorf("the after hook reads %+v, want turn 1's event a", kept) } if after, _ := f.store.Kept(f.ref, 1); len(after) != 0 || !exists(f, "ops-a-2") { t.Errorf("turn 1 still keeps %+v, or turn 2 did not start, after the hook ended", after) } }) } func TestASessionDoesNotFinishWhileItsAfterHookRuns(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, nil, 1) hooked(t, f, false, true) f.pass(t, room, false) _, _ = f.store.Take(f.ref, 1) f.end(t, "ops-a-1", true) f.pass(t, room, false) waiting := f.session() f.end(t, "ops-a-1-after", true) f.pass(t, room, false) if waiting.Status.Phase.Ended() || waiting.Status.WaitingOn != v1alpha1.WaitingOnHook { t.Errorf("status = %+v while the after hook runs, want waiting on it", waiting.Status) } if s := f.session(); s.Status.Phase != v1alpha1.PhaseFinished { t.Errorf("status = %+v after the hook ended, want Finished", s.Status) } }) } func TestTheAfterHookOfTheTurnThatFailsTheSessionCarriesTheReason(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) hooked(t, f, false, true) for turn := 1; turn <= 3; turn++ { if turn > 1 { time.Sleep(backoffs[turn-2]) } f.pass(t, room, false) _, _ = f.store.Take(f.ref, turn) f.end(t, session.JobName("ops-a", turn), false) f.pass(t, room, false) if turn < 3 { f.end(t, session.HookJobName("ops-a", turn, "after"), true) f.pass(t, room, false) } } waiting := f.session() f.end(t, "ops-a-3-after", true) f.pass(t, room, false) if waiting.Status.Phase.Ended() || waiting.Status.Turns[2].After.Reason != v1alpha1.ReasonTurnsFailed || waiting.Status.Turns[1].After.Reason != "" { t.Errorf("status = %+v, want the third turn's after hook running with TurnsFailed, and the second's with no reason", waiting.Status) } if s := f.session(); s.Status.Phase != v1alpha1.PhaseFailed || s.Status.Conditions[0].Reason != v1alpha1.ReasonTurnsFailed { t.Errorf("status = %+v after the hook ended, want Failed with TurnsFailed", s.Status) } }) } func TestASessionPastMaxTurnsRunsItsAfterHookOnceBeforeItFails(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) m, _ := hooked(t, f, false, true) m.Spec.Sessions.MaxTurns = 1 f.w.Put(cluster.Mandates, m) synctest.Wait() afterTurn(t, f, true) f.end(t, "ops-a-1-after", true) f.pass(t, room, false) waiting := f.session() f.end(t, "ops-a-end", true) f.pass(t, room, false) if waiting.Status.Phase.Ended() || waiting.Status.End == nil || waiting.Status.End.Reason != v1alpha1.ReasonMaxTurns || !exists(f, "ops-a-end") { t.Errorf("status = %+v, want the Session's after hook running with MaxTurns", waiting.Status) } if s := f.session(); s.Status.Phase != v1alpha1.PhaseFailed || s.Status.Conditions[0].Reason != v1alpha1.ReasonMaxTurns { t.Errorf("status = %+v after the hook ended, want Failed with MaxTurns", s.Status) } }) } func TestAStopInterruptsABeforeHookAndTheNextTurnRunsItsOwn(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) hooked(t, f, true, false) f.pass(t, room, false) f.pass(t, room, true) stopped := f.session() f.pass(t, room, false) turn := stopped.Status.Turns[0] if exists(f, "ops-a-1-before") || exists(f, "ops-a-1") || turn.Outcome != v1alpha1.OutcomeInterrupted || turn.Before.Outcome != v1alpha1.OutcomeInterrupted { t.Errorf("turn 1 is %+v, want it and its before hook Interrupted, and neither Job left", turn) } if !exists(f, "ops-a-2-before") { t.Errorf("status = %+v, want turn 2's before hook running", f.session().Status) } }) } func TestAStopDeletesAnAfterHookAndItRunsAgainWhenSimmerStarts(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) hooked(t, f, false, true) afterTurn(t, f, true) f.pass(t, room, true) stopped := f.session() f.pass(t, room, true) gone := !exists(f, "ops-a-1-after") f.pass(t, room, false) if !gone || stopped.Status.Turns[0].After.Outcome != v1alpha1.OutcomeInterrupted || stopped.Status.WaitingOn != v1alpha1.WaitingOnHook { t.Errorf("status = %+v, the Job gone = %v; want the after hook Interrupted and the Session waiting on it", stopped.Status, gone) } if s := f.session(); !exists(f, "ops-a-1-after") || s.Status.Turns[0].After.Outcome != "" || exists(f, "ops-a-2") { t.Errorf("status = %+v, want the after hook running again before turn 2", s.Status) } }) } func TestAHookWithNoContainerFailsAtOnceAndTheTurnRuns(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) _, duty := hooked(t, f, true, false) duty.Spec.Hooks.Before = json.RawMessage(`{"spec":{}}`) f.w.Put(cluster.Duties, duty) synctest.Wait() f.pass(t, room, false) f.pass(t, room, false) s := f.session() if exists(f, "ops-a-1-before") || !exists(f, "ops-a-1") || s.Status.Turns[0].Before.Outcome != v1alpha1.OutcomeFailed || warnings(f, "HookFailed") != 1 { t.Errorf("status = %+v, want the hook Failed with a warning and turn 1 running", s.Status) } }) } func TestAHookReadsTheContextOfItsRun(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) hooked(t, f, false, true) afterTurn(t, f, true) s := f.session() s.Spec.Origin = &v1alpha1.Origin{Signal: "alerts", Key: "k"} s.Status.Turns = append(s.Status.Turns, v1alpha1.Turn{Job: "ops-a-2", Before: &v1alpha1.HookRun{Job: "ops-a-2-before"}}) s.Status.End = &v1alpha1.HookRun{Job: "ops-a-end", Reason: v1alpha1.ReasonMaxTurns} after, _ := session.HookContext(f.store, &s, "ops-a-1-after") before, _ := session.HookContext(f.store, &s, "ops-a-2-before") end, _ := session.HookContext(f.store, &s, "ops-a-end") _, err := session.HookContext(f.store, &s, "ops-a-2") if after.Hook != "after" || after.Turn != 1 || after.Outcome != v1alpha1.OutcomeSucceeded || len(after.Events) != 1 || after.Events[0].ID != "a" || after.Origin.Key != "k" { t.Errorf("the after hook reads %+v, want turn 1, Succeeded, and its event a", after) } if before.Hook != "before" || before.Turn != 2 || before.Outcome != "" || len(before.Events) != 1 || before.Events[0].ID != "b" { t.Errorf("the before hook reads %+v, want turn 2 and the waiting event b", before) } if end.Outcome != v1alpha1.OutcomeFailed || end.Reason != v1alpha1.ReasonMaxTurns { t.Errorf("the Session's after hook reads %+v, want Failed with MaxTurns", end) } if !errors.Is(err, dataplane.ErrUnknownSession) { t.Errorf("a turn's own Job reads a hook context: %v", err) } }) } func TestAnAfterHookAddedToTheDutyDoesNotRunForATurnThatEndedBeforeIt(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) f.pass(t, room, false) _, _ = f.store.Take(f.ref, 1) f.end(t, "ops-a-1", true) f.pass(t, room, false) hooked(t, f, false, true) f.pass(t, room, false) if s := f.session(); exists(f, "ops-a-1-after") || s.Status.WaitingOn != v1alpha1.WaitingOnEvent { t.Errorf("status = %+v, want no after hook for turn 1 and the Session waiting on an event", s.Status) } }) } func TestAnAfterHookDroppedFromTheDutyDropsTheEventsItWouldRead(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) hooked(t, f, false, true) afterTurn(t, f, true) f.pass(t, room, true) hooked(t, f, false, false) f.pass(t, room, false) kept, _ := f.store.Kept(f.ref, 1) if s := f.session(); len(kept) != 0 || exists(f, "ops-a-1-after") || s.Status.Turns[0].After != nil { t.Errorf("turn 1 keeps %+v and status = %+v, want its events dropped and no after hook", kept, s.Status) } }) } func TestATurnThatAStopInterruptedGetsItsAfterHookWhenSimmerStarts(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) hooked(t, f, false, true) f.pass(t, room, false) _, _ = f.store.Take(f.ref, 1) f.pass(t, room, true) stopped := f.session() f.pass(t, room, false) if exists(f, "ops-a-1") || stopped.Status.Turns[0].Outcome != v1alpha1.OutcomeInterrupted || stopped.Status.WaitingOn != v1alpha1.WaitingOnHook { t.Errorf("status = %+v, want turn 1 Interrupted and its after hook waiting on the Stop", stopped.Status) } context, _ := session.HookContext(f.store, ptr(f.session()), "ops-a-1-after") if !exists(f, "ops-a-1-after") || exists(f, "ops-a-2") || context.Outcome != v1alpha1.OutcomeInterrupted { t.Errorf("context = %+v, want the after hook running for the Interrupted turn before turn 2", context) } }) } func ptr[T any](v T) *T { return &v } func TestAHooksJobThatAPassCreatedAndDidNotRecordIsTheHook(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) m, duty := hooked(t, f, true, false) s := f.session() job, err := session.HookJob(f.r.Settings, &s, m, duty, duty.Spec.Hooks, "before", "ops-a-1-before", 1) if err != nil { t.Fatal(err) } f.w.Put(cluster.Jobs, &cluster.Job{Job: *job}) synctest.Wait() f.pass(t, room, false) if s := f.session(); len(s.Status.Turns) != 1 || s.Status.Turns[0].Before.Job != "ops-a-1-before" || s.Status.WaitingOn != v1alpha1.WaitingOnHook { t.Errorf("status = %+v, want the Job that exists taken as turn 1's before hook", s.Status) } }) } func TestAHooksJobIsNotTheRunningTurn(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) hooked(t, f, false, true) afterTurn(t, f, true) jobs, _ := f.w.Cluster.Jobs() s := f.session() s.Status.Turns = s.Status.Turns[:1] if got := session.TurnNumber(&s, jobs); got != 1 { t.Errorf("turn number %d, want 1 with the Job ops-a-1-after", got) } }) } func TestATurnWhoseJobCannotBeCreatedAfterItsBeforeHookFailsAndFreesItsSlot(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) m, _ := hooked(t, f, true, false) f.pass(t, room, false) m.Spec.Template = json.RawMessage(`{"spec":{"containers":"not a list"}}`) f.w.Put(cluster.Mandates, m) synctest.Wait() f.end(t, "ops-a-1-before", true) if err := f.try(room, false); err == nil { t.Error("the pass that could not create turn 1's Job answered no error") } hooked(t, f, true, false) f.pass(t, room, false) s := f.session() if s.Status.Turns[0].Outcome != v1alpha1.OutcomeFailed || s.Status.WaitingOn != v1alpha1.WaitingOnBackoff || warnings(f, "TurnFailed") != 1 { t.Errorf("status = %+v, want turn 1 Failed with a warning and the Session backing off", s.Status) } }) } func TestASessionsAfterHookRunsToItsEndWhenMaxTurnsIsRaised(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) m, _ := hooked(t, f, false, true) m.Spec.Sessions.MaxTurns = 1 f.w.Put(cluster.Mandates, m) synctest.Wait() afterTurn(t, f, true) f.end(t, "ops-a-1-after", true) f.pass(t, room, false) m.Spec.Sessions.MaxTurns = 5 f.w.Put(cluster.Mandates, m) synctest.Wait() f.pass(t, room, false) running, early := f.session(), exists(f, "ops-a-2") f.end(t, "ops-a-end", true) f.pass(t, room, false) if early || running.Status.WaitingOn != v1alpha1.WaitingOnHook { t.Errorf("status = %+v, want turn 2 to wait for the running end hook", running.Status) } if s := f.session(); s.Status.Phase.Ended() || !exists(f, "ops-a-2") { t.Errorf("status = %+v, want turn 2 running after the hook ended", s.Status) } }) } func TestATurnWhoseJobCannotBeCreatedStillGetsItsAfterHookAndTheThirdCarriesTheReason(t *testing.T) { synctest.Test(t, func(t *testing.T) { f := start(t, []string{"k"}, 1) good, _ := hooked(t, f, true, true) bad := *good bad.Spec.Template = json.RawMessage(`{"spec":{"containers":"not a list"}}`) for turn := 1; turn <= 3; turn++ { if turn > 1 { time.Sleep(backoffs[turn-2]) } f.w.Put(cluster.Mandates, good) synctest.Wait() f.pass(t, room, false) f.end(t, session.HookJobName("ops-a", turn, "before"), true) f.w.Put(cluster.Mandates, &bad) synctest.Wait() _ = f.try(room, false) _ = f.try(room, false) if turn < 3 { f.end(t, session.HookJobName("ops-a", turn, "after"), true) _ = f.try(room, false) } } waiting := f.session() f.end(t, "ops-a-3-after", true) _ = f.try(room, false) last := waiting.Status.Turns[2] if waiting.Status.Phase.Ended() || last.Outcome != v1alpha1.OutcomeFailed || last.After == nil || last.After.Reason != v1alpha1.ReasonTurnsFailed || !exists(f, "ops-a-3-after") { t.Errorf("status = %+v, want turn 3's after hook running with TurnsFailed before the Session fails", waiting.Status) } if s := f.session(); s.Status.Phase != v1alpha1.PhaseFailed || s.Status.Conditions[0].Reason != v1alpha1.ReasonTurnsFailed { t.Errorf("status = %+v after the hook ended, want Failed with TurnsFailed", s.Status) } }) }