1use std::collections::BTreeMap;
11
12use k8s_openapi::{
13 api::core::v1::{EnvVar, ResourceRequirements},
14 apimachinery::pkg::{
15 api::resource::Quantity,
16 apis::meta::v1::{Condition, Time},
17 },
18 jiff::Timestamp,
19};
20use kube::{CustomResource, Resource, ResourceExt};
21use schemars::JsonSchema;
22use semver::Version;
23use serde::{Deserialize, Serialize};
24use uuid::Uuid;
25
26use crate::crd::{ManagedResource, MaterializeCertSpec, new_resource_id};
27use mz_server_core::listeners::AuthenticatorKind;
28
29pub const LAST_KNOWN_ACTIVE_GENERATION_ANNOTATION: &str =
30 "materialize.cloud/last-known-active-generation";
31
32pub mod v1alpha1 {
33 use super::*;
34
35 #[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize, JsonSchema)]
36 pub enum MaterializeRolloutStrategy {
37 #[default]
41 WaitUntilReady,
42
43 ManuallyPromote,
65
66 ImmediatelyPromoteCausingDowntime,
77 }
78
79 #[derive(
80 CustomResource,
81 Clone,
82 Debug,
83 Default,
84 PartialEq,
85 Deserialize,
86 Serialize,
87 JsonSchema
88 )]
89 #[serde(rename_all = "camelCase")]
90 #[kube(
91 namespaced,
92 group = "materialize.cloud",
93 version = "v1alpha1",
94 kind = "Materialize",
95 singular = "materialize",
96 plural = "materializes",
97 shortname = "mzs",
98 status = "MaterializeStatus",
99 printcolumn = r#"{"name": "ImageRefRunning", "type": "string", "description": "Reference to the Docker image that is currently in use.", "jsonPath": ".status.lastCompletedRolloutEnvironmentdImageRef", "priority": 1}"#,
100 printcolumn = r#"{"name": "ImageRefToDeploy", "type": "string", "description": "Reference to the Docker image which will be deployed on the next rollout.", "jsonPath": ".spec.environmentdImageRef", "priority": 1}"#,
101 printcolumn = r#"{"name": "UpToDate", "type": "string", "description": "Whether the spec has been applied", "jsonPath": ".status.conditions[?(@.type==\"UpToDate\")].status", "priority": 1}"#
102 )]
103 pub struct MaterializeSpec {
104 pub environmentd_image_ref: String,
106 pub environmentd_extra_args: Option<Vec<String>>,
108 pub environmentd_extra_env: Option<Vec<EnvVar>>,
110 #[kube(deprecated)]
119 pub environmentd_iam_role_arn: Option<String>,
120 pub environmentd_connection_role_arn: Option<String>,
123 pub environmentd_resource_requirements: Option<ResourceRequirements>,
125 pub environmentd_scratch_volume_storage_requirement: Option<Quantity>,
127 pub balancerd_resource_requirements: Option<ResourceRequirements>,
129 pub console_resource_requirements: Option<ResourceRequirements>,
131 pub balancerd_replicas: Option<i32>,
133 pub console_replicas: Option<i32>,
135
136 pub service_account_name: Option<String>,
139 pub service_account_annotations: Option<BTreeMap<String, String>>,
146 pub service_account_labels: Option<BTreeMap<String, String>>,
148 pub pod_annotations: Option<BTreeMap<String, String>>,
150 pub pod_labels: Option<BTreeMap<String, String>>,
152
153 #[serde(default)]
165 pub request_rollout: Uuid,
166 #[serde(default)]
171 pub force_promote: Uuid,
172 #[serde(default)]
179 pub force_rollout: Uuid,
180 #[kube(deprecated)]
184 #[serde(default)]
185 pub in_place_rollout: bool,
186 #[serde(default)]
188 pub rollout_strategy: MaterializeRolloutStrategy,
189 pub backend_secret_name: String,
194 #[serde(default)]
196 pub authenticator_kind: AuthenticatorKind,
197 #[serde(default)]
199 pub enable_rbac: bool,
200
201 #[serde(default)]
208 pub environment_id: Uuid,
209
210 pub system_parameter_configmap_name: Option<String>,
225
226 pub balancerd_external_certificate_spec: Option<MaterializeCertSpec>,
230 pub console_external_certificate_spec: Option<MaterializeCertSpec>,
235 pub internal_certificate_spec: Option<MaterializeCertSpec>,
240 }
241
242 impl Materialize {
243 pub fn backend_secret_name(&self) -> String {
244 self.spec.backend_secret_name.clone()
245 }
246
247 pub fn namespace(&self) -> String {
248 self.meta().namespace.clone().unwrap()
249 }
250
251 pub fn create_service_account(&self) -> bool {
252 self.spec.service_account_name.is_none()
253 }
254
255 pub fn service_account_name(&self) -> String {
256 self.spec
257 .service_account_name
258 .clone()
259 .unwrap_or_else(|| self.name_unchecked())
260 }
261
262 pub fn role_name(&self) -> String {
263 self.name_unchecked()
264 }
265
266 pub fn role_binding_name(&self) -> String {
267 self.name_unchecked()
268 }
269
270 pub fn environmentd_statefulset_name(&self, generation: u64) -> String {
271 self.name_prefixed(&format!("environmentd-{generation}"))
272 }
273
274 pub fn environmentd_app_name(&self) -> String {
275 "environmentd".to_owned()
276 }
277
278 pub fn environmentd_service_name(&self) -> String {
279 self.name_prefixed("environmentd")
280 }
281
282 pub fn environmentd_service_internal_fqdn(&self) -> String {
283 format!(
284 "{}.{}.svc.cluster.local",
285 self.environmentd_service_name(),
286 self.meta().namespace.as_ref().unwrap()
287 )
288 }
289
290 pub fn environmentd_generation_service_name(&self, generation: u64) -> String {
291 self.name_prefixed(&format!("environmentd-{generation}"))
292 }
293
294 pub fn balancerd_app_name(&self) -> String {
295 "balancerd".to_owned()
296 }
297
298 pub fn environmentd_certificate_name(&self) -> String {
299 self.name_prefixed("environmentd-external")
300 }
301
302 pub fn environmentd_certificate_secret_name(&self) -> String {
303 self.name_prefixed("environmentd-tls")
304 }
305
306 pub fn balancerd_deployment_name(&self) -> String {
307 self.name_prefixed("balancerd")
308 }
309
310 pub fn balancerd_service_name(&self) -> String {
311 self.name_prefixed("balancerd")
312 }
313
314 pub fn console_app_name(&self) -> String {
315 "console".to_owned()
316 }
317
318 pub fn balancerd_external_certificate_name(&self) -> String {
319 self.name_prefixed("balancerd-external")
320 }
321
322 pub fn balancerd_external_certificate_secret_name(&self) -> String {
323 self.name_prefixed("balancerd-external-tls")
324 }
325
326 pub fn balancerd_replicas(&self) -> i32 {
327 self.spec.balancerd_replicas.unwrap_or(2)
328 }
329
330 pub fn console_replicas(&self) -> i32 {
331 self.spec.console_replicas.unwrap_or(2)
332 }
333
334 pub fn console_configmap_name(&self) -> String {
335 self.name_prefixed("console")
336 }
337
338 pub fn console_deployment_name(&self) -> String {
339 self.name_prefixed("console")
340 }
341
342 pub fn console_service_name(&self) -> String {
343 self.name_prefixed("console")
344 }
345
346 pub fn console_external_certificate_name(&self) -> String {
347 self.name_prefixed("console-external")
348 }
349
350 pub fn console_external_certificate_secret_name(&self) -> String {
351 self.name_prefixed("console-external-tls")
352 }
353
354 pub fn persist_pubsub_service_name(&self, generation: u64) -> String {
355 self.name_prefixed(&format!("persist-pubsub-{generation}"))
356 }
357
358 pub fn listeners_configmap_name(&self, generation: u64) -> String {
359 self.name_prefixed(&format!("listeners-{generation}"))
360 }
361
362 pub fn name_prefixed(&self, suffix: &str) -> String {
363 format!("mz{}-{}", self.resource_id(), suffix)
364 }
365
366 pub fn resource_id(&self) -> &str {
367 &self.status.as_ref().unwrap().resource_id
368 }
369
370 pub fn system_parameter_configmap_name(&self) -> Option<String> {
371 self.spec.system_parameter_configmap_name.clone()
372 }
373
374 pub fn environmentd_scratch_volume_storage_requirement(&self) -> Quantity {
375 self.spec
376 .environmentd_scratch_volume_storage_requirement
377 .clone()
378 .unwrap_or_else(|| {
379 self.spec
380 .environmentd_resource_requirements
381 .as_ref()
382 .and_then(|requirements| {
383 requirements
384 .requests
385 .as_ref()
386 .or(requirements.limits.as_ref())
387 })
388 .and_then(|requirements| requirements.get("memory").cloned())
393 .unwrap_or_else(|| Quantity("4096Mi".to_string()))
395 })
396 }
397
398 pub fn environment_id(&self, cloud_provider: &str, region: &str) -> String {
399 format!(
400 "{}-{}-{}-0",
401 cloud_provider, region, self.spec.environment_id,
402 )
403 }
404
405 pub fn requested_reconciliation_id(&self) -> Uuid {
406 self.spec.request_rollout
407 }
408
409 pub fn rollout_requested(&self) -> bool {
410 self.requested_reconciliation_id()
411 != self
412 .status
413 .as_ref()
414 .map_or_else(Uuid::nil, |status| status.last_completed_rollout_request)
415 }
416
417 pub fn set_force_promote(&mut self) {
418 self.spec.force_promote = self.spec.request_rollout;
419 }
420
421 pub fn should_force_promote(&self) -> bool {
422 self.spec.force_promote == self.spec.request_rollout
423 || self.spec.rollout_strategy
424 == MaterializeRolloutStrategy::ImmediatelyPromoteCausingDowntime
425 }
426
427 pub fn conditions_need_update(&self) -> bool {
428 let Some(status) = self.status.as_ref() else {
429 return true;
430 };
431 if status.conditions.is_empty() {
432 return true;
433 }
434 for condition in &status.conditions {
435 if condition.observed_generation != self.meta().generation {
436 return true;
437 }
438 }
439 false
440 }
441
442 pub fn is_ready_to_promote(&self, resources_hash: &str) -> bool {
443 let Some(status) = self.status.as_ref() else {
444 return false;
445 };
446 if status.conditions.is_empty() {
447 return false;
448 }
449 status
450 .conditions
451 .iter()
452 .any(|condition| condition.reason == "ReadyToPromote")
453 && &status.resources_hash == resources_hash
454 }
455
456 pub fn is_promoting(&self) -> bool {
457 let Some(status) = self.status.as_ref() else {
458 return false;
459 };
460 if status.conditions.is_empty() {
461 return false;
462 }
463 status
464 .conditions
465 .iter()
466 .any(|condition| condition.reason == "Promoting")
467 }
468
469 pub fn update_in_progress(&self) -> bool {
470 let Some(status) = self.status.as_ref() else {
471 return false;
472 };
473 if status.conditions.is_empty() {
474 return false;
475 }
476 for condition in &status.conditions {
477 if condition.type_ == "UpToDate" && condition.status == "Unknown" {
478 return true;
479 }
480 }
481 false
482 }
483
484 pub fn meets_minimum_version(&self, minimum: &Version) -> bool {
488 let version = parse_image_ref(&self.spec.environmentd_image_ref);
489 match version {
490 Some(version) => version.cmp_precedence(minimum).is_ge(),
492 None => {
498 tracing::warn!(
499 image_ref = %self.spec.environmentd_image_ref,
500 "failed to parse image ref",
501 );
502 true
503 }
504 }
505 }
506
507 pub fn is_valid_upgrade_version(active_version: &Version, next_version: &Version) -> bool {
511 if next_version.cmp_precedence(active_version) == std::cmp::Ordering::Less {
516 return false;
517 }
518
519 if active_version.major == 0 {
520 if next_version.major != active_version.major {
521 if next_version.major == 26 {
522 return (active_version.minor == 147 && active_version.patch >= 20)
526 || active_version.minor >= 164;
527 } else {
528 return false;
529 }
530 }
531 if next_version.minor == 147 && active_version.minor == 130 {
533 return true;
534 }
535 return next_version.minor <= active_version.minor + 1;
537 } else if active_version.major >= 26 {
538 return next_version.major <= active_version.major + 1;
540 }
541
542 true
543 }
544
545 pub fn within_upgrade_window(&self) -> bool {
548 let active_environmentd_version = self
549 .status
550 .as_ref()
551 .and_then(|status| {
552 status
553 .last_completed_rollout_environmentd_image_ref
554 .as_ref()
555 })
556 .and_then(|image_ref| parse_image_ref(image_ref));
557
558 if let (Some(next_environmentd_version), Some(active_environmentd_version)) = (
559 parse_image_ref(&self.spec.environmentd_image_ref),
560 active_environmentd_version,
561 ) {
562 Self::is_valid_upgrade_version(
563 &active_environmentd_version,
564 &next_environmentd_version,
565 )
566 } else {
567 true
570 }
571 }
572
573 pub fn status(&self) -> MaterializeStatus {
574 self.status.clone().unwrap_or_else(|| {
575 let mut status = MaterializeStatus::default();
576
577 status.resource_id = new_resource_id();
578
579 if let Some(last_active_generation) = self
584 .annotations()
585 .get(LAST_KNOWN_ACTIVE_GENERATION_ANNOTATION)
586 {
587 status.active_generation = last_active_generation
588 .parse()
589 .expect("valid int generation");
590 }
591
592 status.last_completed_rollout_environmentd_image_ref =
595 Some(self.spec.environmentd_image_ref.clone());
596
597 status
598 })
599 }
600 }
601
602 #[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema, PartialEq)]
603 #[serde(rename_all = "camelCase")]
604 pub struct MaterializeStatus {
605 pub resource_id: String,
607 pub active_generation: u64,
609 pub last_completed_rollout_request: Uuid,
611 pub last_completed_rollout_environmentd_image_ref: Option<String>,
615 pub resources_hash: String,
620 pub conditions: Vec<Condition>,
621 }
622
623 impl MaterializeStatus {
624 pub fn needs_update(&self, other: &Self) -> bool {
625 let now = Timestamp::now();
626 let mut a = self.clone();
627 for condition in &mut a.conditions {
628 condition.last_transition_time = Time(now);
629 }
630 let mut b = other.clone();
631 for condition in &mut b.conditions {
632 condition.last_transition_time = Time(now);
633 }
634 a != b
635 }
636 }
637
638 impl ManagedResource for Materialize {
639 fn default_labels(&self) -> BTreeMap<String, String> {
640 BTreeMap::from_iter([
641 (
642 "materialize.cloud/organization-name".to_owned(),
643 self.name_unchecked(),
644 ),
645 (
646 "materialize.cloud/organization-namespace".to_owned(),
647 self.namespace(),
648 ),
649 (
650 "materialize.cloud/mz-resource-id".to_owned(),
651 self.resource_id().to_owned(),
652 ),
653 ])
654 }
655 }
656}
657
658fn parse_image_ref(image_ref: &str) -> Option<Version> {
659 image_ref
660 .rsplit_once(':')
661 .and_then(|(_repo, tag)| tag.strip_prefix('v'))
662 .and_then(|tag| {
663 let tag = tag.replace("--", "+");
668 Version::parse(&tag).ok()
669 })
670}
671
672#[cfg(test)]
673mod tests {
674 use kube::core::ObjectMeta;
675 use semver::Version;
676
677 use super::v1alpha1::{Materialize, MaterializeSpec};
678
679 #[mz_ore::test]
680 fn meets_minimum_version() {
681 let mut mz = Materialize {
682 spec: MaterializeSpec {
683 environmentd_image_ref:
684 "materialize/environmentd:devel-47116c24b8d0df33d3f60a9ee476aa8d7bce5953"
685 .to_owned(),
686 ..Default::default()
687 },
688 metadata: ObjectMeta {
689 ..Default::default()
690 },
691 status: None,
692 };
693
694 assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
696 mz.spec.environmentd_image_ref = "materialize/environmentd:v0.34.0".to_owned();
697 assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
698 mz.spec.environmentd_image_ref = "materialize/environmentd:v0.35.0".to_owned();
699 assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
700 mz.spec.environmentd_image_ref = "materialize/environmentd:v0.34.3".to_owned();
701 assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
702 mz.spec.environmentd_image_ref = "materialize/environmentd@41af286dc0b172ed2f1ca934fd2278de4a1192302ffa07087cea2682e7d372e3".to_owned();
703 assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
704 mz.spec.environmentd_image_ref = "my.private.registry:5000:v0.34.3".to_owned();
705 assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
706 mz.spec.environmentd_image_ref = "materialize/environmentd:v0.asdf.0".to_owned();
707 assert!(mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
708 mz.spec.environmentd_image_ref =
709 "materialize/environmentd:v0.146.0-dev.0--pr.g5a05a9e4ba873be8adaa528644aaae6e4c7cd29b"
710 .to_owned();
711 assert!(mz.meets_minimum_version(&Version::parse("0.146.0-dev.0").unwrap()));
712
713 mz.spec.environmentd_image_ref = "materialize/environmentd:v0.34.0-dev".to_owned();
715 assert!(!mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
716 mz.spec.environmentd_image_ref = "materialize/environmentd:v0.33.0".to_owned();
717 assert!(!mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
718 mz.spec.environmentd_image_ref = "materialize/environmentd:v0.34.0".to_owned();
719 assert!(!mz.meets_minimum_version(&Version::parse("1.0.0").unwrap()));
720 mz.spec.environmentd_image_ref = "my.private.registry:5000:v0.33.3".to_owned();
721 assert!(!mz.meets_minimum_version(&Version::parse("0.34.0").unwrap()));
722 }
723
724 #[mz_ore::test]
725 fn within_upgrade_window() {
726 use super::v1alpha1::MaterializeStatus;
727
728 let mut mz = Materialize {
729 spec: MaterializeSpec {
730 environmentd_image_ref: "materialize/environmentd:v26.0.0".to_owned(),
731 ..Default::default()
732 },
733 metadata: ObjectMeta {
734 ..Default::default()
735 },
736 status: Some(MaterializeStatus {
737 last_completed_rollout_environmentd_image_ref: Some(
738 "materialize/environmentd:v26.0.0".to_owned(),
739 ),
740 ..Default::default()
741 }),
742 };
743
744 mz.spec.environmentd_image_ref = "materialize/environmentd:v27.7.3".to_owned();
746 assert!(mz.within_upgrade_window());
747
748 mz.spec.environmentd_image_ref = "materialize/environmentd:v27.7.8-dev.0".to_owned();
750 assert!(mz.within_upgrade_window());
751
752 mz.spec.environmentd_image_ref = "materialize/environmentd:v28.0.1".to_owned();
754 assert!(!mz.within_upgrade_window());
755
756 mz.spec.environmentd_image_ref =
758 "materialize/environmentd:v28.0.1.not_a_valid_version".to_owned();
759 assert!(mz.within_upgrade_window());
760
761 mz.status
763 .as_mut()
764 .unwrap()
765 .last_completed_rollout_environmentd_image_ref =
766 Some("materialize/environmentd:v0.147.20".to_owned());
767 mz.spec.environmentd_image_ref = "materialize/environmentd:v26.1.0".to_owned();
768 assert!(mz.within_upgrade_window());
769
770 mz.status
772 .as_mut()
773 .unwrap()
774 .last_completed_rollout_environmentd_image_ref =
775 Some("materialize/environmentd:v26.11.0-dev.0+b".to_owned());
776 mz.spec.environmentd_image_ref = "materialize/environmentd:v26.11.0-dev.0+a".to_owned();
777 assert!(mz.within_upgrade_window());
778 }
779
780 #[mz_ore::test]
781 fn is_valid_upgrade_version() {
782 let success_tests = [
783 (Version::new(0, 83, 0), Version::new(0, 83, 0)),
784 (Version::new(0, 83, 0), Version::new(0, 84, 0)),
785 (Version::new(0, 9, 0), Version::new(0, 10, 0)),
786 (Version::new(0, 99, 0), Version::new(0, 100, 0)),
787 (Version::new(0, 83, 0), Version::new(0, 83, 1)),
788 (Version::new(0, 83, 0), Version::new(0, 83, 2)),
789 (Version::new(0, 83, 2), Version::new(0, 83, 10)),
790 (Version::new(0, 147, 20), Version::new(26, 0, 0)),
792 (Version::new(0, 164, 0), Version::new(26, 0, 0)),
793 (Version::new(26, 0, 0), Version::new(26, 1, 0)),
794 (Version::new(26, 5, 3), Version::new(26, 10, 0)),
795 (Version::new(0, 130, 0), Version::new(0, 147, 0)),
796 ];
797 for (active_version, next_version) in success_tests {
798 assert!(
799 Materialize::is_valid_upgrade_version(&active_version, &next_version),
800 "v{active_version} can upgrade to v{next_version}"
801 );
802 }
803
804 let failure_tests = [
805 (Version::new(0, 83, 0), Version::new(0, 82, 0)),
806 (Version::new(0, 83, 3), Version::new(0, 83, 2)),
807 (Version::new(0, 83, 3), Version::new(1, 83, 3)),
808 (Version::new(0, 83, 0), Version::new(0, 85, 0)),
809 (Version::new(26, 0, 0), Version::new(28, 0, 0)),
810 (Version::new(0, 130, 0), Version::new(26, 1, 0)),
811 (Version::new(0, 147, 1), Version::new(26, 0, 0)),
813 (Version::new(0, 148, 0), Version::new(26, 0, 0)),
815 ];
816 for (active_version, next_version) in failure_tests {
817 assert!(
818 !Materialize::is_valid_upgrade_version(&active_version, &next_version),
819 "v{active_version} can't upgrade to v{next_version}"
820 );
821 }
822 }
823}