Skip to main content

mz_orchestratord/controller/
materialize.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::BTreeSet,
12    sync::{Arc, Mutex},
13    time::Duration,
14};
15
16use anyhow::Context as _;
17use http::HeaderValue;
18use k8s_controller::{
19    Outcome, TraceMetadata,
20    events::{Event, EventType},
21};
22use k8s_openapi::{
23    api::core::v1::{Affinity, Probe, ResourceRequirements, Secret, Toleration},
24    apimachinery::pkg::apis::meta::v1::{Condition, Time},
25    jiff::{SignedDuration, Timestamp},
26};
27use kube::{
28    Api, Client, Resource, ResourceExt,
29    api::{ListParams, PostParams},
30    runtime::controller::Action,
31};
32use tracing::{debug, trace, warn};
33use uuid::Uuid;
34
35use crate::{
36    Error,
37    controller::materialize::generation::V161,
38    k8s::{apply_resource, delete_resource},
39    matching_image_from_environmentd_image_ref,
40    metrics::Metrics,
41    parse_image_tag,
42    tls::{DefaultCertificateSpecs, issuer_ref_defined, resolved_dns_names},
43};
44use mz_cloud_provider::CloudProvider;
45use mz_cloud_resources::crd::{
46    ManagedResource,
47    balancer::v1alpha1::{Balancer, BalancerSpec},
48    console::v1alpha1::{BalancerdRef, Console, ConsoleSpec, HttpConnectionScheme},
49    materialize::LAST_KNOWN_RESOURCE_ID_ANNOTATION,
50    materialize::MaterializeRolloutStrategy,
51    materialize::v1alpha1::{Materialize, MaterializeStatus},
52};
53use mz_license_keys::validate;
54use mz_orchestrator_kubernetes::KubernetesImagePullPolicy;
55use mz_orchestrator_tracing::TracingCliArgs;
56use mz_ore::{cast::CastFrom, cli::KeyValueArg, instrument};
57
58pub mod generation;
59pub mod global;
60pub mod teleport;
61
62/// The name identifying this controller in its reconciliation metrics and in
63/// the reporter of the events it publishes.
64pub const CONTROLLER_NAME: &str = "materialize";
65
66#[derive(Clone)]
67pub struct Config {
68    pub cloud_provider: CloudProvider,
69    pub region: String,
70    pub create_balancers: bool,
71    pub create_console: bool,
72    pub helm_chart_version: Option<String>,
73    pub secrets_controller: String,
74    pub collect_pod_metrics: bool,
75    pub enable_prometheus_scrape_annotations: bool,
76
77    pub segment_api_key: Option<String>,
78    pub segment_client_side: bool,
79
80    pub console_image_tag_default: String,
81    pub console_image_tag_map: Vec<KeyValueArg<String, String>>,
82
83    pub aws_account_id: Option<String>,
84    pub environmentd_iam_role_arn: Option<String>,
85    pub environmentd_connection_role_arn: Option<String>,
86    pub aws_secrets_controller_tags: Vec<String>,
87    pub environmentd_availability_zones: Option<Vec<String>>,
88
89    pub ephemeral_volume_class: Option<String>,
90    pub scheduler_name: Option<String>,
91    pub enable_security_context: bool,
92    /// Whether to run environmentd and clusterd pods in a Kubernetes user
93    /// namespace (`hostUsers: false`).
94    pub enable_user_namespaces: bool,
95    pub enable_internal_statement_logging: bool,
96    pub statement_logging_max_sample_rate: Option<f64>,
97    pub statement_logging_target_data_rate: Option<usize>,
98
99    pub orchestratord_pod_selector_labels: Vec<KeyValueArg<String, String>>,
100    pub environmentd_node_selector: Vec<KeyValueArg<String, String>>,
101    pub environmentd_affinity: Option<Affinity>,
102    pub environmentd_tolerations: Option<Vec<Toleration>>,
103    pub environmentd_default_resources: Option<ResourceRequirements>,
104    /// Overlaid onto the built-in environmentd readiness probe. See
105    /// `generation::environmentd_probe` for the overlay semantics.
106    pub environmentd_default_readiness_probe: Option<Probe>,
107    /// Overlaid onto the built-in environmentd liveness probe. See
108    /// `generation::environmentd_probe` for the overlay semantics.
109    pub environmentd_default_liveness_probe: Option<Probe>,
110    /// Overlaid onto the built-in environmentd probe to form the startup
111    /// probe. See `generation::environmentd_probe` for the overlay semantics.
112    pub environmentd_default_startup_probe: Option<Probe>,
113    /// The name of a `PriorityClass` to assign to environmentd pods, if any.
114    pub environmentd_priority_class_name: Option<String>,
115    pub clusterd_node_selector: Vec<KeyValueArg<String, String>>,
116    pub clusterd_affinity: Option<Affinity>,
117    pub clusterd_tolerations: Option<Vec<Toleration>>,
118    /// The name of a `PriorityClass` to assign to clusterd pods, if any.
119    pub clusterd_priority_class_name: Option<String>,
120    pub image_pull_policy: KubernetesImagePullPolicy,
121    pub network_policies_internal_enabled: bool,
122    pub network_policies_ingress_enabled: bool,
123    pub network_policies_ingress_cidrs: Vec<String>,
124    pub network_policies_egress_enabled: bool,
125    pub network_policies_egress_cidrs: Vec<String>,
126
127    pub environmentd_cluster_replica_sizes: Option<String>,
128    pub bootstrap_default_cluster_replica_size: Option<String>,
129    pub bootstrap_builtin_system_cluster_replica_size: Option<String>,
130    pub bootstrap_builtin_probe_cluster_replica_size: Option<String>,
131    pub bootstrap_builtin_support_cluster_replica_size: Option<String>,
132    pub bootstrap_builtin_catalog_server_cluster_replica_size: Option<String>,
133    pub bootstrap_builtin_analytics_cluster_replica_size: Option<String>,
134    pub bootstrap_builtin_system_cluster_replication_factor: Option<u32>,
135    pub bootstrap_builtin_probe_cluster_replication_factor: Option<u32>,
136    pub bootstrap_builtin_support_cluster_replication_factor: Option<u32>,
137    pub bootstrap_builtin_analytics_cluster_replication_factor: Option<u32>,
138
139    pub environmentd_allowed_origins: Vec<HeaderValue>,
140    pub internal_console_proxy_url: String,
141
142    pub environmentd_sql_port: u16,
143    pub environmentd_http_port: u16,
144    pub environmentd_internal_sql_port: u16,
145    pub environmentd_internal_http_port: u16,
146    pub environmentd_internal_persist_pubsub_port: u16,
147
148    pub default_certificate_specs: DefaultCertificateSpecs,
149
150    pub disable_license_key_checks: bool,
151    pub disable_database_network_policies: bool,
152
153    pub tracing: TracingCliArgs,
154    pub orchestratord_namespace: String,
155
156    pub teleport: Option<teleport::TeleportConfig>,
157}
158
159pub struct Context {
160    config: Config,
161    metrics: Arc<Metrics>,
162    needs_update: Arc<Mutex<BTreeSet<String>>>,
163}
164
165impl Context {
166    pub fn new(config: Config, metrics: Arc<Metrics>) -> Self {
167        if config.cloud_provider == CloudProvider::Aws {
168            assert!(
169                config.aws_account_id.is_some(),
170                "--aws-account-id is required when using --cloud-provider=aws"
171            );
172        }
173
174        Self {
175            config,
176            metrics,
177            needs_update: Default::default(),
178        }
179    }
180
181    fn set_needs_update(&self, mz: &Materialize, needs_update: bool) {
182        let mut needs_update_set = self.needs_update.lock().unwrap();
183        if needs_update {
184            needs_update_set.insert(mz.name_unchecked());
185        } else {
186            needs_update_set.remove(&mz.name_unchecked());
187        }
188        self.metrics
189            .environmentd_needs_update
190            .set(u64::cast_from(needs_update_set.len()));
191    }
192
193    /// Writes `status`, if it differs from the current status in anything but
194    /// its timestamps, and publishes the new `UpToDate` condition as an event
195    /// once it has been written.
196    async fn update_status(
197        &self,
198        metadata: &TraceMetadata,
199        mz_api: &Api<Materialize>,
200        mz: &Materialize,
201        status: MaterializeStatus,
202        needs_update: bool,
203    ) -> Result<Materialize, kube::Error> {
204        self.set_needs_update(mz, needs_update);
205
206        let mut new_mz = mz.clone();
207        if !mz
208            .status
209            .as_ref()
210            .map_or(true, |mz_status| mz_status.needs_update(&status))
211        {
212            return Ok(new_mz);
213        }
214
215        let condition = status.conditions.first().cloned();
216        new_mz.status = Some(status);
217        let new_mz = mz_api
218            .replace_status(&mz.name_unchecked(), &PostParams::default(), &new_mz)
219            .await?;
220
221        if let Some(condition) = condition {
222            metadata
223                .publish_event(Event {
224                    type_: transition_event_type(&condition),
225                    reason: condition.reason,
226                    action: "Reconcile".into(),
227                    note: Some(condition.message),
228                    related: None,
229                })
230                .await;
231        }
232
233        Ok(new_mz)
234    }
235
236    /// Deletes `generation`'s resources, releasing the read holds its
237    /// environmentd was keeping.
238    async fn teardown_generation(
239        &self,
240        metadata: &TraceMetadata,
241        client: &Client,
242        mz: &Materialize,
243        resources: &generation::Resources,
244        generation: u64,
245    ) -> Result<(), Error> {
246        let step = metadata.step("teardown_generation");
247        resources
248            .teardown_generation(client, mz, generation)
249            .await?;
250        step.finish(Outcome::Completed);
251        Ok(())
252    }
253
254    async fn promote(
255        &self,
256        metadata: &TraceMetadata,
257        client: &Client,
258        mz: &Materialize,
259        resources: generation::Resources,
260        active_generation: u64,
261        desired_generation: u64,
262        resources_hash: String,
263    ) -> Result<Option<Action>, Error> {
264        let step = metadata.step("promote");
265        if let Some(action) = resources
266            .promote_services(client, mz.should_force_promote(), &mz.namespace())
267            .await?
268        {
269            step.finish(Outcome::Waiting);
270            return Ok(Some(action));
271        }
272        step.finish(Outcome::Completed);
273
274        self.teardown_generation(metadata, client, mz, &resources, active_generation)
275            .await?;
276        let mz_api: Api<Materialize> = Api::namespaced(client.clone(), &mz.namespace());
277        self.update_status(
278            metadata,
279            &mz_api,
280            mz,
281            MaterializeStatus {
282                active_generation: desired_generation,
283                last_completed_rollout_request: mz.requested_reconciliation_id(),
284                last_completed_rollout_environmentd_image_ref: Some(
285                    mz.spec.environmentd_image_ref.clone(),
286                ),
287                resource_id: mz.status().resource_id,
288                resources_hash,
289                last_completed_rollout_hash: None,
290                conditions: vec![Condition {
291                    type_: "UpToDate".into(),
292                    status: "True".into(),
293                    last_transition_time: Time(Timestamp::now()),
294                    message: format!(
295                        "Successfully applied changes for generation {desired_generation}"
296                    ),
297                    observed_generation: mz.meta().generation,
298                    reason: "Applied".into(),
299                }],
300            },
301            false,
302        )
303        .await?;
304        Ok(None)
305    }
306
307    async fn check_environment_id_conflicts(
308        &self,
309        client: &Client,
310        mz: &Materialize,
311    ) -> Result<(), Error> {
312        if mz.spec.environment_id.is_nil() {
313            // this is always a bug - we delay doing this check until the
314            // resource should have an environment id set, either from the
315            // license key, or explicitly given, or randomly defaulted.
316            return Err(Error::Anyhow(anyhow::anyhow!(
317                "trying to reconcile a materialize resource with no environment id - this is a bug!"
318            )));
319        }
320
321        let mz_api: Api<Materialize> = Api::all(client.clone());
322        let all_mz = mz_api.list(&ListParams::default()).await?;
323        for existing_mz in &all_mz.items {
324            if existing_mz.spec.environment_id == mz.spec.environment_id
325                && existing_mz.metadata.uid != mz.metadata.uid
326            {
327                return Err(Error::Anyhow(anyhow::anyhow!(
328                    "Materialize resources {}/{} and {}/{} have the environmentId field set to the same value. This field must be unique across environments.",
329                    mz.namespace(),
330                    mz.name_unchecked(),
331                    existing_mz.namespace(),
332                    existing_mz.name_unchecked(),
333                )));
334            }
335        }
336
337        Ok(())
338    }
339
340    /// Checks that no other Materialize resource uses, or is about to use,
341    /// `resource_id`, the ID that `mz`'s initial status gets. That ID comes
342    /// from `mz`'s [`LAST_KNOWN_RESOURCE_ID_ANNOTATION`] if it has one, and is
343    /// random otherwise.
344    ///
345    /// Resources are named after the resource ID, so two Materialize
346    /// resources sharing one would manage, and tear down, each other's
347    /// resources.
348    async fn check_resource_id_conflicts(
349        &self,
350        client: &Client,
351        mz: &Materialize,
352        resource_id: &str,
353    ) -> Result<(), Error> {
354        let mz_api: Api<Materialize> = Api::all(client.clone());
355        let all_mz = mz_api.list(&ListParams::default()).await?;
356        for existing_mz in &all_mz.items {
357            if existing_mz.metadata.uid == mz.metadata.uid {
358                continue;
359            }
360            // A resource with no status yet takes its ID from its annotation,
361            // so two new resources asking for the same ID both conflict.
362            let existing_resource_id = match &existing_mz.status {
363                Some(status) => Some(status.resource_id.as_str()),
364                None => existing_mz
365                    .annotations()
366                    .get(LAST_KNOWN_RESOURCE_ID_ANNOTATION)
367                    .map(|id| id.as_str()),
368            };
369            if existing_resource_id == Some(resource_id) {
370                return Err(Error::Anyhow(anyhow::anyhow!(
371                    "Materialize resource {}/{} would use resource ID {resource_id}, which Materialize resource {}/{} already uses. If it comes from the {LAST_KNOWN_RESOURCE_ID_ANNOTATION} annotation, delete the old resource first, or remove the annotation to get a new resource ID.",
372                    mz.namespace(),
373                    mz.name_unchecked(),
374                    existing_mz.namespace(),
375                    existing_mz.name_unchecked(),
376                )));
377            }
378        }
379
380        Ok(())
381    }
382}
383
384#[async_trait::async_trait]
385impl k8s_controller::Context for Context {
386    type Resource = Materialize;
387    type Error = Error;
388
389    const FINALIZER_NAME: Option<&'static str> =
390        Some("orchestratord.materialize.cloud/materialize");
391
392    #[instrument(fields(organization_name=mz.name_unchecked()))]
393    async fn apply(
394        &self,
395        client: Client,
396        mz: &Self::Resource,
397        metadata: &mut TraceMetadata,
398    ) -> Result<Option<Action>, Self::Error> {
399        let metadata = &*metadata;
400        // First, so that the environment stays described while reconciling
401        // it fails. Every status write triggers another pass, which publishes
402        // the new active generation.
403        self.metrics.observe_environment(
404            &mz.namespace(),
405            &mz.name_unchecked(),
406            mz.spec.environment_id,
407            mz.status.as_ref().map(|status| status.active_generation),
408        );
409        let mz_api: Api<Materialize> = Api::namespaced(client.clone(), &mz.namespace());
410        let balancer_api: Api<Balancer> = Api::namespaced(client.clone(), &mz.namespace());
411        let console_api: Api<Console> = Api::namespaced(client.clone(), &mz.namespace());
412        let secret_api: Api<Secret> = Api::namespaced(client.clone(), &mz.namespace());
413
414        let status = mz.status();
415        if mz.status.is_none() {
416            let step = metadata.step("initialize_status");
417            self.check_resource_id_conflicts(&client, mz, &status.resource_id)
418                .await?;
419            self.update_status(metadata, &mz_api, mz, status, true)
420                .await?;
421            step.finish(Outcome::Completed);
422            // Updating the status should trigger a reconciliation
423            // which will include a status this time.
424            return Ok(None);
425        }
426
427        let step = metadata.step("resolve_environment_id");
428        let backend_secret = secret_api.get(&mz.spec.backend_secret_name).await?;
429        let license_key_environment_id: Option<Uuid> = if let Some(license_key) = backend_secret
430            .data
431            .as_ref()
432            .and_then(|data| data.get("license_key"))
433        {
434            let license_key = validate(
435                str::from_utf8(&license_key.0)
436                    .context("invalid utf8")?
437                    .trim(),
438            )?;
439            let environment_id = license_key
440                .environment_id
441                .parse()
442                .context("invalid environment id in license key")?;
443            Some(environment_id)
444        } else {
445            if mz.meets_minimum_version(&V161) {
446                return Err(Error::Anyhow(anyhow::anyhow!(
447                    "license_key is required when running in kubernetes",
448                )));
449            } else {
450                None
451            }
452        };
453
454        if mz.spec.request_rollout.is_nil() || mz.spec.environment_id.is_nil() {
455            let mut mz = mz.clone();
456            if mz.spec.request_rollout.is_nil() {
457                mz.spec.request_rollout = Uuid::new_v4();
458            }
459            if mz.spec.environment_id.is_nil() {
460                if let Some(environment_id) = license_key_environment_id {
461                    if environment_id.is_nil() {
462                        // this makes it easier to use a license key in
463                        // development with no environment id set
464                        mz.spec.environment_id = Uuid::new_v4();
465                    } else {
466                        mz.spec.environment_id = environment_id;
467                    }
468                } else {
469                    if mz.meets_minimum_version(&V161) {
470                        return Err(Error::Anyhow(anyhow::anyhow!(
471                            "environmentId is not set in materialize resource {}/{} but no license key was given",
472                            mz.namespace(),
473                            mz.name_unchecked()
474                        )));
475                    } else {
476                        mz.spec.environment_id = Uuid::new_v4();
477                    }
478                }
479            }
480            mz_api
481                .replace(&mz.name_unchecked(), &PostParams::default(), &mz)
482                .await?;
483            step.finish(Outcome::Completed);
484            // Updating the spec should also trigger a reconciliation.
485            // We can't do that as part of the above check because you can't
486            // update both the spec and the status in a single api call.
487            return Ok(None);
488        }
489
490        if let Some(environment_id) = license_key_environment_id {
491            // we still allow a nil environment id in the license key to be
492            // accepted for any provided environment id, to support cloud
493            if !environment_id.is_nil() && mz.spec.environment_id != environment_id {
494                return Err(Error::Anyhow(anyhow::anyhow!(
495                    "environment_id is set in materialize resource {}/{} but does not match the environment_id set in the associated license key {}",
496                    mz.namespace(),
497                    mz.name_unchecked(),
498                    environment_id,
499                )));
500            }
501        }
502
503        for (field, probe) in [
504            (
505                "environmentdReadinessProbe",
506                &mz.spec.environmentd_readiness_probe,
507            ),
508            (
509                "environmentdLivenessProbe",
510                &mz.spec.environmentd_liveness_probe,
511            ),
512            (
513                "environmentdStartupProbe",
514                &mz.spec.environmentd_startup_probe,
515            ),
516        ] {
517            if let Some(probe) = probe {
518                generation::validate_probe_handlers(probe).map_err(|e| {
519                    Error::Anyhow(anyhow::anyhow!(
520                        "invalid {field} in materialize resource {}/{}: {e}",
521                        mz.namespace(),
522                        mz.name_unchecked(),
523                    ))
524                })?;
525            }
526        }
527
528        self.check_environment_id_conflicts(&client, mz).await?;
529        step.finish(Outcome::Completed);
530
531        let step = metadata.step("global_resources");
532        global::Resources::new(&self.config, mz)?
533            .apply(&client, &mz.namespace())
534            .await?;
535        step.finish(Outcome::Completed);
536
537        // we compare the hash against the environment resources generated
538        // for the current active generation, since that's what we expect to
539        // have been applied earlier, but we don't want to use these
540        // environment resources because when we apply them, we want to apply
541        // them with data that uses the new generation
542        let active_resources =
543            generation::Resources::new(&self.config, mz, status.active_generation);
544        let has_current_changes = status.resources_hash != active_resources.generate_hash();
545        let active_generation = status.active_generation;
546        let next_generation = active_generation + 1;
547        let desired_generation = if has_current_changes {
548            next_generation
549        } else {
550            active_generation
551        };
552
553        // here we regenerate the environment resources using the
554        // same inputs except with an updated generation
555        let resources = generation::Resources::new(&self.config, mz, desired_generation);
556        let resources_hash = resources.generate_hash();
557
558        let mut result = match (
559            mz.is_promoting(),
560            has_current_changes,
561            mz.rollout_requested(),
562        ) {
563            // If we're in status promoting, we MUST promote now.
564            // We don't know if we successfully promoted or not yet.
565            (true, _, _) => {
566                self.promote(
567                    metadata,
568                    &client,
569                    mz,
570                    resources,
571                    active_generation,
572                    desired_generation,
573                    resources_hash,
574                )
575                .await
576            }
577            // There are changes pending, and we want to apply them.
578            (false, true, true) => {
579                // If a rollout has been in progress for longer than the
580                // configured timeout, cancel it. While a rollout is in
581                // progress the new generation runs un-promoted and holds back
582                // compaction via read holds; promoting it after a long delay
583                // can cause incident-inducing load, so we abort instead and
584                // let the user retry by requesting a fresh rollout.
585                //
586                // We never cancel a force-promoting rollout (including the
587                // `ImmediatelyPromoteCausingDowntime` strategy), because by
588                // then the previously-active generation may already be torn
589                // down, leaving nothing to fall back to.
590                if !mz.should_force_promote() {
591                    if let Some(started) = mz.rollout_in_progress_since() {
592                        let timeout = mz.rollout_request_timeout();
593                        let elapsed = Timestamp::now().duration_since(started);
594                        let timed_out = SignedDuration::try_from(timeout)
595                            .is_ok_and(|timeout| elapsed >= timeout);
596                        if timed_out {
597                            warn!(
598                                "rollout to generation {desired_generation} exceeded timeout, cancelling"
599                            );
600                            // Tear down the un-promoted generation to release
601                            // its read holds.
602                            self.teardown_generation(
603                                metadata,
604                                &client,
605                                mz,
606                                &resources,
607                                next_generation,
608                            )
609                            .await?;
610                            self.update_status(
611                                metadata,
612                                &mz_api,
613                                mz,
614                                MaterializeStatus {
615                                    active_generation,
616                                    // Mark this rollout request as completed so
617                                    // that we don't immediately retry it; the
618                                    // user must request a new rollout to try
619                                    // again.
620                                    last_completed_rollout_request: mz
621                                        .requested_reconciliation_id(),
622                                    last_completed_rollout_environmentd_image_ref: status
623                                        .last_completed_rollout_environmentd_image_ref
624                                        .clone(),
625                                    resource_id: status.resource_id.clone(),
626                                    resources_hash: status.resources_hash.clone(),
627                                    last_completed_rollout_hash: None,
628                                    conditions: vec![Condition {
629                                        type_: "UpToDate".into(),
630                                        status: "False".into(),
631                                        last_transition_time: Time(Timestamp::now()),
632                                        message: format!(
633                                            "Cancelled rollout to generation \
634                                             {desired_generation} after it \
635                                             exceeded the rollout timeout of {}",
636                                            humantime::format_duration(timeout),
637                                        ),
638                                        observed_generation: mz.meta().generation,
639                                        reason: "RolloutTimeout".into(),
640                                    }],
641                                },
642                                active_generation != desired_generation,
643                            )
644                            .await?;
645                            return Ok(None);
646                        }
647                    }
648                }
649
650                if !mz.within_upgrade_window() {
651                    let last_completed_rollout_environmentd_image_ref =
652                        status.last_completed_rollout_environmentd_image_ref;
653
654                    self.update_status(
655                        metadata,
656                        &mz_api,
657                        mz,
658                        MaterializeStatus {
659                            active_generation,
660                            last_completed_rollout_request: status.last_completed_rollout_request,
661                            last_completed_rollout_environmentd_image_ref:
662                                last_completed_rollout_environmentd_image_ref.clone(),
663                            resource_id: status.resource_id,
664                            resources_hash: status.resources_hash,
665                            last_completed_rollout_hash: None,
666                            conditions: vec![Condition {
667                                type_: "UpToDate".into(),
668                                status: "False".into(),
669                                last_transition_time: Time(Timestamp::now()),
670                                message: format!(
671                                    "Refusing to upgrade from {} to {}. \
672                                     More than one major version from \
673                                     last successful rollout. If coming \
674                                     from Self Managed 25.2, upgrade to \
675                                     materialize/environmentd:v0.147.20 \
676                                     first.",
677                                    last_completed_rollout_environmentd_image_ref
678                                        .expect("should be set if upgrade window check fails"),
679                                    mz.spec.environmentd_image_ref,
680                                ),
681                                observed_generation: mz.meta().generation,
682                                reason: "FailedDeploy".into(),
683                            }],
684                        },
685                        active_generation != desired_generation,
686                    )
687                    .await?;
688                    return Ok(None);
689                }
690
691                // we remove the environment resources hash annotation here
692                // because if we fail halfway through applying the resources,
693                // things will be in an inconsistent state, and we don't want
694                // to allow the possibility of the user making a second
695                // change which reverts to the original state and then
696                // skipping retrying this apply, since that would leave
697                // things in a permanently inconsistent state.
698                // note that environment.spec will be empty here after
699                // replace_status, but this is fine because we already
700                // extracted all of the information we want from the spec
701                // earlier.
702                let mz = if mz.is_ready_to_promote(&resources_hash) {
703                    mz
704                } else {
705                    &self
706                        .update_status(
707                            metadata,
708                            &mz_api,
709                            mz,
710                            MaterializeStatus {
711                                active_generation,
712                                // don't update the reconciliation id yet,
713                                // because the rollout hasn't yet completed. if
714                                // we fail later on, we want to ensure that the
715                                // rollout gets retried.
716                                last_completed_rollout_request: status
717                                    .last_completed_rollout_request,
718                                last_completed_rollout_environmentd_image_ref: status
719                                    .last_completed_rollout_environmentd_image_ref,
720                                resource_id: status.resource_id.clone(),
721                                resources_hash: String::new(),
722                                last_completed_rollout_hash: None,
723                                conditions: vec![Condition {
724                                    type_: "UpToDate".into(),
725                                    status: "Unknown".into(),
726                                    last_transition_time: Time(Timestamp::now()),
727                                    message: format!(
728                                        "Applying changes for generation {desired_generation}"
729                                    ),
730                                    observed_generation: mz.meta().generation,
731                                    reason: "Applying".into(),
732                                }],
733                            },
734                            active_generation != desired_generation,
735                        )
736                        .await?
737                };
738                let status = mz.status();
739
740                if mz.spec.rollout_strategy
741                    == MaterializeRolloutStrategy::ImmediatelyPromoteCausingDowntime
742                {
743                    // The only reason someone would choose this strategy is if they didn't have
744                    // space for the two generations of pods.
745                    // Lets make room for the new ones by deleting the old generation.
746                    self.teardown_generation(metadata, &client, mz, &resources, active_generation)
747                        .await?;
748                }
749
750                trace!("applying environment resources");
751                let step = metadata.step("generation_resources");
752                let applied = resources
753                    .apply(&client, mz.should_force_promote(), &mz.namespace())
754                    .await;
755                step.finish_with(&applied);
756                match applied {
757                    Ok(Some(action)) => {
758                        trace!("new environment is not yet ready");
759                        Ok(Some(action))
760                    }
761                    Ok(None) => {
762                        if mz.spec.rollout_strategy == MaterializeRolloutStrategy::ManuallyPromote
763                            && !mz.should_force_promote()
764                        {
765                            trace!(
766                                "Ready to promote, but not promoting because the instance is configured with ManuallyPromote rollout strategy."
767                            );
768                            self.update_status(
769                                metadata,
770                                &mz_api,
771                                mz,
772                                MaterializeStatus {
773                                    active_generation,
774                                    last_completed_rollout_request: status
775                                        .last_completed_rollout_request,
776                                    last_completed_rollout_environmentd_image_ref: status
777                                        .last_completed_rollout_environmentd_image_ref,
778                                    resource_id: status.resource_id,
779                                    resources_hash,
780                                    last_completed_rollout_hash: None,
781                                    conditions: vec![Condition {
782                                        type_: "UpToDate".into(),
783                                        status: "Unknown".into(),
784                                        // Carry the `Applying` phase's
785                                        // timestamp forward (both phases are
786                                        // `Unknown`) so the rollout timeout
787                                        // spans Applying + ReadyToPromote
788                                        // rather than resetting here.
789                                        last_transition_time: Time(mz.up_to_date_transition_time(
790                                            "Unknown",
791                                            Timestamp::now(),
792                                        )),
793                                        message: format!(
794                                            "Ready to promote generation {desired_generation}"
795                                        ),
796                                        observed_generation: mz.meta().generation,
797                                        reason: "ReadyToPromote".into(),
798                                    }],
799                                },
800                                active_generation != desired_generation,
801                            )
802                            .await?;
803                            return Ok(None);
804                        }
805                        // do this last, so that we keep traffic pointing at
806                        // the previous environmentd until the new one is
807                        // fully ready
808
809                        // Update the status before calling promote, so that we know
810                        // we've crossed the point of no return.
811                        // Once we see this status, we must promote without taking other actions.
812                        self.update_status(
813                            metadata,
814                            &mz_api,
815                            mz,
816                            MaterializeStatus {
817                                active_generation,
818                                // don't update the reconciliation id yet,
819                                // because the rollout hasn't yet completed. if
820                                // we fail later on, we want to ensure that the
821                                // rollout gets retried.
822                                last_completed_rollout_request: status
823                                    .last_completed_rollout_request,
824                                last_completed_rollout_environmentd_image_ref: status
825                                    .last_completed_rollout_environmentd_image_ref,
826                                resource_id: status.resource_id,
827                                resources_hash: resources_hash.clone(),
828                                last_completed_rollout_hash: None,
829                                conditions: vec![Condition {
830                                    type_: "UpToDate".into(),
831                                    status: "Unknown".into(),
832                                    last_transition_time: Time(Timestamp::now()),
833                                    message: format!(
834                                        "Attempting to promote generation {desired_generation}"
835                                    ),
836                                    observed_generation: mz.meta().generation,
837                                    reason: "Promoting".into(),
838                                }],
839                            },
840                            active_generation != desired_generation,
841                        )
842                        .await?;
843                        self.promote(
844                            metadata,
845                            &client,
846                            mz,
847                            resources,
848                            active_generation,
849                            desired_generation,
850                            resources_hash,
851                        )
852                        .await
853                    }
854                    Err(e) => {
855                        self.update_status(
856                            metadata,
857                            &mz_api,
858                            mz,
859                            MaterializeStatus {
860                                active_generation,
861                                // also don't update the reconciliation id
862                                // here, because there was an error during
863                                // the rollout and we want to ensure it gets
864                                // retried.
865                                last_completed_rollout_request: status
866                                    .last_completed_rollout_request,
867                                last_completed_rollout_environmentd_image_ref: status
868                                    .last_completed_rollout_environmentd_image_ref,
869                                resource_id: status.resource_id,
870                                resources_hash: status.resources_hash,
871                                last_completed_rollout_hash: None,
872                                conditions: vec![Condition {
873                                    type_: "UpToDate".into(),
874                                    status: "False".into(),
875                                    last_transition_time: Time(Timestamp::now()),
876                                    message: format!(
877                                        "Failed to apply changes for \
878                                         generation {desired_generation}: {e}"
879                                    ),
880                                    observed_generation: mz.meta().generation,
881                                    reason: "FailedDeploy".into(),
882                                }],
883                            },
884                            active_generation != desired_generation,
885                        )
886                        .await?;
887                        Err(e)
888                    }
889                }
890            }
891            // There are changes pending, but we don't want to apply them yet.
892            (false, true, false) => {
893                let mut needs_update = mz.conditions_need_update();
894                if mz.update_in_progress() {
895                    self.teardown_generation(metadata, &client, mz, &resources, next_generation)
896                        .await?;
897                    needs_update = true;
898                }
899                if needs_update {
900                    self.update_status(metadata, &mz_api,
901                        mz,
902                        MaterializeStatus {
903                            active_generation,
904                            last_completed_rollout_request: mz.requested_reconciliation_id(),
905                            last_completed_rollout_environmentd_image_ref: status
906                                .last_completed_rollout_environmentd_image_ref,
907                            resource_id: status.resource_id.clone(),
908                            resources_hash: status.resources_hash,
909                            last_completed_rollout_hash: None,
910                            conditions: vec![Condition {
911                                type_: "UpToDate".into(),
912                                status: "False".into(),
913                                last_transition_time: Time(Timestamp::now()),
914                                message: format!(
915                                    "Changes detected, waiting for approval for generation {desired_generation}"
916                                ),
917                                observed_generation: mz.meta().generation,
918                                reason: "WaitingForApproval".into(),
919                            }],
920                        },
921                        active_generation != desired_generation,
922                    )
923                    .await?;
924                }
925                debug!("changes detected, waiting for approval");
926                Ok(None)
927            }
928            // No changes pending, but we might need to clean up a partially applied rollout.
929            (false, false, _) => {
930                // this can happen if we update the environment, but then revert
931                // that update before the update was deployed. in this case, we
932                // don't want the environment to still show up as
933                // WaitingForApproval.
934                let mut needs_update = mz.conditions_need_update() || mz.rollout_requested();
935                if mz.update_in_progress() {
936                    self.teardown_generation(metadata, &client, mz, &resources, next_generation)
937                        .await?;
938                    needs_update = true;
939                }
940                if needs_update {
941                    self.update_status(
942                        metadata,
943                        &mz_api,
944                        mz,
945                        MaterializeStatus {
946                            active_generation,
947                            last_completed_rollout_request: mz.requested_reconciliation_id(),
948                            last_completed_rollout_environmentd_image_ref: status
949                                .last_completed_rollout_environmentd_image_ref,
950                            resource_id: status.resource_id.clone(),
951                            resources_hash: status.resources_hash,
952                            last_completed_rollout_hash: None,
953                            conditions: vec![Condition {
954                                type_: "UpToDate".into(),
955                                status: "True".into(),
956                                last_transition_time: Time(Timestamp::now()),
957                                message: format!(
958                                    "No changes found from generation {active_generation}"
959                                ),
960                                observed_generation: mz.meta().generation,
961                                reason: "Applied".into(),
962                            }],
963                        },
964                        active_generation != desired_generation,
965                    )
966                    .await?;
967                }
968                debug!("no changes");
969                Ok(None)
970            }
971        }?;
972
973        if let Some(action) = result {
974            return Ok(Some(action));
975        }
976
977        // balancers rely on the environmentd service existing, which is
978        // enforced by the environmentd rollout process being able to call
979        // into the promotion endpoint
980
981        let step = metadata.step("balancer");
982        if self.config.create_balancers {
983            let balancer = Balancer {
984                metadata: mz.managed_resource_meta(mz.name_unchecked()),
985                spec: BalancerSpec {
986                    balancerd_image_ref: matching_image_from_environmentd_image_ref(
987                        mz.active_environmentd_image_ref(),
988                        "balancerd",
989                        None,
990                    ),
991                    resource_requirements: mz.spec.balancerd_resource_requirements.clone(),
992                    configmap_name: mz.spec.balancerd_configmap_name.clone(),
993                    replicas: Some(mz.balancerd_replicas()),
994                    externally_scaled: mz.spec.balancerd_externally_scaled,
995                    external_certificate_spec: mz.spec.balancerd_external_certificate_spec.clone(),
996                    internal_certificate_spec: mz.spec.internal_certificate_spec.clone(),
997                    pod_annotations: mz.spec.pod_annotations.clone(),
998                    pod_labels: mz.spec.pod_labels.clone(),
999                    static_routing: Some(
1000                        mz_cloud_resources::crd::balancer::v1alpha1::StaticRoutingConfig {
1001                            environmentd_namespace: mz.namespace(),
1002                            environmentd_service_name: mz.environmentd_service_name(),
1003                        },
1004                    ),
1005                    frontegg_routing: None,
1006                    resource_id: Some(status.resource_id.clone()),
1007                },
1008                status: None,
1009            };
1010            let balancer = apply_resource(&balancer_api, &balancer).await?;
1011            result = wait_for_balancer(&balancer)?;
1012            step.finish(match result {
1013                Some(_) => Outcome::Waiting,
1014                None => Outcome::Completed,
1015            });
1016        } else {
1017            delete_resource(&balancer_api, &mz.name_unchecked()).await?;
1018            step.finish(Outcome::Skipped);
1019        }
1020
1021        if let Some(action) = result {
1022            return Ok(Some(action));
1023        }
1024
1025        // and the console relies on the balancer service existing, which is
1026        // enforced by wait_for_balancer
1027
1028        let step = metadata.step("console");
1029        if self.config.create_console {
1030            let active_environmentd_image_ref = mz.active_environmentd_image_ref();
1031            let environmentd_image_tag =
1032                parse_image_tag(active_environmentd_image_ref).unwrap_or("latest");
1033            let console_image_tag = self
1034                .config
1035                .console_image_tag_map
1036                .iter()
1037                .find(|kv| kv.key == environmentd_image_tag)
1038                .map(|kv| kv.value.clone())
1039                .unwrap_or_else(|| self.config.console_image_tag_default.clone());
1040            let console = Console {
1041                metadata: mz.managed_resource_meta(mz.name_unchecked()),
1042                spec: ConsoleSpec {
1043                    console_image_ref: matching_image_from_environmentd_image_ref(
1044                        active_environmentd_image_ref,
1045                        "console",
1046                        Some(&console_image_tag),
1047                    ),
1048                    resource_requirements: mz.spec.console_resource_requirements.clone(),
1049                    replicas: Some(mz.console_replicas()),
1050                    external_certificate_spec: mz.spec.console_external_certificate_spec.clone(),
1051                    pod_annotations: mz.spec.pod_annotations.clone(),
1052                    pod_labels: mz.spec.pod_labels.clone(),
1053                    balancerd: BalancerdRef {
1054                        service_name: mz.balancerd_service_name(),
1055                        namespace: mz.namespace(),
1056                        scheme: if issuer_ref_defined(
1057                            &self.config.default_certificate_specs.balancerd_external,
1058                            &mz.spec.balancerd_external_certificate_spec,
1059                        ) {
1060                            HttpConnectionScheme::Https
1061                        } else {
1062                            HttpConnectionScheme::Http
1063                        },
1064                        dns_names: resolved_dns_names(
1065                            &self.config.default_certificate_specs.balancerd_external,
1066                            &mz.spec.balancerd_external_certificate_spec,
1067                        ),
1068                    },
1069                    authenticator_kind: mz.spec.authenticator_kind,
1070                    resource_id: Some(status.resource_id),
1071                },
1072                status: None,
1073            };
1074            apply_resource(&console_api, &console).await?;
1075            step.finish(Outcome::Completed);
1076        } else {
1077            delete_resource(&console_api, &mz.name_unchecked()).await?;
1078            step.finish(Outcome::Skipped);
1079        }
1080
1081        Ok(result)
1082    }
1083
1084    #[instrument(fields(organization_name=mz.name_unchecked()))]
1085    async fn cleanup(
1086        &self,
1087        _client: Client,
1088        mz: &Self::Resource,
1089        _metadata: &mut TraceMetadata,
1090    ) -> Result<Option<Action>, Self::Error> {
1091        self.set_needs_update(mz, false);
1092        self.metrics
1093            .forget_environment(&mz.namespace(), &mz.name_unchecked());
1094
1095        Ok(None)
1096    }
1097}
1098
1099/// The type of the event reporting that the `UpToDate` condition became
1100/// `condition`: a warning if the environment is not up to date for any reason
1101/// other than waiting for a rollout to be approved, which is the operator
1102/// following its configuration.
1103fn transition_event_type(condition: &Condition) -> EventType {
1104    match condition.reason.as_str() {
1105        "WaitingForApproval" => EventType::Normal,
1106        _ if condition.status == "False" => EventType::Warning,
1107        _ => EventType::Normal,
1108    }
1109}
1110
1111fn wait_for_balancer(balancer: &Balancer) -> Result<Option<Action>, Error> {
1112    if let Some(conditions) = balancer
1113        .status
1114        .as_ref()
1115        .map(|status| status.conditions.as_slice())
1116    {
1117        if conditions
1118            .iter()
1119            .any(|condition| condition.type_ == "Ready" && condition.status == "True")
1120        {
1121            return Ok(None);
1122        }
1123    }
1124
1125    Ok(Some(Action::requeue(Duration::from_secs(1))))
1126}
1127
1128#[cfg(test)]
1129mod tests {
1130    use super::*;
1131
1132    fn condition(status: &str, reason: &str) -> Condition {
1133        Condition {
1134            type_: "UpToDate".into(),
1135            status: status.into(),
1136            reason: reason.into(),
1137            message: String::new(),
1138            last_transition_time: Time(Timestamp::now()),
1139            observed_generation: None,
1140        }
1141    }
1142
1143    #[mz_ore::test]
1144    fn test_transition_event_type() {
1145        for (status, reason, expected) in [
1146            ("True", "Applied", EventType::Normal),
1147            ("Unknown", "Applying", EventType::Normal),
1148            ("Unknown", "ReadyToPromote", EventType::Normal),
1149            ("Unknown", "Promoting", EventType::Normal),
1150            ("False", "WaitingForApproval", EventType::Normal),
1151            ("False", "FailedDeploy", EventType::Warning),
1152            ("False", "RolloutTimeout", EventType::Warning),
1153            ("False", "SomeFutureFailure", EventType::Warning),
1154            ("Unknown", "SomeFuturePhase", EventType::Normal),
1155        ] {
1156            assert_eq!(
1157                transition_event_type(&condition(status, reason)),
1158                expected,
1159                "status={status} reason={reason}",
1160            );
1161        }
1162    }
1163}