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