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.compute.drop_replica(cluster_id, replica_id)?;
538 self.storage.drop_replica(cluster_id, replica_id);
539 Ok(())
540 }
541
542 pub(crate) fn remove_past_generation_replicas_in_background(&self) {
544 let deploy_generation = self.deploy_generation;
545 let dyncfg = Arc::clone(self.compute.dyncfg());
546 let orchestrator = Arc::clone(&self.orchestrator);
547 task::spawn(
548 || "controller_remove_past_generation_replicas",
549 async move {
550 info!("attempting to remove past generation replicas");
551 loop {
552 match try_remove_past_generation_replicas(&*orchestrator, deploy_generation)
553 .await
554 {
555 Ok(()) => {
556 info!("successfully removed past generation replicas");
557 return;
558 }
559 Err(e) => {
560 let interval =
561 CONTROLLER_PAST_GENERATION_REPLICA_CLEANUP_RETRY_INTERVAL
562 .get(&dyncfg);
563 warn!(%e, "failed to remove past generation replicas; will retry in {interval:?}");
564 time::sleep(interval).await;
565 }
566 }
567 }
568 },
569 );
570 }
571
572 #[instrument]
574 pub async fn remove_orphaned_replicas(
575 &mut self,
576 next_user_replica_id: u64,
577 next_system_replica_id: u64,
578 ) -> Result<(), anyhow::Error> {
579 let desired: BTreeSet<_> = self.metrics_tasks.keys().copied().collect();
580
581 let actual: BTreeSet<_> = self
582 .orchestrator
583 .list_services()
584 .await?
585 .iter()
586 .map(|s| ReplicaServiceName::from_str(s))
587 .collect::<Result<_, _>>()?;
588
589 for ReplicaServiceName {
590 cluster_id,
591 replica_id,
592 generation,
593 } in actual
594 {
595 if generation != self.deploy_generation {
599 continue;
600 }
601
602 let smaller_next = match replica_id {
603 ReplicaId::User(id) if id >= next_user_replica_id => {
604 Some(ReplicaId::User(next_user_replica_id))
605 }
606 ReplicaId::System(id) if id >= next_system_replica_id => {
607 Some(ReplicaId::System(next_system_replica_id))
608 }
609 _ => None,
610 };
611 if let Some(next) = smaller_next {
612 halt!("found replica ID ({replica_id}) in orchestrator >= next ID ({next})");
617 }
618 if !desired.contains(&replica_id) {
619 self.deprovision_replica(cluster_id, replica_id, generation)?;
620 }
621 }
622
623 Ok(())
624 }
625
626 pub fn events_stream(&self) -> BoxStream<'static, ClusterEvent> {
627 let deploy_generation = self.deploy_generation;
628
629 fn translate_event(event: ServiceEvent) -> Result<(ClusterEvent, u64), anyhow::Error> {
630 let ReplicaServiceName {
631 cluster_id,
632 replica_id,
633 generation: replica_generation,
634 ..
635 } = event.service_id.parse()?;
636
637 let event = ClusterEvent {
638 cluster_id,
639 replica_id,
640 process_id: event.process_id,
641 status: event.status,
642 restart_count: event.restart_count,
643 time: event.time,
644 };
645
646 Ok((event, replica_generation))
647 }
648
649 let stream = self
650 .orchestrator
651 .watch_services()
652 .map(|event| event.and_then(translate_event))
653 .filter_map(move |event| async move {
654 match event {
655 Ok((event, replica_generation)) => {
656 if replica_generation == deploy_generation {
657 Some(event)
658 } else {
659 None
660 }
661 }
662 Err(error) => {
663 error!("service watch error: {error}");
664 None
665 }
666 }
667 });
668
669 Box::pin(stream)
670 }
671
672 fn provision_replica(
674 &self,
675 cluster_id: ClusterId,
676 replica_id: ReplicaId,
677 cluster_name: String,
678 replica_name: String,
679 role: ClusterRole,
680 location: ManagedReplicaLocation,
681 enable_worker_core_affinity: bool,
682 enable_storage_introspection_logs: bool,
683 ) -> Result<(Box<dyn Service>, AbortOnDropHandle<()>), anyhow::Error> {
684 let service_name = ReplicaServiceName {
685 cluster_id,
686 replica_id,
687 generation: self.deploy_generation,
688 }
689 .to_string();
690 let role_label = match role {
691 ClusterRole::SystemCritical => "system-critical",
692 ClusterRole::System => "system",
693 ClusterRole::User => "user",
694 };
695 let environment_id = self.connection_context().environment_id.clone();
696 let aws_external_id_prefix = self.connection_context().aws_external_id_prefix.clone();
697 let aws_connection_role_arn = self.connection_context().aws_connection_role_arn.clone();
698 let persist_pubsub_url = self.persist_pubsub_url.clone();
699 let secrets_args = self.secrets_args.to_flags();
700
701 let storage_proto_timely_config = TimelyConfig {
703 arrangement_exert_proportionality: 1337,
704 ..Default::default()
705 };
706 let compute_proto_timely_config = TimelyConfig {
707 arrangement_exert_proportionality: ARRANGEMENT_EXERT_PROPORTIONALITY.get(&self.dyncfg),
708 enable_zero_copy: ENABLE_TIMELY_ZERO_COPY.get(&self.dyncfg),
709 enable_zero_copy_lgalloc: ENABLE_TIMELY_ZERO_COPY_LGALLOC.get(&self.dyncfg),
710 zero_copy_limit: TIMELY_ZERO_COPY_LIMIT.get(&self.dyncfg),
711 ..Default::default()
712 };
713
714 let mut disk_limit = location.allocation.disk_limit;
715 let memory_limit = location.allocation.memory_limit;
716 let mut memory_request = None;
717
718 if location.allocation.swap_enabled {
719 disk_limit = Some(DiskLimit::ZERO);
723
724 memory_request = memory_limit.map(|MemoryLimit(limit)| {
728 let request = ByteSize::b(limit.as_u64() - 1);
729 MemoryLimit(request)
730 });
731 }
732
733 let service = self.orchestrator.ensure_service(
734 &service_name,
735 ServiceConfig {
736 app_name: "clusterd".into(),
737 image: self.clusterd_image.clone(),
738 init_container_image: self.init_container_image.clone(),
739 args: Box::new(move |assigned| {
740 let storage_timely_config = TimelyConfig {
741 workers: location.allocation.workers.get(),
742 addresses: assigned.peer_addresses("storage"),
743 ..storage_proto_timely_config
744 };
745 let compute_timely_config = TimelyConfig {
746 workers: location.allocation.workers.get(),
747 addresses: assigned.peer_addresses("compute"),
748 ..compute_proto_timely_config
749 };
750
751 let mut args = vec![
752 format!(
753 "--storage-controller-listen-addr={}",
754 assigned.listen_addrs["storagectl"]
755 ),
756 format!(
757 "--compute-controller-listen-addr={}",
758 assigned.listen_addrs["computectl"]
759 ),
760 format!(
761 "--internal-http-listen-addr={}",
762 assigned.listen_addrs["internal-http"]
763 ),
764 format!("--opentelemetry-resource=cluster_id={}", cluster_id),
765 format!("--opentelemetry-resource=replica_id={}", replica_id),
766 format!("--persist-pubsub-url={}", persist_pubsub_url),
767 format!("--environment-id={}", environment_id),
768 format!(
769 "--storage-timely-config={}",
770 storage_timely_config.to_string(),
771 ),
772 format!(
773 "--compute-timely-config={}",
774 compute_timely_config.to_string(),
775 ),
776 ];
777 if let Some(aws_external_id_prefix) = &aws_external_id_prefix {
778 args.push(format!(
779 "--aws-external-id-prefix={}",
780 aws_external_id_prefix
781 ));
782 }
783 if let Some(aws_connection_role_arn) = &aws_connection_role_arn {
784 args.push(format!(
785 "--aws-connection-role-arn={}",
786 aws_connection_role_arn
787 ));
788 }
789 if let Some(memory_limit) = location.allocation.memory_limit {
790 args.push(format!(
791 "--announce-memory-limit={}",
792 memory_limit.0.as_u64()
793 ));
794 }
795 if location.allocation.cpu_exclusive && enable_worker_core_affinity {
796 args.push("--worker-core-affinity".into());
797 }
798 if enable_storage_introspection_logs {
799 args.push("--enable-storage-introspection-logs".into());
800 }
801 if location.allocation.is_cc {
802 args.push("--is-cc".into());
803 }
804
805 if location.allocation.swap_enabled
808 && let Some(memory_limit) = location.allocation.memory_limit
809 && let Some(disk_limit) = location.allocation.disk_limit
810 && disk_limit != DiskLimit::ZERO
814 {
815 let heap_limit = memory_limit.0 + disk_limit.0;
816 args.push(format!("--heap-limit={}", heap_limit.as_u64()));
817 }
818
819 args.extend(secrets_args.clone());
820 args
821 }),
822 ports: vec![
823 ServicePort {
824 name: "storagectl".into(),
825 port_hint: 2100,
826 },
827 ServicePort {
831 name: "storage".into(),
832 port_hint: 2103,
833 },
834 ServicePort {
835 name: "computectl".into(),
836 port_hint: 2101,
837 },
838 ServicePort {
839 name: "compute".into(),
840 port_hint: 2102,
841 },
842 ServicePort {
843 name: "internal-http".into(),
844 port_hint: 6878,
845 },
846 ],
847 cpu_limit: location.allocation.cpu_limit,
848 cpu_request: location.allocation.cpu_request,
849 memory_limit,
850 memory_request,
851 scale: location.allocation.scale,
852 labels: BTreeMap::from([
853 ("replica-id".into(), replica_id.to_string()),
854 ("cluster-id".into(), cluster_id.to_string()),
855 ("generation".into(), self.deploy_generation.to_string()),
856 ("type".into(), "cluster".into()),
857 ("replica-role".into(), role_label.into()),
858 ("workers".into(), location.allocation.workers.to_string()),
859 (
860 "size".into(),
861 location
862 .size
863 .to_string()
864 .replace("=", "-")
865 .replace(",", "_"),
866 ),
867 ]),
868 annotations: BTreeMap::from([
869 (
870 "replica-name".into(),
871 format!("{cluster_name}.{replica_name}"),
872 ),
873 ("cluster-name".into(), cluster_name),
874 ]),
875 availability_zones: Some(location.availability_zones).filter(|azs| !azs.is_empty()),
878 other_replicas_selector: vec![
891 LabelSelector {
892 label_name: "cluster-id".to_string(),
893 logic: LabelSelectionLogic::Eq {
894 value: cluster_id.to_string(),
895 },
896 },
897 LabelSelector {
899 label_name: "replica-id".into(),
900 logic: LabelSelectionLogic::NotEq {
901 value: replica_id.to_string(),
902 },
903 },
904 LabelSelector {
905 label_name: "generation".into(),
906 logic: LabelSelectionLogic::Eq {
907 value: self.deploy_generation.to_string(),
908 },
909 },
910 ],
911 replicas_selector: vec![
912 LabelSelector {
913 label_name: "cluster-id".to_string(),
914 logic: LabelSelectionLogic::Eq {
916 value: cluster_id.to_string(),
917 },
918 },
919 LabelSelector {
920 label_name: "generation".into(),
921 logic: LabelSelectionLogic::Eq {
922 value: self.deploy_generation.to_string(),
923 },
924 },
925 ],
926 disk_limit,
927 node_selector: location.allocation.selectors,
928 },
929 )?;
930
931 let metrics_task = mz_ore::task::spawn(|| format!("replica-metrics-{replica_id}"), {
932 let tx = self.metrics_tx.clone();
933 let orchestrator = Arc::clone(&self.orchestrator);
934 let service_name = service_name.clone();
935 async move {
936 const METRICS_INTERVAL: Duration = Duration::from_secs(60);
937
938 let mut interval = tokio::time::interval(METRICS_INTERVAL);
946 loop {
947 interval.tick().await;
948 match orchestrator.fetch_service_metrics(&service_name).await {
949 Ok(metrics) => {
950 let _ = tx.send((replica_id, metrics));
951 }
952 Err(e) => {
953 warn!("failed to get metrics for replica {replica_id}: {e}");
954 }
955 }
956 }
957 }
958 });
959
960 Ok((service, metrics_task.abort_on_drop()))
961 }
962
963 fn deprovision_replica(
965 &self,
966 cluster_id: ClusterId,
967 replica_id: ReplicaId,
968 generation: u64,
969 ) -> Result<(), anyhow::Error> {
970 let service_name = ReplicaServiceName {
971 cluster_id,
972 replica_id,
973 generation,
974 }
975 .to_string();
976 self.orchestrator.drop_service(&service_name)
977 }
978}
979
980async fn try_remove_past_generation_replicas(
982 orchestrator: &dyn NamespacedOrchestrator,
983 deploy_generation: u64,
984) -> Result<(), anyhow::Error> {
985 let services: BTreeSet<_> = orchestrator.list_services().await?.into_iter().collect();
986
987 for service in services {
988 let name: ReplicaServiceName = service.parse()?;
989 if name.generation < deploy_generation {
990 info!(
991 cluster_id = %name.cluster_id,
992 replica_id = %name.replica_id,
993 "removing past generation replica",
994 );
995 orchestrator.drop_service(&service)?;
996 }
997 }
998
999 Ok(())
1000}
1001
1002#[derive(PartialEq, Eq, PartialOrd, Ord)]
1004pub struct ReplicaServiceName {
1005 pub cluster_id: ClusterId,
1006 pub replica_id: ReplicaId,
1007 pub generation: u64,
1008}
1009
1010impl fmt::Display for ReplicaServiceName {
1011 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1012 let ReplicaServiceName {
1013 cluster_id,
1014 replica_id,
1015 generation,
1016 } = self;
1017 write!(f, "{cluster_id}-replica-{replica_id}-gen-{generation}")
1018 }
1019}
1020
1021impl FromStr for ReplicaServiceName {
1022 type Err = anyhow::Error;
1023
1024 fn from_str(s: &str) -> Result<Self, Self::Err> {
1025 static SERVICE_NAME_RE: LazyLock<Regex> = LazyLock::new(|| {
1026 Regex::new(r"(?-u)^([us]\d+)-replica-([us]\d+)(?:-gen-(\d+))?$").unwrap()
1027 });
1028
1029 let caps = SERVICE_NAME_RE
1030 .captures(s)
1031 .ok_or_else(|| anyhow!("invalid service name: {s}"))?;
1032
1033 Ok(ReplicaServiceName {
1034 cluster_id: caps.get(1).unwrap().as_str().parse().unwrap(),
1035 replica_id: caps.get(2).unwrap().as_str().parse().unwrap(),
1036 generation: caps.get(3).map_or("0", |m| m.as_str()).parse().unwrap(),
1040 })
1041 }
1042}