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    /// The size *family* this size belongs to, e.g. the size `D.1-xsmall`
99    /// belongs to family `D` and the legacy t-shirt sizes belong to family
100    /// `legacy`. The family is the coarse axis and is *not* a prefix of the size
101    /// name in general. Used as the
102    /// `replica_size_family` attribute when evaluating replica-local scoped
103    /// feature flags (see the scoped feature flags design). When unset, the
104    /// family falls back to a value derived from [`Self::is_cc`] via
105    /// [`ReplicaAllocation::family`].
106    #[serde(default)]
107    pub family: Option<String>,
108    /// Whether instances of this type use swap as the spill-to-disk mechanism.
109    #[serde(default)]
110    pub swap_enabled: bool,
111    /// Whether instances of this type can be created.
112    #[serde(default)]
113    pub disabled: bool,
114    /// Additional node selectors.
115    #[serde(default)]
116    pub selectors: BTreeMap<String, String>,
117}
118
119impl ReplicaAllocation {
120    /// The name of the size family this allocation belongs to, used as the
121    /// `replica_size_family` attribute when evaluating replica-local scoped
122    /// feature flags.
123    ///
124    /// Falls back to a value derived from [`Self::is_cc`] when [`Self::family`]
125    /// is unset: `"cc"` for modern sizes and `"legacy"` for the legacy t-shirt
126    /// sizes. This keeps the legacy family targetable even before every size
127    /// gains an explicit `family` in the size configuration.
128    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// We test this particularly because we deserialize values from strings.
143#[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
144fn 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    // `scale` and `workers` must be non-zero.
223    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)] // unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
233fn test_replica_allocation_family() {
234    let parse = |json: &str| -> ReplicaAllocation {
235        serde_json::from_str(json).expect("deserialization from JSON succeeds")
236    };
237
238    // An explicit `family` is used verbatim.
239    assert_eq!(
240        parse(r#"{"scale": 1, "workers": 1, "credits_per_hour": "0", "family": "D"}"#).family(),
241        "D"
242    );
243    // Without an explicit `family`, modern (`is_cc`) sizes fall back to "cc".
244    // `is_cc` defaults to true.
245    assert_eq!(
246        parse(r#"{"scale": 1, "workers": 1, "credits_per_hour": "0"}"#).family(),
247        "cc"
248    );
249    // Without an explicit `family`, legacy (non-`is_cc`) sizes fall back to
250    // "legacy".
251    assert_eq!(
252        parse(r#"{"scale": 1, "workers": 1, "credits_per_hour": "0", "is_cc": false}"#).family(),
253        "legacy"
254    );
255    // An explicit family wins even for a legacy size.
256    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/// Configures the location of a cluster replica.
266#[derive(Clone, Debug, Serialize, PartialEq)]
267pub enum ReplicaLocation {
268    /// An unmanaged replica.
269    Unmanaged(UnmanagedReplicaLocation),
270    /// A managed replica.
271    Managed(ManagedReplicaLocation),
272}
273
274impl ReplicaLocation {
275    /// Returns the number of processes specified by this replica location.
276    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    /// Returns the number of workers specified by this replica location.
304    ///
305    /// `None` for unmanaged replicas, whose worker count we don't know.
306    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    /// A pending replica is created as part of an alter cluster of an managed
316    /// cluster. the configuration of a pending replica will not match that of
317    /// the clusters until the alter has been finalized promoting the pending
318    /// replicas and setting this value to false.
319    pub fn pending(&self) -> bool {
320        match self {
321            ReplicaLocation::Managed(ManagedReplicaLocation { pending, .. }) => *pending,
322            ReplicaLocation::Unmanaged(_) => false,
323        }
324    }
325}
326
327/// The "role" of a cluster, which is currently used to determine the
328/// severity of alerts for problems with its replicas.
329#[derive(Debug, Clone)]
330pub enum ClusterRole {
331    /// The existence and proper functioning of the cluster's replicas is
332    /// business-critical for Materialize.
333    SystemCritical,
334    /// Assuming no bugs, the cluster's replicas should always exist and function
335    /// properly. If it doesn't, however, that is less urgent than
336    /// would be the case for a `SystemCritical` replica.
337    System,
338    /// The cluster is controlled by the user, and might go down for
339    /// reasons outside our control (e.g., OOMs).
340    User,
341}
342
343/// The location of an unmanaged replica.
344#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
345pub struct UnmanagedReplicaLocation {
346    /// The network addresses of the storagectl endpoints for each process in
347    /// the replica.
348    pub storagectl_addrs: Vec<String>,
349    /// The network addresses of the computectl endpoints for each process in
350    /// the replica.
351    pub computectl_addrs: Vec<String>,
352}
353
354/// The location of a managed replica.
355#[derive(Clone, Debug, Serialize, PartialEq)]
356pub struct ManagedReplicaLocation {
357    /// The resource allocation for the replica.
358    pub allocation: ReplicaAllocation,
359    /// SQL size parameter used for allocation
360    pub size: String,
361    /// If `true`, Materialize support owns this replica.
362    pub internal: bool,
363    /// Optional SQL size parameter used for billing.
364    pub billed_as: Option<String>,
365    /// The availability zones the replica may be placed in; empty means
366    /// unconstrained.
367    ///
368    /// For a replica of a managed cluster this is the cluster's
369    /// `AVAILABILITY ZONES` pool; for a replica of an unmanaged cluster it is
370    /// the single user-pinned `AVAILABILITY ZONE`, as a zero- or one-element
371    /// list.
372    ///
373    /// Not serialized: this is re-derived from the cluster config at
374    /// concretization, not read back from a durable record.
375    #[serde(skip)]
376    pub availability_zones: Vec<String>,
377    /// Whether the replica is pending reconfiguration
378    pub pending: bool,
379}
380
381impl ManagedReplicaLocation {
382    /// Return the size which should be used to determine billing-related information.
383    pub fn size_for_billing(&self) -> &str {
384        self.billed_as.as_deref().unwrap_or(&self.size)
385    }
386}
387
388/// Configures logging for a cluster replica.
389pub type ReplicaLogging = ComputeReplicaLogging;
390
391/// Identifier of a process within a replica.
392pub type ProcessId = u64;
393
394/// An event describing a change in status of a cluster replica process.
395#[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    /// Cumulative restart count of the process, propagated from the orchestrator.
402    /// See [`mz_orchestrator::ServiceEvent::restart_count`].
403    pub restart_count: u64,
404    pub time: DateTime<Utc>,
405}
406
407impl Controller {
408    /// Creates a cluster with the specified identifier and configuration.
409    ///
410    /// A cluster is a combination of a storage instance and a compute instance.
411    /// A cluster has zero or more replicas; each replica colocates the storage
412    /// and compute layers on the same physical resources.
413    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    /// Updates the workload class for a cluster.
426    ///
427    /// # Panics
428    ///
429    /// Panics if the instance does not exist in the StorageController or the ComputeController.
430    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    /// Drops the specified cluster.
439    ///
440    /// # Panics
441    ///
442    /// Panics if the cluster still has replicas.
443    pub fn drop_cluster(&mut self, id: ClusterId) {
444        self.storage.drop_instance(id);
445        self.compute.drop_instance(id);
446    }
447
448    /// Creates a replica of the specified cluster with the specified identifier
449    /// and configuration.
450    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                // Register the replica for HTTP proxying.
498                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    /// Drops the specified replica of the specified cluster.
521    pub fn drop_replica(
522        &mut self,
523        cluster_id: ClusterId,
524        replica_id: ReplicaId,
525    ) -> Result<(), anyhow::Error> {
526        // We unconditionally deprovision even for unmanaged replicas to avoid
527        // needing to keep track of which replicas are managed and which are
528        // unmanaged. Deprovisioning is a no-op if the replica ID was never
529        // provisioned.
530        self.deprovision_replica(cluster_id, replica_id, self.deploy_generation)?;
531        self.metrics_tasks.remove(&replica_id);
532
533        // Remove HTTP addresses from the locator.
534        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    /// Removes replicas from past generations in a background task.
543    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    /// Remove replicas that are orphaned in the current generation.
573    #[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            // We limit our attention here to replicas from the current deploy
596            // generation. Replicas from past generations are cleaned up during
597            // `Controller::allow_writes`.
598            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                // Found a replica in the orchestrator with a higher replica ID
613                // than what we are aware of. This must have been created by an
614                // environmentd that's competing for control of this generation.
615                // Abort to let the other process have full control.
616                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    /// Provisions a replica with the service orchestrator.
673    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        // TODO(teskje): use the same values as for compute?
702        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            // The disk limit we specify in the service config decides whether or not the replica
720            // gets a scratch disk attached. We want to avoid attaching disks to swap replicas, so
721            // make sure to set the disk limit accordingly.
722            disk_limit = Some(DiskLimit::ZERO);
723
724            // We want to keep the memory request equal to the memory limit, to avoid
725            // over-provisioning and ensure replicas have predictable performance. However, to
726            // enable swap, Kubernetes currently requires that request and limit are different.
727            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 swap is enabled, make the replica limit its own heap usage based on the
806                    // configured memory and disk limits.
807                    if location.allocation.swap_enabled
808                        && let Some(memory_limit) = location.allocation.memory_limit
809                        && let Some(disk_limit) = location.allocation.disk_limit
810                        // Currently, the way for replica sizes to request unlimited swap is to
811                        // specify a `disk_limit` of 0. Ideally we'd change this to make them
812                        // specify no disk limit instead, but for now we need to special-case here.
813                        && 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                    // To simplify the changes to tests, the port
828                    // chosen here is _after_ the compute ones.
829                    // TODO(petrosagg): fix the numerical ordering here
830                    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                // An empty list means no AZ constraint; a non-empty one pins
876                // placement to those zones.
877                availability_zones: Some(location.availability_zones).filter(|azs| !azs.is_empty()),
878                // This provides the orchestrator with some label selectors that
879                // are used to constraint the scheduling of replicas, based on
880                // its internal configuration.
881                //
882                // Selectors include `generation` so that scheduling constraints
883                // (anti-affinity, topology spread) only consider pods of the same
884                // deploy generation. Otherwise, during a generation rollout, the
885                // new-generation pods would be constrained by the placement of
886                // old-generation pods that are about to be torn down, which can
887                // prevent the new pods from scheduling (e.g., when only one AZ
888                // has capacity but it is already occupied by an old-generation
889                // pod).
890                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                    // Select other replicas (but not oneself)
898                    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                        // Select ALL replicas.
915                        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                // TODO[btv] -- I tried implementing a `watch_metrics` function,
939                // similar to `watch_services`, but it crashed due to
940                // https://github.com/kube-rs/kube/issues/1092 .
941                //
942                // If `metrics-server` can be made to fill in `resourceVersion`,
943                // or if that bug is fixed, we can try that again rather than using this inelegant
944                // loop.
945                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    /// Deprovisions a replica with the service orchestrator.
964    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
980/// Remove all replicas from past generations.
981async 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/// Represents the name of a cluster replica service in the orchestrator.
1003#[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            // Old versions of Materialize did not include generations in
1037            // replica service names. Synthesize generation 0 if absent.
1038            // TODO: remove this in the next version of Materialize.
1039            generation: caps.get(3).map_or("0", |m| m.as_str()).parse().unwrap(),
1040        })
1041    }
1042}