Skip to main content

mz_orchestratord/controller/
console.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::collections::BTreeMap;
11
12use k8s_controller::{Outcome, TraceMetadata};
13use k8s_openapi::{
14    api::{
15        apps::v1::{Deployment, DeploymentSpec},
16        core::v1::{
17            Affinity, Capabilities, ConfigMap, ConfigMapVolumeSource, Container, ContainerPort,
18            EmptyDirVolumeSource, EnvVar, HTTPGetAction, KeyToPath, PodSecurityContext, PodSpec,
19            PodTemplateSpec, Probe, ResourceRequirements, SeccompProfile, SecretVolumeSource,
20            SecurityContext, Service, ServicePort, ServiceSpec, Toleration, Volume, VolumeMount,
21        },
22        networking::v1::{
23            IPBlock, NetworkPolicy, NetworkPolicyIngressRule, NetworkPolicyPeer, NetworkPolicyPort,
24            NetworkPolicySpec,
25        },
26        policy::v1::PodDisruptionBudget,
27    },
28    apimachinery::pkg::{
29        apis::meta::v1::{Condition, LabelSelector, Time},
30        util::intstr::IntOrString,
31    },
32    jiff::Timestamp,
33};
34use kube::{
35    Api, Client, Resource, ResourceExt,
36    api::{DeleteParams, ObjectMeta, PostParams},
37    runtime::{conditions::is_deployment_completed, controller::Action, wait::await_condition},
38};
39use maplit::btreemap;
40use serde::Serialize;
41use tracing::{trace, warn};
42
43use crate::{
44    Error,
45    k8s::{
46        apply_resource, get_resource, pod_disruption_budget, recommended_k8s_labels,
47        replace_resource,
48    },
49    tls::{DefaultCertificateSpecs, create_certificate, issuer_ref_defined},
50};
51use mz_cloud_resources::crd::{
52    ManagedResource,
53    console::v1alpha1::{Console, HttpConnectionScheme},
54    generated::cert_manager::certificates::{Certificate, CertificatePrivateKeyAlgorithm},
55};
56use mz_orchestrator_kubernetes::KubernetesImagePullPolicy;
57use mz_ore::{cli::KeyValueArg, instrument};
58use mz_server_core::listeners::AuthenticatorKind;
59
60/// The name identifying this controller in its reconciliation metrics and in
61/// the reporter of the events it publishes.
62pub const CONTROLLER_NAME: &str = "console";
63
64#[derive(Clone)]
65pub struct Config {
66    pub enable_security_context: bool,
67    /// Whether to run pods in a Kubernetes user namespace (`hostUsers: false`).
68    pub enable_user_namespaces: bool,
69    pub enable_prometheus_scrape_annotations: bool,
70
71    pub image_pull_policy: KubernetesImagePullPolicy,
72    pub scheduler_name: Option<String>,
73    pub console_node_selector: Vec<KeyValueArg<String, String>>,
74    pub console_affinity: Option<Affinity>,
75    pub console_tolerations: Option<Vec<Toleration>>,
76    pub console_default_resources: Option<ResourceRequirements>,
77    pub network_policies_ingress_enabled: bool,
78    pub network_policies_ingress_cidrs: Vec<String>,
79
80    pub default_certificate_specs: DefaultCertificateSpecs,
81
82    pub console_http_port: u16,
83    /// The plain HTTP port the console's nginx serves `/metrics` on.
84    pub console_internal_http_port: u16,
85    pub balancerd_http_port: u16,
86}
87
88#[derive(Serialize)]
89struct AppConfig {
90    version: String,
91    auth: AppConfigAuth,
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    balancerd_dns_names: Option<Vec<String>>,
94}
95
96#[derive(Serialize)]
97struct AppConfigAuth {
98    mode: AuthenticatorKind,
99}
100
101pub struct Context {
102    config: Config,
103}
104
105impl Context {
106    pub fn new(config: Config) -> Self {
107        Self { config }
108    }
109
110    async fn sync_deployment_status(
111        &self,
112        client: &Client,
113        console: &Console,
114    ) -> Result<(), Error> {
115        let namespace = console.namespace();
116        let console_api: Api<Console> = Api::namespaced(client.clone(), &namespace);
117        let deployment_api: Api<Deployment> = Api::namespaced(client.clone(), &namespace);
118
119        let Some(deployment) = get_resource(&deployment_api, &console.deployment_name()).await?
120        else {
121            return Ok(());
122        };
123
124        let Some(deployment_conditions) = &deployment
125            .status
126            .as_ref()
127            .and_then(|status| status.conditions.as_ref())
128        else {
129            // if the deployment doesn't have any conditions set yet, there
130            // is nothing to sync
131            return Ok(());
132        };
133
134        let ready = deployment_conditions
135            .iter()
136            .any(|condition| condition.type_ == "Available" && condition.status == "True");
137        let ready_str = if ready { "True" } else { "False" };
138
139        let mut status = console.status.clone().unwrap();
140        if status
141            .conditions
142            .iter()
143            .any(|condition| condition.type_ == "Ready" && condition.status == ready_str)
144        {
145            // if the deployment status is already set correctly, we don't
146            // need to set it again (this prevents us from getting stuck in
147            // a reconcile loop)
148            return Ok(());
149        }
150
151        status.conditions = vec![Condition {
152            type_: "Ready".to_string(),
153            status: ready_str.to_string(),
154            last_transition_time: Time(Timestamp::now()),
155            message: format!(
156                "console deployment is{} ready",
157                if ready { "" } else { " not" }
158            ),
159            observed_generation: None,
160            reason: "DeploymentStatus".to_string(),
161        }];
162        let mut new_console = console.clone();
163        new_console.status = Some(status);
164
165        console_api
166            .replace_status(
167                &console.name_unchecked(),
168                &PostParams::default(),
169                &new_console,
170            )
171            .await?;
172
173        Ok(())
174    }
175
176    fn create_network_policies(&self, console: &Console) -> Vec<NetworkPolicy> {
177        let mut network_policies = Vec::new();
178        if self.config.network_policies_ingress_enabled {
179            let console_label_selector = LabelSelector {
180                match_labels: Some(
181                    console
182                        .default_labels()
183                        .into_iter()
184                        .chain([("materialize.cloud/app".to_owned(), console.app_name())])
185                        .collect(),
186                ),
187                ..Default::default()
188            };
189            network_policies.extend([NetworkPolicy {
190                metadata: console.managed_resource_meta(console.name_prefixed("console-ingress")),
191                spec: Some(NetworkPolicySpec {
192                    ingress: Some(vec![NetworkPolicyIngressRule {
193                        from: Some(
194                            self.config
195                                .network_policies_ingress_cidrs
196                                .iter()
197                                .map(|cidr| NetworkPolicyPeer {
198                                    ip_block: Some(IPBlock {
199                                        cidr: cidr.to_owned(),
200                                        except: None,
201                                    }),
202                                    ..Default::default()
203                                })
204                                .collect(),
205                        ),
206                        ports: Some(vec![NetworkPolicyPort {
207                            port: Some(IntOrString::Int(self.config.console_http_port.into())),
208                            protocol: Some("TCP".to_string()),
209                            ..Default::default()
210                        }]),
211                        ..Default::default()
212                    }]),
213                    pod_selector: Some(console_label_selector),
214                    policy_types: Some(vec!["Ingress".to_owned()]),
215                    ..Default::default()
216                }),
217            }]);
218        }
219        network_policies
220    }
221
222    fn create_console_external_certificate(
223        &self,
224        console: &Console,
225    ) -> anyhow::Result<Option<Certificate>> {
226        create_certificate(
227            self.config
228                .default_certificate_specs
229                .console_external
230                .clone(),
231            console,
232            console.spec.external_certificate_spec.clone(),
233            console.external_certificate_name(),
234            console.external_certificate_secret_name(),
235            None,
236            CertificatePrivateKeyAlgorithm::Ecdsa,
237            Some(256),
238        )
239    }
240
241    fn create_console_app_configmap_object(&self, console: &Console) -> ConfigMap {
242        let balancerd_dns_names = console.spec.balancerd.dns_names.clone();
243        let version: String = console
244            .spec
245            .console_image_ref
246            .rsplitn(2, ':')
247            .next()
248            .expect("at least one chunk, even if empty")
249            .to_owned();
250        let app_config_json = serde_json::to_string(&AppConfig {
251            version,
252            balancerd_dns_names,
253            auth: AppConfigAuth {
254                mode: console.spec.authenticator_kind,
255            },
256        })
257        .expect("known valid");
258        ConfigMap {
259            binary_data: None,
260            data: Some(btreemap! {
261                "app-config.json".to_owned() => app_config_json,
262            }),
263            immutable: None,
264            metadata: console.managed_resource_meta(console.configmap_name()),
265        }
266    }
267
268    fn create_console_deployment_object(&self, console: &Console) -> Deployment {
269        let mut pod_template_labels = console.default_labels();
270        pod_template_labels.insert(
271            "materialize.cloud/name".to_owned(),
272            console.deployment_name(),
273        );
274        pod_template_labels.insert("app".to_owned(), "console".to_string());
275        pod_template_labels.insert("materialize.cloud/app".to_owned(), console.app_name());
276
277        let ports = vec![
278            ContainerPort {
279                container_port: self.config.console_http_port.into(),
280                name: Some("http".into()),
281                protocol: Some("TCP".into()),
282                ..Default::default()
283            },
284            ContainerPort {
285                container_port: self.config.console_internal_http_port.into(),
286                name: Some("internal-http".into()),
287                protocol: Some("TCP".into()),
288                ..Default::default()
289            },
290        ];
291        let mut pod_template_annotations = BTreeMap::new();
292        if self.config.enable_prometheus_scrape_annotations {
293            pod_template_annotations.extend(btreemap! {
294                "prometheus.io/scrape".to_owned() => "true".to_string(),
295                "prometheus.io/port".to_owned() => self.config.console_internal_http_port.to_string(),
296                "prometheus.io/path".to_owned() => "/metrics".to_string(),
297                "prometheus.io/scheme".to_owned() => "http".to_string(),
298            });
299        }
300
301        let scheme = match console.spec.balancerd.scheme {
302            HttpConnectionScheme::Http => "http",
303            HttpConnectionScheme::Https => "https",
304        };
305        let mut env = vec![EnvVar {
306            name: "MZ_ENDPOINT".to_string(),
307            value: Some(format!(
308                "{}://{}.{}.svc.cluster.local:{}",
309                scheme,
310                console.spec.balancerd.service_name,
311                console.spec.balancerd.namespace,
312                self.config.balancerd_http_port,
313            )),
314            ..Default::default()
315        }];
316        // Plain HTTP whether or not the console itself serves TLS.
317        env.push(EnvVar {
318            name: "MZ_NGINX_METRICS_LISTENER_CONFIG".to_string(),
319            value: Some(format!(
320                "listen {};",
321                self.config.console_internal_http_port
322            )),
323            ..Default::default()
324        });
325        let mut volumes = vec![Volume {
326            name: "app-config".to_string(),
327            config_map: Some(ConfigMapVolumeSource {
328                name: console.configmap_name(),
329                default_mode: Some(256),
330                optional: Some(false),
331                items: Some(vec![KeyToPath {
332                    key: "app-config.json".to_string(),
333                    path: "app-config.json".to_string(),
334                    ..Default::default()
335                }]),
336            }),
337            ..Default::default()
338        }];
339        let mut volume_mounts = vec![VolumeMount {
340            name: "app-config".to_string(),
341            mount_path: "/usr/share/nginx/html/app-config".to_string(),
342            ..Default::default()
343        }];
344        if self.config.enable_security_context {
345            // The security context makes the root filesystem read-only. nginx
346            // writes its pid and temp files to /tmp, and the image entrypoint
347            // renders its config template into /etc/nginx/conf.d.
348            for (name, mount_path) in [("tmp", "/tmp"), ("nginx-conf", "/etc/nginx/conf.d")] {
349                volumes.push(Volume {
350                    name: name.to_string(),
351                    empty_dir: Some(EmptyDirVolumeSource::default()),
352                    ..Default::default()
353                });
354                volume_mounts.push(VolumeMount {
355                    name: name.to_string(),
356                    mount_path: mount_path.to_string(),
357                    ..Default::default()
358                });
359            }
360            // Without this, Cluster Autoscaler won't scale down a node running
361            // a console pod, because the pod has local emptyDir storage.
362            pod_template_annotations.insert(
363                "cluster-autoscaler.kubernetes.io/safe-to-evict-local-volumes".to_owned(),
364                "tmp,nginx-conf".to_owned(),
365            );
366        }
367
368        let scheme = if issuer_ref_defined(
369            &self.config.default_certificate_specs.console_external,
370            &console.spec.external_certificate_spec,
371        ) {
372            volumes.push(Volume {
373                name: "external-certificate".to_owned(),
374                secret: Some(SecretVolumeSource {
375                    default_mode: Some(0o400),
376                    secret_name: Some(console.external_certificate_secret_name()),
377                    items: None,
378                    optional: Some(false),
379                }),
380                ..Default::default()
381            });
382            volume_mounts.push(VolumeMount {
383                name: "external-certificate".to_owned(),
384                mount_path: "/nginx/tls".to_owned(),
385                read_only: Some(true),
386                ..Default::default()
387            });
388            env.push(EnvVar {
389                name: "MZ_NGINX_LISTENER_CONFIG".to_string(),
390                value: Some(format!(
391                    "listen {} ssl;
392ssl_certificate /nginx/tls/tls.crt;
393ssl_certificate_key /nginx/tls/tls.key;",
394                    self.config.console_http_port
395                )),
396                ..Default::default()
397            });
398            Some("HTTPS".to_owned())
399        } else {
400            env.push(EnvVar {
401                name: "MZ_NGINX_LISTENER_CONFIG".to_string(),
402                value: Some(format!("listen {};", self.config.console_http_port)),
403                ..Default::default()
404            });
405            Some("HTTP".to_owned())
406        };
407
408        let probe = Probe {
409            http_get: Some(HTTPGetAction {
410                path: Some("/".to_string()),
411                port: IntOrString::Int(self.config.console_http_port.into()),
412                scheme,
413                ..Default::default()
414            }),
415            ..Default::default()
416        };
417
418        let security_context = if self.config.enable_security_context {
419            // Since we want to adhere to the most restrictive security context, all
420            // of these fields have to be set how they are.
421            // See https://kubernetes.io/docs/concepts/security/pod-security-standards/#restricted
422            Some(SecurityContext {
423                run_as_non_root: Some(true),
424                capabilities: Some(Capabilities {
425                    drop: Some(vec!["ALL".to_string()]),
426                    ..Default::default()
427                }),
428                seccomp_profile: Some(SeccompProfile {
429                    type_: "RuntimeDefault".to_string(),
430                    ..Default::default()
431                }),
432                allow_privilege_escalation: Some(false),
433                read_only_root_filesystem: Some(true),
434                ..Default::default()
435            })
436        } else {
437            None
438        };
439
440        let container = Container {
441            name: "console".to_owned(),
442            image: Some(console.spec.console_image_ref.clone()),
443            image_pull_policy: Some(self.config.image_pull_policy.to_string()),
444            ports: Some(ports),
445            env: Some(env),
446            startup_probe: Some(Probe {
447                period_seconds: Some(1),
448                failure_threshold: Some(10),
449                ..probe.clone()
450            }),
451            readiness_probe: Some(Probe {
452                period_seconds: Some(30),
453                failure_threshold: Some(1),
454                ..probe.clone()
455            }),
456            liveness_probe: Some(Probe {
457                period_seconds: Some(30),
458                ..probe.clone()
459            }),
460            resources: console
461                .spec
462                .resource_requirements
463                .clone()
464                .or_else(|| self.config.console_default_resources.clone()),
465            security_context,
466            volume_mounts: Some(volume_mounts),
467            ..Default::default()
468        };
469
470        let match_labels = pod_template_labels.clone();
471        pod_template_labels.extend(recommended_k8s_labels("console".into()));
472
473        let deployment_spec = DeploymentSpec {
474            replicas: Some(console.replicas()),
475            selector: LabelSelector {
476                match_labels: Some(match_labels),
477                ..Default::default()
478            },
479            template: PodTemplateSpec {
480                // not using managed_resource_meta because the pod should be
481                // owned by the deployment, not the materialize instance
482                metadata: Some(ObjectMeta {
483                    labels: Some(pod_template_labels),
484                    annotations: (!pod_template_annotations.is_empty())
485                        .then_some(pod_template_annotations),
486                    ..Default::default()
487                }),
488                spec: Some(PodSpec {
489                    containers: vec![container],
490                    node_selector: Some(
491                        self.config
492                            .console_node_selector
493                            .iter()
494                            .map(|selector| (selector.key.clone(), selector.value.clone()))
495                            .collect(),
496                    ),
497                    affinity: self.config.console_affinity.clone(),
498                    tolerations: self.config.console_tolerations.clone(),
499                    scheduler_name: self.config.scheduler_name.clone(),
500                    volumes: Some(volumes),
501                    security_context: Some(PodSecurityContext {
502                        fs_group: Some(101),
503                        ..Default::default()
504                    }),
505                    // `None` rather than `Some(true)` when disabled, so the
506                    // pod spec is unchanged from before user namespace support.
507                    host_users: self.config.enable_user_namespaces.then_some(false),
508                    ..Default::default()
509                }),
510            },
511            ..Default::default()
512        };
513
514        Deployment {
515            metadata: ObjectMeta {
516                ..console.managed_resource_meta(console.deployment_name())
517            },
518            spec: Some(deployment_spec),
519            status: None,
520        }
521    }
522
523    fn create_console_service_object(&self, console: &Console) -> Service {
524        let selector =
525            btreemap! {"materialize.cloud/name".to_string() => console.deployment_name()};
526
527        let ports = vec![ServicePort {
528            name: Some("http".to_string()),
529            protocol: Some("TCP".to_string()),
530            port: self.config.console_http_port.into(),
531            target_port: Some(IntOrString::Int(self.config.console_http_port.into())),
532            ..Default::default()
533        }];
534
535        let spec = ServiceSpec {
536            type_: Some("ClusterIP".to_string()),
537            cluster_ip: Some("None".to_string()),
538            selector: Some(selector),
539            ports: Some(ports),
540            ..Default::default()
541        };
542
543        Service {
544            metadata: console.managed_resource_meta(console.service_name()),
545            spec: Some(spec),
546            status: None,
547        }
548    }
549
550    // TODO: remove this once everyone is upgraded to an orchestratord
551    // version with the separate console operator
552    async fn fix_deployment(
553        &self,
554        deployment_api: &Api<Deployment>,
555        new_deployment: &Deployment,
556    ) -> Result<(), Error> {
557        let Some(mut existing_deployment) =
558            get_resource(deployment_api, &new_deployment.name_unchecked()).await?
559        else {
560            return Ok(());
561        };
562
563        if existing_deployment.spec.as_ref().unwrap().selector
564            == new_deployment.spec.as_ref().unwrap().selector
565        {
566            return Ok(());
567        }
568
569        warn!("found existing deployment with old label selector, fixing");
570
571        // this is sufficient because the new labels are a superset of the
572        // old labels, so the existing label selector should still be valid
573        existing_deployment
574            .spec
575            .as_mut()
576            .unwrap()
577            .template
578            .metadata
579            .as_mut()
580            .unwrap()
581            .labels = new_deployment
582            .spec
583            .as_ref()
584            .unwrap()
585            .template
586            .metadata
587            .as_ref()
588            .unwrap()
589            .labels
590            .clone();
591
592        // using await_condition is not ideal in a controller loop, but this
593        // is very temporary and will only ever happen once, so this feels
594        // simpler than trying to introduce an entire state machine here
595        replace_resource(deployment_api, &existing_deployment).await?;
596        await_condition(
597            deployment_api.clone(),
598            &existing_deployment.name_unchecked(),
599            |deployment: Option<&Deployment>| {
600                let observed_generation = deployment
601                    .and_then(|deployment| deployment.status.as_ref())
602                    .and_then(|status| status.observed_generation)
603                    .unwrap_or(0);
604                let current_generation = deployment
605                    .and_then(|deployment| deployment.meta().generation)
606                    .unwrap_or(0);
607                let previous_generation = existing_deployment.meta().generation.unwrap_or(0);
608                observed_generation == current_generation
609                    && current_generation > previous_generation
610            },
611        )
612        .await
613        .map_err(|e| anyhow::anyhow!(e))?;
614        await_condition(
615            deployment_api.clone(),
616            &existing_deployment.name_unchecked(),
617            is_deployment_completed(),
618        )
619        .await
620        .map_err(|e| anyhow::anyhow!(e))?;
621
622        // delete the deployment but leave the pods around (via
623        // DeleteParams::orphan)
624        match kube::runtime::wait::delete::delete_and_finalize(
625            deployment_api.clone(),
626            &existing_deployment.name_unchecked(),
627            &DeleteParams::orphan(),
628        )
629        .await
630        {
631            Ok(_) => {}
632            Err(kube::runtime::wait::delete::Error::Delete(kube::Error::Api(e)))
633                if e.code == 404 =>
634            {
635                // the resource already doesn't exist
636            }
637            Err(e) => return Err(anyhow::anyhow!(e).into()),
638        }
639
640        // now, the normal apply of the new deployment (in the main loop)
641        // will take over the existing pods from the old deployment we just
642        // deleted, since we already updated the pod labels to be the same as
643        // the new label selector
644
645        Ok(())
646    }
647}
648
649#[async_trait::async_trait]
650impl k8s_controller::Context for Context {
651    type Resource = Console;
652    type Error = Error;
653
654    #[instrument(fields())]
655    async fn apply(
656        &self,
657        client: Client,
658        console: &Self::Resource,
659        metadata: &mut TraceMetadata,
660    ) -> Result<Option<Action>, Self::Error> {
661        if console.status.is_none() {
662            let step = metadata.step("initialize_status");
663            let console_api: Api<Console> =
664                Api::namespaced(client.clone(), &console.meta().namespace.clone().unwrap());
665            let mut new_console = console.clone();
666            new_console.status = Some(console.status());
667            console_api
668                .replace_status(
669                    &console.name_unchecked(),
670                    &PostParams::default(),
671                    &new_console,
672                )
673                .await?;
674            step.finish(Outcome::Completed);
675            // Updating the status should trigger a reconciliation
676            // which will include a status this time.
677            return Ok(None);
678        }
679
680        let namespace = console.namespace();
681        let network_policy_api: Api<NetworkPolicy> = Api::namespaced(client.clone(), &namespace);
682        let configmap_api: Api<ConfigMap> = Api::namespaced(client.clone(), &namespace);
683        let deployment_api: Api<Deployment> = Api::namespaced(client.clone(), &namespace);
684        let service_api: Api<Service> = Api::namespaced(client.clone(), &namespace);
685        let certificate_api: Api<Certificate> = Api::namespaced(client.clone(), &namespace);
686        let pdb_api: Api<PodDisruptionBudget> = Api::namespaced(client.clone(), &namespace);
687
688        let step = metadata.step("network_policies");
689        trace!("creating new network policies");
690        let network_policies = self.create_network_policies(console);
691        for network_policy in &network_policies {
692            apply_resource(&network_policy_api, network_policy).await?;
693        }
694        step.finish(if network_policies.is_empty() {
695            Outcome::Skipped
696        } else {
697            Outcome::Completed
698        });
699
700        let step = metadata.step("configmap");
701        trace!("creating new console configmap");
702        let console_configmap = self.create_console_app_configmap_object(console);
703        apply_resource(&configmap_api, &console_configmap).await?;
704        step.finish(Outcome::Completed);
705
706        let step = metadata.step("deployment");
707        trace!("creating new console deployment");
708        let console_deployment = self.create_console_deployment_object(console);
709        self.fix_deployment(&deployment_api, &console_deployment)
710            .await?;
711        apply_resource(&deployment_api, &console_deployment).await?;
712        step.finish(Outcome::Completed);
713
714        let step = metadata.step("pod_disruption_budget");
715        let pdb = pod_disruption_budget(
716            console.managed_resource_meta(console.deployment_name()),
717            &console_deployment,
718        );
719        apply_resource(&pdb_api, &pdb).await?;
720        step.finish(Outcome::Completed);
721
722        let step = metadata.step("service");
723        trace!("creating new console service");
724        let console_service = self.create_console_service_object(console);
725        apply_resource(&service_api, &console_service).await?;
726        step.finish(Outcome::Completed);
727
728        let step = metadata.step("certificate");
729        let console_external_certificate = self.create_console_external_certificate(console)?;
730        if let Some(certificate) = &console_external_certificate {
731            trace!("creating new console external certificate");
732            apply_resource(&certificate_api, certificate).await?;
733            step.finish(Outcome::Completed);
734        } else {
735            step.finish(Outcome::Skipped);
736        }
737
738        let step = metadata.step("sync_status");
739        self.sync_deployment_status(&client, console).await?;
740        step.finish(Outcome::Completed);
741
742        Ok(None)
743    }
744}
745
746#[cfg(test)]
747mod tests {
748    use mz_cloud_resources::crd::console::v1alpha1::ConsoleSpec;
749
750    use super::*;
751
752    fn test_context(enable_prometheus_scrape_annotations: bool) -> Context {
753        Context::new(Config {
754            enable_security_context: false,
755            enable_user_namespaces: false,
756            enable_prometheus_scrape_annotations,
757            image_pull_policy: KubernetesImagePullPolicy::IfNotPresent,
758            scheduler_name: None,
759            console_node_selector: vec![],
760            console_affinity: None,
761            console_tolerations: None,
762            console_default_resources: None,
763            network_policies_ingress_enabled: false,
764            network_policies_ingress_cidrs: vec![],
765            default_certificate_specs: DefaultCertificateSpecs::default(),
766            console_http_port: 8080,
767            console_internal_http_port: 8081,
768            balancerd_http_port: 6876,
769        })
770    }
771
772    fn test_console() -> Console {
773        let mut console = Console::new(
774            "test",
775            ConsoleSpec {
776                console_image_ref: "materialize/console:v0.0.0".to_owned(),
777                ..Default::default()
778            },
779        );
780        console.metadata.namespace = Some("test".to_owned());
781        console.metadata.uid = Some("test".to_owned());
782        console.status = Some(console.status());
783        console
784    }
785
786    #[mz_ore::test]
787    fn user_namespaces_set_host_users() {
788        for (enabled, expected) in [(false, None), (true, Some(false))] {
789            let mut context = test_context(false);
790            context.config.enable_user_namespaces = enabled;
791            let pod = context
792                .create_console_deployment_object(&test_console())
793                .spec
794                .unwrap()
795                .template
796                .spec
797                .unwrap();
798            assert_eq!(pod.host_users, expected);
799        }
800    }
801
802    #[mz_ore::test]
803    fn metrics_listener_is_exposed_and_annotated_when_enabled() {
804        for annotate in [false, true] {
805            let deployment =
806                test_context(annotate).create_console_deployment_object(&test_console());
807            let template = deployment.spec.unwrap().template;
808            let container = &template.spec.unwrap().containers[0];
809
810            let port = container
811                .ports
812                .iter()
813                .flatten()
814                .find(|port| port.name.as_deref() == Some("internal-http"))
815                .expect("the metrics port is declared");
816            assert_eq!(port.container_port, 8081);
817            let listener = container
818                .env
819                .iter()
820                .flatten()
821                .find(|var| var.name == "MZ_NGINX_METRICS_LISTENER_CONFIG")
822                .expect("nginx is told where to listen");
823            assert_eq!(listener.value.as_deref(), Some("listen 8081;"));
824
825            let scrape_port = template
826                .metadata
827                .and_then(|meta| meta.annotations)
828                .and_then(|annotations| annotations.get("prometheus.io/port").cloned());
829            assert_eq!(scrape_port.as_deref(), annotate.then_some("8081"));
830        }
831    }
832}