Skip to main content

mz_environmentd/
lib.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#![recursion_limit = "256"]
11
12//! A SQL stream processor built on top of [timely dataflow] and
13//! [differential dataflow].
14//!
15//! [differential dataflow]: ../differential_dataflow/index.html
16//! [timely dataflow]: ../timely/index.html
17
18use ::http::HeaderValue;
19use std::collections::BTreeMap;
20use std::panic::AssertUnwindSafe;
21use std::path::PathBuf;
22use std::pin::Pin;
23use std::sync::Arc;
24use std::time::{Duration, Instant};
25use std::{env, io};
26
27use anyhow::{Context, anyhow};
28use derivative::Derivative;
29use futures::FutureExt;
30use ipnet::IpNet;
31use mz_adapter::config::{
32    SystemParameterSyncClientConfig, SystemParameterSyncConfig, system_parameter_sync,
33};
34use mz_adapter::webhook::WebhookConcurrencyLimiter;
35use mz_adapter::{AdapterError, Client as AdapterClient, load_remote_system_parameters};
36use mz_adapter_types::bootstrap_builtin_cluster_config::BootstrapBuiltinClusterConfig;
37use mz_adapter_types::dyncfgs::{
38    ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT, WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL,
39    WITH_0DT_DEPLOYMENT_MAX_WAIT,
40};
41use mz_auth::password::Password;
42use mz_authenticator::GenericOidcAuthenticator;
43use mz_build_info::{BuildInfo, build_info};
44use mz_catalog::config::ClusterReplicaSizeMap;
45use mz_catalog::durable::BootstrapArgs;
46use mz_cloud_resources::CloudResourceController;
47use mz_controller::ControllerConfig;
48use mz_dyncfg::ConfigSet;
49use mz_frontegg_auth::Authenticator as FronteggAuthenticator;
50use mz_license_keys::ValidatedLicenseKey;
51use mz_ore::future::OreFutureExt;
52use mz_ore::metrics::MetricsRegistry;
53use mz_ore::now::NowFn;
54use mz_ore::tracing::TracingHandle;
55use mz_ore::url::SensitiveUrl;
56use mz_ore::{instrument, task};
57use mz_persist_client::cache::PersistClientCache;
58use mz_persist_client::usage::StorageUsageClient;
59use mz_pgwire::MetricsConfig;
60use mz_pgwire_common::ConnectionCounter;
61use mz_repr::strconv;
62use mz_secrets::SecretsController;
63use mz_server_core::listeners::v26_32_0::ListenersConfig;
64use mz_server_core::listeners::{HttpListenerConfig, ListenerConfig, SqlListenerConfig};
65use mz_server_core::{
66    ConnectionStream, ListenerHandle, ReloadTrigger, ReloadingSslContext, ServeConfig,
67    TlsCertConfig, TlsMode,
68};
69use mz_sql::catalog::EnvironmentId;
70use mz_sql::session::vars::{Value, VarInput};
71use tokio::sync::oneshot;
72use tower_http::cors::AllowOrigin;
73use tracing::{Instrument, info, info_span};
74
75use crate::deployment::preflight::{PreflightInput, PreflightOutput};
76use crate::deployment::state::DeploymentState;
77use crate::http::{HttpConfig, HttpServer, InternalRouteConfig};
78
79pub use crate::http::{SqlResponse, WebSocketAuth, WebSocketResponse};
80
81mod deployment;
82pub mod environmentd;
83pub mod http;
84mod telemetry;
85#[cfg(feature = "test")]
86pub mod test_util;
87
88pub const BUILD_INFO: BuildInfo = build_info!();
89
90/// Configuration for an `environmentd` server.
91#[derive(Derivative)]
92#[derivative(Debug)]
93pub struct Config {
94    // === Special modes. ===
95    /// Whether to permit usage of unsafe features. This is never meant to run
96    /// in production.
97    pub unsafe_mode: bool,
98    /// Whether the environmentd is running on a local dev machine. This is
99    /// never meant to run in production or CI.
100    pub all_features: bool,
101
102    // === Connection options. ===
103    /// TLS encryption and authentication configuration.
104    pub tls: Option<TlsCertConfig>,
105    /// Trigger to attempt to reload TLS certififcates.
106    #[derivative(Debug = "ignore")]
107    pub tls_reload_certs: ReloadTrigger,
108    /// Password of the mz_system user.
109    pub external_login_password_mz_system: Option<Password>,
110    /// Frontegg JWT authenticator.
111    pub frontegg: Option<FronteggAuthenticator>,
112    /// Frontegg workspace URL advertised in MCP OAuth discovery.
113    pub frontegg_oauth_issuer_url: Option<String>,
114    /// Origins for which cross-origin resource sharing (CORS) for HTTP requests
115    /// is permitted.
116    pub cors_allowed_origin: AllowOrigin,
117    /// Raw list of allowed CORS origins. Retained alongside `cors_allowed_origin`
118    /// (which is the computed predicate) so that endpoints like MCP can perform
119    /// server-side Origin validation to defend against DNS rebinding attacks
120    /// (where same-origin requests bypass CORS enforcement).
121    pub cors_allowed_origin_list: Vec<HeaderValue>,
122    /// Public IP addresses which the cloud environment has configured for
123    /// egress.
124    pub egress_addresses: Vec<IpNet>,
125    /// The external host name to connect to the HTTP server of this
126    /// environment.
127    ///
128    /// Presently used to render webhook URLs for end users in notices and the
129    /// system catalog. Not used to establish connections directly.
130    pub http_host_name: Option<String>,
131    /// The URL of the Materialize console to proxy from the /internal-console
132    /// endpoint on the internal HTTP server.
133    pub internal_console_redirect_url: Option<String>,
134
135    // === Controller options. ===
136    /// Storage and compute controller configuration.
137    pub controller: ControllerConfig,
138    /// Secrets controller configuration.
139    pub secrets_controller: Arc<dyn SecretsController>,
140    /// VpcEndpoint controller configuration.
141    pub cloud_resource_controller: Option<Arc<dyn CloudResourceController>>,
142    /// The process-wide live system dyncfg set.
143    pub system_dyncfgs: Arc<ConfigSet>,
144
145    // === Storage options. ===
146    /// The interval at which to collect storage usage information.
147    pub storage_usage_collection_interval: Duration,
148    /// How long to retain storage usage records for.
149    pub storage_usage_retention_period: Option<Duration>,
150
151    // === Adapter options. ===
152    /// Catalog configuration.
153    pub catalog_config: CatalogConfig,
154    /// Availability zones in which storage and compute resources may be
155    /// deployed.
156    pub availability_zones: Vec<String>,
157    /// A map from size name to resource allocations for cluster replicas.
158    pub cluster_replica_sizes: ClusterReplicaSizeMap,
159    /// The PostgreSQL URL for the Postgres-backed timestamp oracle.
160    pub timestamp_oracle_url: Option<SensitiveUrl>,
161    /// An API key for Segment. Enables export of audit events to Segment.
162    pub segment_api_key: Option<String>,
163    /// Whether the Segment client is being used on the client side
164    /// (rather than the server side).
165    pub segment_client_side: bool,
166    /// Only create a dummy segment client, only to get more testing coverage.
167    pub test_only_dummy_segment_client: bool,
168    /// An SDK key for LaunchDarkly. Enables system parameter synchronization
169    /// with LaunchDarkly.
170    pub launchdarkly_sdk_key: Option<String>,
171    /// Overrides the LaunchDarkly service endpoints with a single base URL, as
172    /// for a relay proxy or a mock server in tests.
173    pub launchdarkly_base_uri: Option<String>,
174    /// An invertible map from system parameter names to LaunchDarkly feature
175    /// keys to use when propagating values from the latter to the former.
176    pub launchdarkly_key_map: BTreeMap<String, String>,
177    /// The duration at which the system parameter synchronization times out during startup.
178    pub config_sync_timeout: Duration,
179    /// The interval in seconds at which to synchronize system parameter values.
180    pub config_sync_loop_interval: Option<Duration>,
181    /// The path for file based config sync
182    pub config_sync_file_path: Option<PathBuf>,
183
184    // === Bootstrap options. ===
185    /// The cloud ID of this environment.
186    pub environment_id: EnvironmentId,
187    /// What role, if any, should be initially created with elevated privileges.
188    pub bootstrap_role: Option<String>,
189    /// The size of the default cluster replica if bootstrapping.
190    pub bootstrap_default_cluster_replica_size: String,
191    /// The default number of replicas if bootstrapping.
192    pub bootstrap_default_cluster_replication_factor: u32,
193    /// The config of the builtin system cluster replicas if bootstrapping.
194    pub bootstrap_builtin_system_cluster_config: BootstrapBuiltinClusterConfig,
195    /// The config of the builtin catalog server cluster replicas if bootstrapping.
196    pub bootstrap_builtin_catalog_server_cluster_config: BootstrapBuiltinClusterConfig,
197    /// The config of the builtin probe cluster replicas if bootstrapping.
198    pub bootstrap_builtin_probe_cluster_config: BootstrapBuiltinClusterConfig,
199    /// The config of the builtin support cluster replicas if bootstrapping.
200    pub bootstrap_builtin_support_cluster_config: BootstrapBuiltinClusterConfig,
201    /// The config of the builtin analytics cluster replicas if bootstrapping.
202    pub bootstrap_builtin_analytics_cluster_config: BootstrapBuiltinClusterConfig,
203    /// Values to set for system parameters, if those system parameters have not
204    /// already been set by the system user.
205    pub system_parameter_defaults: BTreeMap<String, String>,
206    /// Helm chart version
207    pub helm_chart_version: Option<String>,
208    /// Configuration managed by license keys
209    pub license_key: ValidatedLicenseKey,
210
211    // === AWS options. ===
212    /// The AWS account ID, which will be used to generate ARNs for
213    /// Materialize-controlled AWS resources.
214    pub aws_account_id: Option<String>,
215    /// Supported AWS PrivateLink availability zone ids.
216    pub aws_privatelink_availability_zones: Option<Vec<String>>,
217
218    // === Observability options. ===
219    /// The metrics registry to use.
220    pub metrics_registry: MetricsRegistry,
221    /// Handle to tracing.
222    pub tracing_handle: TracingHandle,
223
224    // === Testing options. ===
225    /// A now generation function for mocking time.
226    pub now: NowFn,
227    /// If `Some`, force running builtin schema migration using the specified
228    /// migration mechanism ("evolution" or "replacement").
229    pub force_builtin_schema_migration: Option<String>,
230}
231
232/// Configuration for the Catalog.
233#[derive(Debug, Clone)]
234pub struct CatalogConfig {
235    /// A process-global cache of (blob_uri, consensus_uri) -> PersistClient.
236    pub persist_clients: Arc<PersistClientCache>,
237    /// Persist catalog metrics.
238    pub metrics: Arc<mz_catalog::durable::Metrics>,
239}
240
241pub struct Listener<C> {
242    pub handle: ListenerHandle,
243    connection_stream: Pin<Box<dyn ConnectionStream>>,
244    config: C,
245}
246impl<C> Listener<C>
247where
248    C: ListenerConfig,
249{
250    /// Initializes network listeners for a later call to `serve` at the
251    /// specified addresses.
252    ///
253    /// Splitting this function out from `serve` has two benefits:
254    ///
255    ///   * It initializes network listeners as early as possible, so that the OS
256    ///     will queue incoming connections while the server is booting.
257    ///
258    ///   * It allows the caller to communicate with the server via the internal
259    ///     HTTP port while it is booting.
260    ///
261    async fn bind(config: C) -> Result<Self, io::Error> {
262        let (handle, connection_stream) = mz_server_core::listen(&config.addr()).await?;
263        Ok(Self {
264            handle,
265            connection_stream,
266            config,
267        })
268    }
269}
270
271impl Listener<SqlListenerConfig> {
272    #[instrument(name = "environmentd::serve_sql")]
273    pub async fn serve_sql(
274        self,
275        name: String,
276        active_connection_counter: ConnectionCounter,
277        tls_reloading_context: Option<ReloadingSslContext>,
278        frontegg: Option<FronteggAuthenticator>,
279        adapter_client: AdapterClient,
280        oidc: GenericOidcAuthenticator,
281        metrics: MetricsConfig,
282        helm_chart_version: Option<String>,
283    ) -> ListenerHandle {
284        let label: &'static str = Box::leak(name.into_boxed_str());
285        let tls = tls_reloading_context.map(|context| mz_server_core::ReloadingTlsConfig {
286            context,
287            mode: if self.config.enable_tls {
288                TlsMode::Require
289            } else {
290                TlsMode::Allow
291            },
292        });
293
294        task::spawn(|| format!("{}_sql_server", label), {
295            let sql_server = mz_pgwire::Server::new(mz_pgwire::Config {
296                label,
297                tls,
298                adapter_client,
299                authenticator_kind: self.config.authenticator_kind,
300                frontegg,
301                oidc,
302                metrics,
303                active_connection_counter,
304                helm_chart_version,
305                allowed_roles: self.config.allowed_roles,
306            });
307            mz_server_core::serve(ServeConfig {
308                conns: self.connection_stream,
309                server: sql_server,
310                // `environmentd` does not currently need to dynamically
311                // configure graceful termination behavior.
312                dyncfg: None,
313            })
314        });
315        self.handle
316    }
317}
318
319impl Listener<HttpListenerConfig> {
320    #[instrument(name = "environmentd::serve_http")]
321    pub async fn serve_http(self, config: HttpConfig) -> ListenerHandle {
322        let task_name = format!("{}_http_server", &config.source);
323        task::spawn(|| task_name, {
324            let http_server = HttpServer::new(config);
325            mz_server_core::serve(ServeConfig {
326                conns: self.connection_stream,
327                server: http_server,
328                // `environmentd` does not currently need to dynamically
329                // configure graceful termination behavior.
330                dyncfg: None,
331            })
332        });
333        self.handle
334    }
335}
336
337pub struct Listeners {
338    pub http: BTreeMap<String, Listener<HttpListenerConfig>>,
339    pub sql: BTreeMap<String, Listener<SqlListenerConfig>>,
340}
341
342impl Listeners {
343    pub async fn bind(config: ListenersConfig) -> Result<Self, io::Error> {
344        let mut sql = BTreeMap::new();
345        for (name, config) in config.sql {
346            sql.insert(name, Listener::bind(config).await?);
347        }
348
349        let mut http = BTreeMap::new();
350        for (name, config) in config.http {
351            http.insert(name, Listener::bind(config).await?);
352        }
353
354        Ok(Listeners { http, sql })
355    }
356
357    /// Starts an `environmentd` server.
358    ///
359    /// Returns a handle to the server once it is fully booted.
360    #[instrument(name = "environmentd::serve")]
361    pub async fn serve(self, config: Config) -> Result<Server, AdapterError> {
362        let serve_start = Instant::now();
363        info!("startup: envd serve: beginning");
364        info!("startup: envd serve: preamble beginning");
365
366        // Validate TLS configuration, if present.
367        let tls_reloading_context = match config.tls {
368            Some(tls_config) => Some(tls_config.reloading_context(config.tls_reload_certs)?),
369            None => None,
370        };
371
372        let active_connection_counter = ConnectionCounter::default();
373        let (deployment_state, deployment_state_handle) = DeploymentState::new();
374
375        // Launch HTTP servers.
376        //
377        // We start these servers before we've completed initialization so that
378        // metrics are accessible during initialization. Some HTTP
379        // endpoints require the adapter to be initialized; requests to those
380        // endpoints block until the adapter client is installed.
381        // One of these endpoints is /api/readyz,
382        // which assumes we're ready when the adapter client exists.
383        let webhook_concurrency_limit = WebhookConcurrencyLimiter::default();
384        let internal_route_config = Arc::new(InternalRouteConfig {
385            deployment_state_handle,
386            internal_console_redirect_url: config.internal_console_redirect_url,
387        });
388
389        let (authenticator_oidc_tx, authenticator_oidc_rx) = oneshot::channel();
390        let authenticator_oidc_rx = authenticator_oidc_rx.shared();
391        let (adapter_client_tx, adapter_client_rx) = oneshot::channel();
392        let adapter_client_rx = adapter_client_rx.shared();
393
394        let metrics_registry = config.metrics_registry.clone();
395        let metrics = http::Metrics::register_into(&metrics_registry, "mz_http");
396        let mcp_metrics = http::mcp_metrics::McpMetrics::register_into(&metrics_registry);
397        let oauth_metadata_metrics =
398            http::oauth_metadata::OauthMetadataMetrics::register_into(&metrics_registry);
399        let mut http_listener_handles = BTreeMap::new();
400        for (name, listener) in self.http {
401            let authenticator_kind = listener.config.authenticator_kind();
402            let source: &'static str = Box::leak(name.clone().into_boxed_str());
403            let tls = if listener.config.enable_tls() {
404                tls_reloading_context.clone()
405            } else {
406                None
407            };
408            let http_config = HttpConfig {
409                adapter_client_rx: adapter_client_rx.clone(),
410                active_connection_counter: active_connection_counter.clone(),
411                helm_chart_version: config.helm_chart_version.clone(),
412                http_host_name: config.http_host_name.clone(),
413                frontegg_oauth_issuer_url: config.frontegg_oauth_issuer_url.clone(),
414                source,
415                tls,
416                authenticator_kind,
417                frontegg: config.frontegg.clone(),
418                oidc_rx: authenticator_oidc_rx.clone(),
419                allowed_origin: config.cors_allowed_origin.clone(),
420                allowed_origin_list: config.cors_allowed_origin_list.clone(),
421                concurrent_webhook_req: webhook_concurrency_limit.semaphore(),
422                dyncfgs: Arc::clone(&config.system_dyncfgs),
423                metrics: metrics.clone(),
424                metrics_registry: metrics_registry.clone(),
425                mcp_metrics: mcp_metrics.clone(),
426                oauth_metadata_metrics: oauth_metadata_metrics.clone(),
427                internal_route_config: Arc::clone(&internal_route_config),
428                routes_enabled: listener.config.routes,
429                replica_http_locator: Arc::clone(&config.controller.replica_http_locator),
430            };
431            http_listener_handles.insert(name.clone(), listener.serve_http(http_config).await);
432        }
433
434        info!(
435            "startup: envd serve: preamble complete in {:?}",
436            serve_start.elapsed()
437        );
438
439        let catalog_init_start = Instant::now();
440        info!("startup: envd serve: catalog init beginning");
441
442        // Get the current timestamp so we can record when we booted.
443        let boot_ts = (config.now)().into();
444
445        let persist_client = config
446            .catalog_config
447            .persist_clients
448            .open(config.controller.persist_location.clone())
449            .await
450            .context("opening persist client")?;
451        let mut openable_adapter_storage = mz_catalog::durable::persist_backed_catalog_state(
452            persist_client.clone(),
453            config.environment_id.organization_id(),
454            BUILD_INFO.semver_version(),
455            Some(config.controller.deploy_generation),
456            Arc::clone(&config.catalog_config.metrics),
457        )
458        .await?;
459
460        info!(
461            "startup: envd serve: catalog init complete in {:?}",
462            catalog_init_start.elapsed()
463        );
464
465        let system_param_sync_start = Instant::now();
466        info!("startup: envd serve: system parameter sync beginning");
467        // Initialize the system parameter frontend
468        let system_parameter_sync_config =
469            match (config.launchdarkly_sdk_key, config.config_sync_file_path) {
470                (None, None) => None,
471                (None, Some(f)) => {
472                    info!("Using config file path {:?}", f);
473                    Some(SystemParameterSyncConfig::new(
474                        config.environment_id.clone(),
475                        &BUILD_INFO,
476                        &config.metrics_registry,
477                        config.launchdarkly_key_map,
478                        SystemParameterSyncClientConfig::File { path: f },
479                    ))
480                }
481                (Some(key), None) => Some(SystemParameterSyncConfig::new(
482                    config.environment_id.clone(),
483                    &BUILD_INFO,
484                    &config.metrics_registry,
485                    config.launchdarkly_key_map,
486                    SystemParameterSyncClientConfig::LaunchDarkly {
487                        sdk_key: key,
488                        base_uri: config.launchdarkly_base_uri,
489                        now_fn: config.now.clone(),
490                    },
491                )),
492
493                (Some(_), Some(_)) => {
494                    panic!("Cannot configure both file and Launchdarkly based config syncing")
495                }
496            };
497
498        let remote_system_parameters = load_remote_system_parameters(
499            &mut openable_adapter_storage,
500            system_parameter_sync_config.clone(),
501            config.config_sync_timeout,
502        )
503        .await?;
504        info!(
505            "startup: envd serve: system parameter sync complete in {:?}",
506            system_param_sync_start.elapsed()
507        );
508
509        let preflight_checks_start = Instant::now();
510        info!("startup: envd serve: preflight checks beginning");
511
512        // Determine the maximum wait time when doing a 0dt deployment.
513        let with_0dt_deployment_max_wait = {
514            let cli_default = config
515                .system_parameter_defaults
516                .get(WITH_0DT_DEPLOYMENT_MAX_WAIT.name())
517                .map(|x| {
518                    Duration::parse(VarInput::Flat(x)).map_err(|err| {
519                        anyhow!(
520                            "failed to parse default for {}: {:?}",
521                            WITH_0DT_DEPLOYMENT_MAX_WAIT.name(),
522                            err
523                        )
524                    })
525                })
526                .transpose()?;
527            let compiled_default = WITH_0DT_DEPLOYMENT_MAX_WAIT.default().clone();
528            let ld = get_ld_value(
529                WITH_0DT_DEPLOYMENT_MAX_WAIT.name(),
530                &remote_system_parameters,
531                |x| {
532                    Duration::parse(VarInput::Flat(x)).map_err(|err| {
533                        format!(
534                            "failed to parse LD value {} for {}: {:?}",
535                            x,
536                            WITH_0DT_DEPLOYMENT_MAX_WAIT.name(),
537                            err
538                        )
539                    })
540                },
541            )?;
542            let catalog = openable_adapter_storage
543                .get_0dt_deployment_max_wait()
544                .await?;
545            let computed = ld.or(catalog).or(cli_default).unwrap_or(compiled_default);
546            info!(
547                ?computed,
548                ?ld,
549                ?catalog,
550                ?cli_default,
551                ?compiled_default,
552                "determined value for {} system parameter",
553                WITH_0DT_DEPLOYMENT_MAX_WAIT.name()
554            );
555            computed
556        };
557        // Determine the DDL check interval when doing a 0dt deployment.
558        let with_0dt_deployment_ddl_check_interval = {
559            let cli_default = config
560                .system_parameter_defaults
561                .get(WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL.name())
562                .map(|x| {
563                    Duration::parse(VarInput::Flat(x)).map_err(|err| {
564                        anyhow!(
565                            "failed to parse default for {}: {:?}",
566                            WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL.name(),
567                            err
568                        )
569                    })
570                })
571                .transpose()?;
572            let compiled_default = WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL.default().clone();
573            let ld = get_ld_value(
574                WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL.name(),
575                &remote_system_parameters,
576                |x| {
577                    Duration::parse(VarInput::Flat(x)).map_err(|err| {
578                        format!(
579                            "failed to parse LD value {} for {}: {:?}",
580                            x,
581                            WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL.name(),
582                            err
583                        )
584                    })
585                },
586            )?;
587            let catalog = openable_adapter_storage
588                .get_0dt_deployment_ddl_check_interval()
589                .await?;
590            let computed = ld.or(catalog).or(cli_default).unwrap_or(compiled_default);
591            info!(
592                ?computed,
593                ?ld,
594                ?catalog,
595                ?cli_default,
596                ?compiled_default,
597                "determined value for {} system parameter",
598                WITH_0DT_DEPLOYMENT_DDL_CHECK_INTERVAL.name()
599            );
600            computed
601        };
602
603        // Determine whether we should panic if we reach the maximum wait time
604        // without the preflight checks succeeding.
605        let enable_0dt_deployment_panic_after_timeout = {
606            let cli_default = config
607                .system_parameter_defaults
608                .get(ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT.name())
609                .map(|x| {
610                    strconv::parse_bool(x).map_err(|err| {
611                        anyhow!(
612                            "failed to parse default for {}: {}",
613                            ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT.name(),
614                            err
615                        )
616                    })
617                })
618                .transpose()?;
619            let compiled_default = ENABLE_0DT_DEPLOYMENT_PANIC_AFTER_TIMEOUT.default().clone();
620            let ld = get_ld_value(
621                "enable_0dt_deployment_panic_after_timeout",
622                &remote_system_parameters,
623                |x| strconv::parse_bool(x).map_err(|x| x.to_string()),
624            )?;
625            let catalog = openable_adapter_storage
626                .get_enable_0dt_deployment_panic_after_timeout()
627                .await?;
628            let computed = ld.or(catalog).or(cli_default).unwrap_or(compiled_default);
629            info!(
630                %computed,
631                ?ld,
632                ?catalog,
633                ?cli_default,
634                ?compiled_default,
635                "determined value for enable_0dt_deployment_panic_after_timeout system parameter",
636            );
637            computed
638        };
639
640        // Perform preflight checks.
641        //
642        // Preflight checks determine whether to boot in read-only mode or not.
643        let bootstrap_args = BootstrapArgs {
644            default_cluster_replica_size: config.bootstrap_default_cluster_replica_size.clone(),
645            default_cluster_replication_factor: config.bootstrap_default_cluster_replication_factor,
646            bootstrap_role: config.bootstrap_role.clone(),
647            cluster_replica_size_map: config.cluster_replica_sizes.clone(),
648        };
649        let preflight_config = PreflightInput {
650            boot_ts,
651            environment_id: config.environment_id.clone(),
652            persist_client,
653            deploy_generation: config.controller.deploy_generation,
654            deployment_state: deployment_state.clone(),
655            openable_adapter_storage,
656            catalog_metrics: Arc::clone(&config.catalog_config.metrics),
657            caught_up_max_wait: with_0dt_deployment_max_wait,
658            panic_after_timeout: enable_0dt_deployment_panic_after_timeout,
659            bootstrap_args,
660            ddl_check_interval: with_0dt_deployment_ddl_check_interval,
661        };
662        let PreflightOutput {
663            openable_adapter_storage,
664            read_only,
665            caught_up_trigger,
666        } = deployment::preflight::preflight_0dt(preflight_config).await?;
667
668        info!(
669            "startup: envd serve: preflight checks complete in {:?}",
670            preflight_checks_start.elapsed()
671        );
672
673        let catalog_open_start = Instant::now();
674        info!("startup: envd serve: durable catalog open beginning");
675
676        let bootstrap_args = BootstrapArgs {
677            default_cluster_replica_size: config.bootstrap_default_cluster_replica_size.clone(),
678            default_cluster_replication_factor: config.bootstrap_default_cluster_replication_factor,
679            bootstrap_role: config.bootstrap_role,
680            cluster_replica_size_map: config.cluster_replica_sizes.clone(),
681        };
682
683        // Load the adapter durable storage.
684        let adapter_storage = if read_only {
685            // TODO: behavior of migrations when booting in savepoint mode is
686            // not well defined.
687            let adapter_storage = openable_adapter_storage
688                .open_savepoint(boot_ts, &bootstrap_args)
689                .await?;
690            // In read-only mode, we intentionally do not call `set_is_leader`,
691            // because we are by definition not the leader if we are in
692            // read-only mode.
693
694            adapter_storage
695        } else {
696            let adapter_storage = openable_adapter_storage
697                .open(boot_ts, &bootstrap_args)
698                .await?;
699
700            // Once we have successfully opened the adapter storage in
701            // read/write mode, we can announce we are the leader, as we've
702            // fenced out all other environments using the adapter storage.
703            deployment_state.set_is_leader();
704
705            adapter_storage
706        };
707
708        // Enable Persist compaction if we're not in read only.
709        if !read_only {
710            config.controller.persist_clients.cfg().enable_compaction();
711        }
712
713        info!(
714            "startup: envd serve: durable catalog open complete in {:?}",
715            catalog_open_start.elapsed()
716        );
717
718        let coord_init_start = Instant::now();
719        info!("startup: envd serve: coordinator init beginning");
720
721        if !config
722            .cluster_replica_sizes
723            .0
724            .contains_key(&config.bootstrap_default_cluster_replica_size)
725        {
726            return Err(anyhow!("bootstrap default cluster replica size is unknown").into());
727        }
728        let envd_epoch = adapter_storage.epoch();
729
730        // Initialize storage usage client.
731        let storage_usage_client = StorageUsageClient::open(
732            config
733                .controller
734                .persist_clients
735                .open(config.controller.persist_location.clone())
736                .await
737                .context("opening storage usage client")?,
738        );
739
740        // Initialize adapter.
741        let segment_client = config.segment_api_key.map(|api_key| {
742            mz_segment::Client::new(mz_segment::Config {
743                api_key,
744                client_side: config.segment_client_side,
745            })
746        });
747        let connection_limiter = active_connection_counter.clone();
748        let connection_limit_callback = Box::new(move |limit, superuser_reserved| {
749            connection_limiter.update_limit(limit);
750            connection_limiter.update_superuser_reserved(superuser_reserved);
751        });
752
753        let (adapter_handle, adapter_client) = mz_adapter::serve(mz_adapter::Config {
754            connection_context: config.controller.connection_context.clone(),
755            connection_limit_callback,
756            controller_config: config.controller,
757            controller_envd_epoch: envd_epoch,
758            storage: adapter_storage,
759            timestamp_oracle_url: config.timestamp_oracle_url,
760            unsafe_mode: config.unsafe_mode,
761            all_features: config.all_features,
762            build_info: &BUILD_INFO,
763            environment_id: config.environment_id.clone(),
764            metrics_registry: config.metrics_registry.clone(),
765            now: config.now,
766            secrets_controller: config.secrets_controller,
767            cloud_resource_controller: config.cloud_resource_controller,
768            cluster_replica_sizes: config.cluster_replica_sizes,
769            builtin_system_cluster_config: config.bootstrap_builtin_system_cluster_config,
770            builtin_catalog_server_cluster_config: config
771                .bootstrap_builtin_catalog_server_cluster_config,
772            builtin_probe_cluster_config: config.bootstrap_builtin_probe_cluster_config,
773            builtin_support_cluster_config: config.bootstrap_builtin_support_cluster_config,
774            builtin_analytics_cluster_config: config.bootstrap_builtin_analytics_cluster_config,
775            availability_zones: config.availability_zones,
776            system_parameter_defaults: config.system_parameter_defaults,
777            storage_usage_client,
778            storage_usage_collection_interval: config.storage_usage_collection_interval,
779            storage_usage_retention_period: config.storage_usage_retention_period,
780            segment_client: segment_client.clone(),
781            egress_addresses: config.egress_addresses,
782            remote_system_parameters,
783            aws_account_id: config.aws_account_id,
784            aws_privatelink_availability_zones: config.aws_privatelink_availability_zones,
785            webhook_concurrency_limit: webhook_concurrency_limit.clone(),
786            http_host_name: config.http_host_name,
787            tracing_handle: config.tracing_handle,
788            read_only_controllers: read_only,
789            caught_up_trigger,
790            helm_chart_version: config.helm_chart_version.clone(),
791            license_key: config.license_key,
792            external_login_password_mz_system: config.external_login_password_mz_system,
793            force_builtin_schema_migration: config.force_builtin_schema_migration,
794        })
795        .instrument(info_span!("adapter::serve"))
796        .await?;
797
798        // Initialize the OIDC authenticator, shared between the HTTP and SQL servers.
799        let oidc = GenericOidcAuthenticator::new(adapter_client.clone());
800
801        info!(
802            "startup: envd serve: coordinator init complete in {:?}",
803            coord_init_start.elapsed()
804        );
805
806        let serve_postamble_start = Instant::now();
807        info!("startup: envd serve: postamble beginning");
808
809        // Send adapter client and OIDC authenticator to the HTTP servers.
810        authenticator_oidc_tx
811            .send(oidc.clone())
812            .expect("rx known to be live");
813        adapter_client_tx
814            .send(adapter_client.clone())
815            .expect("internal HTTP server should not drop first");
816
817        let metrics = mz_pgwire::MetricsConfig::register_into(&config.metrics_registry);
818
819        // Launch SQL server.
820        let mut sql_listener_handles = BTreeMap::new();
821        for (name, listener) in self.sql {
822            sql_listener_handles.insert(
823                name.clone(),
824                listener
825                    .serve_sql(
826                        name,
827                        active_connection_counter.clone(),
828                        tls_reloading_context.clone(),
829                        config.frontegg.clone(),
830                        adapter_client.clone(),
831                        oidc.clone(),
832                        metrics.clone(),
833                        config.helm_chart_version.clone(),
834                    )
835                    .await,
836            );
837        }
838
839        // Start telemetry reporting loop.
840        if let Some(segment_client) = segment_client {
841            telemetry::start_reporting(telemetry::Config {
842                segment_client,
843                adapter_client: adapter_client.clone(),
844                environment_id: config.environment_id,
845                report_interval: Duration::from_secs(3600),
846            });
847        } else if config.test_only_dummy_segment_client {
848            // We only have access to a segment client in production but we
849            // still want to exercise the telemetry reporting code to a degree.
850            // So we create a dummy client and report telemetry into the void.
851            // This way we at least run the telemetry queries the way a
852            // production environment would.
853            tracing::debug!("starting telemetry reporting with a dummy segment client");
854            let segment_client = mz_segment::Client::new_dummy_client();
855            telemetry::start_reporting(telemetry::Config {
856                segment_client,
857                adapter_client: adapter_client.clone(),
858                environment_id: config.environment_id,
859                report_interval: Duration::from_secs(180),
860            });
861        }
862
863        // If system_parameter_sync_config and config_sync_loop_interval are present,
864        // start the system_parameter_sync loop.
865        if let Some(system_parameter_sync_config) = system_parameter_sync_config {
866            task::spawn(
867                || "system_parameter_sync",
868                AssertUnwindSafe(system_parameter_sync(
869                    system_parameter_sync_config,
870                    adapter_client.clone(),
871                    config.config_sync_loop_interval,
872                ))
873                .ore_catch_unwind(),
874            );
875        }
876
877        info!(
878            "startup: envd serve: postamble complete in {:?}",
879            serve_postamble_start.elapsed()
880        );
881        info!(
882            "startup: envd serve: complete in {:?}",
883            serve_start.elapsed()
884        );
885
886        Ok(Server {
887            sql_listener_handles,
888            http_listener_handles,
889            _adapter_handle: adapter_handle,
890        })
891    }
892}
893
894fn get_ld_value<V>(
895    name: &str,
896    remote_system_parameters: &Option<BTreeMap<String, String>>,
897    parse: impl Fn(&str) -> Result<V, String>,
898) -> Result<Option<V>, anyhow::Error> {
899    remote_system_parameters
900        .as_ref()
901        .and_then(|params| params.get(name))
902        .map(|x| {
903            parse(x).map_err(|err| anyhow!("failed to parse remote value for {}: {}", name, err))
904        })
905        .transpose()
906}
907
908/// A running `environmentd` server.
909pub struct Server {
910    // Drop order matters for these fields.
911    pub sql_listener_handles: BTreeMap<String, ListenerHandle>,
912    pub http_listener_handles: BTreeMap<String, ListenerHandle>,
913    _adapter_handle: mz_adapter::Handle,
914}