1use std::collections::{BTreeMap, BTreeSet};
13use std::fmt;
14use std::num::NonZero;
15use std::str::FromStr;
16use std::sync::Arc;
17use std::sync::LazyLock;
18use std::time::Duration;
19
20use anyhow::anyhow;
21use bytesize::ByteSize;
22use chrono::{DateTime, Utc};
23use futures::stream::{BoxStream, StreamExt};
24use mz_cluster_client::client::{ClusterReplicaLocation, TimelyConfig};
25use mz_compute_client::logging::LogVariant;
26use mz_compute_types::config::{ComputeReplicaConfig, ComputeReplicaLogging};
27use mz_controller_types::dyncfgs::{
28 ARRANGEMENT_EXERT_PROPORTIONALITY, CONTROLLER_PAST_GENERATION_REPLICA_CLEANUP_RETRY_INTERVAL,
29 ENABLE_TIMELY_ZERO_COPY, ENABLE_TIMELY_ZERO_COPY_LGALLOC, TIMELY_ZERO_COPY_LIMIT,
30};
31use mz_controller_types::{ClusterId, ReplicaId};
32use mz_orchestrator::NamespacedOrchestrator;
33use mz_orchestrator::{
34 CpuLimit, DiskLimit, LabelSelectionLogic, LabelSelector, MemoryLimit, Service, ServiceConfig,
35 ServiceEvent, ServicePort,
36};
37use mz_ore::cast::CastInto;
38use mz_ore::task::{self, AbortOnDropHandle};
39use mz_ore::{halt, instrument};
40use mz_repr::GlobalId;
41use mz_repr::adt::numeric::Numeric;
42use regex::Regex;
43use serde::{Deserialize, Serialize};
44use tokio::time;
45use tracing::{error, info, warn};
46
47use crate::Controller;
48
49pub struct ClusterConfig {
51 pub arranged_logs: BTreeMap<LogVariant, GlobalId>,
56 pub workload_class: Option<String>,
59}
60
61pub type ClusterStatus = mz_orchestrator::ServiceStatus;
63
64#[derive(Clone, Debug, Serialize, PartialEq)]
66pub struct ReplicaConfig {
67 pub location: ReplicaLocation,
69 pub compute: ComputeReplicaConfig,
71}
72
73#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
75pub struct ReplicaAllocation {
76 pub memory_limit: Option<MemoryLimit>,
78 pub cpu_limit: Option<CpuLimit>,
80 pub cpu_request: Option<CpuLimit>,
82 pub disk_limit: Option<DiskLimit>,
84 pub scale: NonZero<u16>,
86 pub workers: NonZero<usize>,
88 #[serde(deserialize_with = "mz_repr::adt::numeric::str_serde::deserialize")]
90 pub credits_per_hour: Numeric,
91 #[serde(default)]
93 pub cpu_exclusive: bool,
94 #[serde(default = "default_true")]
97 pub is_cc: bool,
98 #[serde(default)]
107 pub family: Option<String>,
108 #[serde(default)]
110 pub swap_enabled: bool,
111 #[serde(default)]
113 pub disabled: bool,
114 #[serde(default)]
116 pub selectors: BTreeMap<String, String>,
117}
118
119impl ReplicaAllocation {
120 pub fn family(&self) -> &str {
129 match &self.family {
130 Some(family) => family.as_str(),
131 None if self.is_cc => "cc",
132 None => "legacy",
133 }
134 }
135}
136
137fn default_true() -> bool {
138 true
139}
140
141#[mz_ore::test]
142#[cfg_attr(miri, ignore)] fn test_replica_allocation_deserialization() {
145 use bytesize::ByteSize;
146 use mz_ore::{assert_err, assert_ok};
147
148 let data = r#"
149 {
150 "cpu_limit": 1.0,
151 "memory_limit": "10GiB",
152 "disk_limit": "100MiB",
153 "scale": 16,
154 "workers": 1,
155 "credits_per_hour": "16",
156 "swap_enabled": true,
157 "selectors": {
158 "key1": "value1",
159 "key2": "value2"
160 }
161 }"#;
162
163 let replica_allocation: ReplicaAllocation = serde_json::from_str(data)
164 .expect("deserialization from JSON succeeds for ReplicaAllocation");
165
166 assert_eq!(
167 replica_allocation,
168 ReplicaAllocation {
169 credits_per_hour: 16.into(),
170 disk_limit: Some(DiskLimit(ByteSize::mib(100))),
171 disabled: false,
172 memory_limit: Some(MemoryLimit(ByteSize::gib(10))),
173 cpu_limit: Some(CpuLimit::from_millicpus(1000)),
174 cpu_request: None,
175 cpu_exclusive: false,
176 is_cc: true,
177 family: None,
178 swap_enabled: true,
179 scale: NonZero::new(16).unwrap(),
180 workers: NonZero::new(1).unwrap(),
181 selectors: BTreeMap::from([
182 ("key1".to_string(), "value1".to_string()),
183 ("key2".to_string(), "value2".to_string())
184 ]),
185 }
186 );
187
188 let data = r#"
189 {
190 "cpu_limit": 0,
191 "memory_limit": "0GiB",
192 "disk_limit": "0MiB",
193 "scale": 1,
194 "workers": 1,
195 "credits_per_hour": "0",
196 "cpu_exclusive": true,
197 "disabled": true
198 }"#;
199
200 let replica_allocation: ReplicaAllocation = serde_json::from_str(data)
201 .expect("deserialization from JSON succeeds for ReplicaAllocation");
202
203 assert_eq!(
204 replica_allocation,
205 ReplicaAllocation {
206 credits_per_hour: 0.into(),
207 disk_limit: Some(DiskLimit(ByteSize::mib(0))),
208 disabled: true,
209 memory_limit: Some(MemoryLimit(ByteSize::gib(0))),
210 cpu_limit: Some(CpuLimit::from_millicpus(0)),
211 cpu_request: None,
212 cpu_exclusive: true,
213 is_cc: true,
214 family: None,
215 swap_enabled: false,
216 scale: NonZero::new(1).unwrap(),
217 workers: NonZero::new(1).unwrap(),
218 selectors: Default::default(),
219 }
220 );
221
222 let data = r#"{"scale": 0, "workers": 1, "credits_per_hour": "0"}"#;
224 assert_err!(serde_json::from_str::<ReplicaAllocation>(data));
225 let data = r#"{"scale": 1, "workers": 0, "credits_per_hour": "0"}"#;
226 assert_err!(serde_json::from_str::<ReplicaAllocation>(data));
227 let data = r#"{"scale": 1, "workers": 1, "credits_per_hour": "0"}"#;
228 assert_ok!(serde_json::from_str::<ReplicaAllocation>(data));
229}
230
231#[mz_ore::test]
232#[cfg_attr(miri, ignore)] fn test_replica_allocation_family() {
234 let parse = |json: &str| -> ReplicaAllocation {
235 serde_json::from_str(json).expect("deserialization from JSON succeeds")
236 };
237
238 assert_eq!(
240 parse(r#"{"scale": 1, "workers": 1, "credits_per_hour": "0", "family": "D"}"#).family(),
241 "D"
242 );
243 assert_eq!(
246 parse(r#"{"scale": 1, "workers": 1, "credits_per_hour": "0"}"#).family(),
247 "cc"
248 );
249 assert_eq!(
252 parse(r#"{"scale": 1, "workers": 1, "credits_per_hour": "0", "is_cc": false}"#).family(),
253 "legacy"
254 );
255 assert_eq!(
257 parse(
258 r#"{"scale": 1, "workers": 1, "credits_per_hour": "0", "is_cc": false, "family": "legacy-special"}"#
259 )
260 .family(),
261 "legacy-special"
262 );
263}
264
265#[derive(Clone, Debug, Serialize, PartialEq)]
267pub enum ReplicaLocation {
268 Unmanaged(UnmanagedReplicaLocation),
270 Managed(ManagedReplicaLocation),
272}
273
274impl ReplicaLocation {
275 pub fn num_processes(&self) -> usize {
277 match self {
278 ReplicaLocation::Unmanaged(UnmanagedReplicaLocation {
279 computectl_addrs, ..
280 }) => computectl_addrs.len(),
281 ReplicaLocation::Managed(ManagedReplicaLocation { allocation, .. }) => {
282 allocation.scale.cast_into()
283 }
284 }
285 }
286
287 pub fn billed_as(&self) -> Option<&str> {
288 match self {
289 ReplicaLocation::Managed(ManagedReplicaLocation { billed_as, .. }) => {
290 billed_as.as_deref()
291 }
292 ReplicaLocation::Unmanaged(_) => None,
293 }
294 }
295
296 pub fn internal(&self) -> bool {
297 match self {
298 ReplicaLocation::Managed(ManagedReplicaLocation { internal, .. }) => *internal,
299 ReplicaLocation::Unmanaged(_) => false,
300 }
301 }
302
303 pub fn workers(&self) -> Option<usize> {
307 match self {
308 ReplicaLocation::Managed(ManagedReplicaLocation { allocation, .. }) => {
309 Some(allocation.workers.get() * self.num_processes())
310 }
311 ReplicaLocation::Unmanaged(_) => None,
312 }
313 }
314
315 pub fn pending(&self) -> bool {
320 match self {
321 ReplicaLocation::Managed(ManagedReplicaLocation { pending, .. }) => *pending,
322 ReplicaLocation::Unmanaged(_) => false,
323 }
324 }
325}
326
327#[derive(Debug, Clone)]
330pub enum ClusterRole {
331 SystemCritical,
334 System,
338 User,
341}
342
343#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
345pub struct UnmanagedReplicaLocation {
346 pub storagectl_addrs: Vec<String>,
349 pub computectl_addrs: Vec<String>,
352}
353
354#[derive(Clone, Debug, Serialize, PartialEq)]
356pub struct ManagedReplicaLocation {
357 pub allocation: ReplicaAllocation,
359 pub size: String,
361 pub internal: bool,
363 pub billed_as: Option<String>,
365 #[serde(skip)]
376 pub availability_zones: Vec<String>,
377 pub pending: bool,
379}
380
381impl ManagedReplicaLocation {
382 pub fn size_for_billing(&self) -> &str {
384 self.billed_as.as_deref().unwrap_or(&self.size)
385 }
386}
387
388pub type ReplicaLogging = ComputeReplicaLogging;
390
391pub type ProcessId = u64;
393
394#[derive(Debug, Clone, Serialize)]
396pub struct ClusterEvent {
397 pub cluster_id: ClusterId,
398 pub replica_id: ReplicaId,
399 pub process_id: ProcessId,
400 pub status: ClusterStatus,
401 pub restart_count: u64,
404 pub time: DateTime<Utc>,
405}
406
407impl Controller {
408 pub fn create_cluster(
414 &mut self,
415 id: ClusterId,
416 config: ClusterConfig,
417 ) -> Result<(), anyhow::Error> {
418 self.storage
419 .create_instance(id, config.workload_class.clone());
420 self.compute
421 .create_instance(id, config.arranged_logs, config.workload_class)?;
422 Ok(())
423 }
424
425 pub fn update_cluster_workload_class(&mut self, id: ClusterId, workload_class: Option<String>) {
431 self.storage
432 .update_instance_workload_class(id, workload_class.clone());
433 self.compute
434 .update_instance_workload_class(id, workload_class)
435 .expect("instance exists");
436 }
437
438 pub fn drop_cluster(&mut self, id: ClusterId) {
444 self.storage.drop_instance(id);
445 self.compute.drop_instance(id);
446 }
447
448 pub fn create_replica(
451 &mut self,
452 cluster_id: ClusterId,
453 replica_id: ReplicaId,
454 cluster_name: String,
455 replica_name: String,
456 role: ClusterRole,
457 config: ReplicaConfig,
458 enable_worker_core_affinity: bool,
459 enable_storage_introspection_logs: bool,
460 ) -> Result<(), anyhow::Error> {
461 let storage_location: ClusterReplicaLocation;
462 let compute_location: ClusterReplicaLocation;
463 let metrics_task: Option<AbortOnDropHandle<()>>;
464
465 match config.location {
466 ReplicaLocation::Unmanaged(UnmanagedReplicaLocation {
467 storagectl_addrs,
468 computectl_addrs,
469 }) => {
470 compute_location = ClusterReplicaLocation {
471 ctl_addrs: computectl_addrs,
472 };
473 storage_location = ClusterReplicaLocation {
474 ctl_addrs: storagectl_addrs,
475 };
476 metrics_task = None;
477 }
478 ReplicaLocation::Managed(m) => {
479 let (service, metrics_task_join_handle) = self.provision_replica(
480 cluster_id,
481 replica_id,
482 cluster_name,
483 replica_name,
484 role,
485 m,
486 enable_worker_core_affinity,
487 enable_storage_introspection_logs,
488 )?;
489 storage_location = ClusterReplicaLocation {
490 ctl_addrs: service.addresses("storagectl"),
491 };
492 compute_location = ClusterReplicaLocation {
493 ctl_addrs: service.addresses("computectl"),
494 };
495 metrics_task = Some(metrics_task_join_handle);
496
497 let http_addresses = service.addresses("internal-http");
499 self.replica_http_locator
500 .register_replica(cluster_id, replica_id, http_addresses);
501 }
502 }
503
504 self.storage
505 .connect_replica(cluster_id, replica_id, storage_location);
506 self.compute.add_replica_to_instance(
507 cluster_id,
508 replica_id,
509 compute_location,
510 config.compute,
511 )?;
512
513 if let Some(task) = metrics_task {
514 self.metrics_tasks.insert(replica_id, task);
515 }
516
517 Ok(())
518 }
519
520 pub fn drop_replica(
522 &mut self,
523 cluster_id: ClusterId,
524 replica_id: ReplicaId,
525 ) -> Result<(), anyhow::Error> {
526 self.deprovision_replica(cluster_id, replica_id, self.deploy_generation)?;
531 self.metrics_tasks.remove(&replica_id);
532
533 self.replica_http_locator
535 .remove_replica(cluster_id, replica_id);
536
537 self.replica_dyncfg_overrides.remove(&replica_id);
541
542 self.compute.drop_replica(cluster_id, replica_id)?;
543 self.storage.drop_replica(cluster_id, replica_id);
544 Ok(())
545 }
546
547 pub(crate) fn remove_past_generation_replicas_in_background(&self) {
549 let deploy_generation = self.deploy_generation;
550 let dyncfg = Arc::clone(self.compute.dyncfg());
551 let orchestrator = Arc::clone(&self.orchestrator);
552 task::spawn(
553 || "controller_remove_past_generation_replicas",
554 async move {
555 info!("attempting to remove past generation replicas");
556 loop {
557 match try_remove_past_generation_replicas(&*orchestrator, deploy_generation)
558 .await
559 {
560 Ok(()) => {
561 info!("successfully removed past generation replicas");
562 return;
563 }
564 Err(e) => {
565 let interval =
566 CONTROLLER_PAST_GENERATION_REPLICA_CLEANUP_RETRY_INTERVAL
567 .get(&dyncfg);
568 warn!(%e, "failed to remove past generation replicas; will retry in {interval:?}");
569 time::sleep(interval).await;
570 }
571 }
572 }
573 },
574 );
575 }
576
577 #[instrument]
579 pub async fn remove_orphaned_replicas(
580 &mut self,
581 next_user_replica_id: u64,
582 next_system_replica_id: u64,
583 ) -> Result<(), anyhow::Error> {
584 let desired: BTreeSet<_> = self.metrics_tasks.keys().copied().collect();
585
586 let actual: BTreeSet<_> = self
587 .orchestrator
588 .list_services()
589 .await?
590 .iter()
591 .map(|s| ReplicaServiceName::from_str(s))
592 .collect::<Result<_, _>>()?;
593
594 for ReplicaServiceName {
595 cluster_id,
596 replica_id,
597 generation,
598 } in actual
599 {
600 if generation != self.deploy_generation {
604 continue;
605 }
606
607 let smaller_next = match replica_id {
608 ReplicaId::User(id) if id >= next_user_replica_id => {
609 Some(ReplicaId::User(next_user_replica_id))
610 }
611 ReplicaId::System(id) if id >= next_system_replica_id => {
612 Some(ReplicaId::System(next_system_replica_id))
613 }
614 _ => None,
615 };
616 if let Some(next) = smaller_next {
617 halt!("found replica ID ({replica_id}) in orchestrator >= next ID ({next})");
622 }
623 if !desired.contains(&replica_id) {
624 self.deprovision_replica(cluster_id, replica_id, generation)?;
625 }
626 }
627
628 Ok(())
629 }
630
631 pub fn events_stream(&self) -> BoxStream<'static, ClusterEvent> {
632 let deploy_generation = self.deploy_generation;
633
634 fn translate_event(event: ServiceEvent) -> Result<(ClusterEvent, u64), anyhow::Error> {
635 let ReplicaServiceName {
636 cluster_id,
637 replica_id,
638 generation: replica_generation,
639 ..
640 } = event.service_id.parse()?;
641
642 let event = ClusterEvent {
643 cluster_id,
644 replica_id,
645 process_id: event.process_id,
646 status: event.status,
647 restart_count: event.restart_count,
648 time: event.time,
649 };
650
651 Ok((event, replica_generation))
652 }
653
654 let stream = self
655 .orchestrator
656 .watch_services()
657 .map(|event| event.and_then(translate_event))
658 .filter_map(move |event| async move {
659 match event {
660 Ok((event, replica_generation)) => {
661 if replica_generation == deploy_generation {
662 Some(event)
663 } else {
664 None
665 }
666 }
667 Err(error) => {
668 error!("service watch error: {error}");
669 None
670 }
671 }
672 });
673
674 Box::pin(stream)
675 }
676
677 fn provision_replica(
679 &self,
680 cluster_id: ClusterId,
681 replica_id: ReplicaId,
682 cluster_name: String,
683 replica_name: String,
684 role: ClusterRole,
685 location: ManagedReplicaLocation,
686 enable_worker_core_affinity: bool,
687 enable_storage_introspection_logs: bool,
688 ) -> Result<(Box<dyn Service>, AbortOnDropHandle<()>), anyhow::Error> {
689 let service_name = ReplicaServiceName {
690 cluster_id,
691 replica_id,
692 generation: self.deploy_generation,
693 }
694 .to_string();
695 let role_label = match role {
696 ClusterRole::SystemCritical => "system-critical",
697 ClusterRole::System => "system",
698 ClusterRole::User => "user",
699 };
700 let environment_id = self.connection_context().environment_id.clone();
701 let aws_external_id_prefix = self.connection_context().aws_external_id_prefix.clone();
702 let aws_connection_role_arn = self.connection_context().aws_connection_role_arn.clone();
703 let persist_pubsub_url = self.persist_pubsub_url.clone();
704 let secrets_args = self.secrets_args.to_flags();
705
706 let storage_proto_timely_config = TimelyConfig {
708 arrangement_exert_proportionality: 1337,
709 ..Default::default()
710 };
711 let overrides = self.replica_dyncfg_overrides.get(&replica_id);
718 let compute_proto_timely_config = TimelyConfig {
719 arrangement_exert_proportionality: ARRANGEMENT_EXERT_PROPORTIONALITY
720 .get_with_overrides(&self.dyncfg, overrides),
721 enable_zero_copy: ENABLE_TIMELY_ZERO_COPY.get_with_overrides(&self.dyncfg, overrides),
722 enable_zero_copy_lgalloc: ENABLE_TIMELY_ZERO_COPY_LGALLOC
723 .get_with_overrides(&self.dyncfg, overrides),
724 zero_copy_limit: TIMELY_ZERO_COPY_LIMIT.get_with_overrides(&self.dyncfg, overrides),
725 ..Default::default()
726 };
727
728 let mut disk_limit = location.allocation.disk_limit;
729 let memory_limit = location.allocation.memory_limit;
730 let mut memory_request = None;
731
732 if location.allocation.swap_enabled {
733 disk_limit = Some(DiskLimit::ZERO);
737
738 memory_request = memory_limit.map(|MemoryLimit(limit)| {
742 let request = ByteSize::b(limit.as_u64() - 1);
743 MemoryLimit(request)
744 });
745 }
746
747 let service = self.orchestrator.ensure_service(
748 &service_name,
749 ServiceConfig {
750 app_name: "clusterd".into(),
751 image: self.clusterd_image.clone(),
752 init_container_image: self.init_container_image.clone(),
753 args: Box::new(move |assigned| {
754 let storage_timely_config = TimelyConfig {
755 workers: location.allocation.workers.get(),
756 addresses: assigned.peer_addresses("storage"),
757 ..storage_proto_timely_config
758 };
759 let compute_timely_config = TimelyConfig {
760 workers: location.allocation.workers.get(),
761 addresses: assigned.peer_addresses("compute"),
762 ..compute_proto_timely_config
763 };
764
765 let mut args = vec![
766 format!(
767 "--storage-controller-listen-addr={}",
768 assigned.listen_addrs["storagectl"]
769 ),
770 format!(
771 "--compute-controller-listen-addr={}",
772 assigned.listen_addrs["computectl"]
773 ),
774 format!(
775 "--internal-http-listen-addr={}",
776 assigned.listen_addrs["internal-http"]
777 ),
778 format!("--opentelemetry-resource=cluster_id={}", cluster_id),
779 format!("--opentelemetry-resource=replica_id={}", replica_id),
780 format!("--persist-pubsub-url={}", persist_pubsub_url),
781 format!("--environment-id={}", environment_id),
782 format!(
783 "--storage-timely-config={}",
784 storage_timely_config.to_string(),
785 ),
786 format!(
787 "--compute-timely-config={}",
788 compute_timely_config.to_string(),
789 ),
790 ];
791 if let Some(aws_external_id_prefix) = &aws_external_id_prefix {
792 args.push(format!(
793 "--aws-external-id-prefix={}",
794 aws_external_id_prefix
795 ));
796 }
797 if let Some(aws_connection_role_arn) = &aws_connection_role_arn {
798 args.push(format!(
799 "--aws-connection-role-arn={}",
800 aws_connection_role_arn
801 ));
802 }
803 if let Some(memory_limit) = location.allocation.memory_limit {
804 args.push(format!(
805 "--announce-memory-limit={}",
806 memory_limit.0.as_u64()
807 ));
808 }
809 if location.allocation.cpu_exclusive && enable_worker_core_affinity {
810 args.push("--worker-core-affinity".into());
811 }
812 if enable_storage_introspection_logs {
813 args.push("--enable-storage-introspection-logs".into());
814 }
815 if location.allocation.is_cc {
816 args.push("--is-cc".into());
817 }
818
819 if location.allocation.swap_enabled
822 && let Some(memory_limit) = location.allocation.memory_limit
823 && let Some(disk_limit) = location.allocation.disk_limit
824 && disk_limit != DiskLimit::ZERO
828 {
829 let heap_limit = memory_limit.0 + disk_limit.0;
830 args.push(format!("--heap-limit={}", heap_limit.as_u64()));
831 }
832
833 args.extend(secrets_args.clone());
834 args
835 }),
836 ports: vec![
837 ServicePort {
838 name: "storagectl".into(),
839 port_hint: 2100,
840 },
841 ServicePort {
845 name: "storage".into(),
846 port_hint: 2103,
847 },
848 ServicePort {
849 name: "computectl".into(),
850 port_hint: 2101,
851 },
852 ServicePort {
853 name: "compute".into(),
854 port_hint: 2102,
855 },
856 ServicePort {
857 name: "internal-http".into(),
858 port_hint: 6878,
859 },
860 ],
861 cpu_limit: location.allocation.cpu_limit,
862 cpu_request: location.allocation.cpu_request,
863 memory_limit,
864 memory_request,
865 scale: location.allocation.scale,
866 labels: BTreeMap::from([
867 ("replica-id".into(), replica_id.to_string()),
868 ("cluster-id".into(), cluster_id.to_string()),
869 ("generation".into(), self.deploy_generation.to_string()),
870 ("type".into(), "cluster".into()),
871 ("replica-role".into(), role_label.into()),
872 ("workers".into(), location.allocation.workers.to_string()),
873 (
874 "size".into(),
875 location
876 .size
877 .to_string()
878 .replace("=", "-")
879 .replace(",", "_"),
880 ),
881 ]),
882 annotations: BTreeMap::from([
883 (
884 "replica-name".into(),
885 format!("{cluster_name}.{replica_name}"),
886 ),
887 ("cluster-name".into(), cluster_name),
888 ]),
889 availability_zones: Some(location.availability_zones).filter(|azs| !azs.is_empty()),
892 other_replicas_selector: vec![
905 LabelSelector {
906 label_name: "cluster-id".to_string(),
907 logic: LabelSelectionLogic::Eq {
908 value: cluster_id.to_string(),
909 },
910 },
911 LabelSelector {
913 label_name: "replica-id".into(),
914 logic: LabelSelectionLogic::NotEq {
915 value: replica_id.to_string(),
916 },
917 },
918 LabelSelector {
919 label_name: "generation".into(),
920 logic: LabelSelectionLogic::Eq {
921 value: self.deploy_generation.to_string(),
922 },
923 },
924 ],
925 replicas_selector: vec![
926 LabelSelector {
927 label_name: "cluster-id".to_string(),
928 logic: LabelSelectionLogic::Eq {
930 value: cluster_id.to_string(),
931 },
932 },
933 LabelSelector {
934 label_name: "generation".into(),
935 logic: LabelSelectionLogic::Eq {
936 value: self.deploy_generation.to_string(),
937 },
938 },
939 ],
940 disk_limit,
941 node_selector: location.allocation.selectors,
942 },
943 )?;
944
945 let metrics_task = mz_ore::task::spawn(|| format!("replica-metrics-{replica_id}"), {
946 let tx = self.metrics_tx.clone();
947 let orchestrator = Arc::clone(&self.orchestrator);
948 let service_name = service_name.clone();
949 async move {
950 const METRICS_INTERVAL: Duration = Duration::from_secs(60);
951
952 let mut interval = tokio::time::interval(METRICS_INTERVAL);
960 loop {
961 interval.tick().await;
962 match orchestrator.fetch_service_metrics(&service_name).await {
963 Ok(metrics) => {
964 let _ = tx.send((replica_id, metrics));
965 }
966 Err(e) => {
967 warn!("failed to get metrics for replica {replica_id}: {e}");
968 }
969 }
970 }
971 }
972 });
973
974 Ok((service, metrics_task.abort_on_drop()))
975 }
976
977 fn deprovision_replica(
979 &self,
980 cluster_id: ClusterId,
981 replica_id: ReplicaId,
982 generation: u64,
983 ) -> Result<(), anyhow::Error> {
984 let service_name = ReplicaServiceName {
985 cluster_id,
986 replica_id,
987 generation,
988 }
989 .to_string();
990 self.orchestrator.drop_service(&service_name)
991 }
992}
993
994async fn try_remove_past_generation_replicas(
996 orchestrator: &dyn NamespacedOrchestrator,
997 deploy_generation: u64,
998) -> Result<(), anyhow::Error> {
999 let services: BTreeSet<_> = orchestrator.list_services().await?.into_iter().collect();
1000
1001 for service in services {
1002 let name: ReplicaServiceName = service.parse()?;
1003 if name.generation < deploy_generation {
1004 info!(
1005 cluster_id = %name.cluster_id,
1006 replica_id = %name.replica_id,
1007 "removing past generation replica",
1008 );
1009 orchestrator.drop_service(&service)?;
1010 }
1011 }
1012
1013 Ok(())
1014}
1015
1016#[derive(PartialEq, Eq, PartialOrd, Ord)]
1018pub struct ReplicaServiceName {
1019 pub cluster_id: ClusterId,
1020 pub replica_id: ReplicaId,
1021 pub generation: u64,
1022}
1023
1024impl fmt::Display for ReplicaServiceName {
1025 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1026 let ReplicaServiceName {
1027 cluster_id,
1028 replica_id,
1029 generation,
1030 } = self;
1031 write!(f, "{cluster_id}-replica-{replica_id}-gen-{generation}")
1032 }
1033}
1034
1035impl FromStr for ReplicaServiceName {
1036 type Err = anyhow::Error;
1037
1038 fn from_str(s: &str) -> Result<Self, Self::Err> {
1039 static SERVICE_NAME_RE: LazyLock<Regex> = LazyLock::new(|| {
1040 Regex::new(r"(?-u)^([us]\d+)-replica-([us]\d+)(?:-gen-(\d+))?$").unwrap()
1041 });
1042
1043 let caps = SERVICE_NAME_RE
1044 .captures(s)
1045 .ok_or_else(|| anyhow!("invalid service name: {s}"))?;
1046
1047 Ok(ReplicaServiceName {
1048 cluster_id: caps.get(1).unwrap().as_str().parse().unwrap(),
1049 replica_id: caps.get(2).unwrap().as_str().parse().unwrap(),
1050 generation: caps.get(3).map_or("0", |m| m.as_str()).parse().unwrap(),
1054 })
1055 }
1056}