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)]
100 pub swap_enabled: bool,
101 #[serde(default)]
103 pub disabled: bool,
104 #[serde(default)]
106 pub selectors: BTreeMap<String, String>,
107}
108
109fn default_true() -> bool {
110 true
111}
112
113#[mz_ore::test]
114#[cfg_attr(miri, ignore)] fn test_replica_allocation_deserialization() {
117 use bytesize::ByteSize;
118 use mz_ore::{assert_err, assert_ok};
119
120 let data = r#"
121 {
122 "cpu_limit": 1.0,
123 "memory_limit": "10GiB",
124 "disk_limit": "100MiB",
125 "scale": 16,
126 "workers": 1,
127 "credits_per_hour": "16",
128 "swap_enabled": true,
129 "selectors": {
130 "key1": "value1",
131 "key2": "value2"
132 }
133 }"#;
134
135 let replica_allocation: ReplicaAllocation = serde_json::from_str(data)
136 .expect("deserialization from JSON succeeds for ReplicaAllocation");
137
138 assert_eq!(
139 replica_allocation,
140 ReplicaAllocation {
141 credits_per_hour: 16.into(),
142 disk_limit: Some(DiskLimit(ByteSize::mib(100))),
143 disabled: false,
144 memory_limit: Some(MemoryLimit(ByteSize::gib(10))),
145 cpu_limit: Some(CpuLimit::from_millicpus(1000)),
146 cpu_request: None,
147 cpu_exclusive: false,
148 is_cc: true,
149 swap_enabled: true,
150 scale: NonZero::new(16).unwrap(),
151 workers: NonZero::new(1).unwrap(),
152 selectors: BTreeMap::from([
153 ("key1".to_string(), "value1".to_string()),
154 ("key2".to_string(), "value2".to_string())
155 ]),
156 }
157 );
158
159 let data = r#"
160 {
161 "cpu_limit": 0,
162 "memory_limit": "0GiB",
163 "disk_limit": "0MiB",
164 "scale": 1,
165 "workers": 1,
166 "credits_per_hour": "0",
167 "cpu_exclusive": true,
168 "disabled": true
169 }"#;
170
171 let replica_allocation: ReplicaAllocation = serde_json::from_str(data)
172 .expect("deserialization from JSON succeeds for ReplicaAllocation");
173
174 assert_eq!(
175 replica_allocation,
176 ReplicaAllocation {
177 credits_per_hour: 0.into(),
178 disk_limit: Some(DiskLimit(ByteSize::mib(0))),
179 disabled: true,
180 memory_limit: Some(MemoryLimit(ByteSize::gib(0))),
181 cpu_limit: Some(CpuLimit::from_millicpus(0)),
182 cpu_request: None,
183 cpu_exclusive: true,
184 is_cc: true,
185 swap_enabled: false,
186 scale: NonZero::new(1).unwrap(),
187 workers: NonZero::new(1).unwrap(),
188 selectors: Default::default(),
189 }
190 );
191
192 let data = r#"{"scale": 0, "workers": 1, "credits_per_hour": "0"}"#;
194 assert_err!(serde_json::from_str::<ReplicaAllocation>(data));
195 let data = r#"{"scale": 1, "workers": 0, "credits_per_hour": "0"}"#;
196 assert_err!(serde_json::from_str::<ReplicaAllocation>(data));
197 let data = r#"{"scale": 1, "workers": 1, "credits_per_hour": "0"}"#;
198 assert_ok!(serde_json::from_str::<ReplicaAllocation>(data));
199}
200
201#[derive(Clone, Debug, Serialize, PartialEq)]
203pub enum ReplicaLocation {
204 Unmanaged(UnmanagedReplicaLocation),
206 Managed(ManagedReplicaLocation),
208}
209
210impl ReplicaLocation {
211 pub fn num_processes(&self) -> usize {
213 match self {
214 ReplicaLocation::Unmanaged(UnmanagedReplicaLocation {
215 computectl_addrs, ..
216 }) => computectl_addrs.len(),
217 ReplicaLocation::Managed(ManagedReplicaLocation { allocation, .. }) => {
218 allocation.scale.cast_into()
219 }
220 }
221 }
222
223 pub fn billed_as(&self) -> Option<&str> {
224 match self {
225 ReplicaLocation::Managed(ManagedReplicaLocation { billed_as, .. }) => {
226 billed_as.as_deref()
227 }
228 ReplicaLocation::Unmanaged(_) => None,
229 }
230 }
231
232 pub fn internal(&self) -> bool {
233 match self {
234 ReplicaLocation::Managed(ManagedReplicaLocation { internal, .. }) => *internal,
235 ReplicaLocation::Unmanaged(_) => false,
236 }
237 }
238
239 pub fn workers(&self) -> Option<usize> {
243 match self {
244 ReplicaLocation::Managed(ManagedReplicaLocation { allocation, .. }) => {
245 Some(allocation.workers.get() * self.num_processes())
246 }
247 ReplicaLocation::Unmanaged(_) => None,
248 }
249 }
250
251 pub fn pending(&self) -> bool {
256 match self {
257 ReplicaLocation::Managed(ManagedReplicaLocation { pending, .. }) => *pending,
258 ReplicaLocation::Unmanaged(_) => false,
259 }
260 }
261}
262
263#[derive(Debug, Clone)]
266pub enum ClusterRole {
267 SystemCritical,
270 System,
274 User,
277}
278
279#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
281pub struct UnmanagedReplicaLocation {
282 pub storagectl_addrs: Vec<String>,
285 pub computectl_addrs: Vec<String>,
288}
289
290#[derive(Clone, Debug, PartialEq, Eq)]
292pub enum ManagedReplicaAvailabilityZones {
293 FromCluster(Option<Vec<String>>),
297 FromReplica(Option<String>),
300}
301
302#[derive(Clone, Debug, Serialize, PartialEq)]
304pub struct ManagedReplicaLocation {
305 pub allocation: ReplicaAllocation,
307 pub size: String,
309 pub internal: bool,
311 pub billed_as: Option<String>,
313 #[serde(skip)]
327 pub availability_zones: ManagedReplicaAvailabilityZones,
328 pub pending: bool,
330}
331
332impl ManagedReplicaLocation {
333 pub fn size_for_billing(&self) -> &str {
335 self.billed_as.as_deref().unwrap_or(&self.size)
336 }
337}
338
339pub type ReplicaLogging = ComputeReplicaLogging;
341
342pub type ProcessId = u64;
344
345#[derive(Debug, Clone, Serialize)]
347pub struct ClusterEvent {
348 pub cluster_id: ClusterId,
349 pub replica_id: ReplicaId,
350 pub process_id: ProcessId,
351 pub status: ClusterStatus,
352 pub time: DateTime<Utc>,
353}
354
355impl Controller {
356 pub fn create_cluster(
362 &mut self,
363 id: ClusterId,
364 config: ClusterConfig,
365 ) -> Result<(), anyhow::Error> {
366 self.storage
367 .create_instance(id, config.workload_class.clone());
368 self.compute
369 .create_instance(id, config.arranged_logs, config.workload_class)?;
370 Ok(())
371 }
372
373 pub fn update_cluster_workload_class(&mut self, id: ClusterId, workload_class: Option<String>) {
379 self.storage
380 .update_instance_workload_class(id, workload_class.clone());
381 self.compute
382 .update_instance_workload_class(id, workload_class)
383 .expect("instance exists");
384 }
385
386 pub fn drop_cluster(&mut self, id: ClusterId) {
392 self.storage.drop_instance(id);
393 self.compute.drop_instance(id);
394 }
395
396 pub fn create_replica(
399 &mut self,
400 cluster_id: ClusterId,
401 replica_id: ReplicaId,
402 cluster_name: String,
403 replica_name: String,
404 role: ClusterRole,
405 config: ReplicaConfig,
406 enable_worker_core_affinity: bool,
407 ) -> Result<(), anyhow::Error> {
408 let storage_location: ClusterReplicaLocation;
409 let compute_location: ClusterReplicaLocation;
410 let metrics_task: Option<AbortOnDropHandle<()>>;
411
412 match config.location {
413 ReplicaLocation::Unmanaged(UnmanagedReplicaLocation {
414 storagectl_addrs,
415 computectl_addrs,
416 }) => {
417 compute_location = ClusterReplicaLocation {
418 ctl_addrs: computectl_addrs,
419 };
420 storage_location = ClusterReplicaLocation {
421 ctl_addrs: storagectl_addrs,
422 };
423 metrics_task = None;
424 }
425 ReplicaLocation::Managed(m) => {
426 let (service, metrics_task_join_handle) = self.provision_replica(
427 cluster_id,
428 replica_id,
429 cluster_name,
430 replica_name,
431 role,
432 m,
433 enable_worker_core_affinity,
434 )?;
435 storage_location = ClusterReplicaLocation {
436 ctl_addrs: service.addresses("storagectl"),
437 };
438 compute_location = ClusterReplicaLocation {
439 ctl_addrs: service.addresses("computectl"),
440 };
441 metrics_task = Some(metrics_task_join_handle);
442
443 let http_addresses = service.addresses("internal-http");
445 self.replica_http_locator
446 .register_replica(cluster_id, replica_id, http_addresses);
447 }
448 }
449
450 self.storage
451 .connect_replica(cluster_id, replica_id, storage_location);
452 self.compute.add_replica_to_instance(
453 cluster_id,
454 replica_id,
455 compute_location,
456 config.compute,
457 )?;
458
459 if let Some(task) = metrics_task {
460 self.metrics_tasks.insert(replica_id, task);
461 }
462
463 Ok(())
464 }
465
466 pub fn drop_replica(
468 &mut self,
469 cluster_id: ClusterId,
470 replica_id: ReplicaId,
471 ) -> Result<(), anyhow::Error> {
472 self.deprovision_replica(cluster_id, replica_id, self.deploy_generation)?;
477 self.metrics_tasks.remove(&replica_id);
478
479 self.replica_http_locator
481 .remove_replica(cluster_id, replica_id);
482
483 self.compute.drop_replica(cluster_id, replica_id)?;
484 self.storage.drop_replica(cluster_id, replica_id);
485 Ok(())
486 }
487
488 pub(crate) fn remove_past_generation_replicas_in_background(&self) {
490 let deploy_generation = self.deploy_generation;
491 let dyncfg = Arc::clone(self.compute.dyncfg());
492 let orchestrator = Arc::clone(&self.orchestrator);
493 task::spawn(
494 || "controller_remove_past_generation_replicas",
495 async move {
496 info!("attempting to remove past generation replicas");
497 loop {
498 match try_remove_past_generation_replicas(&*orchestrator, deploy_generation)
499 .await
500 {
501 Ok(()) => {
502 info!("successfully removed past generation replicas");
503 return;
504 }
505 Err(e) => {
506 let interval =
507 CONTROLLER_PAST_GENERATION_REPLICA_CLEANUP_RETRY_INTERVAL
508 .get(&dyncfg);
509 warn!(%e, "failed to remove past generation replicas; will retry in {interval:?}");
510 time::sleep(interval).await;
511 }
512 }
513 }
514 },
515 );
516 }
517
518 #[instrument]
520 pub async fn remove_orphaned_replicas(
521 &mut self,
522 next_user_replica_id: u64,
523 next_system_replica_id: u64,
524 ) -> Result<(), anyhow::Error> {
525 let desired: BTreeSet<_> = self.metrics_tasks.keys().copied().collect();
526
527 let actual: BTreeSet<_> = self
528 .orchestrator
529 .list_services()
530 .await?
531 .iter()
532 .map(|s| ReplicaServiceName::from_str(s))
533 .collect::<Result<_, _>>()?;
534
535 for ReplicaServiceName {
536 cluster_id,
537 replica_id,
538 generation,
539 } in actual
540 {
541 if generation != self.deploy_generation {
545 continue;
546 }
547
548 let smaller_next = match replica_id {
549 ReplicaId::User(id) if id >= next_user_replica_id => {
550 Some(ReplicaId::User(next_user_replica_id))
551 }
552 ReplicaId::System(id) if id >= next_system_replica_id => {
553 Some(ReplicaId::System(next_system_replica_id))
554 }
555 _ => None,
556 };
557 if let Some(next) = smaller_next {
558 halt!("found replica ID ({replica_id}) in orchestrator >= next ID ({next})");
563 }
564 if !desired.contains(&replica_id) {
565 self.deprovision_replica(cluster_id, replica_id, generation)?;
566 }
567 }
568
569 Ok(())
570 }
571
572 pub fn events_stream(&self) -> BoxStream<'static, ClusterEvent> {
573 let deploy_generation = self.deploy_generation;
574
575 fn translate_event(event: ServiceEvent) -> Result<(ClusterEvent, u64), anyhow::Error> {
576 let ReplicaServiceName {
577 cluster_id,
578 replica_id,
579 generation: replica_generation,
580 ..
581 } = event.service_id.parse()?;
582
583 let event = ClusterEvent {
584 cluster_id,
585 replica_id,
586 process_id: event.process_id,
587 status: event.status,
588 time: event.time,
589 };
590
591 Ok((event, replica_generation))
592 }
593
594 let stream = self
595 .orchestrator
596 .watch_services()
597 .map(|event| event.and_then(translate_event))
598 .filter_map(move |event| async move {
599 match event {
600 Ok((event, replica_generation)) => {
601 if replica_generation == deploy_generation {
602 Some(event)
603 } else {
604 None
605 }
606 }
607 Err(error) => {
608 error!("service watch error: {error}");
609 None
610 }
611 }
612 });
613
614 Box::pin(stream)
615 }
616
617 fn provision_replica(
619 &self,
620 cluster_id: ClusterId,
621 replica_id: ReplicaId,
622 cluster_name: String,
623 replica_name: String,
624 role: ClusterRole,
625 location: ManagedReplicaLocation,
626 enable_worker_core_affinity: bool,
627 ) -> Result<(Box<dyn Service>, AbortOnDropHandle<()>), anyhow::Error> {
628 let service_name = ReplicaServiceName {
629 cluster_id,
630 replica_id,
631 generation: self.deploy_generation,
632 }
633 .to_string();
634 let role_label = match role {
635 ClusterRole::SystemCritical => "system-critical",
636 ClusterRole::System => "system",
637 ClusterRole::User => "user",
638 };
639 let environment_id = self.connection_context().environment_id.clone();
640 let aws_external_id_prefix = self.connection_context().aws_external_id_prefix.clone();
641 let aws_connection_role_arn = self.connection_context().aws_connection_role_arn.clone();
642 let persist_pubsub_url = self.persist_pubsub_url.clone();
643 let secrets_args = self.secrets_args.to_flags();
644
645 let storage_proto_timely_config = TimelyConfig {
647 arrangement_exert_proportionality: 1337,
648 ..Default::default()
649 };
650 let compute_proto_timely_config = TimelyConfig {
651 arrangement_exert_proportionality: ARRANGEMENT_EXERT_PROPORTIONALITY.get(&self.dyncfg),
652 enable_zero_copy: ENABLE_TIMELY_ZERO_COPY.get(&self.dyncfg),
653 enable_zero_copy_lgalloc: ENABLE_TIMELY_ZERO_COPY_LGALLOC.get(&self.dyncfg),
654 zero_copy_limit: TIMELY_ZERO_COPY_LIMIT.get(&self.dyncfg),
655 ..Default::default()
656 };
657
658 let mut disk_limit = location.allocation.disk_limit;
659 let memory_limit = location.allocation.memory_limit;
660 let mut memory_request = None;
661
662 if location.allocation.swap_enabled {
663 disk_limit = Some(DiskLimit::ZERO);
667
668 memory_request = memory_limit.map(|MemoryLimit(limit)| {
672 let request = ByteSize::b(limit.as_u64() - 1);
673 MemoryLimit(request)
674 });
675 }
676
677 let service = self.orchestrator.ensure_service(
678 &service_name,
679 ServiceConfig {
680 image: self.clusterd_image.clone(),
681 init_container_image: self.init_container_image.clone(),
682 args: Box::new(move |assigned| {
683 let storage_timely_config = TimelyConfig {
684 workers: location.allocation.workers.get(),
685 addresses: assigned.peer_addresses("storage"),
686 ..storage_proto_timely_config
687 };
688 let compute_timely_config = TimelyConfig {
689 workers: location.allocation.workers.get(),
690 addresses: assigned.peer_addresses("compute"),
691 ..compute_proto_timely_config
692 };
693
694 let mut args = vec![
695 format!(
696 "--storage-controller-listen-addr={}",
697 assigned.listen_addrs["storagectl"]
698 ),
699 format!(
700 "--compute-controller-listen-addr={}",
701 assigned.listen_addrs["computectl"]
702 ),
703 format!(
704 "--internal-http-listen-addr={}",
705 assigned.listen_addrs["internal-http"]
706 ),
707 format!("--opentelemetry-resource=cluster_id={}", cluster_id),
708 format!("--opentelemetry-resource=replica_id={}", replica_id),
709 format!("--persist-pubsub-url={}", persist_pubsub_url),
710 format!("--environment-id={}", environment_id),
711 format!(
712 "--storage-timely-config={}",
713 storage_timely_config.to_string(),
714 ),
715 format!(
716 "--compute-timely-config={}",
717 compute_timely_config.to_string(),
718 ),
719 ];
720 if let Some(aws_external_id_prefix) = &aws_external_id_prefix {
721 args.push(format!(
722 "--aws-external-id-prefix={}",
723 aws_external_id_prefix
724 ));
725 }
726 if let Some(aws_connection_role_arn) = &aws_connection_role_arn {
727 args.push(format!(
728 "--aws-connection-role-arn={}",
729 aws_connection_role_arn
730 ));
731 }
732 if let Some(memory_limit) = location.allocation.memory_limit {
733 args.push(format!(
734 "--announce-memory-limit={}",
735 memory_limit.0.as_u64()
736 ));
737 }
738 if location.allocation.cpu_exclusive && enable_worker_core_affinity {
739 args.push("--worker-core-affinity".into());
740 }
741 if location.allocation.is_cc {
742 args.push("--is-cc".into());
743 }
744
745 if location.allocation.swap_enabled
748 && let Some(memory_limit) = location.allocation.memory_limit
749 && let Some(disk_limit) = location.allocation.disk_limit
750 && disk_limit != DiskLimit::ZERO
754 {
755 let heap_limit = memory_limit.0 + disk_limit.0;
756 args.push(format!("--heap-limit={}", heap_limit.as_u64()));
757 }
758
759 args.extend(secrets_args.clone());
760 args
761 }),
762 ports: vec![
763 ServicePort {
764 name: "storagectl".into(),
765 port_hint: 2100,
766 },
767 ServicePort {
771 name: "storage".into(),
772 port_hint: 2103,
773 },
774 ServicePort {
775 name: "computectl".into(),
776 port_hint: 2101,
777 },
778 ServicePort {
779 name: "compute".into(),
780 port_hint: 2102,
781 },
782 ServicePort {
783 name: "internal-http".into(),
784 port_hint: 6878,
785 },
786 ],
787 cpu_limit: location.allocation.cpu_limit,
788 cpu_request: location.allocation.cpu_request,
789 memory_limit,
790 memory_request,
791 scale: location.allocation.scale,
792 labels: BTreeMap::from([
793 ("replica-id".into(), replica_id.to_string()),
794 ("cluster-id".into(), cluster_id.to_string()),
795 ("type".into(), "cluster".into()),
796 ("replica-role".into(), role_label.into()),
797 ("workers".into(), location.allocation.workers.to_string()),
798 (
799 "size".into(),
800 location
801 .size
802 .to_string()
803 .replace("=", "-")
804 .replace(",", "_"),
805 ),
806 ]),
807 annotations: BTreeMap::from([
808 ("replica-name".into(), replica_name),
809 ("cluster-name".into(), cluster_name),
810 ]),
811 availability_zones: match location.availability_zones {
812 ManagedReplicaAvailabilityZones::FromCluster(azs) => azs,
813 ManagedReplicaAvailabilityZones::FromReplica(az) => az.map(|z| vec![z]),
814 },
815 other_replicas_selector: vec![
819 LabelSelector {
820 label_name: "cluster-id".to_string(),
821 logic: LabelSelectionLogic::Eq {
822 value: cluster_id.to_string(),
823 },
824 },
825 LabelSelector {
827 label_name: "replica-id".into(),
828 logic: LabelSelectionLogic::NotEq {
829 value: replica_id.to_string(),
830 },
831 },
832 ],
833 replicas_selector: vec![LabelSelector {
834 label_name: "cluster-id".to_string(),
835 logic: LabelSelectionLogic::Eq {
837 value: cluster_id.to_string(),
838 },
839 }],
840 disk_limit,
841 node_selector: location.allocation.selectors,
842 },
843 )?;
844
845 let metrics_task = mz_ore::task::spawn(|| format!("replica-metrics-{replica_id}"), {
846 let tx = self.metrics_tx.clone();
847 let orchestrator = Arc::clone(&self.orchestrator);
848 let service_name = service_name.clone();
849 async move {
850 const METRICS_INTERVAL: Duration = Duration::from_secs(60);
851
852 let mut interval = tokio::time::interval(METRICS_INTERVAL);
860 loop {
861 interval.tick().await;
862 match orchestrator.fetch_service_metrics(&service_name).await {
863 Ok(metrics) => {
864 let _ = tx.send((replica_id, metrics));
865 }
866 Err(e) => {
867 warn!("failed to get metrics for replica {replica_id}: {e}");
868 }
869 }
870 }
871 }
872 });
873
874 Ok((service, metrics_task.abort_on_drop()))
875 }
876
877 fn deprovision_replica(
879 &self,
880 cluster_id: ClusterId,
881 replica_id: ReplicaId,
882 generation: u64,
883 ) -> Result<(), anyhow::Error> {
884 let service_name = ReplicaServiceName {
885 cluster_id,
886 replica_id,
887 generation,
888 }
889 .to_string();
890 self.orchestrator.drop_service(&service_name)
891 }
892}
893
894async fn try_remove_past_generation_replicas(
896 orchestrator: &dyn NamespacedOrchestrator,
897 deploy_generation: u64,
898) -> Result<(), anyhow::Error> {
899 let services: BTreeSet<_> = orchestrator.list_services().await?.into_iter().collect();
900
901 for service in services {
902 let name: ReplicaServiceName = service.parse()?;
903 if name.generation < deploy_generation {
904 info!(
905 cluster_id = %name.cluster_id,
906 replica_id = %name.replica_id,
907 "removing past generation replica",
908 );
909 orchestrator.drop_service(&service)?;
910 }
911 }
912
913 Ok(())
914}
915
916#[derive(PartialEq, Eq, PartialOrd, Ord)]
918pub struct ReplicaServiceName {
919 pub cluster_id: ClusterId,
920 pub replica_id: ReplicaId,
921 pub generation: u64,
922}
923
924impl fmt::Display for ReplicaServiceName {
925 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
926 let ReplicaServiceName {
927 cluster_id,
928 replica_id,
929 generation,
930 } = self;
931 write!(f, "{cluster_id}-replica-{replica_id}-gen-{generation}")
932 }
933}
934
935impl FromStr for ReplicaServiceName {
936 type Err = anyhow::Error;
937
938 fn from_str(s: &str) -> Result<Self, Self::Err> {
939 static SERVICE_NAME_RE: LazyLock<Regex> = LazyLock::new(|| {
940 Regex::new(r"(?-u)^([us]\d+)-replica-([us]\d+)(?:-gen-(\d+))?$").unwrap()
941 });
942
943 let caps = SERVICE_NAME_RE
944 .captures(s)
945 .ok_or_else(|| anyhow!("invalid service name: {s}"))?;
946
947 Ok(ReplicaServiceName {
948 cluster_id: caps.get(1).unwrap().as_str().parse().unwrap(),
949 replica_id: caps.get(2).unwrap().as_str().parse().unwrap(),
950 generation: caps.get(3).map_or("0", |m| m.as_str()).parse().unwrap(),
954 })
955 }
956}