package operator import ( "context" "errors" "log/slog" "net/http" "sync" "sync/atomic" "time" "github.com/liken-sh/liken/kubernetes/apiclient" "tangled.org/guid.foo/simmer/api/v1alpha1" "tangled.org/guid.foo/simmer/brake" "tangled.org/guid.foo/simmer/cluster" "tangled.org/guid.foo/simmer/console" "tangled.org/guid.foo/simmer/dataplane" "tangled.org/guid.foo/simmer/mandate" "tangled.org/guid.foo/simmer/session" "tangled.org/guid.foo/simmer/signal" "tangled.org/guid.foo/simmer/stop" ) // Operator runs every control loop, one pass at a time. type Operator struct { cluster *cluster.Cluster store dataplane.Store bell *Bell metrics *metrics settings Settings brake *brake.Brake mandates *mandate.Reconciler sessions *session.Reconciler cord *stop.Cord signals *signal.Subscriptions consoles *console.Reconciler // mu serializes the pass, the routing of each event, and each data // plane request, so two of them never read one Session and both // write it. mu sync.Mutex goneMu sync.Mutex gone []dataplane.SessionRef // swept is true once a pass has dropped what the Store keeps for // Sessions that were gone before the operator started. swept bool // synced is true once every watch has read its whole collection. synced atomic.Bool } // New builds the operator. It hears the watches' deletes and reopens // from the start, and runs no pass until Attach gives it the cluster // that the watches keep. func New(store dataplane.Store, s Settings, version string, bell *Bell) *Operator { return &Operator{store: store, bell: bell, metrics: newMetrics(version), settings: s} } // Attach builds the control loops on a cluster. wicket is the HTTP // client of the Signals' subscriptions. func (o *Operator) Attach(c *cluster.Cluster, wicket *http.Client) { m, s, store, bell := o.metrics, o.settings, o.store, o.bell o.cluster = c o.brake = &brake.Brake{Cluster: c, Metrics: brake.NewMetrics(m.registry), Settings: s.Inject()} o.mandates = mandate.New(c, store, m.registry) o.mandates.Settings = s.Inject() o.sessions = &session.Reconciler{Cluster: c, Store: store, Settings: s.Inject(), Metrics: session.NewMetrics(m.registry)} o.cord = stop.New(c, store, m.registry) o.consoles = &console.Reconciler{Cluster: c, Settings: s.Inject(), Metrics: console.NewMetrics(m.registry)} signalMetrics := signal.NewMetrics(m.registry) o.signals = &signal.Subscriptions{ WicketURL: s.WicketURL, TokenFile: s.WicketTokenFile, DataDir: s.DataDir, HTTP: wicket, Cluster: c, Metrics: signalMetrics, Wake: func() { bell.Ring(causeSubscription) }, Router: &signal.Router{Cluster: c, Store: store, Lock: &o.mu, Wake: func() { bell.Ring(causeEvent) }, Metrics: signalMetrics}, } } // Observe answers a client that counts each of its requests in // simmer_api_requests_total. func (o *Operator) Observe(c *apiclient.Client) *apiclient.Client { return c.WithObserver(o.metrics.request) } // Handler serves the operator's /metrics, /healthz, and /livez. It // serves after Attach. func (o *Operator) Handler() http.Handler { return o.metrics.handler(o.ready) } // ready reports whether every watch has read its whole collection once. // It holds after that: a watch that the API server refuses later // leaves its pass reading the API server, and the data plane, which // the readiness probe gates, still answers from it. func (o *Operator) ready() bool { if o.synced.Load() { return true } if o.cluster == nil || !o.cluster.Synced() { return false } o.synced.Store(true) return true } // Deleted hears each deleted object from the watches. The Store // forgets a Session that is gone in the next pass. func (o *Operator) Deleted(kind cluster.Kind, namespace, name string) { if kind.Name != cluster.Sessions.Name || kind.Resource != cluster.Sessions.Resource { return } o.goneMu.Lock() o.gone = append(o.gone, dataplane.SessionRef{Namespace: namespace, Name: name}) o.goneMu.Unlock() } // Reopened counts a watch that the API server closed and the operator // opened again. func (o *Operator) Reopened(watch string) { o.metrics.reopened(watch) } // retryFirst and retryLast bound the wait before a failed pass runs // again. A write that failed has no event to wake the pass, so this // clock covers it: an API server that refused a write, or one that was // down for the length of a pass. const ( retryFirst = 5 * time.Second retryLast = 5 * time.Minute ) // Loop runs a pass at once and after each wake, until ctx ends. Between // passes it waits on the bell, which the watches, the subscriptions, // and the data plane ring, and on the earliest time a pass found that // something changes with no event: a duty falls due, a budget pays an // Allowance's debt back, a reading grows stale while work waits on it, a // failed turn's backoff ends, or an ended Session's time to live ends. // Each of those is a clock, not a poll. func (o *Operator) Loop(ctx context.Context) { retry := retryFirst causes := []string{causeStart} for ctx.Err() == nil { o.metrics.passed(causes) next, err := o.Pass(ctx) if err != nil { slog.Error("a pass failed", "error", err.Error(), "retry", retry.String()) next = earliest(next, time.Now().Add(retry)) retry = min(retry*2, retryLast) } else { retry = retryFirst } var clock <-chan time.Time var timer *time.Timer if !next.IsZero() { timer = time.NewTimer(max(time.Until(next), 0)) clock = timer.C } select { case <-ctx.Done(): case <-o.bell.Rung(): causes = o.bell.take() case <-clock: causes = []string{causeClock} if err != nil { causes = []string{causeRetry} } } if timer != nil { timer.Stop() } } } // Pass runs every control loop once, in order, and answers when the // next pass is due with no event. func (o *Operator) Pass(ctx context.Context) (time.Time, error) { o.mu.Lock() defer o.mu.Unlock() now := time.Now() o.forgetGone() r, err := o.read() if err != nil { return time.Time{}, err } if !o.swept { o.swept = o.sweep(r.sessions) } stopped := stop.Stopped(r.stops) var errs []error var next time.Time timed := func(kind string, run func() error) { started := time.Now() err := run() o.metrics.observe(kind, time.Since(started), err) errs = append(errs, err) } var verdicts brake.Verdicts timed("Allowance", func() (err error) { var until time.Time verdicts, until, err = o.brake.Allowances(brake.AllowanceInputs{ Accounts: r.accounts, Allowances: r.allowances, Mandates: r.mandates, Sessions: r.sessions, Stopped: stopped, }, now) next = earliest(next, until) return err }) timed("McpServer", func() error { return mcpServers(o.cluster, r.servers) }) timed("Signal", func() error { return o.signals.Reconcile(ctx, r.signals) }) // A Console is a person's own, so neither the brake nor a Stop // holds it. timed("Console", func() error { return o.consoles.Reconcile(r.servers) }) var held map[string]bool timed("Mandate", func() error { res, err := o.mandates.Reconcile(mandate.Inputs{ Mandates: r.mandates, Duties: r.duties, Allowances: r.allowances, McpServers: r.servers, Signals: r.signals, Sessions: r.sessions, ServiceAccounts: r.serviceAccounts, RoleBindings: r.roleBindings, ClusterRoleBindings: r.clusterRoleBindings, CronJobs: r.cronJobs, Verdicts: verdicts, Stopped: stopped, }, now) next, held = earliest(next, res.Wake), res.Held return err }) // The Sessions' pass reads the Mandates' and Duties' status that the // Mandates' pass wrote, and the Sessions it started. var result session.Result timed("Session", func() error { mandates, err := o.cluster.Mandates() if err != nil { return err } sessions, err := o.cluster.Sessions() if err != nil { return err } duties, err := o.cluster.Duties() if err != nil { return err } r.sessions = sessions result, err = o.sessions.Reconcile(session.Inputs{Sessions: sessions, Jobs: r.jobs, Mandates: mandates, Duties: duties, Signals: r.signals, Verdicts: verdicts, Stopped: stopped}, now) next = earliest(next, result.Wake) // A Duty that waited on a Session's events or on a slot of its // Mandate may start now, and only the Mandates' pass starts it. if result.Freed { o.bell.Ring(causeFreed) } return err }) timed("Stop", func() error { return o.cord.Reconcile(r.stops, r.sessions) }) timed("Account", func() error { for account := range held { result.Waiting[account] = true } stale, err := o.brake.Accounts(brake.AccountInputs{ Accounts: r.accounts, Mandates: r.mandates, ProbeJobs: r.probeJobs, Secrets: r.secrets, Verdicts: verdicts, Waiting: result.Waiting, }, now) next = earliest(next, stale) return err }) return next, errors.Join(errs...) } // sweep drops what the Store keeps for each Session that the list of // Sessions does not hold: one deleted while the operator was down, whose // delete no watch reports. Only the operator creates Sessions, under // the lock that the pass holds, so no Session can be new to the Store // and missing from the list. It answers whether it swept. func (o *Operator) sweep(sessions []v1alpha1.Session) bool { kept, err := o.store.Sessions() if err != nil { slog.Error("could not list the Store's Sessions", "error", err.Error()) return false } live := map[dataplane.SessionRef]bool{} for i := range sessions { live[session.Ref(&sessions[i])] = true } for _, ref := range kept { if live[ref] { continue } slog.Info("forgetting a Session that is gone", "kind", "Session", "namespace", ref.Namespace, "name", ref.Name) if err := o.store.Forget(ref); err != nil { slog.Error("could not forget a Session that is gone", "kind", "Session", "namespace", ref.Namespace, "name", ref.Name, "error", err.Error()) } } return true } // forgetGone drops what the Store keeps for each Session that is gone. func (o *Operator) forgetGone() { o.goneMu.Lock() gone := o.gone o.gone = nil o.goneMu.Unlock() for _, ref := range gone { if err := o.store.Forget(ref); err != nil { slog.Error("could not forget a Session that is gone", "kind", "Session", "namespace", ref.Namespace, "name", ref.Name, "error", err.Error()) } } } func earliest(a, b time.Time) time.Time { switch { case a.IsZero(): return b case b.IsZero() || a.Before(b): return a } return b } // Stop ends the Signals' subscriptions. func (o *Operator) Stop() { o.signals.Stop() }