Skip to main content

isb_core/stack/
controller.rs

1//! The reconciler behind `isb serve`: one worker thread per service keeps its
2//! replicas created, current, running, healthy and in the load balancer.
3//!
4//! A worker never holds a lock across incus calls, and a slow service (an
5//! image pull, a long rollout) never delays another's health checks. Workers
6//! are told about a new deployment through their shared slot and woken early;
7//! a worker whose service went away deletes its own instances and exits, so
8//! nothing ever has to join a worker from inside another.
9
10use std::collections::{BTreeMap, BTreeSet, VecDeque};
11use std::net::{IpAddr, SocketAddr};
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::sync::{Arc, Condvar, Mutex};
14use std::time::{Duration, Instant};
15
16use serde::Serialize;
17
18use super::changes::diff;
19use super::ports::{Published, published};
20use super::secrets::{Cycle, LABEL_SECRETS, StaleSecret};
21use super::{
22    LABEL_REV, LABEL_SERVICE, LABEL_SLOT, LABEL_STACK, StackDef, Store, instance_name, new_id,
23    now_secs, validate_stack_name,
24};
25use crate::balance::Balancer;
26use crate::client::{Client, encode_segment};
27use crate::error::{Error, Result};
28use crate::org::OrgId;
29use crate::plan::Desired;
30use crate::sandbox::{EnsureOptions, Sandbox};
31use crate::secrets::Secrets;
32use crate::spec::{
33    DependCondition, FailureAction, HealthProbe, OnChange, RestartCondition, RestartMode,
34    SandboxSpec, UpdateConfig, UpdateOrder,
35};
36use crate::supervise;
37
38mod dns;
39mod health;
40mod instances;
41pub use dns::{DnsScope, DnsScopeFn};
42use health::InstRt;
43use instances::instance_state;
44pub use instances::list_instances;
45
46/// How long a replaced instance's connections may drain before it is stopped.
47const DRAIN: Duration = Duration::from_secs(10);
48/// How often an unhealthy app is restarted before its instance is replaced.
49const RESTARTS_BEFORE_REPLACE: u32 = 3;
50/// How long a service that was healthy must have no healthy replica before
51/// `health.unhealthy` is raised (restarts and short blips stay quiet).
52const HEALTH_DEBOUNCE: Duration = Duration::from_secs(20);
53
54/// One replica, as `stack_status` reports it.
55#[derive(Debug, Clone, Serialize, Default)]
56pub struct InstanceStatus {
57    pub name: String,
58    pub slot: u32,
59    pub rev: String,
60    /// incus status: Running, Stopped, ...
61    pub status: String,
62    /// `healthy`, `unhealthy`, `starting`, or `none` (no healthcheck: the app
63    /// is judged by its process alone).
64    pub health: String,
65    pub ip: Option<String>,
66    /// Receiving traffic from the balancer.
67    pub in_rotation: bool,
68    pub restarts: u32,
69    #[serde(skip_serializing_if = "String::is_empty")]
70    pub last_probe: String,
71    /// Percent of one core; none until two samples were taken.
72    pub cpu_pct: Option<f32>,
73    pub cpu_history: Vec<f32>,
74    pub mem_bytes: Option<u64>,
75    /// Root disk usage, where the storage driver reports it.
76    pub disk_bytes: Option<u64>,
77    /// Secrets (`on_change: none`, or a restart still to come) whose new
78    /// version reached the replica's files but not its running app.
79    #[serde(skip_serializing_if = "Vec::is_empty")]
80    pub stale_secrets: Vec<StaleSecret>,
81}
82
83/// A published port: TCP served by the balancer, UDP by a NAT proxy on the
84/// replica (`listen` ends in `/udp`, `backends` is the replica).
85#[derive(Debug, Clone, Serialize)]
86pub struct PortStatus {
87    pub listen: String,
88    pub target: u16,
89    pub backends: Vec<String>,
90    #[serde(skip_serializing_if = "Option::is_none")]
91    pub error: Option<String>,
92    /// Connections accepted since the daemon started, and per second lately.
93    pub accepted: u64,
94    pub active: usize,
95    pub rate_history: Vec<f32>,
96}
97
98/// One service of a stack, as `stack_status` reports it.
99#[derive(Debug, Clone, Serialize, Default)]
100pub struct ServiceStatus {
101    pub service: String,
102    pub image: String,
103    pub rev: String,
104    pub replicas: u32,
105    pub running: u32,
106    pub healthy: u32,
107    /// `starting`, `converged`, `updating`, `paused`, `waiting`, `failing`.
108    pub state: String,
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub message: Option<String>,
111    pub instances: Vec<InstanceStatus>,
112    pub ports: Vec<PortStatus>,
113    /// The rollout in progress, slot by slot.
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub rollout: Option<RolloutStatus>,
116    /// Unix seconds of the last completed reconcile pass.
117    pub checked_at: u64,
118    /// The service's domains as the ingress serves them.
119    #[serde(skip_serializing_if = "Vec::is_empty")]
120    pub domains: Vec<crate::ingress::DomainStatus>,
121    /// While not converged: the last replica that failed to come up, without
122    /// its output (`stack_logs` has that).
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub last_failed_attempt: Option<serde_json::Value>,
125}
126
127/// Something that follows which replicas receive traffic: the ingress.
128/// Called from worker threads, never with a controller lock held.
129pub trait Observer: Send + Sync {
130    /// The in-rotation replicas of a service changed. `stack` is qualified.
131    fn rotation(&self, stack: &str, service: &str, ips: &[IpAddr]);
132    /// Wait (at most `timeout`) until requests to `ip` have drained from the
133    /// observer's proxies, before the replica is stopped.
134    fn drain(&self, stack: &str, service: &str, ip: IpAddr, timeout: Duration);
135    /// The deployed definitions changed (deploy, scale, rollback, removal).
136    fn stacks_changed(&self, defs: Vec<Arc<StackDef>>);
137    /// A service's domains for its status.
138    fn domains(&self, stack: &str, service: &str) -> Vec<crate::ingress::DomainStatus>;
139}
140
141/// A rollout in progress.
142#[derive(Debug, Clone, Serialize, Default)]
143pub struct RolloutStatus {
144    pub to_rev: String,
145    /// `stop-first` or `start-first`.
146    pub order: String,
147    pub parallelism: usize,
148    pub done: usize,
149    pub total: usize,
150    /// Unix seconds.
151    pub started_at: u64,
152    pub slots: Vec<SlotRollout>,
153}
154
155/// One slot's handover: the instance going away and the one replacing it.
156#[derive(Debug, Clone, Serialize, Default)]
157pub struct SlotRollout {
158    pub slot: u32,
159    pub old: Option<String>,
160    pub old_rev: Option<String>,
161    /// `serving`, `draining`, `retired`, or `none`.
162    pub old_state: String,
163    pub new: Option<String>,
164    /// `waiting`, `creating`, `probing`, `monitoring`, `serving`, `failed`.
165    pub new_state: String,
166}
167
168/// Something that happened, for the event feed.
169#[derive(Debug, Clone, Serialize)]
170pub struct Event {
171    /// Increases by one per event; pass the last one seen as `since`.
172    pub seq: u64,
173    /// Unix milliseconds.
174    pub at: u64,
175    /// `info`, `warn` or `error`.
176    pub level: String,
177    pub stack: String,
178    #[serde(skip_serializing_if = "String::is_empty")]
179    pub service: String,
180    #[serde(skip_serializing_if = "Option::is_none")]
181    pub instance: Option<String>,
182    pub message: String,
183    /// What happened, for consumers that act on events (notifications):
184    /// dotted, `<subject>.<outcome>`. In use: `deploy.succeeded`,
185    /// `deploy.failed`, `health.unhealthy`, `health.recovered`,
186    /// `backup.succeeded`, `backup.failed`, `restore.succeeded`,
187    /// `restore.failed`, `job.succeeded`, `job.failed`, `cert.issued`,
188    /// `cert.failed`, `secret.rotated` (a new secret version reached a
189    /// service, saying what its `on_change` does; a workspace under stack
190    /// `<org>/@workspaces`), `preview.created`, `preview.removed` (a preview's
191    /// deploys are `deploy.*` under its own stack). Most events have none.
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub kind: Option<String>,
194}
195
196/// Hears every event as it is emitted. It must not block (the history
197/// queues and returns).
198pub type EventSink = Arc<dyn Fn(&Event) + Send + Sync>;
199
200/// Events kept for late readers.
201const EVENTS_KEPT: usize = 1000;
202
203/// The latest host and instance sample.
204#[derive(Debug, Clone, Default)]
205pub struct Snapshot {
206    pub host: crate::metrics::HostSample,
207    /// Keyed by `<project>/<name>`: names are unique per project only.
208    pub instances: BTreeMap<String, crate::metrics::InstanceSample>,
209    /// Unix milliseconds; 0 before the first sample.
210    pub at: u64,
211    /// The host's last hour, oldest first (shared: snapshots are copied
212    /// per request).
213    pub host_history: Arc<[crate::metrics::HostPoint]>,
214}
215
216pub fn now_ms() -> u64 {
217    std::time::SystemTime::now()
218        .duration_since(std::time::UNIX_EPOCH)
219        .map(|d| d.as_millis() as u64)
220        .unwrap_or(0)
221}
222
223/// A stack, as `stack_status` and `stack_list` report it.
224#[derive(Debug, Clone, Serialize)]
225pub struct StackStatus {
226    pub name: String,
227    pub org: String,
228    pub deployed_at: u64,
229    pub deployed_by: String,
230    pub has_previous: bool,
231    /// True when every service has its replicas, all current and healthy.
232    pub converged: bool,
233    pub services: Vec<ServiceStatus>,
234}
235
236/// What a deploy is about to do, per service.
237#[derive(Debug, Clone, Serialize)]
238pub struct DeployChange {
239    pub service: String,
240    /// `create`, `update` (new revision: rolling replace), `scale`, `remove`,
241    /// or `unchanged`.
242    pub change: String,
243    pub rev: String,
244    pub replicas: u32,
245}
246
247/// The shared slot a worker reads its instructions from.
248struct Slot {
249    def: Arc<StackDef>,
250    /// Set when the service left its stack: delete its instances and exit.
251    remove: bool,
252    /// Delete the service's named volumes too (with `remove`).
253    remove_volumes: bool,
254}
255
256struct WorkerShared {
257    slot: Mutex<Slot>,
258    wake: Condvar,
259    stop: AtomicBool,
260    /// Set when something the service was failing on may have changed (an
261    /// org's limits): the worker drops its retry backoff on its next pass.
262    kick: AtomicBool,
263}
264
265struct Inner {
266    client: Client,
267    store: Store,
268    balancer: Balancer,
269    interval: Duration,
270    /// Live workers, by (stack, service).
271    workers: Mutex<BTreeMap<(String, String), Arc<WorkerShared>>>,
272    /// Deployed stacks, by name.
273    stacks: Mutex<BTreeMap<String, Arc<StackDef>>>,
274    status: Mutex<BTreeMap<(String, String), ServiceStatus>>,
275    /// The output of each service's last replica that failed to come up.
276    failures: super::failure::Failures,
277    events: Mutex<(u64, VecDeque<Event>)>,
278    snapshot: Mutex<Snapshot>,
279    /// The org stores secret values are read from at delivery.
280    secrets: Arc<Secrets>,
281    /// Held across read-modify-save of a definition, so a version bump and
282    /// a deploy never overwrite each other.
283    edit: Mutex<()>,
284    /// When driver-backed secrets are next checked for a new version.
285    refresh: Mutex<super::secrets::RefreshSchedule>,
286    observer: Option<Arc<dyn Observer>>,
287    /// Where each event also goes: the persistent history.
288    event_sink: Mutex<Option<EventSink>>,
289    /// Where each sample also goes: the metrics history.
290    metrics_sink: Mutex<Option<std::sync::mpsc::SyncSender<crate::metrics_history::Sample>>>,
291    /// Which project environment a stack's services are also named in.
292    dns_scope: Mutex<Option<DnsScopeFn>>,
293}
294
295impl Inner {
296    fn emit(
297        &self,
298        level: &str,
299        stack: &str,
300        service: &str,
301        instance: Option<&str>,
302        message: String,
303    ) {
304        self.emit_kind(None, level, stack, service, instance, message);
305    }
306
307    fn emit_kind(
308        &self,
309        kind: Option<&str>,
310        level: &str,
311        stack: &str,
312        service: &str,
313        instance: Option<&str>,
314        message: String,
315    ) {
316        let mut e = self.events.lock().unwrap();
317        e.0 += 1;
318        let ev = Event {
319            seq: e.0,
320            at: now_ms(),
321            level: level.into(),
322            stack: stack.into(),
323            service: service.into(),
324            instance: instance.map(String::from),
325            message,
326            kind: kind.map(String::from),
327        };
328        if e.1.len() == EVENTS_KEPT {
329            e.1.pop_front();
330        }
331        let sink = self.event_sink.lock().unwrap().clone();
332        if let Some(s) = sink {
333            s(&ev);
334        }
335        e.1.push_back(ev);
336    }
337}
338
339/// How often the metrics sampler runs.
340const SAMPLE_EVERY: Duration = Duration::from_secs(2);
341/// The longest wait between looking for driver-backed secrets that are due.
342const SECRET_TICK: Duration = Duration::from_secs(10);
343
344/// The daemon's stack controller.
345#[derive(Clone)]
346pub struct Controller {
347    inner: Arc<Inner>,
348}
349
350impl Controller {
351    /// Load every stored stack and start reconciling it. Secret values are
352    /// read from `secrets` whenever they are delivered.
353    pub fn start(
354        client: Client,
355        store: Store,
356        interval: Duration,
357        secrets: Arc<Secrets>,
358    ) -> Result<Controller> {
359        Controller::start_with(client, store, interval, secrets, None)
360    }
361
362    /// [`Controller::start`], telling `observer` about rotation changes from
363    /// the first one on.
364    pub fn start_with(
365        client: Client,
366        store: Store,
367        interval: Duration,
368        secrets: Arc<Secrets>,
369        observer: Option<Arc<dyn Observer>>,
370    ) -> Result<Controller> {
371        let c = Controller {
372            inner: Arc::new(Inner {
373                client,
374                store,
375                balancer: Balancer::new(),
376                interval,
377                workers: Mutex::new(BTreeMap::new()),
378                stacks: Mutex::new(BTreeMap::new()),
379                status: Mutex::new(BTreeMap::new()),
380                failures: Default::default(),
381                events: Mutex::new((0, VecDeque::new())),
382                snapshot: Mutex::new(Snapshot::default()),
383                secrets,
384                edit: Mutex::new(()),
385                refresh: Mutex::new(Default::default()),
386                observer,
387                event_sink: Mutex::new(None),
388                metrics_sink: Mutex::new(None),
389                dns_scope: Mutex::new(None),
390            }),
391        };
392        // Driver-backed secrets are polled on their refresh intervals; the
393        // tick only decides which are due.
394        let weak = Arc::downgrade(&c.inner);
395        let _ = std::thread::Builder::new()
396            .name("isb-secrets".into())
397            .spawn(move || {
398                while let Some(inner) = weak.upgrade() {
399                    let tick = inner.interval.clamp(Duration::from_secs(1), SECRET_TICK);
400                    Controller { inner }.check_due_secrets();
401                    std::thread::sleep(tick);
402                }
403            });
404        // A weak handle, so the sampler ends with the controller.
405        let weak = Arc::downgrade(&c.inner);
406        let _ = std::thread::Builder::new()
407            .name("isb-metrics".into())
408            .spawn(move || {
409                let mut sampler = crate::metrics::Sampler::new();
410                let mut orgs = crate::metrics_history::OrgSet::default();
411                while let Some(inner) = weak.upgrade() {
412                    match sampler.sample(&inner.client) {
413                        Ok((host, insts)) => {
414                            if let Some(tx) = &*inner.metrics_sink.lock().unwrap() {
415                                let s = crate::metrics_history::Sample {
416                                    at: now_ms(),
417                                    orgs: orgs.current(&inner.client, &insts),
418                                    orgs_at: orgs.read_at(),
419                                    instances: insts.clone(),
420                                };
421                                crate::metrics_history::offer(tx, s);
422                            }
423                            *inner.snapshot.lock().unwrap() = Snapshot {
424                                host,
425                                instances: insts
426                                    .into_iter()
427                                    .map(|i| (format!("{}/{}", i.project, i.name), i))
428                                    .collect(),
429                                at: now_ms(),
430                                host_history: sampler.host_points().into(),
431                            };
432                        }
433                        Err(e) => eprintln!("isb serve: metrics: {e}"),
434                    }
435                    drop(inner);
436                    std::thread::sleep(SAMPLE_EVERY);
437                }
438            });
439        let defs = c.inner.store.load_all()?;
440        // Service names of stacks removed while no daemon ran.
441        dns::prune(&defs);
442        for def in defs {
443            eprintln!("isb serve: resuming stack {}", def.name);
444            c.apply(Arc::new(def));
445        }
446        // A vault may have moved on while the daemon was down.
447        let all: Vec<(String, String)> = c
448            .definitions()
449            .iter()
450            .flat_map(|def| {
451                let q = def.qualified();
452                def.secrets.keys().map(move |k| (q.clone(), k.clone()))
453            })
454            .collect();
455        c.poll(all);
456        Ok(c)
457    }
458
459    pub fn balancer(&self) -> &Balancer {
460        &self.inner.balancer
461    }
462
463    /// Events after `since` (0: all kept), oldest first, at most `limit`.
464    pub fn events(&self, since: u64, limit: usize) -> (u64, Vec<Event>) {
465        let e = self.inner.events.lock().unwrap();
466        let out: Vec<Event> = e.1.iter().filter(|x| x.seq > since).cloned().collect();
467        let skip = out.len().saturating_sub(limit);
468        (e.0, out.into_iter().skip(skip).collect())
469    }
470
471    /// A client's resume cursor for [`Self::events`]: one past the newest
472    /// event came from an earlier process (numbering restarts with the
473    /// daemon), so the client starts over from what is kept instead of
474    /// waiting for this feed to count back up to it.
475    pub fn resume_from(&self, since: u64) -> u64 {
476        if since > self.inner.events.lock().unwrap().0 {
477            0
478        } else {
479            since
480        }
481    }
482
483    /// Wait up to `timeout` for an event after `since`.
484    pub fn wait_events(&self, since: u64, limit: usize, timeout: Duration) -> (u64, Vec<Event>) {
485        let started = Instant::now();
486        loop {
487            let r = self.events(since, limit);
488            if !r.1.is_empty() || started.elapsed() >= timeout {
489                return r;
490            }
491            std::thread::sleep(Duration::from_millis(250));
492        }
493    }
494
495    /// Hand every event to `sink` too (the persistent history), starting
496    /// with the ones already kept, so none emitted before it was set is
497    /// missed and none is handed over twice.
498    pub fn set_event_sink(&self, sink: EventSink) {
499        let e = self.inner.events.lock().unwrap();
500        for ev in &e.1 {
501            sink(ev);
502        }
503        *self.inner.event_sink.lock().unwrap() = Some(sink);
504    }
505
506    /// Send every metrics sample to `tx` too (the metrics history).
507    pub fn set_metrics_sink(
508        &self,
509        tx: std::sync::mpsc::SyncSender<crate::metrics_history::Sample>,
510    ) {
511        *self.inner.metrics_sink.lock().unwrap() = Some(tx);
512    }
513
514    /// The latest metrics sample.
515    pub fn snapshot(&self) -> Snapshot {
516        self.inner.snapshot.lock().unwrap().clone()
517    }
518
519    /// Record an event from outside a worker (a deploy, a removal).
520    /// Record an event of a known kind ([`Event::kind`]) about a stack, or
521    /// one of its services when `service` is not empty.
522    pub fn event(&self, kind: &str, level: &str, stack: &str, service: &str, message: String) {
523        eprintln!("isb serve: {stack}: {message}");
524        self.inner
525            .emit_kind(Some(kind), level, stack, service, None, message);
526    }
527
528    pub fn note(&self, level: &str, stack: &str, message: String) {
529        eprintln!("isb serve: {stack}: {message}");
530        self.inner.emit(level, stack, "", None, message);
531    }
532
533    /// Record an event about one service of a stack (an app's deployment
534    /// log, say). Not echoed to stderr: it can be chatty.
535    pub fn note_service(&self, level: &str, stack: &str, service: &str, message: String) {
536        self.inner.emit(level, stack, service, None, message);
537    }
538
539    /// Record an event about one service (`stack` qualified).
540    pub fn service_event(&self, level: &str, stack: &str, service: &str, message: String) {
541        eprintln!("isb serve: {stack}/{service}: {message}");
542        self.inner.emit(level, stack, service, None, message);
543    }
544
545    fn notify_stacks(&self) {
546        if let Some(o) = &self.inner.observer {
547            o.stacks_changed(self.definitions());
548        }
549    }
550
551    /// What deploying `def` would change, without deploying it.
552    pub fn plan(&self, def: &StackDef) -> Result<Vec<DeployChange>> {
553        self.validate(def)?;
554        let mut def = def.clone();
555        self.pin_images(&mut def)?;
556        let def = &def;
557        let old = self
558            .inner
559            .stacks
560            .lock()
561            .unwrap()
562            .get(&def.qualified())
563            .cloned();
564        diff(old.as_deref(), def)
565    }
566
567    pub fn client(&self) -> &Client {
568        &self.inner.client
569    }
570
571    /// Check a stack definition against this host without deploying it:
572    /// every service must resolve (image source, paths, ports) and name its widest slot.
573    pub fn validate(&self, def: &StackDef) -> Result<()> {
574        validate_stack_name(&def.name)?;
575        // In the org's project, which is what `registry:` images resolve in.
576        let host = crate::sandbox::host_facts(&crate::org::client(&self.inner.client, &def.org))?;
577        for (svc, spec) in &def.file.services {
578            let mut s = instance_spec(def, svc, spec, 1, "0000")?;
579            s.name = Some(instance_name(&def.name, svc, 1, "0000")?);
580            instance_name(&def.name, svc, spec.replicas().max(1), "0000")?;
581            crate::plan::resolve(&s, &def.file.volumes, &host, &def.base_dir)?;
582            published(spec)?;
583            crate::ingress::domain::validate(svc, &spec.domains)?;
584        }
585        super::ports::validate_udp(&self.inner.client, def, &self.definitions())
586    }
587
588    /// Deploy (or update) a stack. Returns what will change; the rollout
589    /// itself happens in the background.
590    pub fn deploy(&self, mut def: StackDef) -> Result<Vec<DeployChange>> {
591        self.validate(&def)?;
592        self.pin_images(&mut def)?;
593        let _g = self.inner.edit.lock().unwrap();
594        let old = self
595            .inner
596            .stacks
597            .lock()
598            .unwrap()
599            .get(&def.qualified())
600            .cloned();
601        if let Some(old) = &old {
602            let mut prev = (**old).clone();
603            prev.previous = None;
604            def.previous = Some(Box::new(prev));
605            // A forced update survives a redeploy that does not ask for one.
606            for (k, v) in &old.force {
607                def.force.entry(k.clone()).or_insert(*v);
608            }
609        }
610        let changes = diff(old.as_deref(), &def)?;
611        self.inner.store.save(&def)?;
612        self.apply(Arc::new(def));
613        Ok(changes)
614    }
615
616    /// Hand a definition to the workers: update existing ones, start new
617    /// ones, and tell those whose service is gone to clean up.
618    fn apply(&self, def: Arc<StackDef>) {
619        let name = def.qualified();
620        self.inner
621            .stacks
622            .lock()
623            .unwrap()
624            .insert(name.clone(), def.clone());
625        let mut workers = self.inner.workers.lock().unwrap();
626        for svc in def.file.services.keys() {
627            let key = (name.clone(), svc.clone());
628            match workers.get(&key) {
629                Some(w) => {
630                    let mut slot = w.slot.lock().unwrap();
631                    slot.def = def.clone();
632                    slot.remove = false;
633                    // A new deployment starts from a clean slate: the
634                    // failure the service reported before it is not the
635                    // deployment's, and a waiter must not read it as such.
636                    if let Some(st) = self.inner.status.lock().unwrap().get_mut(&key) {
637                        if st.state == "failing" {
638                            st.state = "updating".into();
639                            st.message = None;
640                        }
641                    }
642                    w.wake.notify_all();
643                }
644                None => {
645                    let shared = Arc::new(WorkerShared {
646                        slot: Mutex::new(Slot {
647                            def: def.clone(),
648                            remove: false,
649                            remove_volumes: false,
650                        }),
651                        wake: Condvar::new(),
652                        stop: AtomicBool::new(false),
653                        kick: AtomicBool::new(false),
654                    });
655                    workers.insert(key, shared.clone());
656                    spawn_worker(self.inner.clone(), &def, svc.clone(), shared);
657                }
658            }
659        }
660        for ((stack, svc), w) in workers.iter() {
661            if *stack == name && !def.file.services.contains_key(svc) {
662                let mut slot = w.slot.lock().unwrap();
663                slot.remove = true;
664                w.wake.notify_all();
665            }
666        }
667        drop(workers);
668        self.notify_stacks();
669    }
670
671    /// An org's limits changed: services of the org that are failing on a
672    /// limit (a quota refusal from incus) retry now instead of after their
673    /// backoff. Returns how many were woken.
674    pub fn org_limits_changed(&self, org: &OrgId) -> usize {
675        let stacks = self.inner.stacks.lock().unwrap();
676        let workers = self.inner.workers.lock().unwrap();
677        let status = self.inner.status.lock().unwrap();
678        let mut n = 0;
679        for (key, w) in workers.iter() {
680            let ours = stacks.get(&key.0).is_some_and(|d| d.org == *org);
681            let limited = status.get(key).is_some_and(|s| {
682                s.state == "failing" && s.message.as_deref().is_some_and(limit_error)
683            });
684            if ours && limited {
685                w.kick.store(true, Ordering::SeqCst);
686                // Under the slot lock, the worker is either waiting (and
687                // wakes) or yet to look at the flag.
688                let _slot = w.slot.lock().unwrap();
689                w.wake.notify_all();
690                n += 1;
691            }
692        }
693        n
694    }
695
696    /// Remove a stack: every instance and published port; with `volumes`,
697    /// its named volumes too. Returns once the workers have cleaned up (or
698    /// after `timeout`).
699    pub fn remove(&self, name: &str, volumes: bool, timeout: Duration) -> Result<()> {
700        {
701            let _g = self.inner.edit.lock().unwrap();
702            let Some(def) = self.inner.stacks.lock().unwrap().remove(name) else {
703                return Err(Error::NotFound(format!("stack {name}")));
704            };
705            self.inner.store.remove(&def.org, &def.name)?;
706        }
707        self.notify_stacks();
708        let ws: Vec<Arc<WorkerShared>> = self
709            .inner
710            .workers
711            .lock()
712            .unwrap()
713            .iter()
714            .filter(|((s, _), _)| s == name)
715            .map(|(_, w)| w.clone())
716            .collect();
717        for w in &ws {
718            let mut slot = w.slot.lock().unwrap();
719            slot.remove = true;
720            slot.remove_volumes = volumes;
721            w.wake.notify_all();
722        }
723        let started = Instant::now();
724        while started.elapsed() < timeout {
725            let left = self
726                .inner
727                .workers
728                .lock()
729                .unwrap()
730                .keys()
731                .any(|(s, _)| s == name);
732            if !left {
733                return Ok(());
734            }
735            std::thread::sleep(Duration::from_millis(200));
736        }
737        Err(Error::invalid(format!(
738            "stack {name}: still removing after {timeout:?}; it carries on in the background"
739        )))
740    }
741
742    /// Go back to the previous deployment (the current one becomes the
743    /// previous, so a second rollback undoes the first).
744    pub fn rollback(&self, name: &str) -> Result<Vec<DeployChange>> {
745        let _g = self.inner.edit.lock().unwrap();
746        let cur = self.get_def(name)?;
747        let prev = cur
748            .previous
749            .clone()
750            .ok_or_else(|| Error::invalid(format!("stack {name} has no previous deployment")))?;
751        let mut def = *prev;
752        def.deployed_at = now_secs();
753        // The store keeps only each secret's current value: that is what a
754        // rollback delivers, under its current version.
755        for b in def.secrets.values_mut() {
756            if let Ok(v) = self.inner.secrets.version_in(&b.driver, &def.org, &b.name) {
757                b.version = v;
758            }
759        }
760        let mut cur2 = (*cur).clone();
761        cur2.previous = None;
762        let changes = diff(Some(&cur), &def)?;
763        def.previous = Some(Box::new(cur2));
764        self.inner.store.save(&def)?;
765        self.apply(Arc::new(def));
766        Ok(changes)
767    }
768
769    /// Change one service's replica count.
770    pub fn scale(&self, name: &str, service: &str, replicas: u32) -> Result<()> {
771        let _g = self.inner.edit.lock().unwrap();
772        let cur = self.get_def(name)?;
773        let mut def = (*cur).clone();
774        let spec = def
775            .file
776            .services
777            .get_mut(service)
778            .ok_or_else(|| Error::NotFound(format!("service {service} in stack {name}")))?;
779        spec.deploy.get_or_insert_with(Default::default).replicas = Some(replicas);
780        super::ports::check_replicas(service, spec)?;
781        // `name` is the controller key (`org/stack`); instances use the bare name.
782        instance_name(&def.name, service, replicas.max(1), "0000")?;
783        self.inner.store.save(&def)?;
784        self.apply(Arc::new(def));
785        Ok(())
786    }
787
788    /// Replace every instance of a service even though its spec is the same
789    /// (`docker service update --force`): picks up a moved image tag or a
790    /// changed bind-mounted file.
791    pub fn redeploy(&self, name: &str, service: &str) -> Result<()> {
792        let _g = self.inner.edit.lock().unwrap();
793        let cur = self.get_def(name)?;
794        cur.service(service)?;
795        let mut def = (*cur).clone();
796        *def.force.entry(service.to_string()).or_insert(0) += 1;
797        // A moved tag is what a redeploy is usually for.
798        self.pin_images(&mut def)?;
799        self.inner.store.save(&def)?;
800        self.apply(Arc::new(def));
801        Ok(())
802    }
803
804    /// Resolve every `registry:` image given by tag to the digest the tag
805    /// names now, in the stack's org (a digest in the file only has to
806    /// exist there).
807    fn pin_images(&self, def: &mut StackDef) -> Result<()> {
808        def.images.clear();
809        for (svc, spec) in &def.file.services {
810            let Some(r) = spec.image.strip_prefix("registry:") else {
811                continue;
812            };
813            let r = crate::registry::ImageRef::parse(r)?;
814            let reg = crate::registry::Registry::shared(&self.inner.client)?;
815            // A digest is checked too, so a typo (or another org's digest)
816            // fails the deploy rather than the rollout.
817            let d = reg.resolve(&def.org, &r)?;
818            if r.digest.is_none() {
819                def.images.insert(svc.clone(), d);
820            }
821        }
822        Ok(())
823    }
824
825    fn get_def(&self, name: &str) -> Result<Arc<StackDef>> {
826        self.inner
827            .stacks
828            .lock()
829            .unwrap()
830            .get(name)
831            .cloned()
832            .ok_or_else(|| Error::NotFound(format!("stack {name}")))
833    }
834
835    /// Every stored definition, without computing status.
836    pub fn definitions(&self) -> Vec<Arc<StackDef>> {
837        self.inner
838            .stacks
839            .lock()
840            .unwrap()
841            .values()
842            .cloned()
843            .collect()
844    }
845
846    /// The stored definition of a stack.
847    pub fn definition(&self, name: &str) -> Result<StackDef> {
848        self.get_def(name).map(|d| (*d).clone())
849    }
850
851    pub fn list(&self) -> Vec<StackStatus> {
852        let names: Vec<String> = self.inner.stacks.lock().unwrap().keys().cloned().collect();
853        names.iter().filter_map(|n| self.status(n).ok()).collect()
854    }
855
856    pub fn status(&self, name: &str) -> Result<StackStatus> {
857        let def = self.get_def(name)?;
858        let st = self.inner.status.lock().unwrap();
859        let services: Vec<ServiceStatus> = def
860            .file
861            .services
862            .keys()
863            .map(|svc| {
864                st.get(&(name.to_string(), svc.clone()))
865                    .cloned()
866                    .unwrap_or_else(|| ServiceStatus {
867                        service: svc.clone(),
868                        state: "starting".into(),
869                        ..Default::default()
870                    })
871            })
872            .collect();
873        drop(st);
874        let mut services = services;
875        if let Some(o) = &self.inner.observer {
876            for s in &mut services {
877                s.domains = o.domains(name, &s.service);
878            }
879        }
880        for s in services.iter_mut().filter(|s| s.state != "converged") {
881            s.last_failed_attempt = self
882                .inner
883                .failures
884                .last(name, &s.service)
885                .map(|f| f.summary());
886        }
887        let converged = services.iter().all(|s| s.state == "converged");
888        Ok(StackStatus {
889            name: def.name.clone(),
890            org: def.org.to_string(),
891            deployed_at: def.deployed_at,
892            deployed_by: def.deployed_by.clone(),
893            has_previous: def.previous.is_some(),
894            converged,
895            services,
896        })
897    }
898
899    /// Recent output of a service's replicas (or one slot's).
900    pub fn logs(
901        &self,
902        name: &str,
903        service: &str,
904        slot: Option<u32>,
905        lines: usize,
906    ) -> Result<BTreeMap<String, String>> {
907        let def = self.get_def(name)?;
908        let oci = crate::plan::ImageSource::parse(&def.service(service)?.image)?.is_oci();
909        let oc = crate::org::client(&self.inner.client, &def.org);
910        super::failure::replica_logs(&oc, &def.name, service, oci, slot, lines)
911    }
912
913    /// The last replica of a service that failed to come up, with its
914    /// output, while the service is not converged (or `always`): after the
915    /// instance is deleted, this is all that is left to read.
916    pub fn last_failure(
917        &self,
918        name: &str,
919        service: &str,
920        always: bool,
921    ) -> Option<super::failure::FailedAttempt> {
922        let state = self.inner.status.lock().unwrap();
923        let converged = state
924            .get(&(name.to_string(), service.to_string()))
925            .is_some_and(|s| s.state == "converged");
926        drop(state);
927        if converged && !always {
928            return None;
929        }
930        self.inner.failures.last(name, service)
931    }
932
933    /// The last failed attempt of each of a stack's services, converged or not.
934    pub fn failed_attempts(&self, name: &str) -> BTreeMap<String, super::failure::FailedAttempt> {
935        self.inner.failures.of_stack(name)
936    }
937
938    /// Stop every worker and the balancer. Apps keep running in their
939    /// instances; published ports stop until the next start.
940    pub fn shutdown(&self) {
941        for w in self.inner.workers.lock().unwrap().values() {
942            w.stop.store(true, Ordering::SeqCst);
943            w.wake.notify_all();
944        }
945        self.inner.balancer.clear();
946    }
947}
948
949/// Whether a failure message is an incus project-limit refusal (see
950/// `org::limits`): one that raising the org's limits can fix.
951fn limit_error(msg: &str) -> bool {
952    msg.contains(" quota (") || msg.contains(" limit (")
953}
954
955/// The spec an instance of `service` is created from: labelled, with its
956/// published TCP ports removed (the balancer serves them) and its UDP ports
957/// as NAT proxies (see [`super::ports`]), and always long-running, as swarm
958/// ignores `restart` in favour of `restart_policy`.
959fn instance_spec(
960    def: &StackDef,
961    service: &str,
962    spec: &SandboxSpec,
963    slot: u32,
964    rev: &str,
965) -> Result<SandboxSpec> {
966    let mut s = spec.clone();
967    s.image = def.instance_image(service, &spec.image);
968    s.restart = Some(RestartMode::Always);
969    (s.ports, s.stack_udp) = super::ports::instance_ports(spec)?;
970    s.domains.clear();
971    if let Some(d) = &s.deploy {
972        s.labels.extend(d.labels.clone());
973    }
974    s.labels.insert(LABEL_STACK.into(), def.name.clone());
975    s.labels.insert(LABEL_SERVICE.into(), service.into());
976    s.labels.insert(LABEL_SLOT.into(), slot.to_string());
977    s.labels.insert(LABEL_REV.into(), rev.into());
978    let live = live_versions(def, service);
979    if !live.is_empty() {
980        s.labels
981            .insert(LABEL_SECRETS.into(), super::secrets::versions_label(&live));
982    }
983    Ok(s)
984}
985
986/// The versions bound now of the secrets `service` takes in place.
987fn live_versions(def: &StackDef, service: &str) -> BTreeMap<String, u64> {
988    def.live_secrets(service)
989        .into_iter()
990        .map(|(k, (_, v))| (k, v))
991        .collect()
992}
993
994/// A stack's instance as listed.
995#[derive(Debug, Clone)]
996#[doc(hidden)]
997pub struct Inst {
998    pub name: String,
999    pub(super) slot: u32,
1000    pub rev: String,
1001    status: String,
1002    /// [`LABEL_SECRETS`]: the `restart`/`none` secret versions its app last
1003    /// started with; `None` on an instance from before the label.
1004    secrets: Option<BTreeMap<String, u64>>,
1005}
1006
1007impl Inst {
1008    #[doc(hidden)]
1009    pub fn is_running(&self) -> bool {
1010        self.running()
1011    }
1012
1013    fn running(&self) -> bool {
1014        self.status.eq_ignore_ascii_case("running")
1015    }
1016}
1017
1018/// A service's worker.
1019struct Worker {
1020    inner: Arc<Inner>,
1021    /// The stack's own name: labels and instance names use it.
1022    stack: String,
1023    /// `org/stack`: the controller's key, and how events name it.
1024    q: String,
1025    /// A client on the stack's org (its incus project).
1026    oclient: Client,
1027    service: String,
1028    shared: Arc<WorkerShared>,
1029    rt: BTreeMap<String, InstRt>,
1030    /// The revision whose rollout failed and paused; not retried until the
1031    /// revision changes.
1032    paused: Option<(String, String)>,
1033    /// Backoff for creating into an empty slot that keeps failing.
1034    create_backoff: Option<(Instant, Duration)>,
1035    routes: BTreeMap<String, Published>,
1036    route_errors: BTreeMap<String, String>,
1037    /// The resolved spec of the current revision, for exec defaults.
1038    template: Option<(String, Desired)>,
1039    state: String,
1040    message: Option<String>,
1041    last_error: Option<String>,
1042    /// The instances as last listed, kept current through a rollout.
1043    insts: Vec<Inst>,
1044    rollout: Option<RolloutStatus>,
1045    /// Per route: accepted count at the last status, when, and conn/s history.
1046    rates: BTreeMap<String, (u64, Instant, VecDeque<f32>)>,
1047    /// `depends_on` was met once: from then on the service is reconciled
1048    /// whatever its dependencies do.
1049    deps_met: bool,
1050    org: OrgId,
1051    /// The addresses last published as the service's name, and the
1052    /// project environment it was also named in.
1053    dns_last: Option<(Vec<IpAddr>, Option<String>)>,
1054    dns_error: Option<String>,
1055    /// The addresses last told to the observer.
1056    observed: Option<Vec<IpAddr>>,
1057    /// The service had a healthy replica at some point in this run.
1058    ever_healthy: bool,
1059    /// Since when no replica has been healthy.
1060    health_down: Option<Instant>,
1061    /// `health.unhealthy` was raised and not yet answered by `recovered`.
1062    health_alarm: bool,
1063    /// The definition the last pass ran on.
1064    seen: Option<Arc<StackDef>>,
1065    /// The secret versions whose in-place restart failed, and why: not
1066    /// tried again on the other replicas until they move.
1067    restart_failed: Option<(BTreeMap<String, u64>, String)>,
1068}
1069
1070fn spawn_worker(inner: Arc<Inner>, def: &StackDef, service: String, shared: Arc<WorkerShared>) {
1071    let (stack, q, org) = (def.name.clone(), def.qualified(), def.org.clone());
1072    let oclient = crate::org::client(&inner.client, &def.org);
1073    let name = format!("isb-{q}-{service}");
1074    let r = std::thread::Builder::new().name(name).spawn(move || {
1075        let mut w = Worker::new(inner, stack, q, oclient, service, shared, org);
1076        w.run();
1077    });
1078    if let Err(e) = r {
1079        eprintln!("isb serve: cannot start a worker thread: {e}");
1080    }
1081}
1082
1083impl Worker {
1084    fn new(
1085        inner: Arc<Inner>,
1086        stack: String,
1087        q: String,
1088        oclient: Client,
1089        service: String,
1090        shared: Arc<WorkerShared>,
1091        org: OrgId,
1092    ) -> Worker {
1093        Worker {
1094            inner,
1095            stack,
1096            q,
1097            oclient,
1098            service,
1099            shared,
1100            rt: BTreeMap::new(),
1101            paused: None,
1102            create_backoff: None,
1103            routes: BTreeMap::new(),
1104            route_errors: BTreeMap::new(),
1105            template: None,
1106            state: "starting".into(),
1107            message: None,
1108            last_error: None,
1109            insts: Vec::new(),
1110            rollout: None,
1111            rates: BTreeMap::new(),
1112            deps_met: false,
1113            org,
1114            dns_last: None,
1115            dns_error: None,
1116            observed: None,
1117            ever_healthy: false,
1118            health_down: None,
1119            health_alarm: false,
1120            seen: None,
1121            restart_failed: None,
1122        }
1123    }
1124
1125    /// Drop the retry backoff when the instructions changed (a new
1126    /// deployment) or were kicked (an org's limits changed), so the next
1127    /// pass makes a fresh attempt, and forget the failure the old
1128    /// instructions ended in.
1129    fn begin_pass(&mut self, def: &Arc<StackDef>) {
1130        let new_def = self.seen.as_ref().is_none_or(|d| !Arc::ptr_eq(d, def));
1131        let kicked = self.shared.kick.swap(false, Ordering::SeqCst);
1132        if new_def {
1133            self.seen = Some(def.clone());
1134            self.last_error = None;
1135            if self.state == "failing" {
1136                self.state = "updating".into();
1137                self.message = None;
1138            }
1139        }
1140        if new_def || kicked {
1141            self.create_backoff = None;
1142        }
1143    }
1144}
1145
1146impl Worker {
1147    fn log(&self, msg: &str) {
1148        self.event("info", None, msg);
1149    }
1150
1151    fn event(&self, level: &str, instance: Option<&str>, msg: &str) {
1152        eprintln!("isb serve: {}/{}: {msg}", self.q, self.service);
1153        self.inner
1154            .emit(level, &self.q, &self.service, instance, msg.to_string());
1155    }
1156
1157    fn client(&self) -> &Client {
1158        &self.oclient
1159    }
1160
1161    /// Raise `health.unhealthy` once a service that was healthy has had no
1162    /// healthy replica for [`HEALTH_DEBOUNCE`] (not while a rollout runs:
1163    /// it reports its own failure), and `health.recovered` when one is back.
1164    fn watch_health(&mut self, healthy: u32, replicas: u32) {
1165        if healthy > 0 {
1166            self.ever_healthy = true;
1167            self.health_down = None;
1168            if self.health_alarm {
1169                self.health_alarm = false;
1170                let msg = format!("{healthy} of {replicas} replicas healthy again");
1171                eprintln!("isb serve: {}/{}: {msg}", self.q, self.service);
1172                self.inner.emit_kind(
1173                    Some("health.recovered"),
1174                    "info",
1175                    &self.q,
1176                    &self.service,
1177                    None,
1178                    msg,
1179                );
1180            }
1181            return;
1182        }
1183        if replicas == 0 || !self.ever_healthy || self.rollout.is_some() {
1184            self.health_down = None;
1185            return;
1186        }
1187        let since = *self.health_down.get_or_insert_with(Instant::now);
1188        if !self.health_alarm && since.elapsed() >= HEALTH_DEBOUNCE {
1189            self.health_alarm = true;
1190            let msg = format!(
1191                "no healthy replica (of {replicas}) for {}s",
1192                since.elapsed().as_secs()
1193            );
1194            eprintln!("isb serve: {}/{}: {msg}", self.q, self.service);
1195            self.inner.emit_kind(
1196                Some("health.unhealthy"),
1197                "error",
1198                &self.q,
1199                &self.service,
1200                None,
1201                msg,
1202            );
1203        }
1204    }
1205
1206    fn key(&self) -> (String, String) {
1207        (self.q.clone(), self.service.clone())
1208    }
1209
1210    fn run(&mut self) {
1211        loop {
1212            if self.shared.stop.load(Ordering::SeqCst) {
1213                return;
1214            }
1215            let (def, remove, remove_volumes) = {
1216                let s = self.shared.slot.lock().unwrap();
1217                (s.def.clone(), s.remove, s.remove_volumes)
1218            };
1219            if remove {
1220                self.teardown(&def, remove_volumes);
1221                // The service may have been deployed again meanwhile: then
1222                // this worker carries on instead of leaving it unattended.
1223                let mut ws = self.inner.workers.lock().unwrap();
1224                let slot = self.shared.slot.lock().unwrap();
1225                if slot.remove || self.shared.stop.load(Ordering::SeqCst) {
1226                    ws.remove(&self.key());
1227                    self.inner.status.lock().unwrap().remove(&self.key());
1228                    return;
1229                }
1230                continue;
1231            }
1232            self.begin_pass(&def);
1233            if let Err(e) = self.pass(&def) {
1234                self.state = "failing".into();
1235                self.message = Some(e.to_string());
1236                // Once per distinct error, not once per pass.
1237                if self.last_error.as_deref() != Some(&e.to_string()) {
1238                    self.event("error", None, &e.to_string());
1239                    self.last_error = Some(e.to_string());
1240                }
1241                self.publish_status(&def);
1242                let slot = self.shared.slot.lock().unwrap();
1243                if Arc::ptr_eq(&slot.def, &def) && !slot.remove {
1244                    let _ = self.shared.wake.wait_timeout(slot, self.inner.interval);
1245                }
1246                continue;
1247            }
1248            self.last_error = None;
1249            let slot = self.shared.slot.lock().unwrap();
1250            if Arc::ptr_eq(&slot.def, &def) && !slot.remove {
1251                let _ = self.shared.wake.wait_timeout(slot, self.inner.interval);
1252            }
1253        }
1254    }
1255
1256    /// A deployment arrived (or removal was asked) since `def` was read.
1257    fn superseded(&self, def: &Arc<StackDef>) -> bool {
1258        let s = self.shared.slot.lock().unwrap();
1259        s.remove || !Arc::ptr_eq(&s.def, def) || self.shared.stop.load(Ordering::SeqCst)
1260    }
1261
1262    /// Delete this service's instances and routes, then leave.
1263    fn teardown(&mut self, def: &StackDef, volumes: bool) {
1264        // The name goes first, whoever published it.
1265        self.unpublish_dns();
1266        if let Some(o) = &self.inner.observer {
1267            o.rotation(&self.q, &self.service, &[]);
1268        }
1269        self.observed = Some(Vec::new());
1270        for (k, _) in std::mem::take(&mut self.routes) {
1271            self.inner.balancer.remove_route(&k);
1272        }
1273        match list_instances(self.client(), &self.stack, Some(&self.service)) {
1274            Ok(insts) => {
1275                for i in insts {
1276                    self.log(&format!("removing {}", i.name));
1277                    if let Err(e) = Sandbox::remove(self.client(), &i.name, true) {
1278                        if !e.is_not_found() {
1279                            self.log(&format!("cannot remove {}: {e}", i.name));
1280                        }
1281                    }
1282                }
1283            }
1284            Err(e) => self.log(&format!("cannot list instances to remove: {e}")),
1285        }
1286        if volumes {
1287            self.remove_volumes(def);
1288        }
1289        self.rt.clear();
1290        self.template = None;
1291    }
1292
1293    fn remove_volumes(&self, def: &StackDef) {
1294        let Ok(spec) = def.service(&self.service) else {
1295            return;
1296        };
1297        let Ok(host) = crate::sandbox::host_facts(self.client()) else {
1298            return;
1299        };
1300        let Ok(pool) = host.pick_pool(spec.storage.as_deref()) else {
1301            return;
1302        };
1303        for v in &spec.volumes {
1304            if v.mount_type != crate::spec::MountType::Volume {
1305                continue;
1306            }
1307            let d = def.file.volumes.get(&v.source);
1308            if v.external || d.is_some_and(|d| d.external) {
1309                continue;
1310            }
1311            let name = d
1312                .and_then(|d| d.name.clone())
1313                .unwrap_or_else(|| v.source.clone());
1314            let vpool = match v.pool.as_deref().or(d.and_then(|d| d.pool.as_deref())) {
1315                Some(p) if p != "auto" => p.to_string(),
1316                _ => pool.clone(),
1317            };
1318            match crate::volume::remove(self.client(), &vpool, &name) {
1319                Ok(()) => self.log(&format!("volume {name}: deleted")),
1320                Err(e) if e.is_not_found() => {}
1321                // Another service of the stack may still be using it.
1322                Err(e) => self.log(&format!("volume {name}: kept ({e})")),
1323            }
1324        }
1325    }
1326
1327    /// One reconcile pass.
1328    #[expect(
1329        clippy::too_many_lines,
1330        reason = "predates the lint ratchet; split it when next changed"
1331    )]
1332    fn pass(&mut self, def: &Arc<StackDef>) -> Result<()> {
1333        let spec = def.service(&self.service)?.clone();
1334        let rev = def.revision(&self.service)?;
1335        let replicas = spec.replicas();
1336        let oci = crate::plan::ImageSource::parse(&spec.image)?.is_oci();
1337        let probe = spec.health_probe().map_err(Error::invalid)?;
1338
1339        if !self.deps_met {
1340            if let Some(msg) = self.waiting_for(&spec) {
1341                self.state = "waiting".into();
1342                self.message = Some(msg);
1343                self.publish_status(def);
1344                return Ok(());
1345            }
1346            self.deps_met = true;
1347        }
1348        if self.template.as_ref().is_none_or(|(r, _)| *r != rev) {
1349            let mut s = instance_spec(def, &self.service, &spec, 1, &rev)?;
1350            s.name = Some(instance_name(&self.stack, &self.service, 1, "0000")?);
1351            let d = crate::sandbox::resolve(self.client(), &s, &def.file.volumes, &def.base_dir)?;
1352            self.template = Some((rev.clone(), d));
1353        }
1354        self.set_routes(&spec);
1355
1356        let mut insts = list_instances(self.client(), &self.stack, Some(&self.service))?;
1357        self.rt.retain(|n, _| insts.iter().any(|i| i.name == *n));
1358
1359        self.scale_down(def, &insts, replicas)?;
1360        insts.retain(|i| i.slot >= 1 && i.slot <= replicas);
1361        self.insts = insts.clone();
1362
1363        // Keep what exists running, set up and healthy.
1364        for i in &insts {
1365            self.maintain(def, i, &spec, oci, probe.as_ref())?;
1366        }
1367        // An interrupted rollout can leave an old instance next to a current
1368        // one in the same slot: once the current one serves, drop the old.
1369        for slot in 1..=replicas {
1370            let current_ok = insts.iter().any(|i| {
1371                i.slot == slot
1372                    && i.rev == rev
1373                    && self.rt.get(&i.name).is_some_and(|r| r.in_rotation)
1374            });
1375            if current_ok {
1376                for i in insts.iter().filter(|i| i.slot == slot && i.rev != rev) {
1377                    self.log(&format!("removing leftover {}", i.name));
1378                    self.retire(&i.name)?;
1379                }
1380            }
1381            let mut current: Vec<&Inst> = insts
1382                .iter()
1383                .filter(|i| i.slot == slot && i.rev == rev)
1384                .collect();
1385            // Two current instances in one slot (a crash mid-create): keep one.
1386            while current.len() > 1 {
1387                let i = current.pop().unwrap();
1388                self.log(&format!("removing duplicate {}", i.name));
1389                self.retire(&i.name)?;
1390            }
1391        }
1392        self.sync_routes();
1393        self.publish_status(def);
1394
1395        // Roll out: slots without a current instance.
1396        let mut pending: Vec<(u32, Option<String>)> = Vec::new();
1397        for slot in 1..=replicas {
1398            if insts.iter().any(|i| i.slot == slot && i.rev == rev) {
1399                continue;
1400            }
1401            let old = insts
1402                .iter()
1403                .find(|i| i.slot == slot)
1404                .map(|i| i.name.clone());
1405            pending.push((slot, old));
1406        }
1407        if pending.is_empty() {
1408            self.create_backoff = None;
1409            // New versions of secrets the service takes in place.
1410            let uc = spec
1411                .deploy
1412                .as_ref()
1413                .and_then(|d| d.update_config.clone())
1414                .unwrap_or_default();
1415            self.cycle_in_place(def, &spec, &uc)?;
1416            let insts = self.insts.clone();
1417            let all_ok = insts
1418                .iter()
1419                .all(|i| i.rev == rev && self.rt.get(&i.name).is_some_and(|r| r.in_rotation));
1420            self.state = if all_ok { "converged" } else { "failing" }.into();
1421            if all_ok {
1422                self.message = self.restart_failed.as_ref().map(|(_, m)| m.clone());
1423            } else if self.message.is_none() {
1424                self.message = Some("some replicas are not healthy".into());
1425            }
1426            self.publish_status(def);
1427            return Ok(());
1428        }
1429        if self.paused.as_ref().is_some_and(|(r, _)| *r == rev) {
1430            self.state = "paused".into();
1431            self.message = self.paused.as_ref().map(|(_, m)| m.clone());
1432            self.publish_status(def);
1433            return Ok(());
1434        }
1435        if let Some((at, wait)) = self.create_backoff {
1436            if at.elapsed() < wait {
1437                return Ok(());
1438            }
1439        }
1440        self.state = "updating".into();
1441        self.message = None;
1442        self.publish_status(def);
1443
1444        let uc: UpdateConfig = spec
1445            .deploy
1446            .as_ref()
1447            .and_then(|d| d.update_config.clone())
1448            .unwrap_or_default();
1449        let parallel = match uc.parallelism.unwrap_or(1) {
1450            0 => pending.len(),
1451            n => n as usize,
1452        };
1453        let delay = uc
1454            .delay
1455            .as_deref()
1456            .map(crate::flex::parse_duration)
1457            .transpose()
1458            .map_err(Error::invalid)?
1459            .unwrap_or_default();
1460        let monitor = uc
1461            .monitor
1462            .as_deref()
1463            .map(crate::flex::parse_duration)
1464            .transpose()
1465            .map_err(Error::invalid)?
1466            .unwrap_or(Duration::from_secs(5));
1467        let order = uc.order.unwrap_or_default();
1468        let order_name = match order {
1469            UpdateOrder::StopFirst => "stop-first",
1470            UpdateOrder::StartFirst => "start-first",
1471        };
1472        self.rollout = Some(RolloutStatus {
1473            to_rev: rev.clone(),
1474            order: order_name.into(),
1475            parallelism: parallel,
1476            done: 0,
1477            total: pending.len(),
1478            started_at: now_secs(),
1479            slots: pending
1480                .iter()
1481                .map(|(slot, old)| SlotRollout {
1482                    slot: *slot,
1483                    old: old.clone(),
1484                    old_rev: old
1485                        .as_ref()
1486                        .and_then(|o| insts.iter().find(|i| i.name == *o))
1487                        .map(|i| i.rev.clone()),
1488                    old_state: if old.is_some() { "serving" } else { "none" }.into(),
1489                    new: None,
1490                    new_state: "waiting".into(),
1491                })
1492                .collect(),
1493        });
1494        let rollout_started = Instant::now();
1495        self.log(&format!(
1496            "rolling out rev {rev} to {} slot(s), {order_name}",
1497            pending.len()
1498        ));
1499        self.publish_status(def);
1500        let r = self.roll(
1501            def,
1502            &spec,
1503            &rev,
1504            &pending,
1505            parallel,
1506            delay,
1507            monitor,
1508            order,
1509            oci,
1510            probe.as_ref(),
1511            &uc,
1512        );
1513        let rollout = self.rollout.take();
1514        if let (Ok(true), Some(ro)) = (&r, rollout) {
1515            self.log(&format!(
1516                "rollout of rev {rev} complete: {}/{} slot(s) in {:.0?}",
1517                ro.done,
1518                ro.total,
1519                rollout_started.elapsed()
1520            ));
1521        }
1522        self.publish_status(def);
1523        r.map(|_| ())
1524    }
1525
1526    /// Replace the pending slots in batches. Ok(true) when every slot made
1527    /// it, Ok(false) when the rollout stopped (paused, rolled back, retrying).
1528    #[expect(clippy::too_many_arguments)]
1529    #[expect(
1530        clippy::excessive_nesting,
1531        reason = "predates the lint ratchet; split it when next changed"
1532    )]
1533    fn roll(
1534        &mut self,
1535        def: &Arc<StackDef>,
1536        spec: &SandboxSpec,
1537        rev: &String,
1538        pending: &[(u32, Option<String>)],
1539        parallel: usize,
1540        delay: Duration,
1541        monitor: Duration,
1542        order: UpdateOrder,
1543        oci: bool,
1544        probe: Option<&HealthProbe>,
1545        uc: &UpdateConfig,
1546    ) -> Result<bool> {
1547        for (n, batch) in pending.chunks(parallel).enumerate() {
1548            if n > 0 && !delay.is_zero() {
1549                std::thread::sleep(delay);
1550            }
1551            if self.superseded(def) {
1552                return Ok(false);
1553            }
1554            for (slot, old) in batch {
1555                let r = self.replace(
1556                    def,
1557                    spec,
1558                    rev,
1559                    *slot,
1560                    old.as_deref(),
1561                    order,
1562                    oci,
1563                    probe,
1564                    monitor,
1565                );
1566                if let Err(e) = r {
1567                    let msg = format!("slot {slot}: {e}");
1568                    self.event("error", None, &msg);
1569                    if old.is_none() {
1570                        // Nothing to protect: keep trying, slower each time.
1571                        let prev = self.create_backoff.map(|(_, w)| w);
1572                        let (wait, m) = super::failure::retry(prev, &spec.image, &msg, &e);
1573                        self.create_backoff = Some((Instant::now(), wait));
1574                        self.state = "failing".into();
1575                        self.message = Some(m);
1576                        self.publish_status(def);
1577                        return Ok(false);
1578                    }
1579                    match uc.failure_action.unwrap_or_default() {
1580                        FailureAction::Continue => continue,
1581                        FailureAction::Pause => {
1582                            self.event("warn", None, &format!("rollout of rev {rev} paused"));
1583                            self.paused = Some((rev.clone(), format!("rollout paused: {msg}")));
1584                            return Ok(false);
1585                        }
1586                        FailureAction::Rollback => {
1587                            self.paused = Some((rev.clone(), format!("rolled back: {msg}")));
1588                            let ctl = Controller {
1589                                inner: self.inner.clone(),
1590                            };
1591                            self.event(
1592                                "warn",
1593                                None,
1594                                &format!("rollout of rev {rev} failed; rolling back"),
1595                            );
1596                            if let Err(e) = ctl.rollback(&self.q) {
1597                                self.event("error", None, &format!("rollback failed: {e}"));
1598                            }
1599                            return Ok(false);
1600                        }
1601                    }
1602                }
1603            }
1604        }
1605        Ok(true)
1606    }
1607
1608    /// Update one slot of the rollout display, and publish it.
1609    fn slot_state(
1610        &mut self,
1611        def: &StackDef,
1612        slot: u32,
1613        old_state: Option<&str>,
1614        new: Option<&str>,
1615        new_state: Option<&str>,
1616    ) {
1617        if let Some(ro) = &mut self.rollout {
1618            if let Some(s) = ro.slots.iter_mut().find(|s| s.slot == slot) {
1619                if let Some(o) = old_state {
1620                    s.old_state = o.into();
1621                }
1622                if let Some(n) = new {
1623                    s.new = Some(n.into());
1624                }
1625                if let Some(n) = new_state {
1626                    s.new_state = n.into();
1627                    if n == "serving" {
1628                        ro.done += 1;
1629                    }
1630                }
1631            }
1632        }
1633        self.publish_status(def);
1634    }
1635
1636    /// Unmet `depends_on`, as a message.
1637    fn waiting_for(&self, spec: &SandboxSpec) -> Option<String> {
1638        let st = self.inner.status.lock().unwrap();
1639        for (dep, d) in &spec.depends_on {
1640            let s = st.get(&(self.q.clone(), dep.clone()));
1641            let ok = match d.condition {
1642                DependCondition::ServiceStarted => s.is_some_and(|s| s.running > 0),
1643                DependCondition::ServiceHealthy => s.is_some_and(|s| s.healthy > 0),
1644            };
1645            if !ok {
1646                return Some(format!("waiting for {dep} ({:?})", d.condition));
1647            }
1648        }
1649        None
1650    }
1651
1652    fn handle(&self, name: &str) -> Sandbox {
1653        let (_, d) = self.template.as_ref().expect("resolved in pass");
1654        Sandbox::like(self.client(), name, d)
1655    }
1656
1657    /// Keep one instance running, set up after every boot, health-checked,
1658    /// and in or out of rotation.
1659    #[expect(
1660        clippy::too_many_lines,
1661        reason = "predates the lint ratchet; split it when next changed"
1662    )]
1663    fn maintain(
1664        &mut self,
1665        def: &StackDef,
1666        i: &Inst,
1667        spec: &SandboxSpec,
1668        oci: bool,
1669        probe: Option<&HealthProbe>,
1670    ) -> Result<()> {
1671        let policy = spec.deploy.as_ref().and_then(|d| d.restart_policy.clone());
1672        let condition = policy
1673            .as_ref()
1674            .and_then(|p| p.condition)
1675            .unwrap_or_default();
1676        let sb = self.handle(&i.name);
1677        if !i.running() {
1678            self.set_rotation(&i.name, false);
1679            if condition == RestartCondition::None {
1680                return Ok(());
1681            }
1682            if self.restart_budget_spent(&i.name, policy.as_ref()) {
1683                self.message = Some(format!("{}: restart limit reached", i.name));
1684                return Ok(());
1685            }
1686            self.event(
1687                "warn",
1688                Some(&i.name),
1689                &format!("{} is {}; starting it", i.name, i.status),
1690            );
1691            self.count_restart(&i.name);
1692            if let Err(e) = sb.start() {
1693                self.log(&format!("cannot start {}: {e}", i.name));
1694                return Ok(());
1695            }
1696        }
1697        let (pid, ip) = match instance_state(self.client(), &i.name) {
1698            Ok(s) => s,
1699            Err(e) if e.is_not_found() => return Ok(()),
1700            Err(e) => return Err(e),
1701        };
1702        let rt = self.rt.entry(i.name.clone()).or_default();
1703        rt.ip = ip;
1704        if rt.pid != pid {
1705            // A (re)boot: /run/secrets is a fresh tmpfs, and the unit may be
1706            // from an older isb. Probing starts over.
1707            let restarted = rt.pid != 0;
1708            rt.pid = pid;
1709            rt.started(Instant::now());
1710            rt.next_probe = None;
1711            let r = self.setup(def, &sb, spec, oci);
1712            if let Err(e) = r {
1713                // Leave pid unset so the next pass tries again.
1714                if let Some(rt) = self.rt.get_mut(&i.name) {
1715                    rt.pid = 0;
1716                }
1717                self.set_rotation(&i.name, false);
1718                return Err(Error::OperationFailed {
1719                    step: format!("set up {}", i.name),
1720                    message: e.to_string(),
1721                });
1722            }
1723            // Seen restarting: its app now runs what setup delivered.
1724            if restarted {
1725                self.mark_started(def, &i.name)?;
1726            }
1727        }
1728        let alive = self.alive(&sb, spec, oci);
1729        let healthy = match probe {
1730            None => alive,
1731            Some(p) => {
1732                let rt = self.rt.get_mut(&i.name).unwrap();
1733                if rt.since.is_none() {
1734                    rt.since = Some(Instant::now());
1735                }
1736                if rt.next_probe.is_none_or(|t| Instant::now() >= t) {
1737                    let r = supervise::probe(&sb, p);
1738                    let rt = self.rt.get_mut(&i.name).unwrap();
1739                    rt.last_probe = r.output.clone();
1740                    rt.record_probe(r.ok, p, Instant::now());
1741                    let wait = if rt.healthy.is_none() {
1742                        p.start_interval
1743                    } else {
1744                        p.interval
1745                    };
1746                    rt.next_probe = Some(Instant::now() + wait);
1747                }
1748                self.rt[&i.name].healthy == Some(true) && alive
1749            }
1750        };
1751        self.set_rotation(&i.name, healthy);
1752        let unhealthy = self.rt[&i.name].healthy == Some(false);
1753        if unhealthy && condition != RestartCondition::None {
1754            if self.restart_budget_spent(&i.name, policy.as_ref()) {
1755                self.message = Some(format!("{}: unhealthy, restart limit reached", i.name));
1756                return Ok(());
1757            }
1758            let n = self.rt[&i.name].unhealthy_restarts;
1759            if n >= RESTARTS_BEFORE_REPLACE {
1760                self.log(&format!(
1761                    "{} stayed unhealthy through {n} restarts; replacing it",
1762                    i.name
1763                ));
1764                let rt = self.rt.get_mut(&i.name).unwrap();
1765                rt.unhealthy_restarts = 0;
1766                drop(sb);
1767                self.retire(&i.name)?;
1768                return Ok(());
1769            }
1770            self.event(
1771                "warn",
1772                Some(&i.name),
1773                &format!(
1774                    "{} is unhealthy ({}); restarting its app",
1775                    i.name,
1776                    self.rt[&i.name]
1777                        .last_probe
1778                        .lines()
1779                        .last()
1780                        .unwrap_or("probe failed")
1781                ),
1782            );
1783            self.count_restart(&i.name);
1784            let rt = self.rt.get_mut(&i.name).unwrap();
1785            rt.unhealthy_restarts += 1;
1786            rt.started(Instant::now());
1787            supervise::restart_app(&sb, &self.service, oci)?;
1788            if !oci {
1789                // The unit restarts within the same instance; it reads the
1790                // files and variables delivered last.
1791                self.mark_started(def, &i.name)?;
1792            }
1793        }
1794        Ok(())
1795    }
1796
1797    /// Secrets and the app's unit, after a boot or on creation.
1798    fn setup(&self, def: &StackDef, sb: &Sandbox, spec: &SandboxSpec, oci: bool) -> Result<()> {
1799        // Read from the store now, never from the definition.
1800        let keys = spec.secret_keys();
1801        let values = if keys.is_empty() {
1802            BTreeMap::new()
1803        } else {
1804            super::secrets::values(&self.inner.secrets, &def.org, &def.secrets, keys)?
1805        };
1806        // A new value for a secret the service takes with `on_change: none`
1807        // is delivered without restarting the app.
1808        let none = |k: &str| def.on_change(&self.service, k) == OnChange::None;
1809        // An OCI app started before its files arrived: restart it once so
1810        // it reads them (the next pass finds them in place).
1811        let pushed = supervise::push_secrets_detailed(sb, spec, &values)?;
1812        if oci && (pushed.missing || pushed.changed.iter().any(|k| !none(k))) {
1813            supervise::restart_app(sb, &self.service, oci)?;
1814        }
1815        if spec.command.is_some() && !oci {
1816            let mut s = spec.clone();
1817            s.restart = Some(RestartMode::Always);
1818            let env = supervise::secret_env(spec, &values)?;
1819            // Only a change all of whose variables are `none` secrets is
1820            // left for the next start.
1821            let env_restarts =
1822                spec.env.secrets.is_empty() || spec.env.secrets.values().any(|k| !none(k));
1823            supervise::install_with(
1824                sb,
1825                &self.service,
1826                &s,
1827                spec.has_secret_files(),
1828                &env,
1829                env_restarts,
1830            )?;
1831        }
1832        Ok(())
1833    }
1834
1835    /// An OCI instance's secret variables, for its config (`environment.KEY`).
1836    fn oci_secret_env(
1837        &self,
1838        def: &StackDef,
1839        spec: &SandboxSpec,
1840    ) -> Result<BTreeMap<String, String>> {
1841        if spec.env.secrets.is_empty() {
1842            return Ok(BTreeMap::new());
1843        }
1844        let values = super::secrets::values(
1845            &self.inner.secrets,
1846            &def.org,
1847            &def.secrets,
1848            spec.env.secrets.values().map(String::as_str),
1849        )?;
1850        supervise::secret_env(spec, &values)
1851    }
1852
1853    /// The app's process is up: its unit is active, or (OCI, or no command)
1854    /// the instance runs.
1855    fn alive(&self, sb: &Sandbox, spec: &SandboxSpec, oci: bool) -> bool {
1856        if spec.command.is_some() && !oci {
1857            return supervise::unit_state(sb, &self.service).is_ok_and(|s| s == "active");
1858        }
1859        sb.info()
1860            .is_ok_and(|i| i.status.eq_ignore_ascii_case("running"))
1861    }
1862
1863    fn count_restart(&mut self, name: &str) {
1864        self.rt
1865            .entry(name.to_string())
1866            .or_default()
1867            .restarts
1868            .push_back(Instant::now());
1869    }
1870
1871    fn restart_budget_spent(
1872        &mut self,
1873        name: &str,
1874        policy: Option<&crate::spec::RestartPolicy>,
1875    ) -> bool {
1876        let Some(p) = policy else { return false };
1877        let Some(max) = p.max_attempts else {
1878            return false;
1879        };
1880        let window = p
1881            .window
1882            .as_deref()
1883            .and_then(|w| crate::flex::parse_duration(w).ok());
1884        let rt = self.rt.entry(name.to_string()).or_default();
1885        if let Some(w) = window {
1886            while rt.restarts.front().is_some_and(|t| t.elapsed() > w) {
1887                rt.restarts.pop_front();
1888            }
1889        }
1890        rt.restarts.len() as u32 >= max
1891    }
1892
1893    /// Replace (or fill) one slot with an instance of the current revision.
1894    #[expect(clippy::too_many_arguments)]
1895    fn replace(
1896        &mut self,
1897        def: &StackDef,
1898        spec: &SandboxSpec,
1899        rev: &str,
1900        slot: u32,
1901        old: Option<&str>,
1902        order: UpdateOrder,
1903        oci: bool,
1904        probe: Option<&HealthProbe>,
1905        monitor: Duration,
1906    ) -> Result<()> {
1907        // Before anything is stopped: a secret that cannot be read leaves
1908        // the old instance serving.
1909        let secret_env = if oci {
1910            self.oci_secret_env(def, spec)?
1911        } else {
1912            BTreeMap::new()
1913        };
1914        // An OCI app reads its files as it starts: write them into the new
1915        // instance before its first start, rather than restarting it after.
1916        let before_start = if oci && spec.has_secret_files() {
1917            let values = super::secrets::values(
1918                &self.inner.secrets,
1919                &def.org,
1920                &def.secrets,
1921                spec.secret_keys(),
1922            )?;
1923            let spec = spec.clone();
1924            Some(crate::plan::BeforeStart(Arc::new(move |c, n| {
1925                supervise::push_secret_files(c, n, &spec, &values).map(|_| ())
1926            })))
1927        } else {
1928            None
1929        };
1930        if let (Some(o), UpdateOrder::StopFirst) = (old, order) {
1931            self.log(&format!("slot {slot}: replacing {o} (stop-first)"));
1932            self.slot_state(def, slot, Some("draining"), None, None);
1933            self.retire(o)?;
1934            self.slot_state(def, slot, Some("retired"), None, None);
1935        }
1936        let name = instance_name(&self.stack, &self.service, slot, &new_id())?;
1937        self.log(&format!("slot {slot}: creating {name} (rev {rev})"));
1938        self.slot_state(def, slot, None, Some(&name), Some("creating"));
1939        let mut s = instance_spec(def, &self.service, spec, slot, rev)?;
1940        s.name = Some(name.clone());
1941        // `env.secrets` stays set, so the values are redacted in reports.
1942        s.env.vars.extend(secret_env);
1943        let mut d = crate::sandbox::resolve(self.client(), &s, &def.file.volumes, &def.base_dir)?;
1944        d.before_start = before_start;
1945        let stack = self.q.clone();
1946        let mut report = |m: &str| eprintln!("isb serve: {stack}: {m}");
1947        let created =
1948            crate::sandbox::ensure(self.client(), &d, EnsureOptions::default(), &mut report);
1949        let result = created.and_then(|_| {
1950            let inst = Inst {
1951                name: name.clone(),
1952                slot,
1953                rev: rev.to_string(),
1954                status: "Running".into(),
1955                secrets: Some(live_versions(def, &self.service)),
1956            };
1957            self.insts.push(inst.clone());
1958            self.slot_state(def, slot, None, None, Some("probing"));
1959            self.wait_serving(def, &inst, spec, oci, probe, monitor)
1960        });
1961        if let Err(e) = result {
1962            // Read its output before it is deleted: it explains the failure.
1963            let (e, attempt) =
1964                super::failure::explain(self.client(), &name, &self.service, oci, e, now_ms());
1965            self.inner.failures.record(&self.q, &self.service, attempt);
1966            self.event(
1967                "error",
1968                Some(&name),
1969                &format!("{name} did not come up: {e}"),
1970            );
1971            self.slot_state(def, slot, None, None, Some("failed"));
1972            let _ = self.retire(&name);
1973            return Err(e);
1974        }
1975        if let (Some(o), UpdateOrder::StartFirst) = (old, order) {
1976            self.log(&format!("slot {slot}: {name} is serving; retiring {o}"));
1977            self.slot_state(def, slot, Some("draining"), None, None);
1978            self.retire(o)?;
1979            self.slot_state(def, slot, Some("retired"), None, None);
1980        }
1981        self.slot_state(def, slot, None, None, Some("serving"));
1982        Ok(())
1983    }
1984
1985    /// Wait for a new instance to pass its health (or, without a
1986    /// healthcheck, for its app to run), put it in rotation, then watch it
1987    /// for `monitor`.
1988    fn wait_serving(
1989        &mut self,
1990        def: &StackDef,
1991        i: &Inst,
1992        spec: &SandboxSpec,
1993        oci: bool,
1994        probe: Option<&HealthProbe>,
1995        monitor: Duration,
1996    ) -> Result<()> {
1997        // Through the startup grace (a starting replica is not failed), then
1998        // `retries` counted failures, then a margin.
1999        let deadline = match probe {
2000            Some(p) => {
2001                p.startup_grace.max(p.start_period)
2002                    + p.interval * p.retries
2003                    + Duration::from_secs(30)
2004            }
2005            None => Duration::from_secs(60),
2006        }
2007        .max(Duration::from_secs(60));
2008        let started = Instant::now();
2009        loop {
2010            self.maintain(def, i, spec, oci, probe)?;
2011            if self.rt.get(&i.name).is_some_and(|r| r.in_rotation) {
2012                break;
2013            }
2014            if self
2015                .rt
2016                .get(&i.name)
2017                .is_some_and(|r| r.healthy == Some(false))
2018            {
2019                return Err(Error::invalid(format!(
2020                    "unhealthy: {}",
2021                    self.rt[&i.name].last_probe
2022                )));
2023            }
2024            if started.elapsed() > deadline {
2025                let why = self
2026                    .rt
2027                    .get(&i.name)
2028                    .map(|r| r.last_probe.clone())
2029                    .filter(|s| !s.is_empty())
2030                    .unwrap_or_else(|| "its app is not running".into());
2031                return Err(Error::invalid(format!(
2032                    "not serving after {:?}: {why}",
2033                    started.elapsed()
2034                )));
2035            }
2036            // Probe on the start interval rather than waiting for the next one.
2037            if let Some(rt) = self.rt.get_mut(&i.name) {
2038                rt.next_probe = None;
2039            }
2040            std::thread::sleep(
2041                probe
2042                    .map(|p| p.start_interval)
2043                    .unwrap_or(Duration::from_secs(1))
2044                    .min(Duration::from_secs(2)),
2045            );
2046        }
2047        self.sync_routes();
2048        self.slot_state(def, i.slot, None, None, Some("monitoring"));
2049        let watch = Instant::now();
2050        while watch.elapsed() < monitor {
2051            std::thread::sleep(Duration::from_secs(1).min(monitor));
2052            if let Some(rt) = self.rt.get_mut(&i.name) {
2053                rt.next_probe = None;
2054            }
2055            self.maintain(def, i, spec, oci, probe)?;
2056            if !self.rt.get(&i.name).is_some_and(|r| r.in_rotation) {
2057                return Err(Error::invalid(format!(
2058                    "failed within the {monitor:?} monitor period"
2059                )));
2060            }
2061        }
2062        Ok(())
2063    }
2064
2065    /// Take an instance out of rotation, let its connections drain, then
2066    /// delete it.
2067    fn retire(&mut self, name: &str) -> Result<()> {
2068        self.drain(name);
2069        if let Ok(sb) = Sandbox::get(self.client(), name) {
2070            let _ = sb.stop(false, Duration::from_secs(10));
2071        }
2072        self.rt.remove(name);
2073        self.insts.retain(|i| i.name != name);
2074        match Sandbox::remove(self.client(), name, true) {
2075            Err(e) if !e.is_not_found() => Err(e),
2076            _ => Ok(()),
2077        }
2078    }
2079
2080    /// Take an instance out of rotation and let its connections drain (up
2081    /// to [`DRAIN`]).
2082    fn drain(&mut self, name: &str) {
2083        let ip = self.rt.get(name).and_then(|r| r.ip);
2084        self.set_rotation(name, false);
2085        self.sync_routes();
2086        if let Some(ip) = ip {
2087            let started = Instant::now();
2088            if let Some(o) = &self.inner.observer {
2089                o.drain(&self.q, &self.service, ip, DRAIN);
2090            }
2091            let left = DRAIN.saturating_sub(started.elapsed());
2092            for (k, p) in &self.routes {
2093                self.inner
2094                    .balancer
2095                    .wait_drained(k, SocketAddr::new(ip, p.target), left);
2096            }
2097        }
2098    }
2099
2100    fn set_rotation(&mut self, name: &str, on: bool) {
2101        let rt = self.rt.entry(name.to_string()).or_default();
2102        if rt.in_rotation != on {
2103            rt.in_rotation = on;
2104            self.sync_routes();
2105        }
2106    }
2107
2108    /// Bring the balancer's routes in line with the spec's published ports.
2109    fn set_routes(&mut self, spec: &SandboxSpec) {
2110        let want: BTreeMap<String, Published> = match published(spec) {
2111            Ok(ps) => ps
2112                .into_iter()
2113                .map(|p| (format!("{}/{}/{}", self.q, self.service, p.display()), p))
2114                .collect(),
2115            Err(e) => {
2116                self.message = Some(e.to_string());
2117                BTreeMap::new()
2118            }
2119        };
2120        let stale: Vec<String> = self
2121            .routes
2122            .keys()
2123            .filter(|k| !want.contains_key(*k))
2124            .cloned()
2125            .collect();
2126        for k in stale {
2127            self.inner.balancer.remove_route(&k);
2128            self.routes.remove(&k);
2129            self.route_errors.remove(&k);
2130        }
2131        for (k, p) in want {
2132            self.routes.entry(k).or_insert(p);
2133        }
2134        self.sync_routes();
2135    }
2136
2137    fn sync_routes(&mut self) {
2138        let mut errors = BTreeMap::new();
2139        // UDP ports are proxy devices on the replica (see super::ports).
2140        for (k, p) in self.routes.iter().filter(|(_, p)| !p.udp) {
2141            let backends: Vec<SocketAddr> = self
2142                .rt
2143                .values()
2144                .filter(|r| r.in_rotation)
2145                .filter_map(|r| r.ip)
2146                .map(|ip| SocketAddr::new(ip, p.target))
2147                .collect();
2148            if let Err(e) = self.inner.balancer.set_route(k, p.listen, backends) {
2149                errors.insert(k.clone(), e.to_string());
2150            }
2151        }
2152        for (k, e) in &errors {
2153            if self.route_errors.get(k) != Some(e) {
2154                self.log(&format!("cannot publish {k}: {e}"));
2155            }
2156        }
2157        self.route_errors = errors;
2158        self.sync_observer();
2159        self.sync_dns();
2160    }
2161
2162    /// Tell the observer (the ingress) when the in-rotation set changed.
2163    fn sync_observer(&mut self) {
2164        let Some(o) = self.inner.observer.clone() else {
2165            return;
2166        };
2167        let mut ips: Vec<IpAddr> = self
2168            .rt
2169            .values()
2170            .filter(|r| r.in_rotation)
2171            .filter_map(|r| r.ip)
2172            .collect();
2173        ips.sort();
2174        if self.observed.as_ref() != Some(&ips) {
2175            o.rotation(&self.q, &self.service, &ips);
2176            self.observed = Some(ips);
2177        }
2178    }
2179
2180    #[expect(
2181        clippy::too_many_lines,
2182        reason = "predates the lint ratchet; split it when next changed"
2183    )]
2184    fn publish_status(&mut self, def: &StackDef) {
2185        // An address can change without a rotation change (a restart).
2186        self.sync_observer();
2187        self.sync_dns();
2188        let Ok(spec) = def.service(&self.service) else {
2189            return;
2190        };
2191        let rev = def.revision(&self.service).unwrap_or_default();
2192        let probe = matches!(spec.health_probe(), Ok(Some(_)));
2193        let live = live_versions(def, &self.service);
2194        let snap = self.inner.snapshot.lock().unwrap().instances.clone();
2195        let instances: Vec<InstanceStatus> = self
2196            .insts
2197            .iter()
2198            .map(|i| {
2199                let rt = self.rt.get(&i.name);
2200                let m = snap.get(&format!("{}/{}", self.oclient.project_name(), i.name));
2201                let health = match (probe, rt.and_then(|r| r.healthy)) {
2202                    (false, _) => "none",
2203                    (true, Some(true)) => "healthy",
2204                    (true, Some(false)) => "unhealthy",
2205                    (true, None) => "starting",
2206                };
2207                InstanceStatus {
2208                    name: i.name.clone(),
2209                    slot: i.slot,
2210                    rev: i.rev.clone(),
2211                    status: m
2212                        .map(|m| m.status.clone())
2213                        .unwrap_or_else(|| i.status.clone()),
2214                    health: health.into(),
2215                    ip: rt.and_then(|r| r.ip).map(|ip| ip.to_string()),
2216                    in_rotation: rt.is_some_and(|r| r.in_rotation),
2217                    restarts: rt.map(|r| r.restarts.len() as u32).unwrap_or(0),
2218                    last_probe: rt.map(|r| r.last_probe.clone()).unwrap_or_default(),
2219                    cpu_pct: m.and_then(|m| m.cpu_pct),
2220                    cpu_history: m.map(|m| m.cpu_history.clone()).unwrap_or_default(),
2221                    mem_bytes: m.and_then(|m| m.mem_bytes),
2222                    disk_bytes: m.and_then(|m| m.disk_bytes),
2223                    stale_secrets: i
2224                        .secrets
2225                        .as_ref()
2226                        .map(|have| super::secrets::stale(have, &live))
2227                        .unwrap_or_default(),
2228                }
2229            })
2230            .collect();
2231        let mut instances = instances;
2232        instances.sort_by(|a, b| (a.slot, &a.name).cmp(&(b.slot, &b.name)));
2233        let routes = self.inner.balancer.routes();
2234        let now = Instant::now();
2235        let mut ports = Vec::new();
2236        for (k, p) in &self.routes {
2237            let r = routes.iter().find(|r| r.key == *k);
2238            let accepted = r.map(|r| r.accepted).unwrap_or(0);
2239            let e = self
2240                .rates
2241                .entry(k.clone())
2242                .or_insert_with(|| (accepted, now, VecDeque::new()));
2243            let dt = now.duration_since(e.1).as_secs_f32();
2244            // Only sample on a reconcile-sized step, so a burst of status
2245            // updates during a rollout does not flatten the curve.
2246            if dt >= 1.0 {
2247                let rate = accepted.saturating_sub(e.0) as f32 / dt;
2248                if e.2.len() == crate::metrics::HISTORY {
2249                    e.2.pop_front();
2250                }
2251                e.2.push_back(rate);
2252                e.0 = accepted;
2253                e.1 = now;
2254            }
2255            ports.push(PortStatus {
2256                listen: p.display(),
2257                target: p.target,
2258                backends: match r {
2259                    _ if p.udp => {
2260                        let ips = self.rt.values().filter_map(|r| r.ip);
2261                        ips.map(|ip| SocketAddr::new(ip, p.target).to_string())
2262                            .collect()
2263                    }
2264                    Some(r) => r.backends.iter().map(|b| b.addr.to_string()).collect(),
2265                    None => Vec::new(),
2266                },
2267                error: self.route_errors.get(k).cloned(),
2268                accepted,
2269                active: r
2270                    .map(|r| {
2271                        r.backends
2272                            .iter()
2273                            .chain(r.draining.iter())
2274                            .map(|b| b.active)
2275                            .sum()
2276                    })
2277                    .unwrap_or(0),
2278                rate_history: e.2.iter().copied().collect(),
2279            });
2280        }
2281        self.rates.retain(|k, _| self.routes.contains_key(k));
2282        let running = instances
2283            .iter()
2284            .filter(|i| i.status.eq_ignore_ascii_case("running"))
2285            .count() as u32;
2286        let healthy = instances.iter().filter(|i| i.in_rotation).count() as u32;
2287        self.watch_health(healthy, spec.replicas());
2288        let st = ServiceStatus {
2289            service: self.service.clone(),
2290            image: spec.image.clone(),
2291            rev,
2292            replicas: spec.replicas(),
2293            running,
2294            healthy,
2295            state: self.state.clone(),
2296            message: self.message.clone(),
2297            instances,
2298            ports,
2299            rollout: self.rollout.clone(),
2300            checked_at: now_secs(),
2301            domains: Vec::new(),
2302            last_failed_attempt: None,
2303        };
2304        self.inner.status.lock().unwrap().insert(self.key(), st);
2305    }
2306}
2307
2308/// Names of the services that are not converged, for a deploy waiting on
2309/// its rollout.
2310pub fn unsettled(st: &StackStatus) -> BTreeSet<String> {
2311    st.services
2312        .iter()
2313        .filter(|s| s.state != "converged")
2314        .map(|s| s.service.clone())
2315        .collect()
2316}
2317
2318#[path = "rotation.rs"]
2319mod rotation;
2320#[path = "scale_down.rs"]
2321mod scale_down;
2322
2323#[cfg(test)]
2324#[path = "controller_tests.rs"]
2325mod tests;