Skip to main content

mz_orchestratord/controller/
balancer.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 anyhow::bail;
11use k8s_controller::{Outcome, TraceMetadata};
12use k8s_openapi::{
13    api::{
14        apps::v1::{Deployment, DeploymentSpec, DeploymentStrategy, RollingUpdateDeployment},
15        core::v1::{
16            Affinity, Capabilities, ConfigMapVolumeSource, Container, ContainerPort, HTTPGetAction,
17            KeyToPath, PodSecurityContext, PodSpec, PodTemplateSpec, Probe, ResourceRequirements,
18            SeccompProfile, SecretVolumeSource, SecurityContext, Service, ServicePort, ServiceSpec,
19            Toleration, Volume, VolumeMount,
20        },
21        policy::v1::PodDisruptionBudget,
22    },
23    apimachinery::pkg::{
24        apis::meta::v1::{Condition, LabelSelector, Time},
25        util::intstr::IntOrString,
26    },
27    jiff::Timestamp,
28};
29use kube::{
30    Api, Client, Resource, ResourceExt,
31    api::{DeleteParams, ObjectMeta, Patch, PatchParams, PostParams},
32    runtime::{conditions::is_deployment_completed, controller::Action, wait::await_condition},
33};
34use maplit::btreemap;
35use tracing::{trace, warn};
36
37use crate::{
38    Error,
39    k8s::{
40        FIELD_MANAGER, apply_resource, get_resource, pod_disruption_budget, recommended_k8s_labels,
41        replace_resource,
42    },
43    tls::{DefaultCertificateSpecs, create_certificate, issuer_ref_defined},
44};
45use mz_cloud_resources::crd::{
46    ManagedResource,
47    balancer::v1alpha1::{Balancer, Routing},
48    generated::cert_manager::certificates::{Certificate, CertificatePrivateKeyAlgorithm},
49};
50use mz_orchestrator_kubernetes::KubernetesImagePullPolicy;
51use mz_ore::{cli::KeyValueArg, instrument};
52
53/// The name identifying this controller in its reconciliation metrics and in
54/// the reporter of the events it publishes.
55pub const CONTROLLER_NAME: &str = "balancer";
56
57#[derive(Clone)]
58pub struct Config {
59    pub enable_security_context: bool,
60    /// Whether to run pods in a Kubernetes user namespace (`hostUsers: false`).
61    pub enable_user_namespaces: bool,
62    pub enable_prometheus_scrape_annotations: bool,
63
64    pub image_pull_policy: KubernetesImagePullPolicy,
65    pub scheduler_name: Option<String>,
66    pub balancerd_node_selector: Vec<KeyValueArg<String, String>>,
67    pub balancerd_affinity: Option<Affinity>,
68    pub balancerd_tolerations: Option<Vec<Toleration>>,
69    pub balancerd_default_resources: Option<ResourceRequirements>,
70
71    pub default_certificate_specs: DefaultCertificateSpecs,
72
73    pub environmentd_sql_port: u16,
74    pub environmentd_http_port: u16,
75    pub balancerd_sql_port: u16,
76    pub balancerd_http_port: u16,
77    pub balancerd_internal_http_port: u16,
78    /// `/api/readyz` takes a balancerd at its connection high watermark out of
79    /// the Service endpoints. `/api/livez` keeps it in, for load balancers that
80    /// read `/api/readyz` in their own health check instead.
81    pub balancerd_readiness_probe_path: String,
82    pub balancerd_termination_grace_period_seconds: i64,
83}
84
85pub struct Context {
86    config: Config,
87}
88
89impl Context {
90    pub fn new(config: Config) -> Self {
91        Self { config }
92    }
93
94    async fn sync_deployment_status(
95        &self,
96        client: &Client,
97        balancer: &Balancer,
98    ) -> Result<(), Error> {
99        let namespace = balancer.namespace();
100        let balancer_api: Api<Balancer> = Api::namespaced(client.clone(), &namespace);
101        let deployment_api: Api<Deployment> = Api::namespaced(client.clone(), &namespace);
102
103        let Some(deployment) = get_resource(&deployment_api, &balancer.deployment_name()).await?
104        else {
105            return Ok(());
106        };
107
108        let Some(deployment_conditions) = &deployment
109            .status
110            .as_ref()
111            .and_then(|status| status.conditions.as_ref())
112        else {
113            // if the deployment doesn't have any conditions set yet, there
114            // is nothing to sync
115            return Ok(());
116        };
117
118        let ready = deployment_conditions
119            .iter()
120            .any(|condition| condition.type_ == "Available" && condition.status == "True");
121        let ready_str = if ready { "True" } else { "False" };
122
123        let mut status = balancer.status.clone().unwrap();
124        if status
125            .conditions
126            .iter()
127            .any(|condition| condition.type_ == "Ready" && condition.status == ready_str)
128        {
129            // if the deployment status is already set correctly, we don't
130            // need to set it again (this prevents us from getting stuck in
131            // a reconcile loop)
132            return Ok(());
133        }
134
135        status.conditions = vec![Condition {
136            type_: "Ready".to_string(),
137            status: ready_str.to_string(),
138            last_transition_time: Time(Timestamp::now()),
139            message: format!(
140                "balancerd deployment is{} ready",
141                if ready { "" } else { " not" }
142            ),
143            observed_generation: None,
144            reason: "DeploymentStatus".to_string(),
145        }];
146        let mut new_balancer = balancer.clone();
147        new_balancer.status = Some(status);
148
149        balancer_api
150            .replace_status(
151                &balancer.name_unchecked(),
152                &PostParams::default(),
153                &new_balancer,
154            )
155            .await?;
156
157        Ok(())
158    }
159
160    fn create_external_certificate_object(
161        &self,
162        balancer: &Balancer,
163    ) -> Result<Option<Certificate>, anyhow::Error> {
164        create_certificate(
165            self.config
166                .default_certificate_specs
167                .balancerd_external
168                .clone(),
169            balancer,
170            balancer.spec.external_certificate_spec.clone(),
171            balancer.external_certificate_name(),
172            balancer.external_certificate_secret_name(),
173            None,
174            CertificatePrivateKeyAlgorithm::Ecdsa,
175            Some(256),
176        )
177    }
178
179    fn create_deployment_object(&self, balancer: &Balancer) -> anyhow::Result<Deployment> {
180        let security_context = if self.config.enable_security_context {
181            // Since we want to adhere to the most restrictive security context, all
182            // of these fields have to be set how they are.
183            // See https://kubernetes.io/docs/concepts/security/pod-security-standards/#restricted
184            Some(SecurityContext {
185                run_as_non_root: Some(true),
186                capabilities: Some(Capabilities {
187                    drop: Some(vec!["ALL".to_string()]),
188                    ..Default::default()
189                }),
190                seccomp_profile: Some(SeccompProfile {
191                    type_: "RuntimeDefault".to_string(),
192                    ..Default::default()
193                }),
194                allow_privilege_escalation: Some(false),
195                read_only_root_filesystem: Some(true),
196                ..Default::default()
197            })
198        } else {
199            None
200        };
201
202        let pod_template_annotations = if self.config.enable_prometheus_scrape_annotations {
203            Some(btreemap! {
204                "prometheus.io/scrape".to_owned() => "true".to_string(),
205                "prometheus.io/port".to_owned() => self.config.balancerd_internal_http_port.to_string(),
206                "prometheus.io/path".to_owned() => "/metrics".to_string(),
207                "prometheus.io/scheme".to_owned() => "http".to_string(),
208            })
209        } else {
210            None
211        };
212        let mut pod_template_labels = balancer.default_labels();
213        pod_template_labels.insert(
214            "materialize.cloud/name".to_owned(),
215            balancer.deployment_name(),
216        );
217        pod_template_labels.insert("app".to_owned(), "balancerd".to_string());
218        pod_template_labels.insert("materialize.cloud/app".to_owned(), balancer.app_name());
219
220        let ports = vec![
221            ContainerPort {
222                container_port: self.config.balancerd_sql_port.into(),
223                name: Some("pgwire".into()),
224                protocol: Some("TCP".into()),
225                ..Default::default()
226            },
227            ContainerPort {
228                container_port: self.config.balancerd_http_port.into(),
229                name: Some("http".into()),
230                protocol: Some("TCP".into()),
231                ..Default::default()
232            },
233            ContainerPort {
234                container_port: self.config.balancerd_internal_http_port.into(),
235                name: Some("internal-http".into()),
236                protocol: Some("TCP".into()),
237                ..Default::default()
238            },
239        ];
240
241        let mut args = vec![
242            "service".to_string(),
243            format!(
244                "--pgwire-listen-addr=0.0.0.0:{}",
245                self.config.balancerd_sql_port
246            ),
247            format!(
248                "--https-listen-addr=0.0.0.0:{}",
249                self.config.balancerd_http_port
250            ),
251            format!(
252                "--internal-http-listen-addr=0.0.0.0:{}",
253                self.config.balancerd_internal_http_port
254            ),
255        ];
256        match balancer.routing()? {
257            Routing::Static(static_routing_config) => {
258                args.extend([
259                    format!(
260                        "--https-resolver-template={}.{}.svc.cluster.local:{}",
261                        static_routing_config.environmentd_service_name,
262                        static_routing_config.environmentd_namespace,
263                        self.config.environmentd_http_port
264                    ),
265                    format!(
266                        "--static-resolver-addr={}.{}.svc.cluster.local:{}",
267                        static_routing_config.environmentd_service_name,
268                        static_routing_config.environmentd_namespace,
269                        self.config.environmentd_sql_port
270                    ),
271                ]);
272            }
273            Routing::Frontegg(_frontegg_routing_config) => {
274                bail!("frontegg routing is not yet implemented");
275            }
276        }
277
278        if issuer_ref_defined(
279            &self.config.default_certificate_specs.internal,
280            &balancer.spec.internal_certificate_spec,
281        ) {
282            args.push("--internal-tls".to_owned())
283        }
284
285        let mut volumes = Vec::new();
286        let mut volume_mounts = Vec::new();
287        if let Some(name) = &balancer.spec.configmap_name {
288            volumes.push(Volume {
289                name: "dynamic-config".to_owned(),
290                config_map: Some(ConfigMapVolumeSource {
291                    name: name.clone(),
292                    // The file must exist at startup or balancerd skips the sync loop.
293                    optional: Some(false),
294                    items: Some(vec![KeyToPath {
295                        key: "config.json".to_owned(),
296                        path: "config.json".to_owned(),
297                        ..Default::default()
298                    }]),
299                    ..Default::default()
300                }),
301                ..Default::default()
302            });
303            volume_mounts.push(VolumeMount {
304                name: "dynamic-config".to_owned(),
305                // Mount the directory: subPath mounts do not receive ConfigMap updates.
306                mount_path: "/etc/balancerd".to_owned(),
307                read_only: Some(true),
308                ..Default::default()
309            });
310            args.extend([
311                "--config-sync-file-path=/etc/balancerd/config.json".to_owned(),
312                "--config-sync-loop-interval=1s".to_owned(),
313            ]);
314        }
315        if issuer_ref_defined(
316            &self.config.default_certificate_specs.balancerd_external,
317            &balancer.spec.external_certificate_spec,
318        ) {
319            volumes.push(Volume {
320                name: "external-certificate".to_owned(),
321                secret: Some(SecretVolumeSource {
322                    default_mode: Some(0o400),
323                    secret_name: Some(balancer.external_certificate_secret_name()),
324                    items: None,
325                    optional: Some(false),
326                }),
327                ..Default::default()
328            });
329            volume_mounts.push(VolumeMount {
330                name: "external-certificate".to_owned(),
331                mount_path: "/etc/external_tls".to_owned(),
332                read_only: Some(true),
333                ..Default::default()
334            });
335            args.extend([
336                "--tls-mode=require".into(),
337                "--tls-cert=/etc/external_tls/tls.crt".into(),
338                "--tls-key=/etc/external_tls/tls.key".into(),
339            ]);
340        } else {
341            args.push("--tls-mode=disable".to_string());
342        }
343
344        let startup_probe = Probe {
345            http_get: Some(HTTPGetAction {
346                port: IntOrString::Int(self.config.balancerd_internal_http_port.into()),
347                path: Some("/api/readyz".into()),
348                ..Default::default()
349            }),
350            failure_threshold: Some(20),
351            initial_delay_seconds: Some(3),
352            period_seconds: Some(3),
353            success_threshold: Some(1),
354            timeout_seconds: Some(1),
355            ..Default::default()
356        };
357        // Tighter than liveness so that, on `/api/readyz`, a balancerd at its
358        // connection high watermark leaves the Service endpoints within seconds.
359        let readiness_probe = Probe {
360            http_get: Some(HTTPGetAction {
361                port: IntOrString::Int(self.config.balancerd_internal_http_port.into()),
362                path: Some(self.config.balancerd_readiness_probe_path.clone()),
363                ..Default::default()
364            }),
365            failure_threshold: Some(2),
366            period_seconds: Some(2),
367            success_threshold: Some(1),
368            timeout_seconds: Some(1),
369            ..Default::default()
370        };
371        let liveness_probe = Probe {
372            http_get: Some(HTTPGetAction {
373                port: IntOrString::Int(self.config.balancerd_internal_http_port.into()),
374                path: Some("/api/livez".into()),
375                ..Default::default()
376            }),
377            failure_threshold: Some(3),
378            initial_delay_seconds: Some(8),
379            period_seconds: Some(10),
380            success_threshold: Some(1),
381            timeout_seconds: Some(1),
382            ..Default::default()
383        };
384
385        let container = Container {
386            name: "balancerd".to_owned(),
387            image: Some(balancer.spec.balancerd_image_ref.clone()),
388            image_pull_policy: Some(self.config.image_pull_policy.to_string()),
389            ports: Some(ports),
390            args: Some(args),
391            startup_probe: Some(startup_probe),
392            readiness_probe: Some(readiness_probe),
393            liveness_probe: Some(liveness_probe),
394            resources: balancer
395                .spec
396                .resource_requirements
397                .clone()
398                .or_else(|| self.config.balancerd_default_resources.clone()),
399            security_context: security_context.clone(),
400            volume_mounts: Some(volume_mounts),
401            ..Default::default()
402        };
403
404        let match_labels = pod_template_labels.clone();
405        pod_template_labels.extend(recommended_k8s_labels(balancer.app_name()));
406
407        let deployment_spec = DeploymentSpec {
408            replicas: balancer.replicas(),
409            selector: LabelSelector {
410                match_labels: Some(match_labels),
411                ..Default::default()
412            },
413            strategy: Some(DeploymentStrategy {
414                rolling_update: Some(RollingUpdateDeployment {
415                    // Allow a complete set of new pods at once, to minimize the
416                    // chances of a new connection going to a pod that will be
417                    // immediately drained
418                    max_surge: Some(IntOrString::String("100%".into())),
419                    ..Default::default()
420                }),
421                ..Default::default()
422            }),
423            template: PodTemplateSpec {
424                // not using managed_resource_meta because the pod should be
425                // owned by the deployment, not the materialize instance
426                metadata: Some(ObjectMeta {
427                    annotations: pod_template_annotations,
428                    labels: Some(pod_template_labels),
429                    ..Default::default()
430                }),
431                spec: Some(PodSpec {
432                    containers: vec![container],
433                    node_selector: Some(
434                        self.config
435                            .balancerd_node_selector
436                            .iter()
437                            .map(|selector| (selector.key.clone(), selector.value.clone()))
438                            .collect(),
439                    ),
440                    affinity: self.config.balancerd_affinity.clone(),
441                    tolerations: self.config.balancerd_tolerations.clone(),
442                    security_context: Some(PodSecurityContext {
443                        fs_group: Some(999),
444                        run_as_user: Some(999),
445                        run_as_group: Some(999),
446                        ..Default::default()
447                    }),
448                    scheduler_name: self.config.scheduler_name.clone(),
449                    termination_grace_period_seconds: Some(
450                        self.config.balancerd_termination_grace_period_seconds,
451                    ),
452                    volumes: Some(volumes),
453                    // `None` rather than `Some(true)` when disabled, so the
454                    // pod spec is unchanged from before user namespace support.
455                    host_users: self.config.enable_user_namespaces.then_some(false),
456                    ..Default::default()
457                }),
458            },
459            ..Default::default()
460        };
461
462        Ok(Deployment {
463            metadata: balancer.managed_resource_meta(balancer.deployment_name()),
464            spec: Some(deployment_spec),
465            status: None,
466        })
467    }
468
469    fn create_service_object(&self, balancer: &Balancer) -> Service {
470        let selector =
471            btreemap! {"materialize.cloud/name".to_string() => balancer.deployment_name()};
472
473        let ports = vec![
474            ServicePort {
475                name: Some("http".to_string()),
476                protocol: Some("TCP".to_string()),
477                port: self.config.balancerd_http_port.into(),
478                target_port: Some(IntOrString::Int(self.config.balancerd_http_port.into())),
479                ..Default::default()
480            },
481            ServicePort {
482                name: Some("pgwire".to_string()),
483                protocol: Some("TCP".to_string()),
484                port: self.config.balancerd_sql_port.into(),
485                target_port: Some(IntOrString::Int(self.config.balancerd_sql_port.into())),
486                ..Default::default()
487            },
488        ];
489
490        let spec = ServiceSpec {
491            type_: Some("ClusterIP".to_string()),
492            cluster_ip: Some("None".to_string()),
493            selector: Some(selector),
494            ports: Some(ports),
495            ..Default::default()
496        };
497
498        Service {
499            metadata: balancer.managed_resource_meta(balancer.service_name()),
500            spec: Some(spec),
501            status: None,
502        }
503    }
504
505    /// Hands `spec.replicas` to [`REPLICAS_HANDOVER_MANAGER`] at its live value
506    /// while [`FIELD_MANAGER`] still owns it, creating the Deployment with
507    /// `initial_replicas` first if it does not exist yet.
508    ///
509    /// NOTE: Dropping a field from an apply when no other manager owns it
510    /// deletes it, which defaults the Deployment to 1 replica. An autoscaler
511    /// cannot become a co-owner first, because each of its writes triggers a
512    /// reconcile whose forced apply reclaims the field. The handover apply is
513    /// not forced, so a concurrent scale by the autoscaler conflicts and the
514    /// reconcile retries.
515    async fn release_replicas(
516        &self,
517        deployment_api: &Api<Deployment>,
518        deployment: &Deployment,
519        initial_replicas: i32,
520    ) -> Result<(), Error> {
521        let name = deployment.name_unchecked();
522        let existing = match get_resource(deployment_api, &name).await? {
523            Some(existing) => existing,
524            None => {
525                // The handover apply carries no selector or template, so it
526                // cannot create the Deployment. Create it with the initial
527                // count under FIELD_MANAGER, then hand that count over below.
528                let mut seeded = deployment.clone();
529                seeded.spec.as_mut().unwrap().replicas = Some(initial_replicas);
530                apply_resource(deployment_api, &seeded).await?
531            }
532        };
533        if !owns_replicas(&existing) {
534            return Ok(());
535        }
536        let replicas = existing.spec.and_then(|spec| spec.replicas);
537        deployment_api
538            .patch(
539                &name,
540                &PatchParams::apply(REPLICAS_HANDOVER_MANAGER),
541                &Patch::Apply(serde_json::json!({
542                    "apiVersion": "apps/v1",
543                    "kind": "Deployment",
544                    "metadata": { "name": name },
545                    "spec": { "replicas": replicas },
546                })),
547            )
548            .await?;
549        Ok(())
550    }
551
552    // TODO: remove this once everyone is upgraded to an orchestratord
553    // version with the separate balancer operator
554    async fn fix_deployment(
555        &self,
556        deployment_api: &Api<Deployment>,
557        new_deployment: &Deployment,
558    ) -> Result<(), Error> {
559        let Some(mut existing_deployment) =
560            get_resource(deployment_api, &new_deployment.name_unchecked()).await?
561        else {
562            return Ok(());
563        };
564
565        if existing_deployment.spec.as_ref().unwrap().selector
566            == new_deployment.spec.as_ref().unwrap().selector
567        {
568            return Ok(());
569        }
570
571        warn!("found existing deployment with old label selector, fixing");
572
573        // this is sufficient because the new labels are a superset of the
574        // old labels, so the existing label selector should still be valid
575        existing_deployment
576            .spec
577            .as_mut()
578            .unwrap()
579            .template
580            .metadata
581            .as_mut()
582            .unwrap()
583            .labels = new_deployment
584            .spec
585            .as_ref()
586            .unwrap()
587            .template
588            .metadata
589            .as_ref()
590            .unwrap()
591            .labels
592            .clone();
593
594        // using await_condition is not ideal in a controller loop, but this
595        // is very temporary and will only ever happen once, so this feels
596        // simpler than trying to introduce an entire state machine here
597        replace_resource(deployment_api, &existing_deployment).await?;
598        await_condition(
599            deployment_api.clone(),
600            &existing_deployment.name_unchecked(),
601            |deployment: Option<&Deployment>| {
602                let observed_generation = deployment
603                    .and_then(|deployment| deployment.status.as_ref())
604                    .and_then(|status| status.observed_generation)
605                    .unwrap_or(0);
606                let current_generation = deployment
607                    .and_then(|deployment| deployment.meta().generation)
608                    .unwrap_or(0);
609                let previous_generation = existing_deployment.meta().generation.unwrap_or(0);
610                observed_generation == current_generation
611                    && current_generation > previous_generation
612            },
613        )
614        .await
615        .map_err(|e| anyhow::anyhow!(e))?;
616        await_condition(
617            deployment_api.clone(),
618            &existing_deployment.name_unchecked(),
619            is_deployment_completed(),
620        )
621        .await
622        .map_err(|e| anyhow::anyhow!(e))?;
623
624        // delete the deployment but leave the pods around (via
625        // DeleteParams::orphan)
626        match kube::runtime::wait::delete::delete_and_finalize(
627            deployment_api.clone(),
628            &existing_deployment.name_unchecked(),
629            &DeleteParams::orphan(),
630        )
631        .await
632        {
633            Ok(_) => {}
634            Err(kube::runtime::wait::delete::Error::Delete(kube::Error::Api(e)))
635                if e.code == 404 =>
636            {
637                // the resource already doesn't exist
638            }
639            Err(e) => return Err(anyhow::anyhow!(e).into()),
640        }
641
642        // now, the normal apply of the new deployment (in the main loop)
643        // will take over the existing pods from the old deployment we just
644        // deleted, since we already updated the pod labels to be the same as
645        // the new label selector
646
647        Ok(())
648    }
649}
650
651#[async_trait::async_trait]
652impl k8s_controller::Context for Context {
653    type Resource = Balancer;
654    type Error = Error;
655
656    #[instrument(fields())]
657    async fn apply(
658        &self,
659        client: Client,
660        balancer: &Self::Resource,
661        metadata: &mut TraceMetadata,
662    ) -> Result<Option<Action>, Self::Error> {
663        if balancer.status.is_none() {
664            let step = metadata.step("initialize_status");
665            let balancer_api: Api<Balancer> =
666                Api::namespaced(client.clone(), &balancer.meta().namespace.clone().unwrap());
667            let mut new_balancer = balancer.clone();
668            new_balancer.status = Some(balancer.status());
669            balancer_api
670                .replace_status(
671                    &balancer.name_unchecked(),
672                    &PostParams::default(),
673                    &new_balancer,
674                )
675                .await?;
676            step.finish(Outcome::Completed);
677            // Updating the status should trigger a reconciliation
678            // which will include a status this time.
679            return Ok(None);
680        }
681
682        let namespace = balancer.namespace();
683        let certificate_api: Api<Certificate> = Api::namespaced(client.clone(), &namespace);
684        let deployment_api: Api<Deployment> = Api::namespaced(client.clone(), &namespace);
685        let service_api: Api<Service> = Api::namespaced(client.clone(), &namespace);
686        let pdb_api: Api<PodDisruptionBudget> = Api::namespaced(client.clone(), &namespace);
687
688        let step = metadata.step("certificate");
689        if let Some(external_certificate) = self.create_external_certificate_object(balancer)? {
690            trace!("creating new balancerd external certificate");
691            apply_resource(&certificate_api, &external_certificate).await?;
692            step.finish(Outcome::Completed);
693        } else {
694            step.finish(Outcome::Skipped);
695        }
696
697        let step = metadata.step("deployment");
698        let deployment = self.create_deployment_object(balancer)?;
699        self.fix_deployment(&deployment_api, &deployment).await?;
700        // Must precede the apply that omits `replicas`; see `release_replicas`.
701        if balancer.replicas().is_none() {
702            self.release_replicas(&deployment_api, &deployment, balancer.initial_replicas())
703                .await?;
704        }
705        trace!("creating new balancerd deployment");
706        apply_resource(&deployment_api, &deployment).await?;
707        step.finish(Outcome::Completed);
708
709        let step = metadata.step("pod_disruption_budget");
710        let pdb = pod_disruption_budget(
711            balancer.managed_resource_meta(balancer.deployment_name()),
712            &deployment,
713        );
714        apply_resource(&pdb_api, &pdb).await?;
715        step.finish(Outcome::Completed);
716
717        let step = metadata.step("service");
718        let service = self.create_service_object(balancer);
719        trace!("creating new balancerd service");
720        apply_resource(&service_api, &service).await?;
721        step.finish(Outcome::Completed);
722
723        let step = metadata.step("sync_status");
724        self.sync_deployment_status(&client, balancer).await?;
725        step.finish(Outcome::Completed);
726
727        Ok(None)
728    }
729}
730
731const REPLICAS_HANDOVER_MANAGER: &str = "orchestratord.materialize.cloud/replicas-handover";
732
733fn owns_replicas(deployment: &Deployment) -> bool {
734    deployment
735        .metadata
736        .managed_fields
737        .iter()
738        .flatten()
739        .filter(|entry| entry.manager.as_deref() == Some(FIELD_MANAGER))
740        .filter_map(|entry| entry.fields_v1.as_ref())
741        .any(|fields| fields.0.pointer("/f:spec/f:replicas").is_some())
742}
743
744#[cfg(test)]
745mod tests {
746    use super::*;
747    use mz_cloud_resources::crd::balancer::v1alpha1::{BalancerSpec, StaticRoutingConfig};
748
749    fn test_context() -> Context {
750        Context::new(Config {
751            enable_security_context: false,
752            enable_user_namespaces: false,
753            enable_prometheus_scrape_annotations: false,
754            image_pull_policy: KubernetesImagePullPolicy::IfNotPresent,
755            scheduler_name: None,
756            balancerd_node_selector: vec![],
757            balancerd_affinity: None,
758            balancerd_tolerations: None,
759            balancerd_default_resources: None,
760            default_certificate_specs: DefaultCertificateSpecs::default(),
761            environmentd_sql_port: 6875,
762            environmentd_http_port: 6876,
763            balancerd_sql_port: 6875,
764            balancerd_http_port: 6876,
765            balancerd_internal_http_port: 6878,
766            balancerd_readiness_probe_path: "/api/readyz".to_owned(),
767            balancerd_termination_grace_period_seconds: 600,
768        })
769    }
770
771    fn test_balancer(spec: BalancerSpec) -> Balancer {
772        let mut balancer = Balancer::new(
773            "test",
774            BalancerSpec {
775                static_routing: Some(StaticRoutingConfig {
776                    environmentd_namespace: "test".to_owned(),
777                    environmentd_service_name: "environmentd".to_owned(),
778                }),
779                ..spec
780            },
781        );
782        balancer.metadata.namespace = Some("test".to_owned());
783        balancer.metadata.uid = Some("test".to_owned());
784        balancer.status = Some(balancer.status());
785        balancer
786    }
787
788    #[mz_ore::test]
789    fn externally_scaled_omits_replicas() {
790        let context = test_context();
791        for (externally_scaled, expected) in [(None, Some(3)), (Some(true), None)] {
792            let balancer = test_balancer(BalancerSpec {
793                replicas: Some(3),
794                externally_scaled,
795                ..Default::default()
796            });
797            let deployment = context.create_deployment_object(&balancer).unwrap();
798            assert_eq!(deployment.spec.unwrap().replicas, expected);
799            assert_eq!(balancer.initial_replicas(), 3);
800        }
801    }
802
803    #[mz_ore::test]
804    fn user_namespaces_set_host_users() {
805        let balancer = test_balancer(BalancerSpec::default());
806        for (enabled, expected) in [(false, None), (true, Some(false))] {
807            let mut context = test_context();
808            context.config.enable_user_namespaces = enabled;
809            let pod = context
810                .create_deployment_object(&balancer)
811                .unwrap()
812                .spec
813                .unwrap()
814                .template
815                .spec
816                .unwrap();
817            assert_eq!(pod.host_users, expected);
818        }
819    }
820
821    #[mz_ore::test]
822    fn pdb_selects_deployment_pods() {
823        let balancer = test_balancer(BalancerSpec::default());
824        let deployment = test_context().create_deployment_object(&balancer).unwrap();
825        let pdb = pod_disruption_budget(
826            balancer.managed_resource_meta(balancer.deployment_name()),
827            &deployment,
828        );
829        let spec = pdb.spec.unwrap();
830        assert_eq!(spec.max_unavailable, Some(IntOrString::Int(1)));
831        assert_eq!(
832            spec.unhealthy_pod_eviction_policy.as_deref(),
833            Some("AlwaysAllow")
834        );
835        let match_labels = spec.selector.unwrap().match_labels.unwrap();
836        let pod_labels = deployment
837            .spec
838            .unwrap()
839            .template
840            .metadata
841            .unwrap()
842            .labels
843            .unwrap();
844        assert!(!match_labels.is_empty());
845        assert!(
846            match_labels
847                .iter()
848                .all(|(k, v)| pod_labels.get(k) == Some(v)),
849            "PDB selector {match_labels:?} does not match pod labels {pod_labels:?}",
850        );
851    }
852
853    #[mz_ore::test]
854    fn owns_replicas_reads_managed_fields() {
855        use k8s_openapi::apimachinery::pkg::apis::meta::v1::{FieldsV1, ManagedFieldsEntry};
856        let deployment = |manager: &str| Deployment {
857            metadata: ObjectMeta {
858                managed_fields: Some(vec![ManagedFieldsEntry {
859                    manager: Some(manager.to_owned()),
860                    fields_v1: Some(FieldsV1(
861                        serde_json::json!({ "f:spec": { "f:replicas": {} } }),
862                    )),
863                    ..Default::default()
864                }]),
865                ..Default::default()
866            },
867            ..Default::default()
868        };
869        assert!(owns_replicas(&deployment(FIELD_MANAGER)));
870        assert!(!owns_replicas(&deployment(REPLICAS_HANDOVER_MANAGER)));
871        assert!(!owns_replicas(&Deployment::default()));
872    }
873
874    #[mz_ore::test]
875    fn configmap_reference_controls_file_sync() {
876        let context = test_context();
877        for configmap_name in [None, Some("balancerd-settings".to_owned())] {
878            let balancer = test_balancer(BalancerSpec {
879                configmap_name: configmap_name.clone(),
880                ..Default::default()
881            });
882            let pod = context
883                .create_deployment_object(&balancer)
884                .unwrap()
885                .spec
886                .unwrap()
887                .template
888                .spec
889                .unwrap();
890            let container = &pod.containers[0];
891            let args = container.args.as_ref().unwrap();
892            let volumes = pod.volumes.as_ref().unwrap();
893            let mounts = container.volume_mounts.as_ref().unwrap();
894            if let Some(name) = configmap_name {
895                let source = volumes[0].config_map.as_ref().unwrap();
896                assert_eq!(source.name, name);
897                assert_eq!(source.optional, Some(false));
898                assert_eq!(source.items.as_ref().unwrap()[0].key, "config.json");
899                assert_eq!(mounts[0].read_only, Some(true));
900                assert!(mounts[0].sub_path.is_none());
901                assert!(args.contains(&format!(
902                    "--config-sync-file-path={}/config.json",
903                    mounts[0].mount_path
904                )));
905                assert!(args.contains(&"--config-sync-loop-interval=1s".to_owned()));
906            } else {
907                assert!(volumes.is_empty());
908                assert!(mounts.is_empty());
909                assert!(!args.iter().any(|arg| arg.starts_with("--config-sync-")));
910            }
911        }
912    }
913}