Skip to main content

mz_orchestratord/controller/materialize/
generation.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::{
11    collections::BTreeMap,
12    net::{IpAddr, Ipv4Addr, SocketAddr},
13    sync::LazyLock,
14    time::Duration,
15};
16
17use anyhow::Context;
18use k8s_openapi::{
19    api::{
20        apps::v1::{StatefulSet, StatefulSetSpec},
21        core::v1::{
22            Capabilities, ConfigMap, ConfigMapVolumeSource, Container, ContainerPort,
23            EmptyDirVolumeSource, EnvVar, EnvVarSource, KeyToPath, PodSecurityContext, PodSpec,
24            PodTemplateSpec, Probe, SeccompProfile, Secret, SecretKeySelector, SecretVolumeSource,
25            SecurityContext, Service, ServicePort, ServiceSpec, TCPSocketAction, Toleration,
26            Volume, VolumeMount,
27        },
28    },
29    apimachinery::pkg::{apis::meta::v1::LabelSelector, util::intstr::IntOrString},
30};
31use kube::{Api, Client, ResourceExt, api::ObjectMeta, runtime::controller::Action};
32use maplit::btreemap;
33use mz_server_core::listeners::{
34    AllowedRoles, AuthenticatorKind, BaseListenerConfig, RouteGroup, SqlListenerConfig,
35    VersionedListenersConfig, v0_147_0, v26_32_0,
36};
37use reqwest::{Client as HttpClient, StatusCode};
38use semver::{BuildMetadata, Prerelease, Version};
39use serde::{Deserialize, Serialize};
40use sha2::{Digest, Sha256};
41use tracing::{error, trace};
42
43use super::Error;
44use super::matching_image_from_environmentd_image_ref;
45use crate::k8s::{apply_resource, delete_resource, get_resource};
46use crate::tls::issuer_ref_defined;
47use mz_cloud_provider::CloudProvider;
48use mz_cloud_resources::crd::materialize::v1alpha1::Materialize;
49use mz_cloud_resources::crd::{ManagedResource, recommended_k8s_labels};
50use mz_orchestrator_kubernetes::{
51    ADDITIONAL_TRUST_BUNDLE_DIR, ADDITIONAL_TRUST_BUNDLE_FILE, additional_trust_bundle_volume,
52};
53use mz_ore::instrument;
54
55static V140_DEV0: LazyLock<Version> = LazyLock::new(|| Version {
56    major: 0,
57    minor: 140,
58    patch: 0,
59    pre: Prerelease::new("dev.0").expect("dev.0 is valid prerelease"),
60    build: BuildMetadata::new("").expect("empty string is valid buildmetadata"),
61});
62const V143: Version = Version::new(0, 143, 0);
63const V144: Version = Version::new(0, 144, 0);
64static V147_DEV0: LazyLock<Version> = LazyLock::new(|| Version {
65    major: 0,
66    minor: 147,
67    patch: 0,
68    pre: Prerelease::new("dev.0").expect("dev.0 is valid prerelease"),
69    build: BuildMetadata::new("").expect("empty string is valid buildmetadata"),
70});
71const V153: Version = Version::new(0, 153, 0);
72static V154_DEV0: LazyLock<Version> = LazyLock::new(|| Version {
73    major: 0,
74    minor: 154,
75    patch: 0,
76    pre: Prerelease::new("").expect("dev.0 is valid prerelease"),
77    build: BuildMetadata::new("").expect("empty string is valid buildmetadata"),
78});
79pub const V161: Version = Version::new(0, 161, 0);
80
81/// Version at which `environmentd` learned
82/// `--orchestrator-kubernetes-priority-class-name`. Older images reject the
83/// unknown argument and fail to start, so the flag is only forwarded at or
84/// above this version.
85static V26_42_0: LazyLock<Version> = LazyLock::new(|| Version {
86    major: 26,
87    minor: 42,
88    patch: 0,
89    pre: Prerelease::new("dev.0").expect("dev.0 is valid prerelease"),
90    build: BuildMetadata::new("").expect("empty string is valid buildmetadata"),
91});
92
93/// Version at which `environmentd` learned
94/// `--orchestrator-kubernetes-enable-user-namespaces`. Older images reject the
95/// unknown argument and fail to start.
96static V26_50_0: LazyLock<Version> = LazyLock::new(|| Version {
97    major: 26,
98    minor: 50,
99    patch: 0,
100    pre: Prerelease::new("dev.0").expect("dev.0 is valid prerelease"),
101    build: BuildMetadata::new("").expect("empty string is valid buildmetadata"),
102});
103
104/// Version at which `environmentd` and `clusterd` learned
105/// `--additional-trust-bundle`, and `environmentd` learned
106/// `--orchestrator-kubernetes-additional-trust-bundle`. Older images reject the
107/// unknown arguments and fail to start.
108static V26_54_0: LazyLock<Version> = LazyLock::new(|| Version {
109    major: 26,
110    minor: 54,
111    patch: 0,
112    pre: Prerelease::new("dev.0").expect("dev.0 is valid prerelease"),
113    build: BuildMetadata::new("").expect("empty string is valid buildmetadata"),
114});
115
116static V26_1_0: LazyLock<Version> = LazyLock::new(|| Version {
117    major: 26,
118    minor: 1,
119    patch: 0,
120    pre: Prerelease::new("dev.0").expect("dev.0 is valid prerelease"),
121    build: BuildMetadata::new("").expect("empty string is valid buildmetadata"),
122});
123
124/// Version at which HTTP listeners moved `allowed_roles` to be per route group
125/// (the `v26_32_0::ListenersConfig` schema). Older `environmentd` parses the
126/// legacy `v0_147_0::ListenersConfig` schema, so we serve that to them.
127static PER_ROUTE_GROUP_ROLES_VERSION: LazyLock<Version> = LazyLock::new(|| Version {
128    major: 26,
129    minor: 32,
130    patch: 0,
131    pre: Prerelease::new("dev.0").expect("dev.0 is valid prerelease"),
132    build: BuildMetadata::new("").expect("empty string is valid buildmetadata"),
133});
134
135/// Describes the status of a deployment.
136///
137/// This is a simplified representation of `DeploymentState`, suitable for
138/// announcement to the external orchestrator.
139#[derive(
140    Debug,
141    Serialize,
142    Deserialize,
143    Clone,
144    Copy,
145    PartialEq,
146    Eq,
147    PartialOrd,
148    Ord
149)]
150pub enum DeploymentStatus {
151    /// This deployment is not the leader. It is initializing and is not yet
152    /// ready to become the leader.
153    Initializing,
154    /// This deployment is not the leader, but it is ready to become the leader.
155    ReadyToPromote,
156    /// This deployment is in the process of becoming the leader.
157    Promoting,
158    /// This deployment is the leader.
159    IsLeader,
160}
161
162#[derive(
163    Debug,
164    Serialize,
165    Deserialize,
166    Clone,
167    Copy,
168    PartialEq,
169    Eq,
170    PartialOrd,
171    Ord
172)]
173pub struct GetLeaderStatusResponse {
174    status: DeploymentStatus,
175}
176
177#[derive(Deserialize, Serialize)]
178pub struct LoginCredentials {
179    username: String,
180    // TODO Password type?
181    password: String,
182}
183
184#[derive(Debug, Serialize)]
185pub struct ConnectionInfo {
186    pub environmentd_url: String,
187    pub mz_system_secret_name: Option<String>,
188    pub listeners_configmap: ConfigMap,
189}
190
191#[derive(Debug, Serialize)]
192pub struct Resources {
193    pub generation: u64,
194    pub public_service: Box<Service>,
195    pub generation_service: Box<Service>,
196    pub persist_pubsub_service: Box<Service>,
197    pub environmentd_statefulset: Box<StatefulSet>,
198    pub connection_info: Box<ConnectionInfo>,
199}
200
201impl Resources {
202    pub fn new(config: &super::Config, mz: &Materialize, generation: u64) -> Result<Self, Error> {
203        let public_service = Box::new(create_public_service_object(config, mz, generation));
204        let generation_service = Box::new(create_generation_service_object(config, mz, generation));
205        let persist_pubsub_service =
206            Box::new(create_persist_pubsub_service(config, mz, generation));
207        let environmentd_statefulset = Box::new(create_environmentd_statefulset_object(
208            config, mz, generation,
209        )?);
210        let connection_info = Box::new(create_connection_info(config, mz, generation));
211
212        Ok(Self {
213            generation,
214            public_service,
215            generation_service,
216            persist_pubsub_service,
217            environmentd_statefulset,
218            connection_info,
219        })
220    }
221
222    #[instrument]
223    pub async fn apply(
224        &self,
225        client: &Client,
226        force_promote: bool,
227        namespace: &str,
228    ) -> Result<Option<Action>, Error> {
229        let service_api: Api<Service> = Api::namespaced(client.clone(), namespace);
230        let statefulset_api: Api<StatefulSet> = Api::namespaced(client.clone(), namespace);
231        let configmap_api: Api<ConfigMap> = Api::namespaced(client.clone(), namespace);
232
233        trace!("applying environmentd per-generation service");
234        apply_resource(&service_api, &*self.generation_service).await?;
235
236        trace!("creating persist pubsub service");
237        apply_resource(&service_api, &*self.persist_pubsub_service).await?;
238
239        trace!("applying listeners configmap");
240        apply_resource(&configmap_api, &self.connection_info.listeners_configmap).await?;
241
242        trace!("creating new environmentd statefulset");
243        apply_resource(&statefulset_api, &*self.environmentd_statefulset).await?;
244
245        let retry_action = Action::requeue(Duration::from_secs(rand::random_range(5..10)));
246
247        let statefulset = get_resource(
248            &statefulset_api,
249            &self.environmentd_statefulset.name_unchecked(),
250        )
251        .await?;
252        if statefulset
253            .and_then(|statefulset| statefulset.status)
254            .and_then(|status| status.ready_replicas)
255            .unwrap_or(0)
256            == 0
257        {
258            trace!("environmentd statefulset is not ready yet...");
259            return Ok(Some(retry_action));
260        }
261
262        let Some(http_client) = self.get_http_client(client.clone(), namespace).await else {
263            return Ok(Some(retry_action));
264        };
265        let status_url = reqwest::Url::parse(&format!(
266            "{}/api/leader/status",
267            self.connection_info.environmentd_url,
268        ))
269        .unwrap();
270
271        match http_client.get(status_url.clone()).send().await {
272            Ok(response) => {
273                let response: GetLeaderStatusResponse = match response.error_for_status() {
274                    Ok(response) => response.json().await?,
275                    Err(e) => {
276                        trace!("failed to get status of environmentd, retrying... ({e})");
277                        return Ok(Some(retry_action));
278                    }
279                };
280                if force_promote {
281                    self.skip_catchup(&http_client).await?;
282                } else {
283                    match response.status {
284                        DeploymentStatus::Initializing => {
285                            trace!("environmentd is still initializing, retrying...");
286                            return Ok(Some(retry_action));
287                        }
288                        DeploymentStatus::ReadyToPromote
289                        | DeploymentStatus::Promoting
290                        | DeploymentStatus::IsLeader => trace!("environmentd is ready"),
291                    }
292                }
293            }
294            Err(e) => {
295                trace!("failed to connect to environmentd, retrying... ({e})");
296                return Ok(Some(retry_action));
297            }
298        }
299
300        Ok(None)
301    }
302
303    async fn skip_catchup(&self, http_client: &HttpClient) -> Result<(), Error> {
304        trace!("skipping cluster catchup");
305        let skip_catchup_url = reqwest::Url::parse(&format!(
306            "{}/api/leader/skip-catchup",
307            self.connection_info.environmentd_url,
308        ))
309        .unwrap();
310        let response = http_client.post(skip_catchup_url).send().await?;
311        if response.status() == StatusCode::BAD_REQUEST {
312            let err: SkipCatchupError = response.json().await?;
313            return Err(anyhow::anyhow!("failed to skip catchup: {}", err.message).into());
314        }
315        Ok(())
316    }
317
318    #[instrument]
319    async fn get_http_client(&self, client: Client, namespace: &str) -> Option<HttpClient> {
320        let secret_api: Api<Secret> = Api::namespaced(client.clone(), namespace);
321        Some(match &self.connection_info.mz_system_secret_name {
322            Some(mz_system_secret_name) => {
323                let http_client = reqwest::Client::builder()
324                    .timeout(std::time::Duration::from_secs(10))
325                    .cookie_store(true)
326                    // TODO add_root_certificate instead
327                    .danger_accept_invalid_certs(true)
328                    .build()
329                    .unwrap();
330
331                let secret = secret_api
332                    .get(mz_system_secret_name)
333                    .await
334                    .map_err(|e| {
335                        error!("Failed to get backend secret: {:?}", e);
336                        e
337                    })
338                    .ok()?;
339                if let Some(data) = secret.data {
340                    if let Some(password) = data.get("external_login_password_mz_system").cloned() {
341                        let password = String::from_utf8_lossy(&password.0).to_string();
342                        let login_url = reqwest::Url::parse(&format!(
343                            "{}/api/login",
344                            self.connection_info.environmentd_url,
345                        ))
346                        .unwrap();
347                        match http_client
348                            .post(login_url)
349                            .body(
350                                serde_json::to_string(&LoginCredentials {
351                                    username: "mz_system".to_owned(),
352                                    password,
353                                })
354                                .expect(
355                                    "Serializing a simple struct with utf8 strings doesn't fail.",
356                                ),
357                            )
358                            .header("Content-Type", "application/json")
359                            .send()
360                            .await
361                        {
362                            Ok(response) => {
363                                if let Err(e) = response.error_for_status() {
364                                    trace!("failed to login to environmentd, retrying... ({e})");
365                                    return None;
366                                }
367                            }
368                            Err(e) => {
369                                trace!("failed to connect to environmentd, retrying... ({e})");
370                                return None;
371                            }
372                        };
373                    }
374                };
375                http_client
376            }
377            None => reqwest::Client::builder()
378                .timeout(std::time::Duration::from_secs(10))
379                .build()
380                .unwrap(),
381        })
382    }
383
384    #[instrument]
385    pub async fn promote_services(
386        &self,
387        client: &Client,
388        force_promote: bool,
389        namespace: &str,
390    ) -> Result<Option<Action>, Error> {
391        let service_api: Api<Service> = Api::namespaced(client.clone(), namespace);
392        let retry_action = Action::requeue(Duration::from_secs(rand::random_range(5..10)));
393
394        let promote_url = reqwest::Url::parse(&format!(
395            "{}/api/leader/promote",
396            self.connection_info.environmentd_url,
397        ))
398        .unwrap();
399
400        let Some(http_client) = self.get_http_client(client.clone(), namespace).await else {
401            return Ok(Some(retry_action));
402        };
403
404        // The skip lives in the environmentd process. If that process restarted
405        // since `apply` skipped catchup, the new one waits to catch up again and
406        // rejects promotion until `with_0dt_deployment_max_wait` elapses.
407        if force_promote {
408            self.skip_catchup(&http_client).await?;
409        }
410
411        trace!("promoting new environmentd to leader");
412        let response = http_client.post(promote_url).send().await?;
413        let response: BecomeLeaderResponse = response.error_for_status()?.json().await?;
414        if let BecomeLeaderResult::Failure { message } = response.result {
415            return Err(Error::Anyhow(anyhow::anyhow!(
416                "failed to promote new environmentd: {message}"
417            )));
418        }
419
420        // A successful POST to the promotion endpoint only indicates
421        // that the promotion process was kicked off. It does not
422        // guarantee that the environment will be successfully promoted
423        // (e.g., if the environment crashes immediately after responding
424        // to the request, but before executing the takeover, the
425        // promotion will be lost).
426        //
427        // To guarantee the environment has been promoted successfully,
428        // we must wait to see at least one `IsLeader` status returned
429        // from the environment.
430
431        let status_url = reqwest::Url::parse(&format!(
432            "{}/api/leader/status",
433            self.connection_info.environmentd_url,
434        ))
435        .unwrap();
436        match http_client.get(status_url.clone()).send().await {
437            Ok(response) => {
438                let response: GetLeaderStatusResponse = response.json().await?;
439                if response.status != DeploymentStatus::IsLeader {
440                    trace!(
441                        "environmentd is still promoting (status: {:?}), retrying...",
442                        response.status
443                    );
444                    return Ok(Some(retry_action));
445                } else {
446                    trace!("environmentd is ready");
447                }
448            }
449            Err(e) => {
450                trace!("failed to connect to environmentd, retrying... ({e})");
451                return Ok(Some(retry_action));
452            }
453        }
454
455        trace!("applying environmentd public service");
456        apply_resource(&service_api, &*self.public_service).await?;
457
458        Ok(None)
459    }
460
461    #[instrument]
462    pub async fn teardown_generation(
463        &self,
464        client: &Client,
465        mz: &Materialize,
466        generation: u64,
467    ) -> Result<(), anyhow::Error> {
468        let configmap_api: Api<ConfigMap> = Api::namespaced(client.clone(), &mz.namespace());
469        let service_api: Api<Service> = Api::namespaced(client.clone(), &mz.namespace());
470        let statefulset_api: Api<StatefulSet> = Api::namespaced(client.clone(), &mz.namespace());
471
472        trace!("deleting environmentd statefulset for generation {generation}");
473        delete_resource(
474            &statefulset_api,
475            &mz.environmentd_statefulset_name(generation),
476        )
477        .await?;
478
479        trace!("deleting persist pubsub service for generation {generation}");
480        delete_resource(&service_api, &mz.persist_pubsub_service_name(generation)).await?;
481
482        trace!("deleting environmentd per-generation service for generation {generation}");
483        delete_resource(
484            &service_api,
485            &mz.environmentd_generation_service_name(generation),
486        )
487        .await?;
488
489        trace!("deleting listeners configmap for generation {generation}");
490        delete_resource(&configmap_api, &mz.listeners_configmap_name(generation)).await?;
491
492        Ok(())
493    }
494
495    // ideally we would just be able to hash the objects directly, but the
496    // generated kubernetes objects don't implement the Hash trait
497    pub fn generate_hash(&self) -> String {
498        let mut hasher = Sha256::new();
499        hasher.update(&serde_json::to_string(self).unwrap());
500        hex::encode(hasher.finalize())
501    }
502}
503
504fn create_public_service_object(
505    config: &super::Config,
506    mz: &Materialize,
507    generation: u64,
508) -> Service {
509    let mut service = create_base_service_object(
510        config,
511        mz,
512        generation,
513        &mz.environmentd_service_name(),
514        true,
515    );
516    // Only the stable, public Service is annotated for Teleport discovery,
517    // not the per-generation Service: the agent must not see the name churn
518    // on every rollout.
519    super::teleport::apply_teleport_registration(config, mz, &mut service);
520    service
521}
522
523fn create_generation_service_object(
524    config: &super::Config,
525    mz: &Materialize,
526    generation: u64,
527) -> Service {
528    create_base_service_object(
529        config,
530        mz,
531        generation,
532        &mz.environmentd_generation_service_name(generation),
533        false,
534    )
535}
536
537fn create_base_service_object(
538    config: &super::Config,
539    mz: &Materialize,
540    generation: u64,
541    service_name: &str,
542    headless: bool,
543) -> Service {
544    let ports = vec![
545        ServicePort {
546            port: config.environmentd_sql_port.into(),
547            protocol: Some("TCP".to_string()),
548            name: Some("sql".to_string()),
549            ..Default::default()
550        },
551        ServicePort {
552            port: config.environmentd_http_port.into(),
553            protocol: Some("TCP".to_string()),
554            name: Some("https".to_string()),
555            ..Default::default()
556        },
557        ServicePort {
558            port: config.environmentd_internal_sql_port.into(),
559            protocol: Some("TCP".to_string()),
560            name: Some("internal-sql".to_string()),
561            ..Default::default()
562        },
563        ServicePort {
564            port: config.environmentd_internal_http_port.into(),
565            protocol: Some("TCP".to_string()),
566            name: Some("internal-http".to_string()),
567            ..Default::default()
568        },
569    ];
570
571    let selector = btreemap! {"materialize.cloud/name".to_string() => mz.environmentd_statefulset_name(generation)};
572
573    let spec = ServiceSpec {
574        type_: Some("ClusterIP".to_string()),
575        cluster_ip: if headless {
576            Some("None".to_string())
577        } else {
578            None
579        },
580        selector: Some(selector),
581        ports: Some(ports),
582        ..Default::default()
583    };
584
585    Service {
586        metadata: mz.managed_resource_meta(service_name.to_string()),
587        spec: Some(spec),
588        status: None,
589    }
590}
591
592fn create_persist_pubsub_service(
593    config: &super::Config,
594    mz: &Materialize,
595    generation: u64,
596) -> Service {
597    Service {
598        metadata: mz.managed_resource_meta(mz.persist_pubsub_service_name(generation)),
599        spec: Some(ServiceSpec {
600            type_: Some("ClusterIP".to_string()),
601            cluster_ip: Some("None".to_string()),
602            selector: Some(btreemap! {
603                "materialize.cloud/name".to_string() => mz.environmentd_statefulset_name(generation),
604            }),
605            ports: Some(vec![ServicePort {
606                name: Some("grpc".to_string()),
607                protocol: Some("TCP".to_string()),
608                port: config.environmentd_internal_persist_pubsub_port.into(),
609                ..Default::default()
610            }]),
611            ..Default::default()
612        }),
613        status: None,
614    }
615}
616
617fn create_environmentd_statefulset_object(
618    config: &super::Config,
619    mz: &Materialize,
620    generation: u64,
621) -> Result<StatefulSet, anyhow::Error> {
622    // IMPORTANT: Only pass secrets via environment variables. All other
623    // parameters should be passed as command line arguments, possibly gated
624    // with a `meets_minimum_version` call. This ensures typos cause
625    // `environmentd` to fail to start, rather than silently ignoring the
626    // configuration.
627    //
628    // When passing a secret, use a `SecretKeySelector` to forward a secret into
629    // the pod. Do *not* hardcode a secret as the value directly, as doing so
630    // will leak the secret to anyone with permission to describe the pod.
631    let mut env = vec![
632        EnvVar {
633            name: "MZ_METADATA_BACKEND_URL".to_string(),
634            value_from: Some(EnvVarSource {
635                secret_key_ref: Some(SecretKeySelector {
636                    name: mz.backend_secret_name(),
637                    key: "metadata_backend_url".to_string(),
638                    optional: Some(false),
639                }),
640                ..Default::default()
641            }),
642            ..Default::default()
643        },
644        EnvVar {
645            name: "MZ_PERSIST_BLOB_URL".to_string(),
646            value_from: Some(EnvVarSource {
647                secret_key_ref: Some(SecretKeySelector {
648                    name: mz.backend_secret_name(),
649                    key: "persist_backend_url".to_string(),
650                    optional: Some(false),
651                }),
652                ..Default::default()
653            }),
654            ..Default::default()
655        },
656    ];
657
658    env.push(EnvVar {
659        name: "AWS_REGION".to_string(),
660        value: Some(config.region.clone()),
661        ..Default::default()
662    });
663
664    env.extend(mz.spec.environmentd_extra_env.iter().flatten().cloned());
665
666    let mut args = vec![];
667
668    if let Some(helm_chart_version) = &config.helm_chart_version {
669        args.push(format!("--helm-chart-version={helm_chart_version}"));
670    }
671
672    // Add environment ID argument.
673    args.push(format!(
674        "--environment-id={}",
675        mz.environment_id(&config.cloud_provider.to_string(), &config.region)
676    ));
677
678    // Add clusterd image argument based on environmentd tag.
679    args.push(format!(
680        "--clusterd-image={}",
681        matching_image_from_environmentd_image_ref(
682            &mz.spec.environmentd_image_ref,
683            "clusterd",
684            None
685        )
686    ));
687
688    // Add cluster and storage host size arguments.
689    args.extend(
690        [
691            config
692                .environmentd_cluster_replica_sizes
693                .as_ref()
694                .map(|sizes| format!("--cluster-replica-sizes={sizes}")),
695            config
696                .bootstrap_default_cluster_replica_size
697                .as_ref()
698                .map(|size| format!("--bootstrap-default-cluster-replica-size={size}")),
699            config
700                .bootstrap_builtin_system_cluster_replica_size
701                .as_ref()
702                .map(|size| format!("--bootstrap-builtin-system-cluster-replica-size={size}")),
703            config
704                .bootstrap_builtin_probe_cluster_replica_size
705                .as_ref()
706                .map(|size| format!("--bootstrap-builtin-probe-cluster-replica-size={size}")),
707            config
708                .bootstrap_builtin_support_cluster_replica_size
709                .as_ref()
710                .map(|size| format!("--bootstrap-builtin-support-cluster-replica-size={size}")),
711            config
712                .bootstrap_builtin_catalog_server_cluster_replica_size
713                .as_ref()
714                .map(|size| format!("--bootstrap-builtin-catalog-server-cluster-replica-size={size}")),
715            config
716                .bootstrap_builtin_analytics_cluster_replica_size
717                .as_ref()
718                .map(|size| format!("--bootstrap-builtin-analytics-cluster-replica-size={size}")),
719            config
720                .bootstrap_builtin_system_cluster_replication_factor
721                .as_ref()
722                .map(|replication_factor| {
723                    format!("--bootstrap-builtin-system-cluster-replication-factor={replication_factor}")
724                }),
725            config
726                .bootstrap_builtin_probe_cluster_replication_factor
727                .as_ref()
728                .map(|replication_factor| format!("--bootstrap-builtin-probe-cluster-replication-factor={replication_factor}")),
729            config
730                .bootstrap_builtin_support_cluster_replication_factor
731                .as_ref()
732                .map(|replication_factor| format!("--bootstrap-builtin-support-cluster-replication-factor={replication_factor}")),
733            config
734                .bootstrap_builtin_analytics_cluster_replication_factor
735                .as_ref()
736                .map(|replication_factor| format!("--bootstrap-builtin-analytics-cluster-replication-factor={replication_factor}")),
737        ]
738        .into_iter()
739        .flatten(),
740    );
741
742    args.extend(
743        config
744            .environmentd_allowed_origins
745            .iter()
746            .map(|origin| format!("--cors-allowed-origin={}", origin.to_str().unwrap())),
747    );
748
749    args.push(format!(
750        "--secrets-controller={}",
751        config.secrets_controller
752    ));
753
754    if let Some(cluster_replica_sizes) = &config.environmentd_cluster_replica_sizes {
755        if let Ok(cluster_replica_sizes) =
756            serde_json::from_str::<BTreeMap<String, serde_json::Value>>(cluster_replica_sizes)
757        {
758            let cluster_replica_sizes: Vec<_> =
759                cluster_replica_sizes.keys().map(|s| s.as_str()).collect();
760            args.push(format!(
761                "--system-parameter-default=allowed_cluster_replica_sizes='{}'",
762                cluster_replica_sizes.join("', '")
763            ));
764        }
765    }
766    if !config.cloud_provider.is_cloud() {
767        args.push("--system-parameter-default=cluster_enable_topology_spread=false".into());
768    }
769
770    if config.enable_internal_statement_logging {
771        args.push("--system-parameter-default=enable_internal_statement_logging=true".into());
772    }
773
774    if let Some(rate) = config.statement_logging_max_sample_rate {
775        args.push(format!(
776            "--system-parameter-default=statement_logging_max_sample_rate={rate}"
777        ));
778    }
779
780    if let Some(rate) = config.statement_logging_target_data_rate {
781        args.push(format!(
782            "--system-parameter-default=statement_logging_target_data_rate={rate}"
783        ));
784    }
785
786    if !mz.spec.enable_rbac {
787        args.push("--system-parameter-default=enable_rbac_checks=false".into());
788    }
789
790    if config.disable_database_network_policies {
791        args.push("--system-parameter-default=enable_network_policies=false".into());
792    }
793
794    // Add persist arguments.
795
796    // Configure the Persist Isolated Runtime to use one less thread than the total available.
797    args.push("--persist-isolated-runtime-threads=-1".to_string());
798
799    // Add AWS arguments.
800    if config.cloud_provider == CloudProvider::Aws {
801        if let Some(azs) = config.environmentd_availability_zones.as_ref() {
802            for az in azs {
803                args.push(format!("--availability-zone={az}"));
804            }
805        }
806
807        if let Some(environmentd_connection_role_arn) = mz
808            .spec
809            .environmentd_connection_role_arn
810            .as_deref()
811            .or(config.environmentd_connection_role_arn.as_deref())
812        {
813            args.push(format!(
814                "--aws-connection-role-arn={}",
815                environmentd_connection_role_arn
816            ));
817        }
818        if let Some(account_id) = &config.aws_account_id {
819            args.push(format!("--aws-account-id={account_id}"));
820        }
821
822        args.extend([format!(
823            "--aws-secrets-controller-tags=Environment={}",
824            mz.name_unchecked()
825        )]);
826        args.extend_from_slice(&config.aws_secrets_controller_tags);
827    }
828
829    // Add Kubernetes arguments.
830    args.extend([
831        "--orchestrator=kubernetes".into(),
832        format!(
833            "--orchestrator-kubernetes-service-account={}",
834            mz.service_account_name()
835        ),
836        format!(
837            "--orchestrator-kubernetes-image-pull-policy={}",
838            config.image_pull_policy.as_kebab_case_str(),
839        ),
840    ]);
841    for selector in &config.clusterd_node_selector {
842        args.push(format!(
843            "--orchestrator-kubernetes-service-node-selector={}={}",
844            selector.key, selector.value,
845        ));
846    }
847    if mz.meets_minimum_version(&V144) {
848        if let Some(affinity) = &config.clusterd_affinity {
849            let affinity = serde_json::to_string(affinity).unwrap();
850            args.push(format!(
851                "--orchestrator-kubernetes-service-affinity={affinity}"
852            ))
853        }
854        if let Some(tolerations) = &config.clusterd_tolerations {
855            let tolerations = serde_json::to_string(tolerations).unwrap();
856            args.push(format!(
857                "--orchestrator-kubernetes-service-tolerations={tolerations}"
858            ))
859        }
860    }
861    if let Some(scheduler_name) = &config.scheduler_name {
862        args.push(format!(
863            "--orchestrator-kubernetes-scheduler-name={}",
864            scheduler_name
865        ));
866    }
867    if mz.meets_minimum_version(&V26_42_0) {
868        if let Some(priority_class_name) = &config.clusterd_priority_class_name {
869            args.push(format!(
870                "--orchestrator-kubernetes-priority-class-name={priority_class_name}"
871            ));
872        }
873    }
874    if mz.meets_minimum_version(&V154_DEV0) {
875        args.extend(
876            mz.spec
877                .pod_annotations
878                .as_ref()
879                .map(|annotations| annotations.iter())
880                .unwrap_or_default()
881                .map(|(key, val)| {
882                    format!("--orchestrator-kubernetes-service-annotation={key}={val}")
883                }),
884        );
885    }
886    args.extend(
887        mz.default_labels()
888            .iter()
889            .chain(
890                mz.spec
891                    .pod_labels
892                    .as_ref()
893                    .map(|labels| labels.iter())
894                    .unwrap_or_default(),
895            )
896            .map(|(key, val)| format!("--orchestrator-kubernetes-service-label={key}={val}")),
897    );
898    if let Some(status) = &mz.status {
899        args.push(format!(
900            "--orchestrator-kubernetes-name-prefix=mz{}-",
901            status.resource_id
902        ));
903    }
904
905    // Add logging and tracing arguments.
906    args.extend(["--log-format=json".into()]);
907    if let Some(endpoint) = &config.tracing.opentelemetry_endpoint {
908        args.push(format!("--opentelemetry-endpoint={}", endpoint));
909    }
910    // --opentelemetry-resource also configures sentry tags
911    args.extend([
912        format!(
913            "--opentelemetry-resource=organization_id={}",
914            mz.spec.environment_id
915        ),
916        format!(
917            "--opentelemetry-resource=environment_name={}",
918            mz.name_unchecked()
919        ),
920    ]);
921
922    if let Some(segment_api_key) = &config.segment_api_key {
923        args.push(format!("--segment-api-key={}", segment_api_key));
924        if config.segment_client_side {
925            args.push("--segment-client-side".into());
926        }
927    }
928
929    let mut volumes = Vec::new();
930    let mut volume_mounts = Vec::new();
931    if issuer_ref_defined(
932        &config.default_certificate_specs.internal,
933        &mz.spec.internal_certificate_spec,
934    ) {
935        volumes.push(Volume {
936            name: "certificate".to_owned(),
937            secret: Some(SecretVolumeSource {
938                default_mode: Some(0o400),
939                secret_name: Some(mz.environmentd_certificate_secret_name()),
940                items: None,
941                optional: Some(false),
942            }),
943            ..Default::default()
944        });
945        volume_mounts.push(VolumeMount {
946            name: "certificate".to_owned(),
947            mount_path: "/etc/materialized".to_owned(),
948            read_only: Some(true),
949            ..Default::default()
950        });
951        args.extend([
952            "--tls-mode=require".into(),
953            "--tls-cert=/etc/materialized/tls.crt".into(),
954            "--tls-key=/etc/materialized/tls.key".into(),
955        ]);
956    } else {
957        args.push("--tls-mode=disable".to_string());
958    }
959    if let Some(ephemeral_volume_class) = &config.ephemeral_volume_class {
960        args.push(format!(
961            "--orchestrator-kubernetes-ephemeral-volume-class={}",
962            ephemeral_volume_class
963        ));
964    }
965    // The `materialize` user used by clusterd always has gid 999.
966    args.push("--orchestrator-kubernetes-service-fs-group=999".to_string());
967
968    // Add system_param configmap
969    // This feature was enabled in 0.163 but did not have testing until after 0.164.
970    // 0.165 should work with anything greater than 0.164 including v26 and v25.
971    if mz.meets_minimum_version(&V26_1_0) {
972        if let Some(ref name) = mz.spec.system_parameter_configmap_name {
973            volumes.push(Volume {
974                name: "system-params".to_string(),
975                config_map: Some(ConfigMapVolumeSource {
976                    default_mode: Some(0o400),
977                    name: name.to_owned(),
978                    items: None,
979                    optional: Some(true),
980                }),
981                ..Default::default()
982            });
983            volume_mounts.push(VolumeMount {
984                name: "system-params".to_string(),
985                // The user must write to the `system-params.json` entry in the config map
986                mount_path: "/system-params".to_owned(),
987                read_only: Some(true),
988                ..Default::default()
989            });
990            args.push("--config-sync-file-path=/system-params/system-params.json".to_string());
991            args.push("--config-sync-loop-interval=1s".to_string());
992        }
993    }
994
995    if let Some((volume, volume_mount, bundle_args)) = additional_trust_bundle_args(mz)? {
996        volumes.push(volume);
997        volume_mounts.push(volume_mount);
998        args.extend(bundle_args);
999    }
1000
1001    // Add Sentry arguments.
1002    if let Some(sentry_dsn) = &config.tracing.sentry_dsn {
1003        args.push(format!("--sentry-dsn={}", sentry_dsn));
1004        if let Some(sentry_environment) = &config.tracing.sentry_environment {
1005            args.push(format!("--sentry-environment={}", sentry_environment));
1006        }
1007        args.push(format!("--sentry-tag=region={}", config.region));
1008    }
1009
1010    // Add Persist PubSub arguments
1011    args.push(format!(
1012        "--persist-pubsub-url=http://{}:{}",
1013        mz.persist_pubsub_service_name(generation),
1014        config.environmentd_internal_persist_pubsub_port,
1015    ));
1016    args.push(format!(
1017        "--internal-persist-pubsub-listen-addr=0.0.0.0:{}",
1018        config.environmentd_internal_persist_pubsub_port
1019    ));
1020
1021    args.push(format!("--deploy-generation={}", generation));
1022
1023    // Add URL for internal user impersonation endpoint
1024    args.push(format!(
1025        "--internal-console-redirect-url={}",
1026        config.internal_console_proxy_url,
1027    ));
1028
1029    if !config.collect_pod_metrics {
1030        args.push("--orchestrator-kubernetes-disable-pod-metrics-collection".into());
1031    }
1032    if config.enable_prometheus_scrape_annotations {
1033        args.push("--orchestrator-kubernetes-enable-prometheus-scrape-annotations".into());
1034    }
1035    // Older environmentd images reject the unknown argument, so their clusterd
1036    // pods keep running in the host user namespace.
1037    if config.enable_user_namespaces && mz.meets_minimum_version(&V26_50_0) {
1038        args.push("--orchestrator-kubernetes-enable-user-namespaces".into());
1039    }
1040
1041    // the --disable-license-key-checks environmentd flag only existed
1042    // between these versions
1043    if config.disable_license_key_checks {
1044        if mz.meets_minimum_version(&V143) && !mz.meets_minimum_version(&V153) {
1045            args.push("--disable-license-key-checks".into());
1046        }
1047    }
1048
1049    // as of version 0.153, the ability to disable license key checks was
1050    // removed, so we should always set up license keys in that case
1051    if (mz.meets_minimum_version(&V140_DEV0) && !config.disable_license_key_checks)
1052        || mz.meets_minimum_version(&V153)
1053    {
1054        volume_mounts.push(VolumeMount {
1055            name: "license-key".to_string(),
1056            mount_path: "/license_key".to_string(),
1057            ..Default::default()
1058        });
1059        volumes.push(Volume {
1060            name: "license-key".to_string(),
1061            secret: Some(SecretVolumeSource {
1062                default_mode: Some(256),
1063                optional: Some(false),
1064                secret_name: Some(mz.backend_secret_name()),
1065                items: Some(vec![KeyToPath {
1066                    key: "license_key".to_string(),
1067                    path: "license_key".to_string(),
1068                    ..Default::default()
1069                }]),
1070                ..Default::default()
1071            }),
1072            ..Default::default()
1073        });
1074        env.push(EnvVar {
1075            name: "MZ_LICENSE_KEY".to_string(),
1076            value: Some("/license_key/license_key".to_string()),
1077            ..Default::default()
1078        });
1079    }
1080
1081    // Add user-specified extra arguments.
1082    if let Some(extra_args) = &mz.spec.environmentd_extra_args {
1083        args.extend(extra_args.iter().cloned());
1084    }
1085
1086    // NOTE: environmentd binds its SQL listeners before booting but only
1087    // accepts once boot completes, so connections queue in the kernel until
1088    // then. balancerd and clients use the external SQL port and can fill its
1089    // queue, after which TCP probes against it time out and liveness kills the
1090    // pod mid-boot. Probing the internal port keeps client traffic out of the
1091    // probes' queue. Some authenticator kinds have no internal SQL listener,
1092    // and probing an unbound port fails every check, so fall back to the
1093    // external one.
1094    let listeners_config = create_v0_147_0_listeners_config(config, mz);
1095    let probe_port = listeners_config
1096        .sql
1097        .get("internal")
1098        .or_else(|| listeners_config.sql.get("external"))
1099        .expect("external SQL listener is always configured")
1100        .addr
1101        .port();
1102    let base_probe = Probe {
1103        initial_delay_seconds: Some(1),
1104        failure_threshold: Some(12),
1105        tcp_socket: Some(TCPSocketAction {
1106            host: None,
1107            port: IntOrString::Int(probe_port.into()),
1108        }),
1109        ..Default::default()
1110    };
1111    let readiness_probe = environmentd_probe(
1112        base_probe.clone(),
1113        config.environmentd_default_readiness_probe.as_ref(),
1114        mz.spec.environmentd_readiness_probe.as_ref(),
1115    );
1116    let liveness_probe = environmentd_probe(
1117        base_probe.clone(),
1118        config.environmentd_default_liveness_probe.as_ref(),
1119        mz.spec.environmentd_liveness_probe.as_ref(),
1120    );
1121    // Unlike readiness and liveness, environmentd has no startup probe unless
1122    // one is configured.
1123    let startup_probe = (config.environmentd_default_startup_probe.is_some()
1124        || mz.spec.environmentd_startup_probe.is_some())
1125    .then(|| {
1126        environmentd_probe(
1127            base_probe,
1128            config.environmentd_default_startup_probe.as_ref(),
1129            mz.spec.environmentd_startup_probe.as_ref(),
1130        )
1131    });
1132
1133    let mut security_context = if config.enable_security_context {
1134        // Since we want to adhere to the most restrictive security context, all
1135        // of these fields have to be set how they are.
1136        // See https://kubernetes.io/docs/concepts/security/pod-security-standards/#restricted
1137        Some(SecurityContext {
1138            run_as_non_root: Some(true),
1139            capabilities: Some(Capabilities {
1140                drop: Some(vec!["ALL".to_string()]),
1141                ..Default::default()
1142            }),
1143            seccomp_profile: Some(SeccompProfile {
1144                type_: "RuntimeDefault".to_string(),
1145                ..Default::default()
1146            }),
1147            allow_privilege_escalation: Some(false),
1148            ..Default::default()
1149        })
1150    } else {
1151        None
1152    };
1153    if let Some(ctx) = &mut security_context {
1154        ctx.read_only_root_filesystem = Some(true);
1155        // `/tmp` holds SSH tunnel keys, heap profile dumps and, through
1156        // `XDG_STATE_HOME`, the SSH control sockets openssh would otherwise put
1157        // under `$HOME`. Server-side apply rejects duplicate names, so an
1158        // `environmentdExtraEnv` value wins.
1159        if !env.iter().any(|e| e.name == "XDG_STATE_HOME") {
1160            env.push(EnvVar {
1161                name: "XDG_STATE_HOME".to_string(),
1162                value: Some("/tmp".to_string()),
1163                ..Default::default()
1164            });
1165        }
1166        volume_mounts.push(VolumeMount {
1167            name: "tmp".to_string(),
1168            mount_path: "/tmp".to_string(),
1169            ..Default::default()
1170        });
1171        volumes.push(Volume {
1172            name: "tmp".to_string(),
1173            empty_dir: Some(EmptyDirVolumeSource::default()),
1174            ..Default::default()
1175        });
1176    }
1177
1178    let ports = vec![
1179        ContainerPort {
1180            container_port: config.environmentd_sql_port.into(),
1181            name: Some("sql".to_owned()),
1182            ..Default::default()
1183        },
1184        ContainerPort {
1185            container_port: config.environmentd_internal_sql_port.into(),
1186            name: Some("internal-sql".to_owned()),
1187            ..Default::default()
1188        },
1189        ContainerPort {
1190            container_port: config.environmentd_http_port.into(),
1191            name: Some("http".to_owned()),
1192            ..Default::default()
1193        },
1194        ContainerPort {
1195            container_port: config.environmentd_internal_http_port.into(),
1196            name: Some("internal-http".to_owned()),
1197            ..Default::default()
1198        },
1199        ContainerPort {
1200            container_port: config.environmentd_internal_persist_pubsub_port.into(),
1201            name: Some("persist-pubsub".to_owned()),
1202            ..Default::default()
1203        },
1204    ];
1205
1206    // Add networking arguments.
1207    if mz.meets_minimum_version(&V147_DEV0) {
1208        volume_mounts.push(VolumeMount {
1209            name: "listeners-configmap".to_string(),
1210            mount_path: "/listeners".to_string(),
1211            ..Default::default()
1212        });
1213        volumes.push(Volume {
1214            name: "listeners-configmap".to_string(),
1215            config_map: Some(ConfigMapVolumeSource {
1216                name: mz.listeners_configmap_name(generation),
1217                default_mode: Some(256),
1218                optional: Some(false),
1219                items: Some(vec![KeyToPath {
1220                    key: "listeners.json".to_string(),
1221                    path: "listeners.json".to_string(),
1222                    ..Default::default()
1223                }]),
1224            }),
1225            ..Default::default()
1226        });
1227        args.push("--listeners-config-path=/listeners/listeners.json".to_owned());
1228        if matches!(
1229            mz.spec.authenticator_kind,
1230            AuthenticatorKind::Password | AuthenticatorKind::Sasl | AuthenticatorKind::Oidc
1231        ) {
1232            args.push("--system-parameter-default=enable_password_auth=true".into());
1233            env.push(EnvVar {
1234                name: "MZ_EXTERNAL_LOGIN_PASSWORD_MZ_SYSTEM".to_string(),
1235                value_from: Some(EnvVarSource {
1236                    secret_key_ref: Some(SecretKeySelector {
1237                        name: mz.backend_secret_name(),
1238                        key: "external_login_password_mz_system".to_string(),
1239                        optional: Some(false),
1240                    }),
1241                    ..Default::default()
1242                }),
1243                ..Default::default()
1244            })
1245        }
1246    } else {
1247        args.extend([
1248            format!("--sql-listen-addr=0.0.0.0:{}", config.environmentd_sql_port),
1249            format!(
1250                "--http-listen-addr=0.0.0.0:{}",
1251                config.environmentd_http_port
1252            ),
1253            format!(
1254                "--internal-sql-listen-addr=0.0.0.0:{}",
1255                config.environmentd_internal_sql_port
1256            ),
1257            format!(
1258                "--internal-http-listen-addr=0.0.0.0:{}",
1259                config.environmentd_internal_http_port
1260            ),
1261        ]);
1262    }
1263
1264    let container = Container {
1265        name: "environmentd".to_owned(),
1266        image: Some(mz.spec.environmentd_image_ref.to_owned()),
1267        image_pull_policy: Some(config.image_pull_policy.to_string()),
1268        ports: Some(ports),
1269        args: Some(args),
1270        env: Some(env),
1271        volume_mounts: Some(volume_mounts),
1272        startup_probe,
1273        liveness_probe: Some(liveness_probe),
1274        readiness_probe: Some(readiness_probe),
1275        resources: mz
1276            .spec
1277            .environmentd_resource_requirements
1278            .clone()
1279            .or_else(|| config.environmentd_default_resources.clone()),
1280        security_context,
1281        ..Default::default()
1282    };
1283
1284    let mut pod_template_labels = mz.default_labels();
1285    pod_template_labels.insert(
1286        "materialize.cloud/name".to_owned(),
1287        mz.environmentd_statefulset_name(generation),
1288    );
1289    pod_template_labels.insert(
1290        "materialize.cloud/app".to_owned(),
1291        mz.environmentd_app_name(),
1292    );
1293    pod_template_labels.extend(recommended_k8s_labels("environmentd".into()));
1294    pod_template_labels.extend(
1295        mz.spec
1296            .pod_labels
1297            .as_ref()
1298            .map(|labels| labels.iter())
1299            .unwrap_or_default()
1300            .map(|(key, value)| (key.clone(), value.clone())),
1301    );
1302
1303    let mut pod_template_annotations = btreemap! {
1304        // We can re-enable eviction once we have HA
1305        "cluster-autoscaler.kubernetes.io/safe-to-evict".to_owned() => "false".to_string(),
1306
1307        // Prevents old (< 0.30) and new versions of karpenter from evicting database pods
1308        "karpenter.sh/do-not-evict".to_owned() => "true".to_string(),
1309        "karpenter.sh/do-not-disrupt".to_owned() => "true".to_string(),
1310        "materialize.cloud/generation".to_owned() => generation.to_string(),
1311    };
1312    if config.enable_prometheus_scrape_annotations {
1313        pod_template_annotations.insert("prometheus.io/scrape".to_owned(), "true".to_string());
1314        pod_template_annotations.insert(
1315            "prometheus.io/port".to_owned(),
1316            config.environmentd_internal_http_port.to_string(),
1317        );
1318        pod_template_annotations.insert("prometheus.io/path".to_owned(), "/metrics".to_string());
1319        pod_template_annotations.insert("prometheus.io/scheme".to_owned(), "http".to_string());
1320        pod_template_annotations.insert(
1321            "materialize.prometheus.io/mz_usage_path".to_owned(),
1322            "/metrics/mz_usage".to_string(),
1323        );
1324        pod_template_annotations.insert(
1325            "materialize.prometheus.io/mz_frontier_path".to_owned(),
1326            "/metrics/mz_frontier".to_string(),
1327        );
1328        pod_template_annotations.insert(
1329            "materialize.prometheus.io/mz_compute_path".to_owned(),
1330            "/metrics/mz_compute".to_string(),
1331        );
1332        pod_template_annotations.insert(
1333            "materialize.prometheus.io/mz_storage_path".to_owned(),
1334            "/metrics/mz_storage".to_string(),
1335        );
1336    }
1337    pod_template_annotations.extend(
1338        mz.spec
1339            .pod_annotations
1340            .as_ref()
1341            .map(|annotations| annotations.iter())
1342            .unwrap_or_default()
1343            .map(|(key, value)| (key.clone(), value.clone())),
1344    );
1345
1346    let mut tolerations = vec![
1347        // When the node becomes `NotReady` it indicates there is a problem with the node,
1348        // By default kubernetes waits 300s (5 minutes) before doing anything in this case,
1349        // But we want to limit this to 30s for faster recovery
1350        Toleration {
1351            effect: Some("NoExecute".into()),
1352            key: Some("node.kubernetes.io/not-ready".into()),
1353            operator: Some("Exists".into()),
1354            toleration_seconds: Some(30),
1355            value: None,
1356        },
1357        Toleration {
1358            effect: Some("NoExecute".into()),
1359            key: Some("node.kubernetes.io/unreachable".into()),
1360            operator: Some("Exists".into()),
1361            toleration_seconds: Some(30),
1362            value: None,
1363        },
1364    ];
1365    if let Some(user_tolerations) = &config.environmentd_tolerations {
1366        tolerations.extend(user_tolerations.iter().cloned());
1367    }
1368    let tolerations = Some(tolerations);
1369
1370    let pod_template_spec = PodTemplateSpec {
1371        // not using managed_resource_meta because the pod should be owned
1372        // by the statefulset, not the materialize instance
1373        metadata: Some(ObjectMeta {
1374            labels: Some(pod_template_labels),
1375            annotations: Some(pod_template_annotations), // This is inserted into later, do not delete.
1376            ..Default::default()
1377        }),
1378        spec: Some(PodSpec {
1379            containers: vec![container],
1380            node_selector: Some(
1381                config
1382                    .environmentd_node_selector
1383                    .iter()
1384                    .map(|selector| (selector.key.clone(), selector.value.clone()))
1385                    .collect(),
1386            ),
1387            affinity: config.environmentd_affinity.clone(),
1388            scheduler_name: config.scheduler_name.clone(),
1389            priority_class_name: config.environmentd_priority_class_name.clone(),
1390            service_account_name: Some(mz.service_account_name()),
1391            volumes: Some(volumes),
1392            security_context: Some(PodSecurityContext {
1393                fs_group: Some(999),
1394                run_as_user: Some(999),
1395                run_as_group: Some(999),
1396                ..Default::default()
1397            }),
1398            // `None` rather than `Some(true)` when disabled, so the pod spec
1399            // (and therefore the generation's resource hash) is unchanged from
1400            // before user namespace support.
1401            host_users: config.enable_user_namespaces.then_some(false),
1402            tolerations,
1403            // This (apparently) has the side effect of automatically starting a new pod
1404            // when the previous pod is currently terminating. This side steps the statefulset fencing
1405            // but allows for quicker recovery from a failed node
1406            // The Kubernetes documentation strongly advises against this
1407            // setting, as StatefulSets attempt to provide "at most once"
1408            // semantics [0]-- that is, the guarantee that for a given pod in a
1409            // StatefulSet there is *at most* one pod with that identity running
1410            // in the cluster
1411            //
1412            // Materialize, however, has been carefully designed to *not* rely
1413            // on this guarantee. (In fact, we do not believe that correct
1414            // distributed systems can meaningfully rely on Kubernetes's
1415            // guarantee--network packets from a pod can be arbitrarily delayed,
1416            // long past that pod's termination.) Running two `environmentd`
1417            // processes is safe: the newer process will safely and correctly
1418            // fence out the older process via CockroachDB. In the future,
1419            // we'll support running multiple `environmentd` processes in
1420            // parallel for high availability.
1421            //
1422            // [0]: https://kubernetes.io/docs/tasks/run-application/force-delete-stateful-set-pod/#statefulset-considerations
1423            termination_grace_period_seconds: Some(0),
1424            ..Default::default()
1425        }),
1426    };
1427
1428    let mut match_labels = BTreeMap::new();
1429    match_labels.insert(
1430        "materialize.cloud/name".to_owned(),
1431        mz.environmentd_statefulset_name(generation),
1432    );
1433
1434    let statefulset_spec = StatefulSetSpec {
1435        replicas: Some(1),
1436        template: pod_template_spec,
1437        service_name: Some(mz.environmentd_service_name()),
1438        selector: LabelSelector {
1439            match_expressions: None,
1440            match_labels: Some(match_labels),
1441        },
1442        ..Default::default()
1443    };
1444
1445    Ok(StatefulSet {
1446        metadata: ObjectMeta {
1447            annotations: Some(btreemap! {
1448                "materialize.cloud/generation".to_owned() => generation.to_string(),
1449                "materialize.cloud/force".to_owned() => mz.force_rollout_value(),
1450            }),
1451            ..mz.managed_resource_meta(mz.environmentd_statefulset_name(generation))
1452        },
1453        spec: Some(statefulset_spec),
1454        status: None,
1455    })
1456}
1457
1458/// The volume, mount and `environmentd` arguments that make `environmentd` and
1459/// its `clusterd` pods trust `additionalTrustBundle`, if it is set.
1460fn additional_trust_bundle_args(
1461    mz: &Materialize,
1462) -> Result<Option<(Volume, VolumeMount, Vec<String>)>, anyhow::Error> {
1463    let Some(bundle) = &mz.spec.additional_trust_bundle else {
1464        return Ok(None);
1465    };
1466    if !mz.meets_minimum_version(&V26_54_0) {
1467        anyhow::bail!(
1468            "additionalTrustBundle requires environmentd v{}.{}.{} or later",
1469            V26_54_0.major,
1470            V26_54_0.minor,
1471            V26_54_0.patch,
1472        );
1473    }
1474    let (volume, volume_mount) =
1475        additional_trust_bundle_volume(bundle).context("invalid additionalTrustBundle")?;
1476    let args = vec![
1477        format!(
1478            "--additional-trust-bundle={ADDITIONAL_TRUST_BUNDLE_DIR}/{ADDITIONAL_TRUST_BUNDLE_FILE}"
1479        ),
1480        format!(
1481            "--orchestrator-kubernetes-additional-trust-bundle={}",
1482            serde_json::to_string(bundle)?
1483        ),
1484    ];
1485    Ok(Some((volume, volume_mount, args)))
1486}
1487
1488/// Rejects a probe that sets more than one handler (`exec`, `grpc`, `httpGet`,
1489/// `tcpSocket`), which Kubernetes would reject when the pod is created.
1490///
1491/// `environmentd_probe` only produces a valid probe if every layer passes
1492/// this check.
1493pub fn validate_probe_handlers(probe: &Probe) -> Result<(), anyhow::Error> {
1494    let handlers: Vec<_> = [
1495        ("exec", probe.exec.is_some()),
1496        ("grpc", probe.grpc.is_some()),
1497        ("httpGet", probe.http_get.is_some()),
1498        ("tcpSocket", probe.tcp_socket.is_some()),
1499    ]
1500    .into_iter()
1501    .filter_map(|(name, set)| set.then_some(name))
1502    .collect();
1503    if handlers.len() > 1 {
1504        anyhow::bail!(
1505            "probe sets more than one handler ({}), but at most one is allowed",
1506            handlers.join(", ")
1507        );
1508    }
1509    Ok(())
1510}
1511
1512/// Layers the operator-wide default and then the per-environment override onto
1513/// `base`, so each layer only has to set the fields it changes.
1514///
1515/// Fields set in a later layer win. The handler (`exec`, `grpc`, `httpGet`,
1516/// `tcpSocket`) is replaced as a unit when a later layer sets any of them,
1517/// because Kubernetes rejects a probe with more than one handler.
1518fn environmentd_probe(
1519    base: Probe,
1520    operator_default: Option<&Probe>,
1521    environment_override: Option<&Probe>,
1522) -> Probe {
1523    [operator_default, environment_override]
1524        .into_iter()
1525        .flatten()
1526        .fold(base, overlay_probe)
1527}
1528
1529fn overlay_probe(base: Probe, overlay: &Probe) -> Probe {
1530    // Exhaustive so that a new `Probe` field fails to compile here instead of
1531    // being silently dropped.
1532    let Probe {
1533        exec,
1534        failure_threshold,
1535        grpc,
1536        http_get,
1537        initial_delay_seconds,
1538        period_seconds,
1539        success_threshold,
1540        tcp_socket,
1541        termination_grace_period_seconds,
1542        timeout_seconds,
1543    } = overlay.clone();
1544    let has_handler =
1545        exec.is_some() || grpc.is_some() || http_get.is_some() || tcp_socket.is_some();
1546    let (exec, grpc, http_get, tcp_socket) = if has_handler {
1547        (exec, grpc, http_get, tcp_socket)
1548    } else {
1549        (base.exec, base.grpc, base.http_get, base.tcp_socket)
1550    };
1551    Probe {
1552        exec,
1553        failure_threshold: failure_threshold.or(base.failure_threshold),
1554        grpc,
1555        http_get,
1556        initial_delay_seconds: initial_delay_seconds.or(base.initial_delay_seconds),
1557        period_seconds: period_seconds.or(base.period_seconds),
1558        success_threshold: success_threshold.or(base.success_threshold),
1559        tcp_socket,
1560        termination_grace_period_seconds: termination_grace_period_seconds
1561            .or(base.termination_grace_period_seconds),
1562        timeout_seconds: timeout_seconds.or(base.timeout_seconds),
1563    }
1564}
1565
1566fn create_v0_147_0_listeners_config(
1567    config: &super::Config,
1568    mz: &Materialize,
1569) -> v0_147_0::ListenersConfig {
1570    let external_enable_tls = issuer_ref_defined(
1571        &config.default_certificate_specs.internal,
1572        &mz.spec.internal_certificate_spec,
1573    );
1574    let authenticator_kind = mz.spec.authenticator_kind;
1575
1576    let mut listeners_config = v0_147_0::ListenersConfig {
1577        sql: btreemap! {
1578            "external".to_owned() => SqlListenerConfig{
1579                addr: SocketAddr::new(
1580                    IpAddr::V4(Ipv4Addr::new(0,0,0,0)),
1581                    config.environmentd_sql_port,
1582                ),
1583                authenticator_kind,
1584                allowed_roles: AllowedRoles::Normal,
1585                enable_tls: external_enable_tls,
1586            },
1587            "internal".to_owned() => SqlListenerConfig{
1588                addr: SocketAddr::new(
1589                    IpAddr::V4(Ipv4Addr::new(0,0,0,0)),
1590                    config.environmentd_internal_sql_port,
1591                ),
1592                authenticator_kind: AuthenticatorKind::None,
1593                // Should this just be Internal?
1594                allowed_roles: AllowedRoles::NormalAndInternal,
1595                enable_tls: false,
1596            },
1597        },
1598        http: btreemap! {
1599            "external".to_owned() => v0_147_0::HttpListenerConfig{
1600                base: BaseListenerConfig {
1601                    addr: SocketAddr::new(
1602                        IpAddr::V4(Ipv4Addr::new(0,0,0,0)),
1603                        config.environmentd_http_port,
1604                    ),
1605                    // SASL authentication is only supported for SQL (PostgreSQL wire protocol).
1606                    // HTTP listeners must use Password authentication when SASL is enabled.
1607                    // This is validated at environmentd startup via ListenerConfig::validate().
1608                    authenticator_kind: if authenticator_kind == AuthenticatorKind::Sasl {
1609                        AuthenticatorKind::Password
1610                    } else {
1611                        authenticator_kind
1612                    },
1613                    allowed_roles: AllowedRoles::Normal,
1614                    enable_tls: external_enable_tls,
1615                },
1616                routes: v0_147_0::HttpRoutes{
1617                    base: true,
1618                    webhook: true,
1619                    internal: false,
1620                    metrics: false,
1621                    profiling: false,
1622                    mcp_agent: true,
1623                    mcp_developer: true,
1624                    console_config: true,
1625                },
1626            },
1627            "internal".to_owned() => v0_147_0::HttpListenerConfig{
1628                base: BaseListenerConfig {
1629                    addr: SocketAddr::new(
1630                        IpAddr::V4(Ipv4Addr::new(0,0,0,0)),
1631                        config.environmentd_internal_http_port,
1632                    ),
1633                    authenticator_kind: AuthenticatorKind::None,
1634                    // Should this just be Internal?
1635                    allowed_roles: AllowedRoles::NormalAndInternal,
1636                    enable_tls: false,
1637                },
1638                routes: v0_147_0::HttpRoutes{
1639                    base: true,
1640                    webhook: true,
1641                    internal: true,
1642                    metrics: true,
1643                    profiling: true,
1644                    mcp_agent: true,
1645                    mcp_developer: true,
1646                    console_config: false,
1647                },
1648            },
1649        },
1650    };
1651
1652    // For password/oidc/sasl auth, we want to get rid of the internal port and
1653    // combine the external and internal listeners into a single listener.
1654    if matches!(
1655        authenticator_kind,
1656        AuthenticatorKind::Password | AuthenticatorKind::Sasl | AuthenticatorKind::Oidc
1657    ) {
1658        listeners_config.sql.remove("internal");
1659        listeners_config.http.remove("internal");
1660
1661        listeners_config.sql.get_mut("external").map(|listener| {
1662            listener.allowed_roles = AllowedRoles::NormalAndInternal;
1663            listener
1664        });
1665        listeners_config.http.get_mut("external").map(|listener| {
1666            listener.base.allowed_roles = AllowedRoles::NormalAndInternal;
1667            listener.routes.internal = true;
1668            listener.routes.profiling = true;
1669            listener
1670        });
1671
1672        listeners_config.http.insert(
1673            "metrics".to_owned(),
1674            v0_147_0::HttpListenerConfig {
1675                base: BaseListenerConfig {
1676                    addr: SocketAddr::new(
1677                        IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)),
1678                        config.environmentd_internal_http_port,
1679                    ),
1680                    authenticator_kind: AuthenticatorKind::None,
1681                    allowed_roles: AllowedRoles::NormalAndInternal,
1682                    enable_tls: false,
1683                },
1684                routes: v0_147_0::HttpRoutes {
1685                    base: false,
1686                    webhook: false,
1687                    internal: false,
1688                    metrics: true,
1689                    profiling: false,
1690                    mcp_agent: false,
1691                    mcp_developer: false,
1692                    console_config: false,
1693                },
1694            },
1695        );
1696    };
1697    listeners_config
1698}
1699
1700fn create_connection_info(
1701    config: &super::Config,
1702    mz: &Materialize,
1703    generation: u64,
1704) -> ConnectionInfo {
1705    let external_enable_tls = issuer_ref_defined(
1706        &config.default_certificate_specs.internal,
1707        &mz.spec.internal_certificate_spec,
1708    );
1709    let authenticator_kind = mz.spec.authenticator_kind;
1710
1711    let listeners_config = create_v0_147_0_listeners_config(config, mz);
1712
1713    // Serve each `environmentd` the schema its version understands. Newer
1714    // versions parse the current (`ListenersConfig`) schema; older versions
1715    // parse the legacy (`v0_147_0::ListenersConfig`) schema.
1716    let listeners_json = if mz.meets_minimum_version(&PER_ROUTE_GROUP_ROLES_VERSION) {
1717        // Convert the legacy `v0_147_0::ListenersConfig` schema to the current `ListenersConfig` schema.
1718        // The main difference is instead of having a single `allowed_roles` property in the HTTP listener
1719        // for all route groups, we now have a per-route group `allowed_roles` property. The migration cascades
1720        // the top level `allowed_roles` into every route group.
1721        let mut listeners_config: v26_32_0::ListenersConfig = listeners_config.into();
1722        // The sole reason for the new `ListenersConfig` schema is because for password/oidc/sasl
1723        // authentication, we were allowing normal roles to access internal and profiling routes
1724        // since we now have a single listener for both external and internal traffic. However we
1725        // want to only allow internal roles to access these routes. Thus we set the `allowed_roles`
1726        // for the internal and profiling route groups to `Internal` and leave the other route groups
1727        // as `NormalAndInternal`.
1728        if matches!(
1729            authenticator_kind,
1730            AuthenticatorKind::Password | AuthenticatorKind::Sasl | AuthenticatorKind::Oidc
1731        ) {
1732            listeners_config.http.get_mut("external").map(|listener| {
1733                listener.routes.internal = RouteGroup::Enabled(AllowedRoles::Internal);
1734                listener.routes.profiling = RouteGroup::Enabled(AllowedRoles::Internal);
1735                listener
1736            });
1737        }
1738
1739        serde_json::to_string(&VersionedListenersConfig::V2(listeners_config)).expect("known valid")
1740    } else {
1741        serde_json::to_string(&VersionedListenersConfig::V1(listeners_config)).expect("known valid")
1742    };
1743    let listeners_configmap = ConfigMap {
1744        binary_data: None,
1745        data: Some(btreemap! {
1746            "listeners.json".to_owned() => listeners_json,
1747        }),
1748        immutable: None,
1749        metadata: ObjectMeta {
1750            annotations: Some(btreemap! {
1751                "materialize.cloud/generation".to_owned() => generation.to_string(),
1752            }),
1753            ..mz.managed_resource_meta(mz.listeners_configmap_name(generation))
1754        },
1755    };
1756
1757    let (scheme, leader_api_port, mz_system_secret_name) = match authenticator_kind {
1758        AuthenticatorKind::Password | AuthenticatorKind::Sasl | AuthenticatorKind::Oidc => {
1759            let scheme = if external_enable_tls { "https" } else { "http" };
1760            (
1761                scheme,
1762                config.environmentd_http_port,
1763                Some(mz.spec.backend_secret_name.clone()),
1764            )
1765        }
1766        _ => ("http", config.environmentd_internal_http_port, None),
1767    };
1768    let environmentd_url = format!(
1769        "{}://{}.{}.svc.cluster.local:{}",
1770        scheme,
1771        mz.environmentd_generation_service_name(generation),
1772        mz.namespace(),
1773        leader_api_port,
1774    );
1775    ConnectionInfo {
1776        environmentd_url,
1777        listeners_configmap,
1778        mz_system_secret_name,
1779    }
1780}
1781
1782// see materialize/src/environmentd/src/http.rs
1783#[derive(Debug, Deserialize, PartialEq, Eq)]
1784struct BecomeLeaderResponse {
1785    result: BecomeLeaderResult,
1786}
1787
1788#[derive(Debug, Deserialize, PartialEq, Eq)]
1789enum BecomeLeaderResult {
1790    Success,
1791    Failure { message: String },
1792}
1793
1794#[derive(Debug, Deserialize, PartialEq, Eq)]
1795struct SkipCatchupError {
1796    message: String,
1797}
1798
1799#[cfg(test)]
1800mod tests {
1801    use k8s_openapi::api::core::v1::{HTTPGetAction, Probe, TCPSocketAction};
1802    use k8s_openapi::apimachinery::pkg::util::intstr::IntOrString;
1803
1804    use kube::api::ObjectMeta;
1805    use mz_cloud_resources::crd::materialize::v1alpha1::{Materialize, MaterializeSpec};
1806    use mz_cloud_resources::crd::materialize::{AdditionalTrustBundle, TrustBundleKeyRef};
1807
1808    use super::{additional_trust_bundle_args, environmentd_probe, validate_probe_handlers};
1809
1810    fn base() -> Probe {
1811        Probe {
1812            initial_delay_seconds: Some(1),
1813            failure_threshold: Some(12),
1814            tcp_socket: Some(TCPSocketAction {
1815                host: None,
1816                port: IntOrString::Int(6877),
1817            }),
1818            ..Default::default()
1819        }
1820    }
1821
1822    #[mz_ore::test]
1823    fn environmentd_probe_without_overrides_is_base() {
1824        assert_eq!(environmentd_probe(base(), None, None), base());
1825    }
1826
1827    #[mz_ore::test]
1828    fn environmentd_probe_layers_fields() {
1829        let operator_default = Probe {
1830            failure_threshold: Some(30),
1831            period_seconds: Some(20),
1832            ..Default::default()
1833        };
1834        let environment_override = Probe {
1835            period_seconds: Some(5),
1836            ..Default::default()
1837        };
1838        assert_eq!(
1839            environmentd_probe(base(), Some(&operator_default), Some(&environment_override)),
1840            Probe {
1841                failure_threshold: Some(30),
1842                period_seconds: Some(5),
1843                ..base()
1844            }
1845        );
1846    }
1847
1848    #[mz_ore::test]
1849    fn environmentd_probe_replaces_handler_as_unit() {
1850        let http_get = HTTPGetAction {
1851            path: Some("/api/readyz".to_owned()),
1852            port: IntOrString::Int(6878),
1853            ..Default::default()
1854        };
1855        let environment_override = Probe {
1856            http_get: Some(http_get.clone()),
1857            ..Default::default()
1858        };
1859        assert_eq!(
1860            environmentd_probe(base(), None, Some(&environment_override)),
1861            Probe {
1862                tcp_socket: None,
1863                http_get: Some(http_get),
1864                ..base()
1865            }
1866        );
1867    }
1868
1869    #[mz_ore::test]
1870    fn additional_trust_bundle_args_require_supported_version() {
1871        let mut mz = Materialize {
1872            spec: MaterializeSpec {
1873                environmentd_image_ref: "materialize/environmentd:v26.53.0".to_owned(),
1874                additional_trust_bundle: Some(AdditionalTrustBundle {
1875                    config_map_key_ref: Some(TrustBundleKeyRef {
1876                        name: "private-ca".to_owned(),
1877                        key: "ca.crt".to_owned(),
1878                    }),
1879                    secret_key_ref: None,
1880                }),
1881                ..Default::default()
1882            },
1883            metadata: ObjectMeta::default(),
1884            status: None,
1885        };
1886        let err = additional_trust_bundle_args(&mz).unwrap_err();
1887        assert!(
1888            err.to_string().contains("v26.54.0"),
1889            "unexpected error: {err}"
1890        );
1891
1892        mz.spec.environmentd_image_ref = "materialize/environmentd:v26.54.0-dev.0".to_owned();
1893        let (volume, volume_mount, args) = additional_trust_bundle_args(&mz)
1894            .unwrap()
1895            .expect("bundle is set");
1896        assert_eq!(volume_mount.name, volume.name);
1897        assert_eq!(
1898            volume.config_map.map(|config_map| config_map.name),
1899            Some("private-ca".to_owned())
1900        );
1901        assert_eq!(
1902            args,
1903            vec![
1904                "--additional-trust-bundle=/etc/materialize/additional-trust-bundle/ca.crt".to_owned(),
1905                r#"--orchestrator-kubernetes-additional-trust-bundle={"configMapKeyRef":{"name":"private-ca","key":"ca.crt"}}"#.to_owned(),
1906            ]
1907        );
1908
1909        mz.spec.additional_trust_bundle = None;
1910        assert!(additional_trust_bundle_args(&mz).unwrap().is_none());
1911    }
1912
1913    #[mz_ore::test]
1914    fn validate_probe_handlers_rejects_multiple_handlers() {
1915        assert!(validate_probe_handlers(&Probe::default()).is_ok());
1916        assert!(validate_probe_handlers(&base()).is_ok());
1917        let both = Probe {
1918            http_get: Some(HTTPGetAction {
1919                port: IntOrString::Int(6878),
1920                ..Default::default()
1921            }),
1922            ..base()
1923        };
1924        let err = validate_probe_handlers(&both).unwrap_err();
1925        assert!(
1926            err.to_string().contains("httpGet, tcpSocket"),
1927            "unexpected error: {err}"
1928        );
1929    }
1930}