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