mz_catalog/
config.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
10use std::collections::{BTreeMap, BTreeSet};
11
12use anyhow::bail;
13use bytesize::ByteSize;
14use ipnet::IpNet;
15use mz_adapter_types::bootstrap_builtin_cluster_config::BootstrapBuiltinClusterConfig;
16use mz_auth::password::Password;
17use mz_build_info::BuildInfo;
18use mz_cloud_resources::AwsExternalIdPrefix;
19use mz_controller::clusters::ReplicaAllocation;
20use mz_license_keys::ValidatedLicenseKey;
21use mz_orchestrator::MemoryLimit;
22use mz_ore::cast::CastFrom;
23use mz_ore::metrics::MetricsRegistry;
24use mz_persist_client::PersistClient;
25use mz_repr::CatalogItemId;
26use mz_repr::adt::numeric::Numeric;
27use mz_sql::catalog::CatalogError as SqlCatalogError;
28use mz_sql::catalog::EnvironmentId;
29use serde::Serialize;
30
31use crate::durable::{CatalogError, DurableCatalogState};
32
33const GIB: u64 = 1024 * 1024 * 1024;
34
35/// Configures a catalog.
36#[derive(Debug)]
37pub struct Config<'a> {
38    /// The connection to the catalog storage.
39    pub storage: Box<dyn DurableCatalogState>,
40    /// The registry that catalog uses to report metrics.
41    pub metrics_registry: &'a MetricsRegistry,
42    pub state: StateConfig,
43}
44
45#[derive(Debug)]
46pub struct StateConfig {
47    /// Whether to enable unsafe mode.
48    pub unsafe_mode: bool,
49    /// Whether the build is a local dev build.
50    pub all_features: bool,
51    /// Information about this build of Materialize.
52    pub build_info: &'static BuildInfo,
53    /// A persistent ID associated with the environment.
54    pub environment_id: EnvironmentId,
55    /// Whether to start Materialize in read-only mode.
56    pub read_only: bool,
57    /// Function to generate wall clock now; can be mocked.
58    pub now: mz_ore::now::NowFn,
59    /// Linearizable timestamp of when this environment booted.
60    pub boot_ts: mz_repr::Timestamp,
61    /// Whether or not to skip catalog migrations.
62    pub skip_migrations: bool,
63    /// Map of strings to corresponding compute replica sizes.
64    pub cluster_replica_sizes: ClusterReplicaSizeMap,
65    /// Builtin system cluster config.
66    pub builtin_system_cluster_config: BootstrapBuiltinClusterConfig,
67    /// Builtin catalog server cluster config.
68    pub builtin_catalog_server_cluster_config: BootstrapBuiltinClusterConfig,
69    /// Builtin probe cluster config.
70    pub builtin_probe_cluster_config: BootstrapBuiltinClusterConfig,
71    /// Builtin support cluster config.
72    pub builtin_support_cluster_config: BootstrapBuiltinClusterConfig,
73    /// Builtin analytics cluster config.
74    pub builtin_analytics_cluster_config: BootstrapBuiltinClusterConfig,
75    /// Dynamic defaults for system parameters.
76    pub system_parameter_defaults: BTreeMap<String, String>,
77    /// An optional map of system parameters pulled from a remote frontend.
78    /// A `None` value indicates that the initial sync was skipped.
79    pub remote_system_parameters: Option<BTreeMap<String, String>>,
80    /// Valid availability zones for replicas.
81    pub availability_zones: Vec<String>,
82    /// IP Addresses which will be used for egress.
83    pub egress_addresses: Vec<IpNet>,
84    /// Context for generating an AWS Principal.
85    pub aws_principal_context: Option<AwsPrincipalContext>,
86    /// Supported AWS PrivateLink availability zone ids.
87    pub aws_privatelink_availability_zones: Option<BTreeSet<String>>,
88    /// Host name or URL for connecting to the HTTP server of this instance.
89    pub http_host_name: Option<String>,
90    /// Context for source and sink connections.
91    pub connection_context: mz_storage_types::connections::ConnectionContext,
92    pub builtin_item_migration_config: BuiltinItemMigrationConfig,
93    pub persist_client: PersistClient,
94    /// Overrides the current value of the [`mz_adapter_types::dyncfgs::ENABLE_EXPRESSION_CACHE`]
95    /// feature flag.
96    pub enable_expression_cache_override: Option<bool>,
97    /// Helm chart version
98    pub helm_chart_version: Option<String>,
99    pub external_login_password_mz_system: Option<Password>,
100    pub license_key: ValidatedLicenseKey,
101}
102
103#[derive(Debug)]
104pub struct BuiltinItemMigrationConfig {
105    pub persist_client: PersistClient,
106    pub read_only: bool,
107}
108
109#[derive(Debug, Clone, Serialize)]
110pub struct ClusterReplicaSizeMap(pub BTreeMap<String, ReplicaAllocation>);
111
112impl ClusterReplicaSizeMap {
113    pub fn parse_from_str(s: &str, credit_consumption_from_memory: bool) -> anyhow::Result<Self> {
114        let mut cluster_replica_sizes: BTreeMap<String, ReplicaAllocation> =
115            serde_json::from_str(s)?;
116        if credit_consumption_from_memory {
117            for (name, replica) in cluster_replica_sizes.iter_mut() {
118                let Some(memory_limit) = replica.memory_limit else {
119                    bail!("No memory limit found in cluster definition for {name}");
120                };
121                replica.credits_per_hour = Numeric::from(
122                    (memory_limit.0 * replica.scale * u64::try_from(replica.workers)?).0,
123                ) / Numeric::from(1 * GIB);
124            }
125        }
126        Ok(Self(cluster_replica_sizes))
127    }
128
129    /// Iterate all enabled (not disabled) replica allocations, with their name.
130    pub fn enabled_allocations(&self) -> impl Iterator<Item = (&String, &ReplicaAllocation)> {
131        self.0.iter().filter(|(_, a)| !a.disabled)
132    }
133
134    /// Get a replica allocation by size name. Returns a reference to the allocation, or an
135    /// error if the size is unknown.
136    pub fn get_allocation_by_name(&self, name: &str) -> Result<&ReplicaAllocation, CatalogError> {
137        self.0.get(name).ok_or_else(|| {
138            CatalogError::Catalog(SqlCatalogError::UnknownClusterReplicaSize(name.into()))
139        })
140    }
141
142    /// Used for testing and local purposes. This default value should not be used in production.
143    ///
144    /// Credits per hour are calculated as being equal to scale. This is not necessarily how the
145    /// value is computed in production.
146    pub fn for_tests() -> Self {
147        // {
148        //     "scale=1,workers=1": {"scale": 1, "workers": 1},
149        //     "scale=1,workers=2": {"scale": 1, "workers": 2},
150        //     "scale=1,workers=4": {"scale": 1, "workers": 4},
151        //     /// ...
152        //     "scale=1,workers=32": {"scale": 1, "workers": 32}
153        //     /// Testing with multiple processes on a single machine
154        //     "scale=2,workers=4": {"scale": 2, "workers": 4},
155        //     /// Used in mzcompose tests
156        //     "scale=2,workers=2": {"scale": 2, "workers": 2},
157        //     ...
158        //     "scale=16,workers=16": {"scale": 16, "workers": 16},
159        //     /// Used in the shared_fate cloudtest tests
160        //     "scale=2,workers=1": {"scale": 2, "workers": 1},
161        //     ...
162        //     "scale=16,workers=1": {"scale": 16, "workers": 1},
163        //     /// Used in the cloudtest tests that force OOMs
164        //     "scale=1,workers=1,mem=2GiB": { "memory_limit": 2GiB },
165        //     ...
166        //     "scale=1,workers=1,mem=16": { "memory_limit": 16GiB },
167        // }
168        let mut inner = (0..=5)
169            .flat_map(|i| {
170                let workers: u8 = 1 << i;
171                [
172                    (format!("scale=1,workers={workers}"), None),
173                    (format!("scale=1,workers={workers},mem=4GiB"), Some(4)),
174                    (format!("scale=1,workers={workers},mem=8GiB"), Some(8)),
175                    (format!("scale=1,workers={workers},mem=16GiB"), Some(16)),
176                    (format!("scale=1,workers={workers},mem=32GiB"), Some(32)),
177                ]
178                .map(|(name, memory_limit)| {
179                    (
180                        name,
181                        ReplicaAllocation {
182                            memory_limit: memory_limit.map(|gib| MemoryLimit(ByteSize::gib(gib))),
183                            cpu_limit: None,
184                            disk_limit: None,
185                            scale: 1,
186                            workers: workers.into(),
187                            credits_per_hour: 1.into(),
188                            cpu_exclusive: false,
189                            is_cc: false,
190                            swap_enabled: false,
191                            disabled: false,
192                            selectors: BTreeMap::default(),
193                        },
194                    )
195                })
196            })
197            .collect::<BTreeMap<_, _>>();
198
199        for i in 1..=5 {
200            let scale = 1 << i;
201            inner.insert(
202                format!("scale={scale},workers=1"),
203                ReplicaAllocation {
204                    memory_limit: None,
205                    cpu_limit: None,
206                    disk_limit: None,
207                    scale,
208                    workers: 1,
209                    credits_per_hour: scale.into(),
210                    cpu_exclusive: false,
211                    is_cc: false,
212                    swap_enabled: false,
213                    disabled: false,
214                    selectors: BTreeMap::default(),
215                },
216            );
217
218            inner.insert(
219                format!("scale={scale},workers={scale}"),
220                ReplicaAllocation {
221                    memory_limit: None,
222                    cpu_limit: None,
223                    disk_limit: None,
224                    scale,
225                    workers: scale.into(),
226                    credits_per_hour: scale.into(),
227                    cpu_exclusive: false,
228                    is_cc: false,
229                    swap_enabled: false,
230                    disabled: false,
231                    selectors: BTreeMap::default(),
232                },
233            );
234
235            inner.insert(
236                format!("scale=1,workers=8,mem={scale}GiB"),
237                ReplicaAllocation {
238                    memory_limit: Some(MemoryLimit(ByteSize(u64::cast_from(scale) * (1 << 30)))),
239                    cpu_limit: None,
240                    disk_limit: None,
241                    scale: 1,
242                    workers: 8,
243                    credits_per_hour: 1.into(),
244                    cpu_exclusive: false,
245                    is_cc: false,
246                    swap_enabled: false,
247                    disabled: false,
248                    selectors: BTreeMap::default(),
249                },
250            );
251        }
252
253        inner.insert(
254            "scale=2,workers=4".to_string(),
255            ReplicaAllocation {
256                memory_limit: None,
257                cpu_limit: None,
258                disk_limit: None,
259                scale: 2,
260                workers: 4,
261                credits_per_hour: 2.into(),
262                cpu_exclusive: false,
263                is_cc: false,
264                swap_enabled: false,
265                disabled: false,
266                selectors: BTreeMap::default(),
267            },
268        );
269
270        inner.insert(
271            "free".to_string(),
272            ReplicaAllocation {
273                memory_limit: None,
274                cpu_limit: None,
275                disk_limit: None,
276                scale: 0,
277                workers: 0,
278                credits_per_hour: 0.into(),
279                cpu_exclusive: false,
280                is_cc: true,
281                swap_enabled: false,
282                disabled: true,
283                selectors: BTreeMap::default(),
284            },
285        );
286
287        Self(inner)
288    }
289}
290
291/// Context used to generate an AWS Principal.
292///
293/// In the case of AWS PrivateLink connections, Materialize will connect to the
294/// VPC endpoint as the AWS Principal generated via this context.
295#[derive(Debug, Clone, Serialize)]
296pub struct AwsPrincipalContext {
297    pub aws_account_id: String,
298    pub aws_external_id_prefix: AwsExternalIdPrefix,
299}
300
301impl AwsPrincipalContext {
302    pub fn to_principal_string(&self, aws_external_id_suffix: CatalogItemId) -> String {
303        format!(
304            "arn:aws:iam::{}:role/mz_{}_{}",
305            self.aws_account_id, self.aws_external_id_prefix, aws_external_id_suffix
306        )
307    }
308}