Skip to main content

mz_controller/
clusters.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
10//! Cluster management.
11
12use 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
49/// Configures a cluster.
50pub struct ClusterConfig {
51    /// The logging variants to enable on the compute instance.
52    ///
53    /// Each logging variant is mapped to the identifier under which to register
54    /// the arrangement storing the log's data.
55    pub arranged_logs: BTreeMap<LogVariant, GlobalId>,
56    /// An optional arbitrary string that describes the class of the workload
57    /// this cluster is running (e.g., `production` or `staging`).
58    pub workload_class: Option<String>,
59}
60
61/// The status of a cluster.
62pub type ClusterStatus = mz_orchestrator::ServiceStatus;
63
64/// Configures a cluster replica.
65#[derive(Clone, Debug, Serialize, PartialEq)]
66pub struct ReplicaConfig {
67    /// The location of the replica.
68    pub location: ReplicaLocation,
69    /// Configuration for the compute half of the replica.
70    pub compute: ComputeReplicaConfig,
71}
72
73/// Configures the resource allocation for a cluster replica.
74#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
75pub struct ReplicaAllocation {
76    /// The memory limit for each process in the replica.
77    pub memory_limit: Option<MemoryLimit>,
78    /// The CPU limit for each process in the replica.
79    pub cpu_limit: Option<CpuLimit>,
80    /// The CPU limit for each process in the replica.
81    pub cpu_request: Option<CpuLimit>,
82    /// The disk limit for each process in the replica.
83    pub disk_limit: Option<DiskLimit>,
84    /// The number of processes in the replica.
85    pub scale: NonZero<u16>,
86    /// The number of worker threads in the replica.
87    pub workers: NonZero<usize>,
88    /// The number of credits per hour that the replica consumes.
89    #[serde(deserialize_with = "mz_repr::adt::numeric::str_serde::deserialize")]
90    pub credits_per_hour: Numeric,
91    /// Whether each process has exclusive access to its CPU cores.
92    #[serde(default)]
93    pub cpu_exclusive: bool,
94    /// Whether this size represents a modern "cc" size rather than a legacy
95    /// T-shirt size.
96    #[serde(default = "default_true")]
97    pub is_cc: bool,
98    /// Whether instances of this type use swap as the spill-to-disk mechanism.
99    #[serde(default)]
100    pub swap_enabled: bool,
101    /// Whether instances of this type can be created.
102    #[serde(default)]
103    pub disabled: bool,
104    /// Additional node selectors.
105    #[serde(default)]
106    pub selectors: BTreeMap<String, String>,
107}
108
109fn default_true() -> bool {
110    true
111}
112
113#[mz_ore::test]
114// We test this particularly because we deserialize values from strings.
115#[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
116fn 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    // `scale` and `workers` must be non-zero.
193    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/// Configures the location of a cluster replica.
202#[derive(Clone, Debug, Serialize, PartialEq)]
203pub enum ReplicaLocation {
204    /// An unmanaged replica.
205    Unmanaged(UnmanagedReplicaLocation),
206    /// A managed replica.
207    Managed(ManagedReplicaLocation),
208}
209
210impl ReplicaLocation {
211    /// Returns the number of processes specified by this replica location.
212    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    /// Returns the number of workers specified by this replica location.
240    ///
241    /// `None` for unmanaged replicas, whose worker count we don't know.
242    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    /// A pending replica is created as part of an alter cluster of an managed
252    /// cluster. the configuration of a pending replica will not match that of
253    /// the clusters until the alter has been finalized promoting the pending
254    /// replicas and setting this value to false.
255    pub fn pending(&self) -> bool {
256        match self {
257            ReplicaLocation::Managed(ManagedReplicaLocation { pending, .. }) => *pending,
258            ReplicaLocation::Unmanaged(_) => false,
259        }
260    }
261}
262
263/// The "role" of a cluster, which is currently used to determine the
264/// severity of alerts for problems with its replicas.
265#[derive(Debug, Clone)]
266pub enum ClusterRole {
267    /// The existence and proper functioning of the cluster's replicas is
268    /// business-critical for Materialize.
269    SystemCritical,
270    /// Assuming no bugs, the cluster's replicas should always exist and function
271    /// properly. If it doesn't, however, that is less urgent than
272    /// would be the case for a `SystemCritical` replica.
273    System,
274    /// The cluster is controlled by the user, and might go down for
275    /// reasons outside our control (e.g., OOMs).
276    User,
277}
278
279/// The location of an unmanaged replica.
280#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
281pub struct UnmanagedReplicaLocation {
282    /// The network addresses of the storagectl endpoints for each process in
283    /// the replica.
284    pub storagectl_addrs: Vec<String>,
285    /// The network addresses of the computectl endpoints for each process in
286    /// the replica.
287    pub computectl_addrs: Vec<String>,
288}
289
290/// Information about availability zone constraints for replicas.
291#[derive(Clone, Debug, PartialEq, Eq)]
292pub enum ManagedReplicaAvailabilityZones {
293    /// Specified if the `Replica` is from `MANAGED` cluster,
294    /// and specifies if there is an `AVAILABILITY ZONES`
295    /// constraint. Empty lists are represented as `None`.
296    FromCluster(Option<Vec<String>>),
297    /// Specified if the `Replica` is from a non-`MANAGED` cluster,
298    /// and specifies if there is a specific `AVAILABILITY ZONE`.
299    FromReplica(Option<String>),
300}
301
302/// The location of a managed replica.
303#[derive(Clone, Debug, Serialize, PartialEq)]
304pub struct ManagedReplicaLocation {
305    /// The resource allocation for the replica.
306    pub allocation: ReplicaAllocation,
307    /// SQL size parameter used for allocation
308    pub size: String,
309    /// If `true`, Materialize support owns this replica.
310    pub internal: bool,
311    /// Optional SQL size parameter used for billing.
312    pub billed_as: Option<String>,
313    /// The replica's availability zones, if specified.
314    ///
315    /// This is either the replica's specific `AVAILABILITY ZONE`,
316    /// or the zones placed here during replica concretization
317    /// from the `MANAGED` cluster config.
318    ///
319    /// We skip serialization (which is used for some validation
320    /// in tests) as the latter case is a "virtual" piece of information,
321    /// that exists only at runtime.
322    ///
323    /// An empty list of availability zones is concretized as `None`,
324    /// as the on-disk serialization of `MANAGED CLUSTER AVAILABILITY ZONES`
325    /// is an empty list if none are specified
326    #[serde(skip)]
327    pub availability_zones: ManagedReplicaAvailabilityZones,
328    /// Whether the replica is pending reconfiguration
329    pub pending: bool,
330}
331
332impl ManagedReplicaLocation {
333    /// Return the size which should be used to determine billing-related information.
334    pub fn size_for_billing(&self) -> &str {
335        self.billed_as.as_deref().unwrap_or(&self.size)
336    }
337}
338
339/// Configures logging for a cluster replica.
340pub type ReplicaLogging = ComputeReplicaLogging;
341
342/// Identifier of a process within a replica.
343pub type ProcessId = u64;
344
345/// An event describing a change in status of a cluster replica process.
346#[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    /// Creates a cluster with the specified identifier and configuration.
357    ///
358    /// A cluster is a combination of a storage instance and a compute instance.
359    /// A cluster has zero or more replicas; each replica colocates the storage
360    /// and compute layers on the same physical resources.
361    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    /// Updates the workload class for a cluster.
374    ///
375    /// # Panics
376    ///
377    /// Panics if the instance does not exist in the StorageController or the ComputeController.
378    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    /// Drops the specified cluster.
387    ///
388    /// # Panics
389    ///
390    /// Panics if the cluster still has replicas.
391    pub fn drop_cluster(&mut self, id: ClusterId) {
392        self.storage.drop_instance(id);
393        self.compute.drop_instance(id);
394    }
395
396    /// Creates a replica of the specified cluster with the specified identifier
397    /// and configuration.
398    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                // Register the replica for HTTP proxying.
444                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    /// Drops the specified replica of the specified cluster.
467    pub fn drop_replica(
468        &mut self,
469        cluster_id: ClusterId,
470        replica_id: ReplicaId,
471    ) -> Result<(), anyhow::Error> {
472        // We unconditionally deprovision even for unmanaged replicas to avoid
473        // needing to keep track of which replicas are managed and which are
474        // unmanaged. Deprovisioning is a no-op if the replica ID was never
475        // provisioned.
476        self.deprovision_replica(cluster_id, replica_id, self.deploy_generation)?;
477        self.metrics_tasks.remove(&replica_id);
478
479        // Remove HTTP addresses from the locator.
480        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    /// Removes replicas from past generations in a background task.
489    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    /// Remove replicas that are orphaned in the current generation.
519    #[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            // We limit our attention here to replicas from the current deploy
542            // generation. Replicas from past generations are cleaned up during
543            // `Controller::allow_writes`.
544            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                // Found a replica in the orchestrator with a higher replica ID
559                // than what we are aware of. This must have been created by an
560                // environmentd that's competing for control of this generation.
561                // Abort to let the other process have full control.
562                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    /// Provisions a replica with the service orchestrator.
618    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        // TODO(teskje): use the same values as for compute?
646        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            // The disk limit we specify in the service config decides whether or not the replica
664            // gets a scratch disk attached. We want to avoid attaching disks to swap replicas, so
665            // make sure to set the disk limit accordingly.
666            disk_limit = Some(DiskLimit::ZERO);
667
668            // We want to keep the memory request equal to the memory limit, to avoid
669            // over-provisioning and ensure replicas have predictable performance. However, to
670            // enable swap, Kubernetes currently requires that request and limit are different.
671            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 swap is enabled, make the replica limit its own heap usage based on the
746                    // configured memory and disk limits.
747                    if location.allocation.swap_enabled
748                        && let Some(memory_limit) = location.allocation.memory_limit
749                        && let Some(disk_limit) = location.allocation.disk_limit
750                        // Currently, the way for replica sizes to request unlimited swap is to
751                        // specify a `disk_limit` of 0. Ideally we'd change this to make them
752                        // specify no disk limit instead, but for now we need to special-case here.
753                        && 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                    // To simplify the changes to tests, the port
768                    // chosen here is _after_ the compute ones.
769                    // TODO(petrosagg): fix the numerical ordering here
770                    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                // This provides the orchestrator with some label selectors that
816                // are used to constraint the scheduling of replicas, based on
817                // its internal configuration.
818                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                    // Select other replicas (but not oneself)
826                    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                    // Select ALL replicas.
836                    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                // TODO[btv] -- I tried implementing a `watch_metrics` function,
853                // similar to `watch_services`, but it crashed due to
854                // https://github.com/kube-rs/kube/issues/1092 .
855                //
856                // If `metrics-server` can be made to fill in `resourceVersion`,
857                // or if that bug is fixed, we can try that again rather than using this inelegant
858                // loop.
859                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    /// Deprovisions a replica with the service orchestrator.
878    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
894/// Remove all replicas from past generations.
895async 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/// Represents the name of a cluster replica service in the orchestrator.
917#[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            // Old versions of Materialize did not include generations in
951            // replica service names. Synthesize generation 0 if absent.
952            // TODO: remove this in the next version of Materialize.
953            generation: caps.get(3).map_or("0", |m| m.as_str()).parse().unwrap(),
954        })
955    }
956}