package session // A duty's hooks are Jobs of the cluster owner's that run before and // after each turn of its Sessions, with no model. plans/hooks.md is the // design. The order of one turn: // // 1. The gate opens for the turn: the brake, the backoff, and a slot. // The operator creates the before hook's Job, which takes the slot. // 2. When the before hook ends, however it ends, the operator creates // the turn's Job, which keeps the slot. The gate is not checked // again. // 3. When the turn's Job ends, the operator creates the after hook's // Job. The next turn, the Session's finish, and its failure wait // for it. // // A Stop deletes a running hook. A before hook that a Stop deleted // interrupts its turn, and the next turn runs its own before hook. An // after hook that a Stop deleted, or that a Stop kept from starting, // runs when simmer starts again. A hook's failure never fails its turn // or its Session. import ( "encoding/json" "errors" "fmt" "log/slog" "slices" "strconv" "time" "github.com/liken-sh/liken/kubernetes/apiclient" batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "tangled.org/guid.foo/simmer/api/v1alpha1" "tangled.org/guid.foo/simmer/cluster" "tangled.org/guid.foo/simmer/dataplane" "tangled.org/guid.foo/simmer/inject" ) // HookJobName names the Job of a turn's hook: --before // or --after. func HookJobName(session string, turn int, hook string) string { return fmt.Sprintf("%s-%d-%s", session, turn, hook) } // EndJobName names the Job of the after hook that runs once for a // Session that fails without a turn. func EndJobName(session string) string { return session + "-end" } // defaultHookTimeout is the timeout of a hook that sets none. const defaultHookTimeout = 2 * time.Minute func hookTimeout(hooks *v1alpha1.Hooks) time.Duration { if parsed, err := time.ParseDuration(hooks.Timeout); err == nil && parsed >= time.Second { return parsed } return defaultHookTimeout } func hasBefore(hooks *v1alpha1.Hooks) bool { return hooks != nil && len(hooks.Before) > 0 } func hasAfter(hooks *v1alpha1.Hooks) bool { return hooks != nil && len(hooks.After) > 0 } // hookEnv are the environment variables that simmer sets in each // container of a hook's pod. A template's variable of the same name is // dropped. var hookEnv = []string{"SIMMER_SESSION", "SIMMER_HOOK", "SIMMER_DATAPLANE_URL", "SIMMER_TOKEN_FILE"} // HookJob builds the Job of one run of a hook, before or after, from // the hook's template. The Mandate's template is not merged into it, so // none of the Mandate's sidecars run as the hook's ServiceAccount. // turn numbers the turn the hook // runs around. func HookJob(s inject.Settings, session *v1alpha1.Session, mandate *v1alpha1.Mandate, duty *v1alpha1.Duty, hooks *v1alpha1.Hooks, hook, name string, turn int) (*batchv1.Job, error) { template := hooks.Before if hook == dataplane.HookAfter { template = hooks.After } var theirs corev1.PodTemplateSpec if err := json.Unmarshal(template, &theirs); err != nil { return nil, fmt.Errorf("the %s hook of the duty %s is not a pod template: %w", hook, session.Spec.Skill, err) } if len(theirs.Spec.Containers) == 0 { return nil, fmt.Errorf("the %s hook of the duty %s has no container", hook, session.Spec.Skill) } namespace := session.Metadata.Namespace containers := slices.Clone(theirs.Spec.Containers) for i := range containers { c := &containers[i] c.Env = slices.DeleteFunc(slices.Clone(c.Env), func(e corev1.EnvVar) bool { return slices.Contains(hookEnv, e.Name) }) c.Env = append(c.Env, corev1.EnvVar{Name: "SIMMER_SESSION", Value: namespace + "/" + session.Metadata.Name}, corev1.EnvVar{Name: "SIMMER_HOOK", Value: hook}, ) } ours := inject.PodOf(s, containers) spec := theirs.Spec spec.Containers = ours.Containers spec.InitContainers = append(ours.InitContainers, theirs.Spec.InitContainers...) spec.Volumes = ours.Volumes for _, v := range theirs.Spec.Volumes { if !slices.ContainsFunc(spec.Volumes, func(held corev1.Volume) bool { return held.Name == v.Name }) { spec.Volumes = append(spec.Volumes, v) } } // The data plane trusts the ServiceAccount, and a hook that the // kubelet ran again would post its status twice. spec.RestartPolicy = corev1.RestartPolicyNever spec.ServiceAccountName = HookServiceAccountOf(mandate, duty) spec.DeprecatedServiceAccount = "" labels := map[string]string{ v1alpha1.LabelSession: session.Metadata.Name, v1alpha1.LabelMandate: mandate.Metadata.Name, v1alpha1.LabelTurn: strconv.Itoa(turn), v1alpha1.LabelHook: hook, } // simmer's labels go on last, so the template cannot drop the hook // label that keeps the pod off a turn's routes. podLabels := map[string]string{} for k, v := range theirs.Labels { podLabels[k] = v } for k, v := range labels { podLabels[k] = v } backoff, controller, deadline := int32(0), true, int64(hookTimeout(hooks)/time.Second) return &batchv1.Job{ TypeMeta: metav1.TypeMeta{APIVersion: "batch/v1", Kind: "Job"}, ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: namespace, Labels: labels, OwnerReferences: []metav1.OwnerReference{{ APIVersion: v1alpha1.APIVersion, Kind: v1alpha1.SessionKind.Name, Name: session.Metadata.Name, UID: types.UID(session.Metadata.UID), Controller: &controller, }}, }, Spec: batchv1.JobSpec{ BackoffLimit: &backoff, ActiveDeadlineSeconds: &deadline, TTLSecondsAfterFinished: finishedJobTTL(), Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{Labels: podLabels, Annotations: theirs.Annotations}, Spec: spec, }, }, }, nil } // errHookJobDeleting means a hook's Job of the same name is still being // deleted after a Stop, so the hook runs again on a later pass. var errHookJobDeleting = errors.New("the hook's earlier Job is still being deleted") // createHook creates the Job of one run of a hook, and answers the run. // A hook that cannot be built, such as one with no container, fails at // once, because no later pass would build it either. A failure to // create the Job is answered as an error, and a later pass tries again. func (r *Reconciler) createHook(s *v1alpha1.Session, mandate *v1alpha1.Mandate, duty *v1alpha1.Duty, hooks *v1alpha1.Hooks, jobs map[string]*cluster.Job, hook, name string, turn int, reason string, now time.Time) (*v1alpha1.HookRun, error) { ref := cluster.Ref(cluster.Sessions, s.Metadata.Namespace, s.Metadata.Name, s.Metadata.UID) run := &v1alpha1.HookRun{Job: name, StartedAt: stamp(now), Reason: reason} spec, err := HookJob(r.Settings, s, mandate, duty, hooks, hook, name, turn) if err != nil { run.FinishedAt, run.Outcome = stamp(now), v1alpha1.OutcomeFailed r.Metrics.hook(s, hook, run.Outcome) r.Cluster.Post(ref, true, "HookFailed", fmt.Sprintf("The %s hook of turn %d could not run: %v", hook, turn, err)) return run, nil } _, err = cluster.Create(r.Cluster, cluster.Jobs, s.Metadata.Namespace, &cluster.Job{Job: *spec}) if errors.Is(err, apiclient.ErrConflict) { // A Job of the name that is being deleted is the run a Stop // interrupted. Any other is the run a pass created and did // not record. if held := jobs[s.Metadata.Namespace+"/"+name]; held != nil && held.DeletionTimestamp != nil { return nil, errHookJobDeleting } return run, nil } if err != nil { return nil, err } r.Cluster.Post(ref, false, "HookStarted", fmt.Sprintf("The %s hook of turn %d runs in the Job %s.", hook, turn, name)) return run, nil } // watchHook records the end of a running hook's Job, in run. While a // Stop exists, it deletes the Job and records the run as Interrupted. // It answers whether the run ended. func (r *Reconciler) watchHook(s *v1alpha1.Session, run *v1alpha1.HookRun, hook string, turn int, jobs map[string]*cluster.Job, stopped bool, now time.Time) (bool, error) { ref := cluster.Ref(cluster.Sessions, s.Metadata.Namespace, s.Metadata.Name, s.Metadata.UID) job := jobs[s.Metadata.Namespace+"/"+run.Job] var message string switch done, succeeded := jobOutcome(job); { // A pass that deleted the Job for a Stop and lost its status write // finds the Job gone while the Stop still exists. case job == nil && stopped: run.Outcome = v1alpha1.OutcomeInterrupted message = fmt.Sprintf("A Stop interrupted the %s hook of turn %d, and its Job %s is gone.", hook, turn, run.Job) case job == nil: run.Outcome = v1alpha1.OutcomeFailed message = fmt.Sprintf("The %s hook of turn %d failed: its Job %s is gone.", hook, turn, run.Job) case done && succeeded: run.Outcome = v1alpha1.OutcomeSucceeded message = fmt.Sprintf("The %s hook of turn %d succeeded.", hook, turn) case done: run.Outcome = v1alpha1.OutcomeFailed message = fmt.Sprintf("The %s hook of turn %d failed. The log of the Job %s says why.", hook, turn, run.Job) case stopped: if err := cluster.Delete(r.Cluster, cluster.Jobs, s.Metadata.Namespace, run.Job); err != nil { return false, err } run.Outcome = v1alpha1.OutcomeInterrupted message = fmt.Sprintf("A Stop interrupted the %s hook of turn %d and deleted its Job %s.", hook, turn, run.Job) default: return false, nil } run.FinishedAt = finishedAt(job, now) r.Metrics.hook(s, hook, run.Outcome) slog.Info("a hook ended", "kind", "Session", "namespace", s.Metadata.Namespace, "name", s.Metadata.Name, "job", run.Job, "outcome", string(run.Outcome)) r.Cluster.Post(ref, run.Outcome == v1alpha1.OutcomeFailed, "Hook"+string(run.Outcome), message) return true, nil } // hooked is what the hooks of a Session's last turn tell its step. type hooked struct { // started names the turn's Job, which this pass created when the // turn's before hook ended. started string // busy names the hook's Job that runs, or the after hook that // waits for a Stop to go. busy string before bool stopped bool } // stepHooks takes the hooks of a Session's last turn one step: it // records the end of a before hook and starts its turn, or starts and // records the after hook of a turn that ended. func (r *Reconciler) stepHooks(s *v1alpha1.Session, mandate *v1alpha1.Mandate, duty *v1alpha1.Duty, next *v1alpha1.SessionStatus, jobs map[string]*cluster.Job, in Inputs, now time.Time) (hooked, error) { count := len(next.Turns) if count == 0 { return hooked{}, nil } t := &next.Turns[count-1] if t.Outcome == "" && t.StartedAt == nil && t.Before != nil { h, err := r.stepBefore(s, mandate, duty, next, jobs, in, now) // A turn whose Job could not be created ended in this pass, and // owes its after hook before anything waits on its failure. if t.Outcome == "" || t.After == nil { return h, err } after, afterErr := r.stepAfter(s, mandate, duty, next, jobs, in, now) return after, errors.Join(err, afterErr) } return r.stepAfter(s, mandate, duty, next, jobs, in, now) } // stepAfter starts and records the after hook that the last turn owes. func (r *Reconciler) stepAfter(s *v1alpha1.Session, mandate *v1alpha1.Mandate, duty *v1alpha1.Duty, next *v1alpha1.SessionStatus, jobs map[string]*cluster.Job, in Inputs, now time.Time) (hooked, error) { count := len(next.Turns) hooks := v1alpha1.HooksOf(duty) t := &next.Turns[count-1] // recordTurn, or stepBefore for a turn whose Job never started, // marks the after hook that an ended turn owes, with no start yet. if t.Outcome == "" || t.After == nil { return hooked{}, nil } if t.After.StartedAt != nil && t.After.Outcome == "" { ended, err := r.watchHook(s, t.After, dataplane.HookAfter, count, jobs, in.Stopped, now) if err != nil || !ended { return hooked{busy: t.After.Job}, err } } if t.After.StartedAt != nil && t.After.Outcome != v1alpha1.OutcomeInterrupted { return hooked{}, r.Store.Drop(Ref(s), count) } // The duty dropped its after hook since the turn ended. if !hasAfter(hooks) { t.After = nil return hooked{}, r.Store.Drop(Ref(s), count) } name := t.After.Job if in.Stopped { return hooked{busy: name, stopped: true}, nil } // The after hook of the turn whose failure fails the Session // carries the Session's reason. reason := "" if failures, _ := failuresInARow(next.Turns); t.Outcome == v1alpha1.OutcomeFailed && failures >= maxFailures { reason = v1alpha1.ReasonTurnsFailed } run, err := r.createHook(s, mandate, duty, hooks, jobs, dataplane.HookAfter, name, count, reason, now) if err != nil { return hooked{busy: name}, err } t.After = run if run.Outcome != "" { return hooked{}, r.Store.Drop(Ref(s), count) } return hooked{busy: name}, nil } // stepBefore records the end of the last turn's before hook, and then // creates the turn's Job. The gate opened for the before hook, so it is // not checked again. A turn whose before hook a Stop interrupted never // runs, and the next turn runs its own before hook. func (r *Reconciler) stepBefore(s *v1alpha1.Session, mandate *v1alpha1.Mandate, duty *v1alpha1.Duty, next *v1alpha1.SessionStatus, jobs map[string]*cluster.Job, in Inputs, now time.Time) (hooked, error) { count := len(next.Turns) t := &next.Turns[count-1] if t.Before.Outcome == "" { ended, err := r.watchHook(s, t.Before, dataplane.HookBefore, count, jobs, in.Stopped, now) if err != nil || !ended { return hooked{busy: t.Before.Job, before: true}, err } } if t.Before.Outcome == v1alpha1.OutcomeInterrupted || in.Stopped || mandate == nil { t.Outcome, t.FinishedAt = v1alpha1.OutcomeInterrupted, stamp(now) r.Metrics.turn(s, t) r.Cluster.Post(cluster.Ref(cluster.Sessions, s.Metadata.Namespace, s.Metadata.Name, s.Metadata.UID), false, "TurnInterrupted", fmt.Sprintf("Turn %d did not start, because a Stop interrupted its before hook.", count)) return hooked{}, nil } account := in.Verdicts.AccountOf[mandate.Spec.Allowance] job, err := r.startTurn(s, mandate, duty, account, count, lastInterrupted(next.Turns[:count-1])) if err != nil { // The turn holds a slot, so it fails and frees it, and the // backoff and the next gate decide when to try again. t.Outcome, t.FinishedAt = v1alpha1.OutcomeFailed, stamp(now) if hasAfter(v1alpha1.HooksOf(duty)) { t.After = &v1alpha1.HookRun{Job: HookJobName(s.Metadata.Name, count, dataplane.HookAfter)} } r.Metrics.turn(s, t) r.Cluster.Post(cluster.Ref(cluster.Sessions, s.Metadata.Namespace, s.Metadata.Name, s.Metadata.UID), true, "TurnFailed", fmt.Sprintf("Turn %d failed: its Job could not be created after its before hook: %v", count, err)) return hooked{}, err } t.StartedAt = stamp(now) return hooked{started: job}, nil } // stepEnd runs the after hook once for a Session that fails without a // turn, and answers whether the Session may fail now. func (r *Reconciler) stepEnd(s *v1alpha1.Session, mandate *v1alpha1.Mandate, duty *v1alpha1.Duty, next *v1alpha1.SessionStatus, reason string, jobs map[string]*cluster.Job, in Inputs, now time.Time) (hooked, error) { hooks := v1alpha1.HooksOf(duty) count := len(next.Turns) if next.End != nil && next.End.StartedAt != nil && next.End.Outcome == "" { ended, err := r.watchHook(s, next.End, dataplane.HookAfter, count, jobs, in.Stopped, now) if err != nil || !ended { return hooked{busy: next.End.Job}, err } } if !hasAfter(hooks) || (next.End != nil && next.End.Outcome != v1alpha1.OutcomeInterrupted) { return hooked{}, nil } name := EndJobName(s.Metadata.Name) if in.Stopped { return hooked{busy: name, stopped: true}, nil } run, err := r.createHook(s, mandate, duty, hooks, jobs, dataplane.HookAfter, name, count, reason, now) if err != nil { return hooked{busy: name}, err } next.End = run if run.Outcome != "" { return hooked{}, nil } return hooked{busy: name}, nil } // HookContext answers the context of the Session's hook that runs in // the Job. A Job that is not one of the Session's hooks is unknown. func HookContext(store dataplane.Store, s *v1alpha1.Session, job string) (dataplane.HookContext, error) { if s == nil || s.Status.Phase.Ended() { return dataplane.HookContext{}, dataplane.ErrUnknownSession } ref := Ref(s) context := dataplane.HookContext{ Namespace: s.Metadata.Namespace, Session: s.Metadata.Name, Mandate: s.Spec.Mandate, Skill: s.Spec.Skill, Origin: s.Spec.Origin, Keys: s.Status.Keys, } var err error switch { case s.Status.End != nil && s.Status.End.Job == job: context.Hook, context.Turn, context.Outcome, context.Reason = dataplane.HookAfter, len(s.Status.Turns), v1alpha1.OutcomeFailed, s.Status.End.Reason context.Events, err = store.Waiting(ref) return context, err } for i, t := range s.Status.Turns { switch { case t.Before != nil && t.Before.Job == job: context.Hook, context.Turn = dataplane.HookBefore, i+1 context.Events, err = store.Waiting(ref) return context, err case t.After != nil && t.After.Job == job: context.Hook, context.Turn, context.Outcome, context.Reason = dataplane.HookAfter, i+1, t.Outcome, t.After.Reason context.Events, err = store.Kept(ref, i+1) return context, err } } return dataplane.HookContext{}, fmt.Errorf("%w: the Job %s runs none of its hooks", dataplane.ErrUnknownSession, job) }