Skip to main content

mz_orchestrator_kubernetes/
lib.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::collections::BTreeMap;
11use std::future::Future;
12use std::num::NonZero;
13use std::sync::{Arc, Mutex};
14use std::time::{Duration, Instant};
15use std::{env, fmt};
16
17use anyhow::{Context, anyhow, bail};
18use async_trait::async_trait;
19use chrono::DateTime;
20use clap::ValueEnum;
21use cloud_resource_controller::KubernetesResourceReader;
22use futures::TryFutureExt;
23use futures::stream::{BoxStream, StreamExt};
24use k8s_openapi::DeepMerge;
25use k8s_openapi::api::apps::v1::{StatefulSet, StatefulSetSpec, StatefulSetUpdateStrategy};
26use k8s_openapi::api::core::v1::{
27    Affinity, Capabilities, Container, ContainerPort, EnvVar, EnvVarSource, EphemeralVolumeSource,
28    NodeAffinity, NodeSelector, NodeSelectorRequirement, NodeSelectorTerm, ObjectFieldSelector,
29    ObjectReference, PersistentVolumeClaim, PersistentVolumeClaimSpec,
30    PersistentVolumeClaimTemplate, Pod, PodAffinity, PodAffinityTerm, PodAntiAffinity,
31    PodSecurityContext, PodSpec, PodTemplateSpec, PreferredSchedulingTerm, ResourceRequirements,
32    SeccompProfile, Secret, SecurityContext, Service as K8sService, ServicePort, ServiceSpec,
33    Sysctl, Toleration, TopologySpreadConstraint, Volume, VolumeMount, VolumeResourceRequirements,
34    WeightedPodAffinityTerm,
35};
36use k8s_openapi::apimachinery::pkg::api::resource::Quantity;
37use k8s_openapi::apimachinery::pkg::apis::meta::v1::{
38    LabelSelector, LabelSelectorRequirement, OwnerReference,
39};
40use k8s_openapi::jiff::Timestamp;
41use kube::ResourceExt;
42use kube::api::{Api, DeleteParams, ObjectMeta, PartialObjectMetaExt, Patch, PatchParams};
43use kube::client::Client;
44use kube::error::Error as K8sError;
45use kube::runtime::{WatchStreamExt, watcher};
46use maplit::btreemap;
47use mz_cloud_resources::AwsExternalIdPrefix;
48use mz_cloud_resources::crd::vpc_endpoint::v1::VpcEndpoint;
49use mz_orchestrator::{
50    DiskLimit, LabelSelectionLogic, LabelSelector as MzLabelSelector, NamespacedOrchestrator,
51    OfflineReason, Orchestrator, Service, ServiceAssignments, ServiceConfig, ServiceEvent,
52    ServiceProcessMetrics, ServiceStatus, recommended_k8s_labels, scheduling_config::*,
53};
54use mz_ore::cast::CastInto;
55use mz_ore::error::ErrorExt;
56use mz_ore::metrics::MetricsRegistry;
57use mz_ore::retry::Retry;
58use mz_ore::task::AbortOnDropHandle;
59use serde::Deserialize;
60use sha2::{Digest, Sha256};
61use tokio::sync::{mpsc, oneshot};
62use tracing::{error, info, warn};
63
64use crate::metrics::{FetchStep, OrchestratorMetrics};
65
66pub mod cloud_resource_controller;
67mod metrics;
68pub mod secrets;
69pub mod util;
70
71const FIELD_MANAGER: &str = "environmentd";
72const NODE_FAILURE_THRESHOLD_SECONDS: i64 = 30;
73/// How many attempts of a failed worker command log at warn level before later attempts log at
74/// error level. With the retry backoff starting at 125ms, the first error-level attempt comes
75/// about 4s after the first failure, so a Kubernetes API error that clears on retry, such as a
76/// new service account's RBAC that has not yet propagated, does not reach Sentry.
77const RETRY_WARN_ATTEMPTS: usize = 5;
78
79const POD_TEMPLATE_HASH_ANNOTATION: &str = "environmentd.materialize.cloud/pod-template-hash";
80
81/// Configures a [`KubernetesOrchestrator`].
82#[derive(Debug, Clone)]
83pub struct KubernetesOrchestratorConfig {
84    /// The name of a Kubernetes context to use, if the Kubernetes configuration
85    /// is loaded from the local kubeconfig.
86    pub context: String,
87    /// The name of a non-default Kubernetes scheduler to use, if any.
88    pub scheduler_name: Option<String>,
89    /// The name of a `PriorityClass` to assign to services, if any.
90    pub priority_class_name: Option<String>,
91    /// Annotations to install on every service created by the orchestrator.
92    pub service_annotations: BTreeMap<String, String>,
93    /// Labels to install on every service created by the orchestrator.
94    pub service_labels: BTreeMap<String, String>,
95    /// Node selector to install on every service created by the orchestrator.
96    pub service_node_selector: BTreeMap<String, String>,
97    /// Affinity to install on every service created by the orchestrator.
98    pub service_affinity: Option<String>,
99    /// Tolerations to install on every service created by the orchestrator.
100    pub service_tolerations: Option<String>,
101    /// The service account that each service should run as, if any.
102    pub service_account: Option<String>,
103    /// The image pull policy to set for services created by the orchestrator.
104    pub image_pull_policy: KubernetesImagePullPolicy,
105    /// An AWS external ID prefix to use when making AWS operations on behalf
106    /// of the environment.
107    pub aws_external_id_prefix: Option<AwsExternalIdPrefix>,
108    /// Whether to use code coverage mode or not. Always false for production.
109    pub coverage: bool,
110    /// The Kubernetes StorageClass to use for the ephemeral volume attached to
111    /// services that request disk.
112    ///
113    /// If unspecified, the orchestrator will refuse to create services that
114    /// request disk.
115    pub ephemeral_volume_storage_class: Option<String>,
116    /// The optional fs group for service's pods' `securityContext`.
117    pub service_fs_group: Option<i64>,
118    /// The prefix to prepend to all object names
119    pub name_prefix: Option<String>,
120    /// Whether we should attempt to collect metrics from kubernetes
121    pub collect_pod_metrics: bool,
122    /// Whether to annotate pods for prometheus service discovery.
123    pub enable_prometheus_scrape_annotations: bool,
124    /// Whether to run service pods in a Kubernetes user namespace by setting
125    /// `hostUsers: false`.
126    pub enable_user_namespaces: bool,
127}
128
129impl KubernetesOrchestratorConfig {
130    pub fn name_prefix(&self) -> String {
131        self.name_prefix.clone().unwrap_or_default()
132    }
133}
134
135/// Specifies whether Kubernetes should pull Docker images when creating pods.
136#[derive(ValueEnum, Debug, Clone, Copy)]
137pub enum KubernetesImagePullPolicy {
138    /// Always pull the Docker image from the registry.
139    Always,
140    /// Pull the Docker image only if the image is not present.
141    IfNotPresent,
142    /// Never pull the Docker image.
143    Never,
144}
145
146impl fmt::Display for KubernetesImagePullPolicy {
147    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
148        match self {
149            KubernetesImagePullPolicy::Always => f.write_str("Always"),
150            KubernetesImagePullPolicy::IfNotPresent => f.write_str("IfNotPresent"),
151            KubernetesImagePullPolicy::Never => f.write_str("Never"),
152        }
153    }
154}
155
156impl KubernetesImagePullPolicy {
157    pub fn as_kebab_case_str(&self) -> &'static str {
158        match self {
159            Self::Always => "always",
160            Self::IfNotPresent => "if-not-present",
161            Self::Never => "never",
162        }
163    }
164}
165
166/// An orchestrator backed by Kubernetes.
167pub struct KubernetesOrchestrator {
168    client: Client,
169    kubernetes_namespace: String,
170    config: KubernetesOrchestratorConfig,
171    secret_api: Api<Secret>,
172    vpc_endpoint_api: Api<VpcEndpoint>,
173    namespaces: Mutex<BTreeMap<String, Arc<dyn NamespacedOrchestrator>>>,
174    resource_reader: Arc<KubernetesResourceReader>,
175    metrics: OrchestratorMetrics,
176}
177
178impl fmt::Debug for KubernetesOrchestrator {
179    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
180        f.debug_struct("KubernetesOrchestrator").finish()
181    }
182}
183
184impl KubernetesOrchestrator {
185    /// Creates a new Kubernetes orchestrator from the provided configuration.
186    pub async fn new(
187        config: KubernetesOrchestratorConfig,
188        metrics_registry: &MetricsRegistry,
189    ) -> Result<KubernetesOrchestrator, anyhow::Error> {
190        let (client, kubernetes_namespace) = util::create_client(config.context.clone()).await?;
191        let resource_reader =
192            Arc::new(KubernetesResourceReader::new(config.context.clone()).await?);
193        Ok(KubernetesOrchestrator {
194            client: client.clone(),
195            kubernetes_namespace,
196            config,
197            secret_api: Api::default_namespaced(client.clone()),
198            vpc_endpoint_api: Api::default_namespaced(client),
199            namespaces: Mutex::new(BTreeMap::new()),
200            resource_reader,
201            metrics: OrchestratorMetrics::register_into(metrics_registry),
202        })
203    }
204}
205
206impl Orchestrator for KubernetesOrchestrator {
207    fn namespace(&self, namespace: &str) -> Arc<dyn NamespacedOrchestrator> {
208        let mut namespaces = self.namespaces.lock().expect("lock poisoned");
209        Arc::clone(namespaces.entry(namespace.into()).or_insert_with(|| {
210            let (command_tx, command_rx) = mpsc::unbounded_channel();
211            let worker = OrchestratorWorker {
212                metrics_api: Api::default_namespaced(self.client.clone()),
213                service_api: Api::default_namespaced(self.client.clone()),
214                stateful_set_api: Api::default_namespaced(self.client.clone()),
215                pod_api: Api::default_namespaced(self.client.clone()),
216                owner_references: vec![],
217                command_rx,
218                name_prefix: self.config.name_prefix.clone().unwrap_or_default(),
219                collect_pod_metrics: self.config.collect_pod_metrics,
220                metrics: self.metrics.clone(),
221            }
222            .spawn(format!("kubernetes-orchestrator-worker:{namespace}"));
223
224            Arc::new(NamespacedKubernetesOrchestrator {
225                pod_api: Api::default_namespaced(self.client.clone()),
226                kubernetes_namespace: self.kubernetes_namespace.clone(),
227                namespace: namespace.into(),
228                config: self.config.clone(),
229                // TODO(guswynn): make this configurable.
230                scheduling_config: Default::default(),
231                service_infos: std::sync::Mutex::new(BTreeMap::new()),
232                command_tx,
233                _worker: worker,
234            })
235        }))
236    }
237}
238
239#[derive(Clone, Copy)]
240struct ServiceInfo {
241    scale: NonZero<u16>,
242}
243
244struct NamespacedKubernetesOrchestrator {
245    pod_api: Api<Pod>,
246    kubernetes_namespace: String,
247    namespace: String,
248    config: KubernetesOrchestratorConfig,
249    scheduling_config: std::sync::RwLock<ServiceSchedulingConfig>,
250    service_infos: std::sync::Mutex<BTreeMap<String, ServiceInfo>>,
251    command_tx: mpsc::UnboundedSender<WorkerCommand>,
252    _worker: AbortOnDropHandle<()>,
253}
254
255impl fmt::Debug for NamespacedKubernetesOrchestrator {
256    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
257        f.debug_struct("NamespacedKubernetesOrchestrator")
258            .field("kubernetes_namespace", &self.kubernetes_namespace)
259            .field("namespace", &self.namespace)
260            .field("config", &self.config)
261            .finish()
262    }
263}
264
265/// Commands sent from a [`NamespacedKubernetesOrchestrator`] to its
266/// [`OrchestratorWorker`].
267///
268/// Commands for which the caller expects a result include a `result_tx` on which the
269/// [`OrchestratorWorker`] will deliver the result.
270enum WorkerCommand {
271    EnsureService {
272        desc: ServiceDescription,
273    },
274    DropService {
275        name: String,
276    },
277    ListServices {
278        namespace: String,
279        result_tx: oneshot::Sender<Vec<String>>,
280    },
281    Flush {
282        result_tx: oneshot::Sender<()>,
283    },
284    FetchServiceMetrics {
285        name: String,
286        info: ServiceInfo,
287        result_tx: oneshot::Sender<Vec<ServiceProcessMetrics>>,
288    },
289}
290
291/// A description of a service to be created by an [`OrchestratorWorker`].
292#[derive(Debug, Clone)]
293struct ServiceDescription {
294    name: String,
295    scale: NonZero<u16>,
296    service: K8sService,
297    stateful_set: StatefulSet,
298    pod_template_hash: String,
299}
300
301/// A task executing blocking work for a [`NamespacedKubernetesOrchestrator`] in the background.
302///
303/// This type exists to enable making [`NamespacedKubernetesOrchestrator::ensure_service`] and
304/// [`NamespacedKubernetesOrchestrator::drop_service`] non-blocking, allowing invocation of these
305/// methods in latency-sensitive contexts.
306///
307/// Note that, apart from `ensure_service` and `drop_service`, this worker also handles blocking
308/// orchestrator calls that query service state (such as `list_services`). These need to be
309/// sequenced through the worker loop to ensure they linearize as expected. For example, we want to
310/// ensure that a `list_services` result contains exactly those services that were previously
311/// created with `ensure_service` and not yet dropped with `drop_service`.
312struct OrchestratorWorker {
313    metrics_api: Api<PodMetrics>,
314    service_api: Api<K8sService>,
315    stateful_set_api: Api<StatefulSet>,
316    pod_api: Api<Pod>,
317    owner_references: Vec<OwnerReference>,
318    command_rx: mpsc::UnboundedReceiver<WorkerCommand>,
319    name_prefix: String,
320    collect_pod_metrics: bool,
321    metrics: OrchestratorMetrics,
322}
323
324#[derive(Deserialize, Clone, Debug)]
325pub struct PodMetricsContainer {
326    pub name: String,
327    pub usage: PodMetricsContainerUsage,
328}
329
330#[derive(Deserialize, Clone, Debug)]
331pub struct PodMetricsContainerUsage {
332    pub cpu: Quantity,
333    pub memory: Quantity,
334}
335
336#[derive(Deserialize, Clone, Debug)]
337pub struct PodMetrics {
338    pub metadata: ObjectMeta,
339    pub timestamp: String,
340    pub window: String,
341    pub containers: Vec<PodMetricsContainer>,
342}
343
344impl k8s_openapi::Resource for PodMetrics {
345    const GROUP: &'static str = "metrics.k8s.io";
346    const KIND: &'static str = "PodMetrics";
347    const VERSION: &'static str = "v1beta1";
348    const API_VERSION: &'static str = "metrics.k8s.io/v1beta1";
349    const URL_PATH_SEGMENT: &'static str = "pods";
350
351    type Scope = k8s_openapi::NamespaceResourceScope;
352}
353
354impl k8s_openapi::Metadata for PodMetrics {
355    type Ty = ObjectMeta;
356
357    fn metadata(&self) -> &Self::Ty {
358        &self.metadata
359    }
360
361    fn metadata_mut(&mut self) -> &mut Self::Ty {
362        &mut self.metadata
363    }
364}
365
366// Note that these types are very weird. We are `get`-ing a
367// `List` object, and lying about it having an `ObjectMeta`
368// (it deserializes as empty, but we don't need it). The custom
369// metrics API is designed this way, which is very non-standard.
370// A discussion in the `kube` channel in the `tokio` discord
371// confirmed that this layout + using `get_subresource` is the
372// best way to handle this.
373
374#[derive(Deserialize, Clone, Debug)]
375pub struct MetricIdentifier {
376    #[serde(rename = "metricName")]
377    pub name: String,
378    // We skip `selector` for now, as we don't use it
379}
380
381#[derive(Deserialize, Clone, Debug)]
382pub struct MetricValue {
383    #[serde(rename = "describedObject")]
384    pub described_object: ObjectReference,
385    #[serde(flatten)]
386    pub metric_identifier: MetricIdentifier,
387    pub timestamp: String,
388    pub value: Quantity,
389    // We skip `windowSeconds`, as we don't need it
390}
391
392impl NamespacedKubernetesOrchestrator {
393    fn service_name(&self, id: &str) -> String {
394        format!(
395            "{}{}-{id}",
396            self.config.name_prefix.as_deref().unwrap_or(""),
397            self.namespace
398        )
399    }
400
401    /// Return a `watcher::Config` instance that limits results to the namespace
402    /// assigned to this orchestrator.
403    fn watch_pod_params(&self) -> watcher::Config {
404        let ns_selector = format!(
405            "environmentd.materialize.cloud/namespace={}",
406            self.namespace
407        );
408        // This watcher timeout must be shorter than the client read timeout.
409        watcher::Config::default().timeout(59).labels(&ns_selector)
410    }
411
412    /// Convert a higher-level label key to the actual one we
413    /// will give to Kubernetes
414    fn make_label_key(&self, key: &str) -> String {
415        format!("{}.environmentd.materialize.cloud/{}", self.namespace, key)
416    }
417
418    fn label_selector_to_k8s(
419        &self,
420        MzLabelSelector { label_name, logic }: MzLabelSelector,
421    ) -> Result<LabelSelectorRequirement, anyhow::Error> {
422        let (operator, values) = match logic {
423            LabelSelectionLogic::Eq { value } => Ok(("In", vec![value])),
424            LabelSelectionLogic::NotEq { value } => Ok(("NotIn", vec![value])),
425            LabelSelectionLogic::Exists => Ok(("Exists", vec![])),
426            LabelSelectionLogic::NotExists => Ok(("DoesNotExist", vec![])),
427            LabelSelectionLogic::InSet { values } => {
428                if values.is_empty() {
429                    Err(anyhow!(
430                        "Invalid selector logic for {label_name}: empty `in` set"
431                    ))
432                } else {
433                    Ok(("In", values))
434                }
435            }
436            LabelSelectionLogic::NotInSet { values } => {
437                if values.is_empty() {
438                    Err(anyhow!(
439                        "Invalid selector logic for {label_name}: empty `notin` set"
440                    ))
441                } else {
442                    Ok(("NotIn", values))
443                }
444            }
445        }?;
446        let lsr = LabelSelectorRequirement {
447            key: self.make_label_key(&label_name),
448            operator: operator.to_string(),
449            values: Some(values),
450        };
451        Ok(lsr)
452    }
453
454    fn send_command(&self, cmd: WorkerCommand) {
455        self.command_tx.send(cmd).expect("worker task not dropped");
456    }
457}
458
459#[derive(Debug)]
460struct ScaledQuantity {
461    integral_part: u64,
462    exponent: i8,
463    base10: bool,
464}
465
466impl ScaledQuantity {
467    pub fn try_to_integer(&self, scale: i8, base10: bool) -> Option<u64> {
468        if base10 != self.base10 {
469            return None;
470        }
471        let exponent = self.exponent - scale;
472        let mut result = self.integral_part;
473        let base = if self.base10 { 10 } else { 2 };
474        if exponent < 0 {
475            for _ in exponent..0 {
476                result /= base;
477            }
478        } else {
479            for _ in 0..exponent {
480                result = result.checked_mul(base)?;
481            }
482        }
483        Some(result)
484    }
485}
486
487// Parse a k8s `Quantity` object
488// into a numeric value.
489//
490// This is intended to support collecting CPU and Memory data.
491// Thus, there are a few that things Kubernetes attempts to do, that we don't,
492// because I've never observed metrics-server specifically sending them:
493// (1) Handle negative numbers (because it's not useful for that use-case)
494// (2) Handle non-integers (because I have never observed them being actually sent)
495// (3) Handle scientific notation (e.g. 1.23e2)
496fn parse_k8s_quantity(s: &str) -> Result<ScaledQuantity, anyhow::Error> {
497    const DEC_SUFFIXES: &[(&str, i8)] = &[
498        ("n", -9),
499        ("u", -6),
500        ("m", -3),
501        ("", 0),
502        ("k", 3), // yep, intentionally lowercase.
503        ("M", 6),
504        ("G", 9),
505        ("T", 12),
506        ("P", 15),
507        ("E", 18),
508    ];
509    const BIN_SUFFIXES: &[(&str, i8)] = &[
510        ("", 0),
511        ("Ki", 10),
512        ("Mi", 20),
513        ("Gi", 30),
514        ("Ti", 40),
515        ("Pi", 50),
516        ("Ei", 60),
517    ];
518
519    let (positive, s) = match s.chars().next() {
520        Some('+') => (true, &s[1..]),
521        Some('-') => (false, &s[1..]),
522        _ => (true, s),
523    };
524
525    if !positive {
526        anyhow::bail!("Negative numbers not supported")
527    }
528
529    fn is_suffix_char(ch: char) -> bool {
530        "numkMGTPEKi".contains(ch)
531    }
532    let (num, suffix) = match s.find(is_suffix_char) {
533        None => (s, ""),
534        Some(idx) => s.split_at(idx),
535    };
536    let num: u64 = num.parse()?;
537    let (exponent, base10) = if let Some((_, exponent)) =
538        DEC_SUFFIXES.iter().find(|(target, _)| suffix == *target)
539    {
540        (exponent, true)
541    } else if let Some((_, exponent)) = BIN_SUFFIXES.iter().find(|(target, _)| suffix == *target) {
542        (exponent, false)
543    } else {
544        anyhow::bail!("Unrecognized suffix: {suffix}");
545    };
546    Ok(ScaledQuantity {
547        integral_part: num,
548        exponent: *exponent,
549        base10,
550    })
551}
552
553#[async_trait]
554impl NamespacedOrchestrator for NamespacedKubernetesOrchestrator {
555    async fn fetch_service_metrics(
556        &self,
557        id: &str,
558    ) -> Result<Vec<ServiceProcessMetrics>, anyhow::Error> {
559        let info = if let Some(info) = self.service_infos.lock().expect("poisoned lock").get(id) {
560            *info
561        } else {
562            // This should have been set in `ensure_service`.
563            tracing::error!("Failed to get info for {id}");
564            anyhow::bail!("Failed to get info for {id}");
565        };
566
567        let (result_tx, result_rx) = oneshot::channel();
568        self.send_command(WorkerCommand::FetchServiceMetrics {
569            name: self.service_name(id),
570            info,
571            result_tx,
572        });
573
574        let metrics = result_rx.await.expect("worker task not dropped");
575        Ok(metrics)
576    }
577
578    fn ensure_service(
579        &self,
580        id: &str,
581        ServiceConfig {
582            app_name,
583            image,
584            init_container_image,
585            args,
586            ports: ports_in,
587            memory_limit,
588            memory_request,
589            cpu_limit,
590            cpu_request,
591            scale,
592            labels: labels_in,
593            annotations: annotations_in,
594            availability_zones,
595            other_replicas_selector,
596            replicas_selector,
597            disk_limit,
598            node_selector,
599        }: ServiceConfig,
600    ) -> Result<Box<dyn Service>, anyhow::Error> {
601        // This is extremely cheap to clone, so just look into the lock once.
602        let scheduling_config: ServiceSchedulingConfig =
603            self.scheduling_config.read().expect("poisoned").clone();
604
605        // Enable disk if the size does not disable it.
606        let disk = disk_limit != Some(DiskLimit::ZERO);
607
608        let name = self.service_name(id);
609        // The match labels should be the minimal set of labels that uniquely
610        // identify the pods in the stateful set. Changing these after the
611        // `StatefulSet` is created is not permitted by Kubernetes, and we're
612        // not yet smart enough to handle deleting and recreating the
613        // `StatefulSet`.
614        let mut match_labels = btreemap! {
615            "environmentd.materialize.cloud/namespace".into() => self.namespace.clone(),
616            "environmentd.materialize.cloud/service-id".into() => id.into(),
617        };
618        for (key, value) in &self.config.service_labels {
619            match_labels.insert(key.clone(), value.clone());
620        }
621
622        let mut labels = match_labels.clone();
623        for (key, value) in labels_in {
624            labels.insert(self.make_label_key(&key), value);
625        }
626
627        let standard_labels = recommended_k8s_labels(app_name);
628
629        // Standard Kubernetes labels
630        labels.extend(standard_labels.clone());
631
632        labels.insert(self.make_label_key("scale"), scale.to_string());
633
634        for port in &ports_in {
635            labels.insert(
636                format!("environmentd.materialize.cloud/port-{}", port.name),
637                "true".into(),
638            );
639        }
640        let mut limits = BTreeMap::new();
641        let mut requests = BTreeMap::new();
642        if let Some(memory_limit) = memory_limit {
643            limits.insert(
644                "memory".into(),
645                Quantity(memory_limit.0.as_u64().to_string()),
646            );
647            requests.insert(
648                "memory".into(),
649                Quantity(memory_limit.0.as_u64().to_string()),
650            );
651        }
652        if let Some(memory_request) = memory_request {
653            requests.insert(
654                "memory".into(),
655                Quantity(memory_request.0.as_u64().to_string()),
656            );
657        }
658        if let Some(cpu_limit) = cpu_limit {
659            limits.insert(
660                "cpu".into(),
661                Quantity(format!("{}m", cpu_limit.as_millicpus())),
662            );
663            requests.insert(
664                "cpu".into(),
665                Quantity(format!("{}m", cpu_limit.as_millicpus())),
666            );
667        }
668        if let Some(cpu_request) = cpu_request {
669            requests.insert(
670                "cpu".into(),
671                Quantity(format!("{}m", cpu_request.as_millicpus())),
672            );
673        }
674        let service = K8sService {
675            metadata: ObjectMeta {
676                name: Some(name.clone()),
677                labels: Some(standard_labels.clone()),
678                ..Default::default()
679            },
680            spec: Some(ServiceSpec {
681                ports: Some(
682                    ports_in
683                        .iter()
684                        .map(|port| ServicePort {
685                            port: port.port_hint.into(),
686                            name: Some(port.name.clone()),
687                            ..Default::default()
688                        })
689                        .collect(),
690                ),
691                cluster_ip: Some("None".to_string()),
692                selector: Some(match_labels.clone()),
693                ..Default::default()
694            }),
695            status: None,
696        };
697
698        let hosts = (0..scale.get())
699            .map(|i| {
700                format!(
701                    "{name}-{i}.{name}.{}.svc.cluster.local",
702                    self.kubernetes_namespace
703                )
704            })
705            .collect::<Vec<_>>();
706        let ports = ports_in
707            .iter()
708            .map(|p| (p.name.clone(), p.port_hint))
709            .collect::<BTreeMap<_, _>>();
710
711        let mut listen_addrs = BTreeMap::new();
712        let mut peer_addrs = vec![BTreeMap::new(); hosts.len()];
713        for (name, port) in &ports {
714            listen_addrs.insert(name.clone(), format!("0.0.0.0:{port}"));
715            for (i, host) in hosts.iter().enumerate() {
716                peer_addrs[i].insert(name.clone(), format!("{host}:{port}"));
717            }
718        }
719        let mut args = args(ServiceAssignments {
720            listen_addrs: &listen_addrs,
721            peer_addrs: &peer_addrs,
722        });
723
724        // This constrains the orchestrator (for those orchestrators that support
725        // anti-affinity, today just k8s) to never schedule pods for different replicas
726        // of the same cluster on the same node. Pods from the _same_ replica are fine;
727        // pods from different clusters are also fine.
728        //
729        // The point is that if pods of two replicas are on the same node, that node
730        // going down would kill both replicas, and so the replication factor of the
731        // cluster in question is illusory.
732        let anti_affinity = Some({
733            let label_selector_requirements = other_replicas_selector
734                .clone()
735                .into_iter()
736                .map(|ls| self.label_selector_to_k8s(ls))
737                .collect::<Result<Vec<_>, _>>()?;
738            let ls = LabelSelector {
739                match_expressions: Some(label_selector_requirements),
740                ..Default::default()
741            };
742            let pat = PodAffinityTerm {
743                label_selector: Some(ls),
744                topology_key: "kubernetes.io/hostname".to_string(),
745                ..Default::default()
746            };
747
748            if !scheduling_config.soften_replication_anti_affinity {
749                PodAntiAffinity {
750                    required_during_scheduling_ignored_during_execution: Some(vec![pat]),
751                    ..Default::default()
752                }
753            } else {
754                PodAntiAffinity {
755                    preferred_during_scheduling_ignored_during_execution: Some(vec![
756                        WeightedPodAffinityTerm {
757                            weight: scheduling_config.soften_replication_anti_affinity_weight,
758                            pod_affinity_term: pat,
759                        },
760                    ]),
761                    ..Default::default()
762                }
763            }
764        });
765
766        let pod_affinity = if let Some(weight) = scheduling_config.multi_pod_az_affinity_weight {
767            // `match_labels` sufficiently selects pods in the same replica.
768            let ls = LabelSelector {
769                match_labels: Some(match_labels.clone()),
770                ..Default::default()
771            };
772            let pat = PodAffinityTerm {
773                label_selector: Some(ls),
774                topology_key: "topology.kubernetes.io/zone".to_string(),
775                ..Default::default()
776            };
777
778            Some(PodAffinity {
779                preferred_during_scheduling_ignored_during_execution: Some(vec![
780                    WeightedPodAffinityTerm {
781                        weight,
782                        pod_affinity_term: pat,
783                    },
784                ]),
785                ..Default::default()
786            })
787        } else {
788            None
789        };
790
791        let topology_spread = if scheduling_config.topology_spread.enabled {
792            let config = &scheduling_config.topology_spread;
793
794            if !config.ignore_non_singular_scale || scale.get() == 1 {
795                let label_selector_requirements = (if config.ignore_non_singular_scale {
796                    let mut replicas_selector_ignoring_scale = replicas_selector.clone();
797
798                    replicas_selector_ignoring_scale.push(mz_orchestrator::LabelSelector {
799                        label_name: "scale".into(),
800                        logic: mz_orchestrator::LabelSelectionLogic::Eq {
801                            value: "1".to_string(),
802                        },
803                    });
804
805                    replicas_selector_ignoring_scale
806                } else {
807                    replicas_selector
808                })
809                .into_iter()
810                .map(|ls| self.label_selector_to_k8s(ls))
811                .collect::<Result<Vec<_>, _>>()?;
812                let ls = LabelSelector {
813                    match_expressions: Some(label_selector_requirements),
814                    ..Default::default()
815                };
816
817                if config.soft && config.min_domains.is_some() {
818                    warn!(
819                        "topology spread is soft but min_domains is set; \
820                         Kubernetes rejects minDomains with ScheduleAnyway, \
821                         so min_domains will be ignored"
822                    );
823                }
824                if availability_zones.is_some() && config.min_domains.is_some() {
825                    warn!(
826                        "topology spread has min_domains set but availability_zones \
827                         constrains eligible topology domains via node affinity; \
828                         minDomains will be ignored to avoid preventing pod scheduling"
829                    );
830                }
831
832                let constraint = TopologySpreadConstraint {
833                    label_selector: Some(ls),
834                    min_domains: topology_spread_min_domains(
835                        config.soft,
836                        availability_zones.is_some(),
837                        config.min_domains,
838                    ),
839                    max_skew: config.max_skew,
840                    topology_key: "topology.kubernetes.io/zone".to_string(),
841                    when_unsatisfiable: if config.soft {
842                        "ScheduleAnyway".to_string()
843                    } else {
844                        "DoNotSchedule".to_string()
845                    },
846                    // TODO(guswynn): restore these once they are supported.
847                    // Consider node affinities when calculating topology spread. This is the
848                    // default: <https://docs.rs/k8s-openapi/latest/k8s_openapi/api/core/v1/struct.TopologySpreadConstraint.html#structfield.node_affinity_policy>,
849                    // made explicit.
850                    // node_affinity_policy: Some("Honor".to_string()),
851                    // Do not consider node taints when calculating topology spread. This is the
852                    // default: <https://docs.rs/k8s-openapi/latest/k8s_openapi/api/core/v1/struct.TopologySpreadConstraint.html#structfield.node_taints_policy>,
853                    // made explicit.
854                    // node_taints_policy: Some("Ignore".to_string()),
855                    match_label_keys: None,
856                    // Once the above are restorted, we should't have `..Default::default()` here because the specifics of these fields are
857                    // subtle enough where we want compilation failures when we upgrade
858                    ..Default::default()
859                };
860                Some(vec![constraint])
861            } else {
862                None
863            }
864        } else {
865            None
866        };
867
868        let mut pod_annotations = btreemap! {
869            // Prevent the cluster-autoscaler (or karpenter) from evicting these pods in attempts to scale down
870            // and terminate nodes.
871            // This will cost us more money, but should give us better uptime.
872            // This does not prevent all evictions by Kubernetes, only the ones initiated by the
873            // cluster-autoscaler (or karpenter). Notably, eviction of pods for resource overuse is still enabled.
874            "cluster-autoscaler.kubernetes.io/safe-to-evict".to_owned() => "false".to_string(),
875            "karpenter.sh/do-not-evict".to_owned() => "true".to_string(),
876
877            // It's called do-not-disrupt in newer versions of karpenter, so adding for forward/backward compatibility
878            "karpenter.sh/do-not-disrupt".to_owned() => "true".to_string(),
879        };
880        for (key, value) in annotations_in {
881            // We want to use the same prefix as our labels keys
882            pod_annotations.insert(self.make_label_key(&key), value);
883        }
884        if self.config.enable_prometheus_scrape_annotations {
885            if let Some(internal_http_port) = ports_in
886                .iter()
887                .find(|port| port.name == "internal-http")
888                .map(|port| port.port_hint.to_string())
889            {
890                // Enable prometheus scrape discovery
891                pod_annotations.insert("prometheus.io/scrape".to_owned(), "true".to_string());
892                pod_annotations.insert("prometheus.io/port".to_owned(), internal_http_port);
893                pod_annotations.insert("prometheus.io/path".to_owned(), "/metrics".to_string());
894                pod_annotations.insert("prometheus.io/scheme".to_owned(), "http".to_string());
895            }
896        }
897        for (key, value) in &self.config.service_annotations {
898            pod_annotations.insert(key.clone(), value.clone());
899        }
900
901        let default_node_selector = if disk {
902            vec![("materialize.cloud/disk".to_string(), disk.to_string())]
903        } else {
904            // if the cluster doesn't require disk, we can omit the selector
905            // allowing it to be scheduled onto nodes with and without the
906            // selector
907            vec![]
908        };
909
910        let node_selector: BTreeMap<String, String> = default_node_selector
911            .into_iter()
912            .chain(self.config.service_node_selector.clone())
913            .chain(node_selector)
914            .collect();
915
916        let node_affinity = if let Some(availability_zones) = availability_zones {
917            let selector = NodeSelectorTerm {
918                match_expressions: Some(vec![NodeSelectorRequirement {
919                    key: "materialize.cloud/availability-zone".to_string(),
920                    operator: "In".to_string(),
921                    values: Some(availability_zones),
922                }]),
923                match_fields: None,
924            };
925
926            if scheduling_config.soften_az_affinity {
927                Some(NodeAffinity {
928                    preferred_during_scheduling_ignored_during_execution: Some(vec![
929                        PreferredSchedulingTerm {
930                            preference: selector,
931                            weight: scheduling_config.soften_az_affinity_weight,
932                        },
933                    ]),
934                    required_during_scheduling_ignored_during_execution: None,
935                })
936            } else {
937                Some(NodeAffinity {
938                    preferred_during_scheduling_ignored_during_execution: None,
939                    required_during_scheduling_ignored_during_execution: Some(NodeSelector {
940                        node_selector_terms: vec![selector],
941                    }),
942                })
943            }
944        } else {
945            None
946        };
947
948        let mut affinity = Affinity {
949            pod_anti_affinity: anti_affinity,
950            pod_affinity,
951            node_affinity,
952            ..Default::default()
953        };
954        if let Some(service_affinity) = &self.config.service_affinity {
955            affinity.merge_from(serde_json::from_str(service_affinity)?);
956        }
957
958        let container_name = image
959            .rsplit_once('/')
960            .and_then(|(_, name_version)| name_version.rsplit_once(':'))
961            .context("`image` is not ORG/NAME:VERSION")?
962            .0
963            .to_string();
964
965        let container_security_context = if scheduling_config.security_context_enabled {
966            Some(SecurityContext {
967                privileged: Some(false),
968                run_as_non_root: Some(true),
969                allow_privilege_escalation: Some(false),
970                seccomp_profile: Some(SeccompProfile {
971                    type_: "RuntimeDefault".to_string(),
972                    ..Default::default()
973                }),
974                capabilities: Some(Capabilities {
975                    drop: Some(vec!["ALL".to_string()]),
976                    ..Default::default()
977                }),
978                ..Default::default()
979            })
980        } else {
981            None
982        };
983
984        let init_containers = init_container_image.map(|image| {
985            vec![Container {
986                name: "init".to_string(),
987                image: Some(image),
988                image_pull_policy: Some(self.config.image_pull_policy.to_string()),
989                resources: Some(ResourceRequirements {
990                    claims: None,
991                    limits: Some(limits.clone()),
992                    requests: Some(requests.clone()),
993                }),
994                security_context: container_security_context.clone(),
995                env: Some(vec![
996                    EnvVar {
997                        name: "MZ_NAMESPACE".to_string(),
998                        value_from: Some(EnvVarSource {
999                            field_ref: Some(ObjectFieldSelector {
1000                                field_path: "metadata.namespace".to_string(),
1001                                ..Default::default()
1002                            }),
1003                            ..Default::default()
1004                        }),
1005                        ..Default::default()
1006                    },
1007                    EnvVar {
1008                        name: "MZ_POD_NAME".to_string(),
1009                        value_from: Some(EnvVarSource {
1010                            field_ref: Some(ObjectFieldSelector {
1011                                field_path: "metadata.name".to_string(),
1012                                ..Default::default()
1013                            }),
1014                            ..Default::default()
1015                        }),
1016                        ..Default::default()
1017                    },
1018                    EnvVar {
1019                        name: "MZ_NODE_NAME".to_string(),
1020                        value_from: Some(EnvVarSource {
1021                            field_ref: Some(ObjectFieldSelector {
1022                                field_path: "spec.nodeName".to_string(),
1023                                ..Default::default()
1024                            }),
1025                            ..Default::default()
1026                        }),
1027                        ..Default::default()
1028                    },
1029                ]),
1030                ..Default::default()
1031            }]
1032        });
1033
1034        let env = if self.config.coverage {
1035            Some(vec![EnvVar {
1036                name: "LLVM_PROFILE_FILE".to_string(),
1037                value: Some(format!("/coverage/{}-%p-%9m%c.profraw", self.namespace)),
1038                ..Default::default()
1039            }])
1040        } else {
1041            None
1042        };
1043
1044        let mut volume_mounts = vec![];
1045
1046        if self.config.coverage {
1047            volume_mounts.push(VolumeMount {
1048                name: "coverage".to_string(),
1049                mount_path: "/coverage".to_string(),
1050                ..Default::default()
1051            })
1052        }
1053
1054        let volumes = match (disk, &self.config.ephemeral_volume_storage_class) {
1055            (true, Some(ephemeral_volume_storage_class)) => {
1056                volume_mounts.push(VolumeMount {
1057                    name: "scratch".to_string(),
1058                    mount_path: "/scratch".to_string(),
1059                    ..Default::default()
1060                });
1061                args.push("--scratch-directory=/scratch".into());
1062
1063                Some(vec![Volume {
1064                    name: "scratch".to_string(),
1065                    ephemeral: Some(EphemeralVolumeSource {
1066                        volume_claim_template: Some(PersistentVolumeClaimTemplate {
1067                            spec: PersistentVolumeClaimSpec {
1068                                access_modes: Some(vec!["ReadWriteOnce".to_string()]),
1069                                storage_class_name: Some(
1070                                    ephemeral_volume_storage_class.to_string(),
1071                                ),
1072                                resources: Some(VolumeResourceRequirements {
1073                                    requests: Some(BTreeMap::from([(
1074                                        "storage".to_string(),
1075                                        Quantity(
1076                                            disk_limit
1077                                                .unwrap_or(DiskLimit::ARBITRARY)
1078                                                .0
1079                                                .as_u64()
1080                                                .to_string(),
1081                                        ),
1082                                    )])),
1083                                    ..Default::default()
1084                                }),
1085                                ..Default::default()
1086                            },
1087                            ..Default::default()
1088                        }),
1089                        ..Default::default()
1090                    }),
1091                    ..Default::default()
1092                }])
1093            }
1094            (true, None) => {
1095                return Err(anyhow!(
1096                    "service requested disk but no ephemeral volume storage class was configured"
1097                ));
1098            }
1099            (false, _) => None,
1100        };
1101
1102        if let Some(name_prefix) = &self.config.name_prefix {
1103            args.push(format!("--secrets-reader-name-prefix={}", name_prefix));
1104        }
1105
1106        let volume_claim_templates = if self.config.coverage {
1107            Some(vec![PersistentVolumeClaim {
1108                metadata: ObjectMeta {
1109                    name: Some("coverage".to_string()),
1110                    ..Default::default()
1111                },
1112                spec: Some(PersistentVolumeClaimSpec {
1113                    access_modes: Some(vec!["ReadWriteOnce".to_string()]),
1114                    resources: Some(VolumeResourceRequirements {
1115                        requests: Some(BTreeMap::from([(
1116                            "storage".to_string(),
1117                            Quantity("10Gi".to_string()),
1118                        )])),
1119                        ..Default::default()
1120                    }),
1121                    ..Default::default()
1122                }),
1123                ..Default::default()
1124            }])
1125        } else {
1126            None
1127        };
1128
1129        let tcp_keepalive_sysctls = vec![
1130            Sysctl {
1131                name: "net.ipv4.tcp_keepalive_time".to_string(),
1132                value: "300".to_string(),
1133            },
1134            Sysctl {
1135                name: "net.ipv4.tcp_keepalive_intvl".to_string(),
1136                value: "30".to_string(),
1137            },
1138            Sysctl {
1139                name: "net.ipv4.tcp_keepalive_probes".to_string(),
1140                value: "3".to_string(),
1141            },
1142        ];
1143
1144        let security_context = if let Some(fs_group) = self.config.service_fs_group {
1145            Some(PodSecurityContext {
1146                fs_group: Some(fs_group),
1147                run_as_user: Some(fs_group),
1148                run_as_group: Some(fs_group),
1149                sysctls: Some(tcp_keepalive_sysctls),
1150                ..Default::default()
1151            })
1152        } else {
1153            Some(PodSecurityContext {
1154                sysctls: Some(tcp_keepalive_sysctls),
1155                ..Default::default()
1156            })
1157        };
1158
1159        let mut tolerations = vec![
1160            // When the node becomes `NotReady` it indicates there is a problem
1161            // with the node. By default Kubernetes waits 300s (5 minutes)
1162            // before descheduling the pod, but we tune this to 30s for faster
1163            // recovery in the case of node failure.
1164            Toleration {
1165                effect: Some("NoExecute".into()),
1166                key: Some("node.kubernetes.io/not-ready".into()),
1167                operator: Some("Exists".into()),
1168                toleration_seconds: Some(NODE_FAILURE_THRESHOLD_SECONDS),
1169                value: None,
1170            },
1171            Toleration {
1172                effect: Some("NoExecute".into()),
1173                key: Some("node.kubernetes.io/unreachable".into()),
1174                operator: Some("Exists".into()),
1175                toleration_seconds: Some(NODE_FAILURE_THRESHOLD_SECONDS),
1176                value: None,
1177            },
1178        ];
1179        if let Some(service_tolerations) = &self.config.service_tolerations {
1180            tolerations.extend(serde_json::from_str::<Vec<_>>(service_tolerations)?);
1181        }
1182        let tolerations = Some(tolerations);
1183
1184        let mut pod_template_spec = PodTemplateSpec {
1185            metadata: Some(ObjectMeta {
1186                labels: Some(labels.clone()),
1187                // Only set `annotations` _after_ we have computed the pod template hash, to
1188                // avoid that annotation changes cause pod replacements.
1189                ..Default::default()
1190            }),
1191            spec: Some(PodSpec {
1192                init_containers,
1193                containers: vec![Container {
1194                    name: container_name,
1195                    image: Some(image),
1196                    args: Some(args),
1197                    image_pull_policy: Some(self.config.image_pull_policy.to_string()),
1198                    ports: Some(
1199                        ports_in
1200                            .iter()
1201                            .map(|port| ContainerPort {
1202                                container_port: port.port_hint.into(),
1203                                name: Some(port.name.clone()),
1204                                ..Default::default()
1205                            })
1206                            .collect(),
1207                    ),
1208                    security_context: container_security_context.clone(),
1209                    resources: Some(ResourceRequirements {
1210                        claims: None,
1211                        limits: Some(limits),
1212                        requests: Some(requests),
1213                    }),
1214                    volume_mounts: if !volume_mounts.is_empty() {
1215                        Some(volume_mounts)
1216                    } else {
1217                        None
1218                    },
1219                    env,
1220                    ..Default::default()
1221                }],
1222                volumes,
1223                security_context,
1224                // `None` rather than `Some(true)` when disabled, so the pod
1225                // template hash is unchanged from before user namespace support.
1226                host_users: self.config.enable_user_namespaces.then_some(false),
1227                node_selector: Some(node_selector),
1228                scheduler_name: self.config.scheduler_name.clone(),
1229                priority_class_name: self.config.priority_class_name.clone(),
1230                service_account: self.config.service_account.clone(),
1231                affinity: Some(affinity),
1232                topology_spread_constraints: topology_spread,
1233                tolerations,
1234                // Setting a 0s termination grace period has the side effect of
1235                // automatically starting a new pod when the previous pod is
1236                // currently terminating. This enables recovery from a node
1237                // failure with no manual intervention. Without this setting,
1238                // the StatefulSet controller will refuse to start a new pod
1239                // until the failed node is manually removed from the Kubernetes
1240                // cluster.
1241                //
1242                // The Kubernetes documentation strongly advises against this
1243                // setting, as StatefulSets attempt to provide "at most once"
1244                // semantics [0]--that is, the guarantee that for a given pod in
1245                // a StatefulSet there is *at most* one pod with that identity
1246                // running in the cluster.
1247                //
1248                // Materialize services, however, are carefully designed to
1249                // *not* rely on this guarantee. In fact, we do not believe that
1250                // correct distributed systems can meaningfully rely on
1251                // Kubernetes's guarantee--network packets from a pod can be
1252                // arbitrarily delayed, long past that pod's termination.
1253                //
1254                // [0]: https://kubernetes.io/docs/tasks/run-application/force-delete-stateful-set-pod/#statefulset-considerations
1255                termination_grace_period_seconds: Some(0),
1256                ..Default::default()
1257            }),
1258        };
1259        let pod_template_json = serde_json::to_string(&pod_template_spec).unwrap();
1260        let mut hasher = Sha256::new();
1261        hasher.update(pod_template_json);
1262        let pod_template_hash = hex::encode(hasher.finalize());
1263        pod_annotations.insert(
1264            POD_TEMPLATE_HASH_ANNOTATION.to_owned(),
1265            pod_template_hash.clone(),
1266        );
1267
1268        pod_template_spec.metadata.as_mut().unwrap().annotations = Some(pod_annotations);
1269
1270        let stateful_set = StatefulSet {
1271            metadata: ObjectMeta {
1272                name: Some(name.clone()),
1273                labels: Some(standard_labels.clone()),
1274                ..Default::default()
1275            },
1276            spec: Some(StatefulSetSpec {
1277                selector: LabelSelector {
1278                    match_labels: Some(match_labels),
1279                    ..Default::default()
1280                },
1281                service_name: Some(name.clone()),
1282                replicas: Some(scale.cast_into()),
1283                template: pod_template_spec,
1284                update_strategy: Some(StatefulSetUpdateStrategy {
1285                    type_: Some("OnDelete".to_owned()),
1286                    ..Default::default()
1287                }),
1288                pod_management_policy: Some("Parallel".to_string()),
1289                volume_claim_templates,
1290                ..Default::default()
1291            }),
1292            status: None,
1293        };
1294
1295        self.send_command(WorkerCommand::EnsureService {
1296            desc: ServiceDescription {
1297                name,
1298                scale,
1299                service,
1300                stateful_set,
1301                pod_template_hash,
1302            },
1303        });
1304
1305        self.service_infos
1306            .lock()
1307            .expect("poisoned lock")
1308            .insert(id.to_string(), ServiceInfo { scale });
1309
1310        Ok(Box::new(KubernetesService { hosts, ports }))
1311    }
1312
1313    /// Drops the identified service, if it exists.
1314    fn drop_service(&self, id: &str) -> Result<(), anyhow::Error> {
1315        fail::fail_point!("kubernetes_drop_service", |_| Err(anyhow!("failpoint")));
1316        self.service_infos.lock().expect("poisoned lock").remove(id);
1317
1318        self.send_command(WorkerCommand::DropService {
1319            name: self.service_name(id),
1320        });
1321
1322        Ok(())
1323    }
1324
1325    /// Lists the identifiers of all known services.
1326    async fn list_services(&self) -> Result<Vec<String>, anyhow::Error> {
1327        let (result_tx, result_rx) = oneshot::channel();
1328        self.send_command(WorkerCommand::ListServices {
1329            namespace: self.namespace.clone(),
1330            result_tx,
1331        });
1332
1333        let list = result_rx.await.expect("worker task not dropped");
1334        Ok(list)
1335    }
1336
1337    async fn flush(&self) -> Result<(), anyhow::Error> {
1338        let (result_tx, result_rx) = oneshot::channel();
1339        self.send_command(WorkerCommand::Flush { result_tx });
1340        result_rx.await.expect("worker task not dropped");
1341        Ok(())
1342    }
1343
1344    fn watch_services(&self) -> BoxStream<'static, Result<ServiceEvent, anyhow::Error>> {
1345        fn into_service_event(pod: Pod) -> Result<ServiceEvent, anyhow::Error> {
1346            let process_id = pod.name_any().split('-').next_back().unwrap().parse()?;
1347            let service_id_label = "environmentd.materialize.cloud/service-id";
1348            let service_id = pod
1349                .labels()
1350                .get(service_id_label)
1351                .ok_or_else(|| anyhow!("missing label: {service_id_label}"))?
1352                .clone();
1353
1354            let oomed = pod
1355                .status
1356                .as_ref()
1357                .and_then(|status| status.container_statuses.as_ref())
1358                .map(|container_statuses| {
1359                    container_statuses.iter().any(|cs| {
1360                        // The container might have already transitioned from "terminated" to
1361                        // "waiting"/"running" state, in which case we need to check its previous
1362                        // state to find out why it terminated.
1363                        let current_state = cs.state.as_ref().and_then(|s| s.terminated.as_ref());
1364                        let last_state = cs.last_state.as_ref().and_then(|s| s.terminated.as_ref());
1365                        let termination_state = current_state.or(last_state);
1366
1367                        // The interesting exit codes are:
1368                        //  * 135 (SIGBUS): occurs when lgalloc runs out of disk
1369                        //  * 137 (SIGKILL): occurs when the OOM killer terminates the container
1370                        //  * 167: occurs when the lgalloc or memory limiter terminates the process
1371                        // We treat the all of these as OOM conditions since swap and lgalloc use
1372                        // disk only for spilling memory.
1373                        let exit_code = termination_state.map(|s| s.exit_code);
1374                        exit_code.is_some_and(|e| [135, 137, 167].contains(&e))
1375                    })
1376                })
1377                .unwrap_or(false);
1378
1379            // Sum the per-container restart counts to get a per-process (per-pod)
1380            // restart count. This is cumulative and survives gaps in the watch
1381            // stream, so it lets consumers detect restarts they'd otherwise miss
1382            // by only sampling the ready/not-ready status.
1383            let restart_count = pod
1384                .status
1385                .as_ref()
1386                .and_then(|status| status.container_statuses.as_ref())
1387                .map(|container_statuses| {
1388                    container_statuses
1389                        .iter()
1390                        .map(|cs| u64::try_from(cs.restart_count).unwrap_or(0))
1391                        .sum()
1392                })
1393                .unwrap_or(0);
1394
1395            let (pod_ready, last_probe_time) = pod
1396                .status
1397                .and_then(|status| status.conditions)
1398                .and_then(|conditions| conditions.into_iter().find(|c| c.type_ == "Ready"))
1399                .map(|c| (c.status == "True", c.last_probe_time))
1400                .unwrap_or((false, None));
1401
1402            let status = if pod_ready {
1403                ServiceStatus::Online
1404            } else {
1405                ServiceStatus::Offline(oomed.then_some(OfflineReason::OomKilled))
1406            };
1407            let time = if let Some(time) = last_probe_time {
1408                time.0
1409            } else {
1410                Timestamp::now()
1411            };
1412
1413            Ok(ServiceEvent {
1414                service_id,
1415                process_id,
1416                status,
1417                restart_count,
1418                time: DateTime::from_timestamp_nanos(
1419                    time.as_nanosecond().try_into().expect("must fit"),
1420                ),
1421            })
1422        }
1423
1424        let stream = watcher(self.pod_api.clone(), self.watch_pod_params())
1425            .touched_objects()
1426            .filter_map(|object| async move {
1427                match object {
1428                    Ok(pod) => Some(into_service_event(pod)),
1429                    Err(error) => {
1430                        // We assume that errors returned by Kubernetes are usually transient, so we
1431                        // just log a warning and ignore them otherwise.
1432                        tracing::warn!("service watch error: {error}");
1433                        None
1434                    }
1435                }
1436            });
1437        Box::pin(stream)
1438    }
1439
1440    fn update_scheduling_config(&self, config: ServiceSchedulingConfig) {
1441        *self.scheduling_config.write().expect("poisoned") = config;
1442    }
1443}
1444
1445impl OrchestratorWorker {
1446    fn spawn(self, name: String) -> AbortOnDropHandle<()> {
1447        mz_ore::task::spawn(|| name, self.run()).abort_on_drop()
1448    }
1449
1450    async fn run(mut self) {
1451        {
1452            info!("initializing Kubernetes orchestrator worker");
1453            let start = Instant::now();
1454
1455            // Fetch the owner reference for our own pod (usually a
1456            // StatefulSet), so that we can propagate it to the services we
1457            // create.
1458            let hostname = env::var("HOSTNAME").unwrap_or_else(|_| panic!("HOSTNAME environment variable missing or invalid; required for Kubernetes orchestrator"));
1459            let orchestrator_pod = Retry::default()
1460                .clamp_backoff(Duration::from_secs(10))
1461                .retry_async(|_| self.pod_api.get(&hostname))
1462                .await
1463                .expect("always retries on error");
1464            self.owner_references
1465                .extend(orchestrator_pod.owner_references().into_iter().cloned());
1466
1467            if !self.collect_pod_metrics {
1468                info!(
1469                    "pod metrics collection is disabled; resource usage graphs in the console will not be available"
1470                );
1471            }
1472
1473            info!(
1474                "Kubernetes orchestrator worker initialized in {:?}",
1475                start.elapsed()
1476            );
1477        }
1478
1479        while let Some(cmd) = self.command_rx.recv().await {
1480            self.handle_command(cmd).await;
1481        }
1482    }
1483
1484    /// Handle a worker command.
1485    ///
1486    /// If handling the command fails, it is automatically retried. All command handlers return
1487    /// [`K8sError`], so we can reasonably assume that a failure is caused by issues communicating
1488    /// with the K8S server and that retrying resolves them eventually.
1489    async fn handle_command(&self, cmd: WorkerCommand) {
1490        async fn retry<F, U, R>(f: F, cmd_type: &str) -> R
1491        where
1492            F: Fn() -> U,
1493            U: Future<Output = Result<R, K8sError>>,
1494        {
1495            let start = Instant::now();
1496            Retry::default()
1497                .clamp_backoff(Duration::from_secs(10))
1498                .retry_async(|state| {
1499                    f().map_err(move |error| {
1500                        let attempt = state.i + 1;
1501                        let elapsed = start.elapsed();
1502                        if state.i < RETRY_WARN_ATTEMPTS {
1503                            tracing::warn!(
1504                                %cmd_type,
1505                                attempt,
1506                                ?elapsed,
1507                                "orchestrator call failed: {error}"
1508                            );
1509                        } else {
1510                            tracing::error!(
1511                                %cmd_type,
1512                                attempt,
1513                                ?elapsed,
1514                                "orchestrator call failed: {error}"
1515                            );
1516                        }
1517                    })
1518                })
1519                .await
1520                .expect("always retries on error")
1521        }
1522
1523        use WorkerCommand::*;
1524        match cmd {
1525            EnsureService { desc } => {
1526                retry(|| self.ensure_service(desc.clone()), "EnsureService").await
1527            }
1528            DropService { name } => retry(|| self.drop_service(&name), "DropService").await,
1529            ListServices {
1530                namespace,
1531                result_tx,
1532            } => {
1533                let result = retry(|| self.list_services(&namespace), "ListServices").await;
1534                let _ = result_tx.send(result);
1535            }
1536            Flush { result_tx } => {
1537                let _ = result_tx.send(());
1538            }
1539            FetchServiceMetrics {
1540                name,
1541                info,
1542                result_tx,
1543            } => {
1544                let result = self.fetch_service_metrics(&name, &info).await;
1545                let _ = result_tx.send(result);
1546            }
1547        }
1548    }
1549
1550    async fn fetch_service_metrics(
1551        &self,
1552        name: &str,
1553        info: &ServiceInfo,
1554    ) -> Vec<ServiceProcessMetrics> {
1555        if !self.collect_pod_metrics {
1556            return (0..info.scale.get())
1557                .map(|_| ServiceProcessMetrics::default())
1558                .collect();
1559        }
1560
1561        /// Usage metrics reported by clusterd processes.
1562        #[derive(Deserialize)]
1563        pub(crate) struct ClusterdUsage {
1564            disk_bytes: Option<u64>,
1565            memory_bytes: Option<u64>,
1566            swap_bytes: Option<u64>,
1567            heap_limit: Option<u64>,
1568        }
1569
1570        /// Get metrics for a particular service and process, converting them into a sane (i.e., numeric) format.
1571        ///
1572        /// Note that we want to keep going even if a lookup fails for whatever reason,
1573        /// so this function is infallible. If we fail to get cpu or memory for a particular pod,
1574        /// we just log a warning and install `None` in the returned struct.
1575        async fn get_metrics(
1576            self_: &OrchestratorWorker,
1577            service_name: &str,
1578            i: usize,
1579        ) -> ServiceProcessMetrics {
1580            let name = format!("{service_name}-{i}");
1581
1582            let clusterd_usage_fut = get_clusterd_usage(self_, service_name, i);
1583            let (metrics, clusterd_usage) =
1584                futures::future::join(self_.metrics_api.get(&name), clusterd_usage_fut).await;
1585            let clusterd_usage = match clusterd_usage {
1586                Ok(clusterd_usage) => Some(clusterd_usage),
1587                Err(e) => {
1588                    self_
1589                        .metrics
1590                        .record_fetch_error(FetchStep::ClusterdUsage, e.as_ref());
1591                    warn!("Failed to fetch clusterd usage for {name}: {e:#}");
1592                    None
1593                }
1594            };
1595            let metrics = match metrics {
1596                Ok(metrics) => metrics,
1597                Err(e) => {
1598                    self_.metrics.record_fetch_error(FetchStep::PodMetrics, &e);
1599                    warn!(
1600                        "Failed to get metrics for {name}: {}",
1601                        e.display_with_causes()
1602                    );
1603                    return ServiceProcessMetrics::default();
1604                }
1605            };
1606            let Some(PodMetricsContainer {
1607                usage:
1608                    PodMetricsContainerUsage {
1609                        cpu: Quantity(cpu_str),
1610                        memory: Quantity(mem_str),
1611                    },
1612                ..
1613            }) = metrics.containers.get(0)
1614            else {
1615                self_
1616                    .metrics
1617                    .record_fetch_failure(FetchStep::PodMetrics, "no_containers");
1618                warn!("metrics result contained no containers for {name}");
1619                return ServiceProcessMetrics::default();
1620            };
1621
1622            let mut process_metrics = ServiceProcessMetrics::default();
1623
1624            match parse_k8s_quantity(cpu_str) {
1625                Ok(q) => match q.try_to_integer(-9, true) {
1626                    Some(nano_cores) => process_metrics.cpu_nano_cores = Some(nano_cores),
1627                    None => error!("CPU value {q:?} out of range"),
1628                },
1629                Err(e) => error!("failed to parse CPU value {cpu_str}: {e}"),
1630            }
1631            match parse_k8s_quantity(mem_str) {
1632                Ok(q) => match q.try_to_integer(0, false) {
1633                    Some(mem) => process_metrics.memory_bytes = Some(mem),
1634                    None => error!("memory value {q:?} out of range"),
1635                },
1636                Err(e) => error!("failed to parse memory value {mem_str}: {e}"),
1637            }
1638
1639            if let Some(usage) = clusterd_usage {
1640                // clusterd may report disk usage as either `disk_bytes`, or `swap_bytes`, or both.
1641                //
1642                // For now the Console expects the swap size to be reported in `disk_bytes`.
1643                // Once the Console has been ported to use `heap_bytes`/`heap_limit`, we can
1644                // simplify things by setting `process_metrics.disk_bytes = usage.disk_bytes`.
1645                process_metrics.disk_bytes = match (usage.disk_bytes, usage.swap_bytes) {
1646                    (Some(disk), Some(swap)) => Some(disk + swap),
1647                    (disk, swap) => disk.or(swap),
1648                };
1649
1650                // clusterd may report heap usage as `memory_bytes` and optionally `swap_bytes`.
1651                // If no `memory_bytes` is reported, we can't know the heap usage.
1652                process_metrics.heap_bytes = match (usage.memory_bytes, usage.swap_bytes) {
1653                    (Some(memory), Some(swap)) => Some(memory + swap),
1654                    (Some(memory), None) => Some(memory),
1655                    (None, _) => None,
1656                };
1657
1658                process_metrics.heap_limit = usage.heap_limit;
1659                process_metrics.swap_bytes = usage.swap_bytes;
1660            }
1661
1662            process_metrics
1663        }
1664
1665        /// Get the current usage metrics exposed by a clusterd process.
1666        ///
1667        /// Usage metrics are collected by connecting to a metrics endpoint exposed by the process.
1668        /// The endpoint is assumed to be reachable at the 'internal-http' under the HTTP path
1669        /// `/api/usage-metrics`.
1670        async fn get_clusterd_usage(
1671            self_: &OrchestratorWorker,
1672            service_name: &str,
1673            i: usize,
1674        ) -> anyhow::Result<ClusterdUsage> {
1675            let service = self_
1676                .service_api
1677                .get(service_name)
1678                .await
1679                .with_context(|| format!("failed to get service {service_name}"))?;
1680            let namespace = service
1681                .metadata
1682                .namespace
1683                .context("missing service namespace")?;
1684            let internal_http_port = service
1685                .spec
1686                .and_then(|spec| spec.ports)
1687                .and_then(|ports| {
1688                    ports
1689                        .into_iter()
1690                        .find(|p| p.name == Some("internal-http".into()))
1691                })
1692                .map(|p| p.port);
1693            let Some(port) = internal_http_port else {
1694                bail!("internal-http port missing in service spec");
1695            };
1696            let metrics_url = format!(
1697                "http://{service_name}-{i}.{service_name}.{namespace}.svc.cluster.local:{port}\
1698                 /api/usage-metrics"
1699            );
1700
1701            let http_client = reqwest::Client::builder()
1702                .timeout(Duration::from_secs(10))
1703                .build()
1704                .context("error building HTTP client")?;
1705            let resp = http_client.get(metrics_url).send().await?;
1706            let usage = resp.json().await?;
1707
1708            Ok(usage)
1709        }
1710
1711        let ret = futures::future::join_all(
1712            (0..info.scale.cast_into()).map(|i| get_metrics(self, name, i)),
1713        );
1714
1715        ret.await
1716    }
1717
1718    async fn ensure_service(&self, mut desc: ServiceDescription) -> Result<(), K8sError> {
1719        // We inject our own pod's owner references into the Kubernetes objects
1720        // created for the service so that if the
1721        // Deployment/StatefulSet/whatever that owns the pod running the
1722        // orchestrator gets deleted, so do all services spawned by this
1723        // orchestrator.
1724        desc.service
1725            .metadata
1726            .owner_references
1727            .get_or_insert(vec![])
1728            .extend(self.owner_references.iter().cloned());
1729        desc.stateful_set
1730            .metadata
1731            .owner_references
1732            .get_or_insert(vec![])
1733            .extend(self.owner_references.iter().cloned());
1734
1735        let ss_spec = desc.stateful_set.spec.as_ref().unwrap();
1736        let pod_metadata = ss_spec.template.metadata.as_ref().unwrap();
1737        let pod_annotations = pod_metadata.annotations.clone();
1738
1739        self.service_api
1740            .patch(
1741                &desc.name,
1742                &PatchParams::apply(FIELD_MANAGER).force(),
1743                &Patch::Apply(desc.service),
1744            )
1745            .await?;
1746        self.stateful_set_api
1747            .patch(
1748                &desc.name,
1749                &PatchParams::apply(FIELD_MANAGER).force(),
1750                &Patch::Apply(desc.stateful_set),
1751            )
1752            .await?;
1753
1754        // We manage pod recreation manually, using the OnDelete StatefulSet update strategy, for
1755        // two reasons:
1756        //  * Kubernetes doesn't always automatically replace StatefulSet pods when their specs
1757        //    change, see https://github.com/kubernetes/kubernetes#67250.
1758        //  * Kubernetes replaces StatefulSet pods when their annotations change, which is not
1759        //    something we want as it could cause unavailability.
1760        //
1761        // Our pod recreation policy is simple: If a pod's template hash changed, delete it, and
1762        // let the StatefulSet controller recreate it. Otherwise, patch the existing pod's
1763        // annotations to line up with the ones in the spec.
1764        for pod_id in 0..desc.scale.get() {
1765            let pod_name = format!("{}-{pod_id}", desc.name);
1766            let pod = match self.pod_api.get(&pod_name).await {
1767                Ok(pod) => pod,
1768                // Pod already doesn't exist.
1769                Err(kube::Error::Api(e)) if e.code == 404 => continue,
1770                Err(e) => return Err(e),
1771            };
1772
1773            let result = if pod.annotations().get(POD_TEMPLATE_HASH_ANNOTATION)
1774                != Some(&desc.pod_template_hash)
1775            {
1776                self.pod_api
1777                    .delete(&pod_name, &DeleteParams::default())
1778                    .await
1779                    .map(|_| ())
1780            } else {
1781                let metadata = ObjectMeta {
1782                    annotations: pod_annotations.clone(),
1783                    ..Default::default()
1784                }
1785                .into_request_partial::<Pod>();
1786                self.pod_api
1787                    .patch_metadata(
1788                        &pod_name,
1789                        &PatchParams::apply(FIELD_MANAGER).force(),
1790                        &Patch::Apply(&metadata),
1791                    )
1792                    .await
1793                    .map(|_| ())
1794            };
1795
1796            match result {
1797                Ok(()) => (),
1798                // Pod was deleted concurrently.
1799                Err(kube::Error::Api(e)) if e.code == 404 => continue,
1800                Err(e) => return Err(e),
1801            }
1802        }
1803
1804        Ok(())
1805    }
1806
1807    async fn drop_service(&self, name: &str) -> Result<(), K8sError> {
1808        let res = self
1809            .stateful_set_api
1810            .delete(name, &DeleteParams::default())
1811            .await;
1812        match res {
1813            Ok(_) => (),
1814            Err(K8sError::Api(e)) if e.code == 404 => (),
1815            Err(e) => return Err(e),
1816        }
1817
1818        let res = self
1819            .service_api
1820            .delete(name, &DeleteParams::default())
1821            .await;
1822        match res {
1823            Ok(_) => Ok(()),
1824            Err(K8sError::Api(e)) if e.code == 404 => Ok(()),
1825            Err(e) => Err(e),
1826        }
1827    }
1828
1829    async fn list_services(&self, namespace: &str) -> Result<Vec<String>, K8sError> {
1830        let stateful_sets = self.stateful_set_api.list(&Default::default()).await?;
1831        let name_prefix = format!("{}{namespace}-", self.name_prefix);
1832        Ok(stateful_sets
1833            .into_iter()
1834            .filter_map(|ss| {
1835                ss.metadata
1836                    .name
1837                    .unwrap()
1838                    .strip_prefix(&name_prefix)
1839                    .map(Into::into)
1840            })
1841            .collect())
1842    }
1843}
1844
1845#[derive(Debug, Clone)]
1846struct KubernetesService {
1847    hosts: Vec<String>,
1848    ports: BTreeMap<String, u16>,
1849}
1850
1851impl Service for KubernetesService {
1852    fn addresses(&self, port: &str) -> Vec<String> {
1853        let port = self.ports[port];
1854        self.hosts
1855            .iter()
1856            .map(|host| format!("{host}:{port}"))
1857            .collect()
1858    }
1859}
1860
1861/// Returns the `minDomains` value for a `TopologySpreadConstraint`.
1862///
1863/// `minDomains` must be suppressed when spread is soft (Kubernetes rejects
1864/// `minDomains` with `ScheduleAnyway`) and when `availability_zones` is set
1865/// (node affinity already constrains eligible domains; if `minDomains` exceeds
1866/// the number of pinned zones the global minimum is treated as 0, causing all
1867/// but one replica to remain pending with `maxSkew=1`).
1868fn topology_spread_min_domains(
1869    soft: bool,
1870    az_pinned: bool,
1871    min_domains: Option<i32>,
1872) -> Option<i32> {
1873    if soft || az_pinned { None } else { min_domains }
1874}
1875
1876#[cfg(test)]
1877mod tests {
1878    use super::*;
1879
1880    #[mz_ore::test]
1881    fn topology_spread_min_domains_suppression() {
1882        // min_domains is kept when neither soft nor az-pinned
1883        assert_eq!(topology_spread_min_domains(false, false, Some(3)), Some(3));
1884        // min_domains is None when not set regardless of flags
1885        assert_eq!(topology_spread_min_domains(false, false, None), None);
1886        // suppressed when soft (Kubernetes rejects minDomains with ScheduleAnyway)
1887        assert_eq!(topology_spread_min_domains(true, false, Some(3)), None);
1888        // suppressed when availability_zones pins to specific AZs
1889        assert_eq!(topology_spread_min_domains(false, true, Some(3)), None);
1890        // suppressed when both
1891        assert_eq!(topology_spread_min_domains(true, true, Some(3)), None);
1892    }
1893
1894    #[mz_ore::test]
1895    fn k8s_quantity_base10_large() {
1896        let cases = &[
1897            ("42", 42),
1898            ("42k", 42000),
1899            ("42M", 42000000),
1900            ("42G", 42000000000),
1901            ("42T", 42000000000000),
1902            ("42P", 42000000000000000),
1903        ];
1904
1905        for (input, expected) in cases {
1906            let quantity = parse_k8s_quantity(input).unwrap();
1907            let number = quantity.try_to_integer(0, true).unwrap();
1908            assert_eq!(number, *expected, "input={input}, quantity={quantity:?}");
1909        }
1910    }
1911
1912    #[mz_ore::test]
1913    fn k8s_quantity_base10_small() {
1914        let cases = &[("42n", 42), ("42u", 42000), ("42m", 42000000)];
1915
1916        for (input, expected) in cases {
1917            let quantity = parse_k8s_quantity(input).unwrap();
1918            let number = quantity.try_to_integer(-9, true).unwrap();
1919            assert_eq!(number, *expected, "input={input}, quantity={quantity:?}");
1920        }
1921    }
1922
1923    #[mz_ore::test]
1924    fn k8s_quantity_base2() {
1925        let cases = &[
1926            ("42Ki", 42 << 10),
1927            ("42Mi", 42 << 20),
1928            ("42Gi", 42 << 30),
1929            ("42Ti", 42 << 40),
1930            ("42Pi", 42 << 50),
1931        ];
1932
1933        for (input, expected) in cases {
1934            let quantity = parse_k8s_quantity(input).unwrap();
1935            let number = quantity.try_to_integer(0, false).unwrap();
1936            assert_eq!(number, *expected, "input={input}, quantity={quantity:?}");
1937        }
1938    }
1939}