Skip to main content

mz_environmentd/environmentd/
main.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//! Manages a single Materialize environment.
11//!
12//! It listens for SQL connections on port 6875 (MTRL) and for HTTP connections
13//! on port 6876.
14
15use std::ffi::CStr;
16use std::fs::File;
17use std::net::{IpAddr, SocketAddr};
18use std::path::PathBuf;
19use std::sync::Arc;
20use std::sync::LazyLock;
21use std::sync::atomic::{AtomicUsize, Ordering};
22use std::time::{Duration, Instant};
23use std::{cmp, env, iter, thread};
24
25use anyhow::{Context, bail};
26use clap::{ArgAction, Parser, ValueEnum};
27use fail::FailScenario;
28use http::header::HeaderValue;
29use ipnet::IpNet;
30use itertools::Itertools;
31use mz_adapter::ResultExt;
32use mz_adapter_types::bootstrap_builtin_cluster_config::{
33    ANALYTICS_CLUSTER_DEFAULT_REPLICATION_FACTOR, BootstrapBuiltinClusterConfig,
34    CATALOG_SERVER_CLUSTER_DEFAULT_REPLICATION_FACTOR, DEFAULT_REPLICATION_FACTOR,
35    PROBE_CLUSTER_DEFAULT_REPLICATION_FACTOR, SUPPORT_CLUSTER_DEFAULT_REPLICATION_FACTOR,
36    SYSTEM_CLUSTER_DEFAULT_REPLICATION_FACTOR,
37};
38use mz_auth::password::Password;
39use mz_aws_secrets_controller::AwsSecretsController;
40use mz_build_info::BuildInfo;
41use mz_catalog::config::ClusterReplicaSizeMap;
42use mz_cloud_resources::{AwsExternalIdPrefix, CloudResourceController};
43use mz_controller::{ControllerConfig, ReplicaHttpLocator};
44use mz_frontegg_auth::{Authenticator as FronteggAuthenticator, FronteggCliArgs};
45use mz_license_keys::{ExpirationBehavior, ValidatedLicenseKey};
46use mz_orchestrator::Orchestrator;
47use mz_orchestrator_kubernetes::{
48    KubernetesImagePullPolicy, KubernetesOrchestrator, KubernetesOrchestratorConfig,
49};
50use mz_orchestrator_process::{
51    ProcessOrchestrator, ProcessOrchestratorConfig, ProcessOrchestratorTcpProxyConfig,
52};
53use mz_orchestrator_tracing::{StaticTracingConfig, TracingCliArgs, TracingOrchestrator};
54use mz_ore::cli::{self, CliConfig, KeyValueArg};
55use mz_ore::error::ErrorExt;
56use mz_ore::metric;
57use mz_ore::metrics::{MetricsRegistry, register_runtime_metrics};
58use mz_ore::now::SYSTEM_TIME;
59use mz_ore::task::RuntimeExt;
60use mz_ore::url::SensitiveUrl;
61use mz_persist_client::PersistLocation;
62use mz_persist_client::cache::PersistClientCache;
63use mz_persist_client::cfg::PersistConfig;
64use mz_persist_client::rpc::{
65    MetricsSameProcessPubSubSender, PersistGrpcPubSubServer, PubSubClientConnection, PubSubSender,
66};
67use mz_secrets::SecretsController;
68use mz_server_core::TlsCliArgs;
69use mz_service::emit_boot_diagnostics;
70use mz_service::secrets::{SecretsControllerKind, SecretsReaderCliArgs};
71use mz_sql::catalog::EnvironmentId;
72use mz_storage_types::connections::ConnectionContext;
73use opentelemetry::trace::TraceContextExt;
74use prometheus::IntGauge;
75use tracing::{Instrument, error, info, info_span, warn};
76use tracing_opentelemetry::OpenTelemetrySpanExt;
77use url::Url;
78
79use crate::environmentd::sys;
80use crate::{BUILD_INFO, CatalogConfig, ListenerConfig, Listeners, ListenersConfig};
81
82static VERSION: LazyLock<String> = LazyLock::new(|| BUILD_INFO.human_version(None));
83static LONG_VERSION: LazyLock<String> = LazyLock::new(|| {
84    iter::once(BUILD_INFO.human_version(None))
85        .chain(build_info())
86        .join("\n")
87});
88
89/// Manages a single Materialize environment.
90#[derive(Parser, Debug)]
91#[clap(
92    name = "environmentd",
93    next_line_help = true,
94    version = VERSION.as_str(),
95    long_version = LONG_VERSION.as_str(),
96)]
97pub struct Args {
98    // === Special modes. ===
99    /// Enable unsafe features. Unsafe features are those that should never run
100    /// in production but are appropriate for testing/local development.
101    #[clap(long, env = "UNSAFE_MODE")]
102    unsafe_mode: bool,
103    /// Enables all feature flags, meant only as a tool for local development;
104    /// this should never be enabled in CI.
105    #[clap(long, env = "ALL_FEATURES")]
106    all_features: bool,
107
108    // === Connection options. ===
109    /// Path to a file containing the json-formatted configuration of our
110    /// metrics, HTTP, and sql listeners.
111    #[clap(
112        long,
113        env = "LISTENERS_CONFIG_PATH",
114        value_name = "PATH",
115        action = ArgAction::Set,
116    )]
117    listeners_config_path: PathBuf,
118    /// Password for the mz_system user.
119    #[clap(
120        long,
121        env = "EXTERNAL_LOGIN_PASSWORD_MZ_SYSTEM",
122        action = ArgAction::Set,
123    )]
124    external_login_password_mz_system: Option<Password>,
125    /// The address on which to listen for Persist PubSub connections.
126    ///
127    /// Connections to this address are not subject to encryption, authentication,
128    /// or access control. Care should be taken to not expose the listen address
129    /// to the public internet or other unauthorized parties.
130    #[clap(
131        long,
132        value_name = "HOST:PORT",
133        env = "INTERNAL_PERSIST_PUBSUB_LISTEN_ADDR",
134        default_value = "127.0.0.1:6879",
135        action = ArgAction::Set,
136    )]
137    internal_persist_pubsub_listen_addr: SocketAddr,
138    /// Enable cross-origin resource sharing (CORS) for HTTP requests from the
139    /// specified origin.
140    ///
141    /// The default allows all local connections.
142    /// "*" allows all.
143    /// "*.domain.com" allows connections from any matching subdomain.
144    ///
145    /// Wildcards in other positions (e.g., "https://*.foo.com" or "https://foo.*.com") have no effect.
146    #[structopt(long, env = "CORS_ALLOWED_ORIGIN")]
147    cors_allowed_origin: Vec<HeaderValue>,
148    /// Public CIDR which the cloud environment has configured for
149    /// egress.
150    #[clap(
151        long,
152        env = "ANNOUNCE_EGRESS_ADDRESS",
153        action = ArgAction::Append,
154        use_value_delimiter = true
155    )]
156    announce_egress_address: Vec<IpNet>,
157    /// The external host name to connect to the HTTP server of this
158    /// environment.
159    ///
160    /// Used to render absolute URLs the server publishes: webhook URLs in
161    /// notices and the system catalog, and the OAuth Protected Resource
162    /// Metadata `resource`/`resource_metadata` URLs (RFC 9728). Not used to
163    /// establish connections directly. When unset, those URLs fall back to
164    /// the request's `Host` header.
165    #[clap(long, env = "HTTP_HOST_NAME")]
166    http_host_name: Option<String>,
167    /// The URL of the Materialize console to proxy from the /internal-console
168    /// endpoint on the internal HTTP server.
169    #[clap(long, env = "INTERNAL_CONSOLE_REDIRECT_URL")]
170    internal_console_redirect_url: Option<String>,
171    /// TLS arguments.
172    #[clap(flatten)]
173    tls: TlsCliArgs,
174    /// Frontegg arguments.
175    #[clap(flatten)]
176    frontegg: FronteggCliArgs,
177    // === Orchestrator options. ===
178    /// The service orchestrator implementation to use.
179    #[structopt(long, value_enum, env = "ORCHESTRATOR")]
180    orchestrator: OrchestratorKind,
181    /// Name of a non-default Kubernetes scheduler, if any.
182    #[structopt(long, env = "ORCHESTRATOR_KUBERNETES_SCHEDULER_NAME")]
183    orchestrator_kubernetes_scheduler_name: Option<String>,
184    /// Name of a `PriorityClass` to assign to services, if any.
185    #[structopt(long, env = "ORCHESTRATOR_KUBERNETES_PRIORITY_CLASS_NAME")]
186    orchestrator_kubernetes_priority_class_name: Option<String>,
187    /// Annotations to apply to all services created by the Kubernetes orchestrator
188    /// in the form `KEY=VALUE`.
189    #[structopt(long, env = "ORCHESTRATOR_KUBERNETES_SERVICE_ANNOTATION")]
190    orchestrator_kubernetes_service_annotation: Vec<KeyValueArg<String, String>>,
191    /// Labels to apply to all services created by the Kubernetes orchestrator
192    /// in the form `KEY=VALUE`.
193    #[structopt(long, env = "ORCHESTRATOR_KUBERNETES_SERVICE_LABEL")]
194    orchestrator_kubernetes_service_label: Vec<KeyValueArg<String, String>>,
195    /// Node selector to apply to all services created by the Kubernetes
196    /// orchestrator in the form `KEY=VALUE`.
197    #[structopt(long, env = "ORCHESTRATOR_KUBERNETES_SERVICE_NODE_SELECTOR")]
198    orchestrator_kubernetes_service_node_selector: Vec<KeyValueArg<String, String>>,
199    /// Affinity to apply to all services created by the Kubernetes
200    /// orchestrator as a JSON string.
201    #[structopt(long, env = "ORCHESTRATOR_KUBERNETES_SERVICE_AFFINITY")]
202    orchestrator_kubernetes_service_affinity: Option<String>,
203    /// Tolerations to apply to all services created by the Kubernetes
204    /// orchestrator as a JSON string.
205    #[structopt(long, env = "ORCHESTRATOR_KUBERNETES_SERVICE_TOLERATIONS")]
206    orchestrator_kubernetes_service_tolerations: Option<String>,
207    /// The name of a service account to apply to all services created by the
208    /// Kubernetes orchestrator.
209    #[structopt(long, env = "ORCHESTRATOR_KUBERNETES_SERVICE_ACCOUNT")]
210    orchestrator_kubernetes_service_account: Option<String>,
211    /// The Kubernetes context to use with the Kubernetes orchestrator.
212    ///
213    /// This defaults to `minikube` to prevent disaster (e.g., connecting to a
214    /// production cluster that happens to be the active Kubernetes context.)
215    #[structopt(
216        long,
217        env = "ORCHESTRATOR_KUBERNETES_CONTEXT",
218        default_value = "minikube"
219    )]
220    orchestrator_kubernetes_context: String,
221    /// The image pull policy to use for services created by the Kubernetes
222    /// orchestrator.
223    #[structopt(
224        long,
225        env = "ORCHESTRATOR_KUBERNETES_IMAGE_PULL_POLICY",
226        default_value = "always",
227        value_enum
228    )]
229    orchestrator_kubernetes_image_pull_policy: KubernetesImagePullPolicy,
230    /// The init container for services created by the Kubernetes orchestrator.
231    #[clap(long, env = "ORCHESTRATOR_KUBERNETES_INIT_CONTAINER_IMAGE")]
232    orchestrator_kubernetes_init_container_image: Option<String>,
233    /// The Kubernetes StorageClass to use for the ephemeral volume attached to
234    /// services that request disk.
235    ///
236    /// If unspecified, the Kubernetes orchestrator will refuse to create
237    /// services that request disk.
238    #[clap(long, env = "ORCHESTRATOR_KUBERNETES_EPHEMERAL_VOLUME_CLASS")]
239    orchestrator_kubernetes_ephemeral_volume_class: Option<String>,
240    /// The optional fs group for service's pods' `securityContext`.
241    #[clap(long, env = "ORCHESTRATOR_KUBERNETES_SERVICE_FS_GROUP")]
242    orchestrator_kubernetes_service_fs_group: Option<i64>,
243    /// The prefix to prepend to all kubernetes object names.
244    #[clap(long, env = "ORCHESTRATOR_KUBERNETES_NAME_PREFIX")]
245    orchestrator_kubernetes_name_prefix: Option<String>,
246    /// Whether to enable pod metrics collection.
247    ///
248    /// Required for resource usage graphs in the console.
249    /// Requires metrics-server to be installed.
250    #[clap(long, env = "ORCHESTRATOR_KUBERNETES_DISABLE_POD_METRICS_COLLECTION")]
251    orchestrator_kubernetes_disable_pod_metrics_collection: bool,
252    /// Whether to annotate pods for prometheus service discovery.
253    #[clap(
254        long,
255        env = "ORCHESTRATOR_KUBERNETES_ENABLE_PROMETHEUS_SCRAPE_ANNOTATIONS"
256    )]
257    orchestrator_kubernetes_enable_prometheus_scrape_annotations: bool,
258    #[clap(long, env = "ORCHESTRATOR_PROCESS_WRAPPER")]
259    orchestrator_process_wrapper: Option<String>,
260    /// Where the process orchestrator should store secrets.
261    #[clap(
262        long,
263        env = "ORCHESTRATOR_PROCESS_SECRETS_DIRECTORY",
264        value_name = "PATH",
265        required_if_eq("orchestrator", "process")
266    )]
267    orchestrator_process_secrets_directory: Option<PathBuf>,
268    /// Whether the process orchestrator should handle crashes in child
269    /// processes by crashing the parent process.
270    #[clap(long, env = "ORCHESTRATOR_PROCESS_PROPAGATE_CRASHES")]
271    orchestrator_process_propagate_crashes: bool,
272    /// An IP address on which the process orchestrator should bind TCP proxies
273    /// for Unix domain sockets.
274    ///
275    /// When specified, for each named port of each created service, the process
276    /// orchestrator will bind a TCP listener to the specified address that
277    /// proxies incoming connections to the underlying Unix domain socket. The
278    /// allocated TCP port will be emitted as a tracing event.
279    ///
280    /// The primary use is live debugging the running child services via tools
281    /// that do not support Unix domain sockets (e.g., Prometheus, web
282    /// browsers).
283    #[clap(long, env = "ORCHESTRATOR_PROCESS_TCP_PROXY_LISTEN_ADDR")]
284    orchestrator_process_tcp_proxy_listen_addr: Option<IpAddr>,
285    /// A directory in which the process orchestrator should write Prometheus
286    /// scrape targets, for use with Prometheus's file-based service discovery.
287    ///
288    /// Each namespaced orchestrator will maintain a single JSON file into the
289    /// directory named `NAMESPACE.json` containing the scrape targets for all
290    /// extant services. The scrape targets will use the TCP proxy address, as
291    /// Prometheus does not support scraping over Unix domain sockets.
292    ///
293    /// This option is ignored unless
294    /// `--orchestrator-process-tcp-proxy-listen-addr` is set.
295    ///
296    /// See also: <https://prometheus.io/docs/guides/file-sd/>
297    #[clap(
298        long,
299        env = "ORCHESTRATOR_PROCESS_PROMETHEUS_SERVICE_DISCOVERY_DIRECTORY"
300    )]
301    orchestrator_process_prometheus_service_discovery_directory: Option<PathBuf>,
302    /// A scratch directory that orchestrated processes can use for ephemeral storage.
303    #[clap(
304        long,
305        env = "ORCHESTRATOR_PROCESS_SCRATCH_DIRECTORY",
306        value_name = "PATH"
307    )]
308    orchestrator_process_scratch_directory: Option<PathBuf>,
309    /// Whether to use coverage build and collect coverage information. Not to be used for
310    /// production, only testing.
311    #[structopt(long, env = "ORCHESTRATOR_KUBERNETES_COVERAGE")]
312    orchestrator_kubernetes_coverage: bool,
313    /// The secrets controller implementation to use.
314    #[structopt(
315        long,
316        value_enum,
317        env = "SECRETS_CONTROLLER",
318        default_value_ifs([
319            ("orchestrator", "kubernetes", Some("kubernetes")),
320            ("orchestrator", "process", Some("local-file"))
321        ]),
322        default_value("kubernetes"), // This shouldn't be possible, but it makes clap happy.
323    )]
324    secrets_controller: SecretsControllerKind,
325    /// The list of tags to be set on AWS Secrets Manager secrets created by the
326    /// AWS secrets controller.
327    #[clap(
328        long,
329        env = "AWS_SECRETS_CONTROLLER_TAGS",
330        action = ArgAction::Append,
331        value_delimiter = ';',
332        required_if_eq("secrets_controller", "aws-secrets-manager")
333    )]
334    aws_secrets_controller_tags: Vec<KeyValueArg<String, String>>,
335    /// The clusterd image reference to use.
336    #[structopt(
337        long,
338        env = "CLUSTERD_IMAGE",
339        required_if_eq("orchestrator", "kubernetes"),
340        default_value_if("orchestrator", "process", Some("clusterd"))
341    )]
342    clusterd_image: Option<String>,
343    /// A number representing the environment's generation.
344    ///
345    /// This is incremented to request that the new process perform a graceful
346    /// transition of power from the prior generation.
347    #[clap(long, env = "DEPLOY_GENERATION", default_value = "0")]
348    deploy_generation: u64,
349
350    /// Can be provided in place of both persist_consensus_url and
351    /// timestamp_oracle_url in order to point both at the same backend
352    #[clap(
353        long,
354        env = "METADATA_BACKEND_URL",
355        conflicts_with_all = &[
356            "persist_consensus_url",
357            "timestamp_oracle_url",
358        ],
359    )]
360    metadata_backend_url: Option<SensitiveUrl>,
361
362    /// Helm chart version for self-hosted Materialize. This version is supposed to correspond to
363    /// the Materialize (core) version. This version is displayed in addition in `SELECT
364    /// mz_version()` if set and if it differs from the Materialize (core) version (which it should
365    /// not!).
366    #[clap(long, env = "HELM_CHART_VERSION")]
367    helm_chart_version: Option<String>,
368
369    // === Storage options. ===
370    /// Where the persist library should store its blob data.
371    #[clap(long, env = "PERSIST_BLOB_URL")]
372    persist_blob_url: SensitiveUrl,
373    /// Where the persist library should perform consensus.
374    #[clap(long, env = "PERSIST_CONSENSUS_URL")]
375    persist_consensus_url: Option<SensitiveUrl>,
376    /// The Persist PubSub URL.
377    ///
378    /// This URL is passed to `clusterd` for discovery of the Persist PubSub service.
379    #[clap(
380        long,
381        env = "PERSIST_PUBSUB_URL",
382        default_value = "http://localhost:6879"
383    )]
384    persist_pubsub_url: String,
385    /// The number of worker threads created for the IsolatedRuntime used for
386    /// storage related tasks. A negative value will subtract from the number
387    /// of threads returned by [`num_cpus::get`].
388    #[clap(long, env = "PERSIST_ISOLATED_RUNTIME_THREADS")]
389    persist_isolated_runtime_threads: Option<isize>,
390    /// The interval in seconds at which to collect storage usage information.
391    #[clap(
392        long,
393        env = "STORAGE_USAGE_COLLECTION_INTERVAL",
394        value_parser = humantime::parse_duration,
395        default_value = "3600s"
396    )]
397    storage_usage_collection_interval_sec: Duration,
398    /// The period for which to retain usage records. Note that the retention
399    /// period is only evaluated at server start time, so rebooting the server
400    /// is required to discard old records.
401    #[clap(long, env = "STORAGE_USAGE_RETENTION_PERIOD", value_parser = humantime::parse_duration)]
402    storage_usage_retention_period: Option<Duration>,
403
404    // === Adapter options. ===
405    /// The PostgreSQL URL for the Postgres-backed timestamp oracle.
406    #[clap(long, env = "TIMESTAMP_ORACLE_URL", value_name = "POSTGRES_URL")]
407    timestamp_oracle_url: Option<SensitiveUrl>,
408    /// Availability zones in which storage and compute resources may be
409    /// deployed.
410    #[clap(long, env = "AVAILABILITY_ZONE", use_value_delimiter = true)]
411    availability_zone: Vec<String>,
412    /// A map from size name to resource allocations for cluster replicas.
413    #[clap(
414        long,
415        env = "CLUSTER_REPLICA_SIZES",
416        requires = "bootstrap_default_cluster_replica_size"
417    )]
418    cluster_replica_sizes: String,
419    /// An API key for Segment. Enables export of audit events to Segment.
420    #[clap(long, env = "SEGMENT_API_KEY")]
421    segment_api_key: Option<String>,
422    /// Whether the Segment client is being used on the client side
423    /// (rather than the server side).
424    ///
425    /// Enabling this causes the Segment server to record the IP address from
426    /// which the event was sent.
427    #[clap(long, env = "SEGMENT_CLIENT_SIDE")]
428    segment_client_side: bool,
429    /// Only create a dummy segment client when no segment api key is provided, only to get more
430    /// testing coverage.
431    #[clap(long, env = "TEST_ONLY_DUMMY_SEGMENT_CLIENT")]
432    test_only_dummy_segment_client: bool,
433    /// An SDK key for LaunchDarkly.
434    ///
435    /// Setting this in combination with [`Self::config_sync_loop_interval`]
436    /// will enable synchronization of LaunchDarkly features with system
437    /// configuration parameters.
438    #[clap(long, env = "LAUNCHDARKLY_SDK_KEY")]
439    launchdarkly_sdk_key: Option<String>,
440    /// Overrides the LaunchDarkly streaming, polling, and events endpoints with
441    /// a single base URL, as for a relay proxy. Primarily intended for pointing
442    /// the SDK at a mock LaunchDarkly server in tests.
443    #[clap(long, env = "LAUNCHDARKLY_BASE_URI", value_name = "URL")]
444    launchdarkly_base_uri: Option<String>,
445    /// A list of PARAM_NAME=KEY_NAME pairs from system parameter names to
446    /// LaunchDarkly feature keys.
447    ///
448    /// This is used (so far only for testing purposes) when propagating values
449    /// from the latter to the former. The identity map is assumed for absent
450    /// parameter names.
451    #[clap(
452        long,
453        env = "LAUNCHDARKLY_KEY_MAP",
454        action = ArgAction::Append,
455        value_delimiter = ';'
456    )]
457    launchdarkly_key_map: Vec<KeyValueArg<String, String>>,
458    /// The duration at which the system parameter synchronization times out during startup.
459    #[clap(
460        long,
461        env = "CONFIG_SYNC_TIMEOUT",
462        value_parser = humantime::parse_duration,
463        default_value = "30s"
464    )]
465    config_sync_timeout: Duration,
466    /// The interval in seconds at which to synchronize system parameter values.
467    ///
468    /// If this is not explicitly set, the loop that synchronizes LaunchDarkly
469    /// features with system configuration parameters will not run _even if
470    /// [`Self::launchdarkly_sdk_key`] is present_.
471    #[clap(
472        long,
473        env = "CONFIG_SYNC_LOOP_INTERVAL",
474        value_parser = humantime::parse_duration,
475    )]
476    config_sync_loop_interval: Option<Duration>,
477    /// Path to a JSON file containing system parameter values.
478    /// If specified, this file will be used instead of LaunchDarkly for configuration.
479    #[clap(long, env = "CONFIG_SYNC_FILE_PATH", value_name = "PATH")]
480    config_sync_file_path: Option<PathBuf>,
481
482    // === Bootstrap options. ===
483    #[clap(
484        long,
485        env = "ENVIRONMENT_ID",
486        value_name = "<CLOUD>-<REGION>-<ORG-ID>-<ORDINAL>"
487    )]
488    environment_id: EnvironmentId,
489    /// If set, a role with the provided name will be created with `CREATEDB`
490    /// and `CREATECLUSTER` attributes. It will also have `CREATE` privileges on
491    /// the `materialize` database, `materialize.public` schema, and
492    /// `quickstart` cluster.
493    ///
494    /// This option is meant for local development and testing to simplify the
495    /// initial process of granting attributes and privileges to some default
496    /// role.
497    #[clap(long, env = "BOOTSTRAP_ROLE")]
498    bootstrap_role: Option<String>,
499    /// The size of the default cluster replica if bootstrapping.
500    #[clap(
501        long,
502        env = "BOOTSTRAP_DEFAULT_CLUSTER_REPLICA_SIZE",
503        default_value = "scale=1,workers=1"
504    )]
505    bootstrap_default_cluster_replica_size: String,
506    /// The size of the builtin system cluster replicas if bootstrapping.
507    #[clap(
508        long,
509        env = "BOOTSTRAP_BUILTIN_SYSTEM_CLUSTER_REPLICA_SIZE",
510        default_value = "scale=1,workers=1"
511    )]
512    bootstrap_builtin_system_cluster_replica_size: String,
513    /// The size of the builtin catalog server cluster replicas if bootstrapping.
514    #[clap(
515        long,
516        env = "BOOTSTRAP_BUILTIN_CATALOG_SERVER_CLUSTER_REPLICA_SIZE",
517        default_value = "scale=1,workers=1"
518    )]
519    bootstrap_builtin_catalog_server_cluster_replica_size: String,
520    /// The size of the builtin probe cluster replicas if bootstrapping.
521    #[clap(
522        long,
523        env = "BOOTSTRAP_BUILTIN_PROBE_CLUSTER_REPLICA_SIZE",
524        default_value = "scale=1,workers=1"
525    )]
526    bootstrap_builtin_probe_cluster_replica_size: String,
527    /// The size of the builtin support cluster replicas if bootstrapping.
528    #[clap(
529        long,
530        env = "BOOTSTRAP_BUILTIN_SUPPORT_CLUSTER_REPLICA_SIZE",
531        default_value = "scale=1,workers=1"
532    )]
533    bootstrap_builtin_support_cluster_replica_size: String,
534    /// The size of the builtin analytics cluster replicas if bootstrapping.
535    #[clap(
536        long,
537        env = "BOOTSTRAP_BUILTIN_ANALYTICS_CLUSTER_REPLICA_SIZE",
538        default_value = "scale=1,workers=1"
539    )]
540    bootstrap_builtin_analytics_cluster_replica_size: String,
541    #[clap(
542        long,
543        env = "BOOTSTRAP_DEFAULT_CLUSTER_REPLICATION_FACTOR",
544        default_value = DEFAULT_REPLICATION_FACTOR.to_string(),
545        value_parser = clap::value_parser!(u32).range(0..=2)
546    )]
547    bootstrap_default_cluster_replication_factor: u32,
548    /// The replication factor of the builtin system cluster replicas if bootstrapping.
549    #[clap(
550        long,
551        env = "BOOTSTRAP_BUILTIN_SYSTEM_CLUSTER_REPLICATION_FACTOR",
552        default_value = SYSTEM_CLUSTER_DEFAULT_REPLICATION_FACTOR.to_string(),
553        value_parser = clap::value_parser!(u32).range(0..=2)
554    )]
555    bootstrap_builtin_system_cluster_replication_factor: u32,
556    /// The replication factor of the builtin catalog server cluster replicas if bootstrapping.
557    #[clap(
558        long,
559        env = "BOOTSTRAP_BUILTIN_CATALOG_SERVER_CLUSTER_REPLICATION_FACTOR",
560        default_value = CATALOG_SERVER_CLUSTER_DEFAULT_REPLICATION_FACTOR.to_string(),
561        value_parser = clap::value_parser!(u32).range(0..=2)
562    )]
563    bootstrap_builtin_catalog_server_cluster_replication_factor: u32,
564    /// The replication factor of the builtin probe cluster replicas if bootstrapping.
565    #[clap(
566        long,
567        env = "BOOTSTRAP_BUILTIN_PROBE_CLUSTER_REPLICATION_FACTOR",
568        default_value = PROBE_CLUSTER_DEFAULT_REPLICATION_FACTOR.to_string(),
569        value_parser = clap::value_parser!(u32).range(0..=2)
570    )]
571    bootstrap_builtin_probe_cluster_replication_factor: u32,
572    /// The replication factor of the builtin support cluster replicas if bootstrapping.
573    #[clap(
574        long,
575        env = "BOOTSTRAP_BUILTIN_SUPPORT_CLUSTER_REPLICATION_FACTOR",
576        default_value = SUPPORT_CLUSTER_DEFAULT_REPLICATION_FACTOR.to_string(),
577        value_parser = clap::value_parser!(u32).range(0..=2)
578    )]
579    bootstrap_builtin_support_cluster_replication_factor: u32,
580    /// The replication factor of the builtin analytics cluster replicas if bootstrapping.
581    #[clap(
582        long,
583        env = "BOOTSTRAP_BUILTIN_ANALYTICS_CLUSTER_REPLICATION_FACTOR",
584        default_value = ANALYTICS_CLUSTER_DEFAULT_REPLICATION_FACTOR.to_string(),
585        value_parser = clap::value_parser!(u32).range(0..=2)
586    )]
587    bootstrap_builtin_analytics_cluster_replication_factor: u32,
588    /// An list of NAME=VALUE pairs used to override static defaults
589    /// for system parameters.
590    #[clap(
591        long,
592        env = "SYSTEM_PARAMETER_DEFAULT",
593        action = ArgAction::Append,
594        value_delimiter = ';'
595    )]
596    system_parameter_default: Vec<KeyValueArg<String, String>>,
597    /// File containing a valid Materialize license key.
598    #[clap(long, env = "LICENSE_KEY")]
599    license_key: Option<String>,
600
601    // === AWS options. ===
602    /// The AWS account ID, which will be used to generate ARNs for
603    /// Materialize-controlled AWS resources.
604    #[clap(long, env = "AWS_ACCOUNT_ID")]
605    aws_account_id: Option<String>,
606    /// The ARN for a Materialize-controlled role to assume before assuming
607    /// a customer's requested role for an AWS connection.
608    #[clap(long, env = "AWS_CONNECTION_ROLE_ARN")]
609    aws_connection_role_arn: Option<String>,
610    /// Prefix for an external ID to be supplied to all AWS AssumeRole operations.
611    ///
612    /// Details: <https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html>
613    #[clap(long, env = "AWS_EXTERNAL_ID_PREFIX", value_name = "ID", value_parser = AwsExternalIdPrefix::new_from_cli_argument_or_environment_variable)]
614    aws_external_id_prefix: Option<AwsExternalIdPrefix>,
615    /// The list of supported AWS PrivateLink availability zone ids.
616    /// Must be zone IDs, of format e.g. "use-az1".
617    #[clap(
618        long,
619        env = "AWS_PRIVATELINK_AVAILABILITY_ZONES",
620        action = ArgAction::Append,
621        use_value_delimiter = true
622    )]
623    aws_privatelink_availability_zones: Option<Vec<String>>,
624
625    // === Tracing options. ===
626    #[clap(flatten)]
627    tracing: TracingCliArgs,
628
629    // === Testing options. ===
630    /// Forces the migration of all builtin storage collections using the
631    /// specified migration mechanism (either "evolution" or "replacement").
632    ///
633    /// This argument is meant for testing only and as the names suggests
634    /// should not be set in production.
635    #[clap(long, value_enum, requires = "unsafe_mode")]
636    unsafe_force_builtin_schema_migration: Option<String>,
637}
638
639#[derive(ValueEnum, Debug, Clone)]
640enum OrchestratorKind {
641    Kubernetes,
642    Process,
643}
644
645// TODO [Alex Hunt] move this to a shared function that can be imported by the
646// region-controller.
647fn aws_secrets_controller_prefix(env_id: &EnvironmentId) -> String {
648    format!("/user-managed/{}/", env_id)
649}
650fn aws_secrets_controller_key_alias(env_id: &EnvironmentId) -> String {
651    // TODO [Alex Hunt] move this to a shared function that can be imported by the
652    // region-controller.
653    format!("alias/customer_key_{}", env_id)
654}
655
656pub fn main() {
657    let args = cli::parse_args(CliConfig {
658        env_prefix: Some("MZ_"),
659        enable_version_flag: true,
660    });
661    if let Err(err) = run(args) {
662        panic!("environmentd: fatal: {}", err.display_with_causes());
663    }
664}
665
666fn run(mut args: Args) -> Result<(), anyhow::Error> {
667    mz_ore::panic::install_enhanced_handler();
668
669    // Pin the rustls crypto provider to aws-lc-rs. The LaunchDarkly SDK uses
670    // hyper-rustls, so building its client resolves the process-default rustls
671    // provider. The workspace also links rustls' `ring` feature (pulled by
672    // other hyper-rustls chains), and with both provider features enabled
673    // rustls cannot choose a default on its own and panics. The call is
674    // idempotent, so ignore the result.
675    let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
676
677    let envd_start = Instant::now();
678
679    // Configure signal handling as soon as possible. We want signals to be
680    // handled to our liking ASAP.
681    sys::enable_sigusr2_coverage_dump()?;
682    sys::enable_termination_signal_cleanup()?;
683
684    let license_key = if let Some(license_key_file) = args.license_key {
685        let license_key_text = std::fs::read_to_string(&license_key_file)
686            .context("failed to open license key file")?;
687        let license_key = mz_license_keys::validate(license_key_text.trim())
688            .context("failed to validate license key file")?;
689        if license_key.expired {
690            let message = format!(
691                "The license key provided at {license_key_file} is expired! Please contact Materialize for assistance."
692            );
693            match license_key.expiration_behavior {
694                ExpirationBehavior::Warn | ExpirationBehavior::DisableClusterCreation => {
695                    warn!("{message}");
696                }
697                ExpirationBehavior::Disable => bail!("{message}"),
698            }
699        }
700        license_key
701    } else if matches!(args.orchestrator, OrchestratorKind::Kubernetes) {
702        bail!("--license-key is required when running in Kubernetes");
703    } else {
704        // license key checks are optional for the emulator
705        ValidatedLicenseKey::disabled()
706    };
707
708    // Configure testing options.
709    let force_builtin_schema_migration = args
710        .unsafe_force_builtin_schema_migration
711        .inspect(|_mechanism| assert!(args.unsafe_mode));
712
713    // Start Tokio runtime.
714
715    let ncpus_useful = usize::max(1, cmp::min(num_cpus::get(), num_cpus::get_physical()));
716    let runtime = Arc::new(
717        tokio::runtime::Builder::new_multi_thread()
718            .worker_threads(ncpus_useful)
719            .thread_stack_size(3 * 1024 * 1024) // 3 MiB
720            // The default thread name exceeds the Linux limit on thread name
721            // length, so pick something shorter.
722            .thread_name_fn(|| {
723                static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
724                let id = ATOMIC_ID.fetch_add(1, Ordering::Relaxed);
725                format!("tokio:work-{}", id)
726            })
727            .enable_all()
728            .build()?,
729    );
730
731    // Configure tracing to log the service name when using the process
732    // orchestrator, which intermingles log output from multiple services. Other
733    // orchestrators separate log output from different services.
734    args.tracing.log_prefix = if matches!(args.orchestrator, OrchestratorKind::Process) {
735        Some("environmentd".to_string())
736    } else {
737        None
738    };
739
740    let metrics_registry = MetricsRegistry::new();
741    let tracing_handle = runtime.block_on(args.tracing.configure_tracing(
742        StaticTracingConfig {
743            service_name: "environmentd",
744            build_info: BUILD_INFO,
745        },
746        metrics_registry.clone(),
747    ))?;
748    register_runtime_metrics("main", runtime.metrics(), &metrics_registry);
749
750    let span = tracing::info_span!("environmentd::run").entered();
751
752    info!("startup: envd init: beginning");
753    info!("startup: envd init: preamble beginning");
754
755    let metrics = Metrics::register_into(&metrics_registry, BUILD_INFO);
756
757    runtime.block_on(mz_alloc::register_metrics_into(&metrics_registry));
758    runtime.block_on(mz_metrics::register_metrics_into(
759        &metrics_registry,
760        mz_dyncfgs::all_dyncfgs(),
761        // environmentd has no scratch directory, so it tracks no disk usage.
762        None,
763    ));
764
765    // Initialize fail crate for failpoint support
766    let _failpoint_scenario = FailScenario::setup();
767
768    // Configure connections.
769    let tls = args.tls.into_config()?;
770    let frontegg_oauth_issuer_url = args.frontegg.oauth_issuer_url().map(str::to_string);
771    let frontegg = FronteggAuthenticator::from_args(args.frontegg, &metrics_registry)?;
772    let listeners_config: ListenersConfig = {
773        let f = File::open(args.listeners_config_path)?;
774        serde_json::from_reader(f)?
775    };
776
777    for (_, listener) in &listeners_config.sql {
778        listener
779            .validate()
780            .map_err(|e| anyhow::anyhow!("invalid SQL listener: {}", e))?;
781    }
782
783    for (_, listener) in &listeners_config.http {
784        listener
785            .validate()
786            .map_err(|e| anyhow::anyhow!("invalid HTTP listener: {}", e))?;
787    }
788
789    // Configure CORS.
790    let allowed_origins = if !args.cors_allowed_origin.is_empty() {
791        args.cors_allowed_origin
792    } else {
793        let mut allowed_origins = Vec::with_capacity(listeners_config.http.len() * 6);
794        for (_, listener) in &listeners_config.http {
795            let port = listener.addr().port();
796            allowed_origins.extend([
797                HeaderValue::from_str(&format!("http://localhost:{}", port)).unwrap(),
798                HeaderValue::from_str(&format!("http://127.0.0.1:{}", port)).unwrap(),
799                HeaderValue::from_str(&format!("http://[::1]:{}", port)).unwrap(),
800                HeaderValue::from_str(&format!("https://localhost:{}", port)).unwrap(),
801                HeaderValue::from_str(&format!("https://127.0.0.1:{}", port)).unwrap(),
802                HeaderValue::from_str(&format!("https://[::1]:{}", port)).unwrap(),
803            ])
804        }
805        allowed_origins
806    };
807    let cors_allowed_origin = mz_http_util::build_cors_allowed_origin(&allowed_origins);
808    let cors_allowed_origin_list = allowed_origins.clone();
809
810    // Configure controller.
811    let entered = info_span!("environmentd::configure_controller").entered();
812    let (orchestrator, secrets_controller, cloud_resource_controller): (
813        Arc<dyn Orchestrator>,
814        Arc<dyn SecretsController>,
815        Option<Arc<dyn CloudResourceController>>,
816    ) = match args.orchestrator {
817        OrchestratorKind::Kubernetes => {
818            if args.orchestrator_process_scratch_directory.is_some() {
819                bail!(
820                    "--orchestrator-process-scratch-directory is \
821                      not currently usable with the kubernetes orchestrator"
822                );
823            }
824
825            let orchestrator = Arc::new(
826                runtime
827                    .block_on(KubernetesOrchestrator::new(KubernetesOrchestratorConfig {
828                        context: args.orchestrator_kubernetes_context.clone(),
829                        scheduler_name: args.orchestrator_kubernetes_scheduler_name,
830                        priority_class_name: args.orchestrator_kubernetes_priority_class_name,
831                        service_annotations: args
832                            .orchestrator_kubernetes_service_annotation
833                            .into_iter()
834                            .map(|l| (l.key, l.value))
835                            .collect(),
836                        service_labels: args
837                            .orchestrator_kubernetes_service_label
838                            .into_iter()
839                            .map(|l| (l.key, l.value))
840                            .collect(),
841                        service_node_selector: args
842                            .orchestrator_kubernetes_service_node_selector
843                            .into_iter()
844                            .map(|l| (l.key, l.value))
845                            .collect(),
846                        service_affinity: args.orchestrator_kubernetes_service_affinity,
847                        service_tolerations: args.orchestrator_kubernetes_service_tolerations,
848                        service_account: args.orchestrator_kubernetes_service_account,
849                        image_pull_policy: args.orchestrator_kubernetes_image_pull_policy,
850                        aws_external_id_prefix: args.aws_external_id_prefix.clone(),
851                        coverage: args.orchestrator_kubernetes_coverage,
852                        ephemeral_volume_storage_class: args
853                            .orchestrator_kubernetes_ephemeral_volume_class
854                            .clone(),
855                        service_fs_group: args.orchestrator_kubernetes_service_fs_group.clone(),
856                        name_prefix: args.orchestrator_kubernetes_name_prefix.clone(),
857                        collect_pod_metrics: !args
858                            .orchestrator_kubernetes_disable_pod_metrics_collection,
859                        enable_prometheus_scrape_annotations: args
860                            .orchestrator_kubernetes_enable_prometheus_scrape_annotations,
861                    }))
862                    .context("creating kubernetes orchestrator")?,
863            );
864            let secrets_controller: Arc<dyn SecretsController> = match args.secrets_controller {
865                SecretsControllerKind::Kubernetes => {
866                    let sc = Arc::clone(&orchestrator);
867                    let sc: Arc<dyn SecretsController> = sc;
868                    sc
869                }
870                SecretsControllerKind::AwsSecretsManager => {
871                    Arc::new(
872                        runtime.block_on(AwsSecretsController::new(
873                            // TODO [Alex Hunt] move this to a shared function that can be imported by the
874                            // region-controller.
875                            &aws_secrets_controller_prefix(&args.environment_id),
876                            &aws_secrets_controller_key_alias(&args.environment_id),
877                            args.aws_secrets_controller_tags
878                                .into_iter()
879                                .map(|tag| (tag.key, tag.value))
880                                .collect(),
881                        )),
882                    )
883                }
884                SecretsControllerKind::LocalFile => bail!(
885                    "SecretsControllerKind::LocalFile is not compatible with Orchestrator::Kubernetes."
886                ),
887            };
888            let cloud_resource_controller = Arc::clone(&orchestrator);
889            (
890                orchestrator,
891                secrets_controller,
892                Some(cloud_resource_controller),
893            )
894        }
895        OrchestratorKind::Process => {
896            if args
897                .orchestrator_kubernetes_ephemeral_volume_class
898                .is_some()
899            {
900                bail!(
901                    "--orchestrator-kubernetes-ephemeral-volume-class is \
902                      not usable with the process orchestrator"
903                );
904            }
905            let orchestrator = Arc::new(
906                runtime
907                    .block_on(ProcessOrchestrator::new(ProcessOrchestratorConfig {
908                        // Look for binaries in the same directory as the
909                        // running binary. When running via `cargo run`, this
910                        // means that debug binaries look for other debug
911                        // binaries and release binaries look for other release
912                        // binaries.
913                        image_dir: env::current_exe()?.parent().unwrap().to_path_buf(),
914                        suppress_output: false,
915                        environment_id: args.environment_id.to_string(),
916                        secrets_dir: args
917                            .orchestrator_process_secrets_directory
918                            .clone()
919                            .expect("clap enforced"),
920                        command_wrapper: args
921                            .orchestrator_process_wrapper
922                            .map_or(Ok(vec![]), |s| shell_words::split(&s))?,
923                        propagate_crashes: args.orchestrator_process_propagate_crashes,
924                        tcp_proxy: args.orchestrator_process_tcp_proxy_listen_addr.map(
925                            |listen_addr| ProcessOrchestratorTcpProxyConfig {
926                                listen_addr,
927                                prometheus_service_discovery_dir: args
928                                    .orchestrator_process_prometheus_service_discovery_directory,
929                            },
930                        ),
931                        scratch_directory: args
932                            .orchestrator_process_scratch_directory
933                            .expect("process orchestrator requires scratch directory"),
934                    }))
935                    .context("creating process orchestrator")?,
936            );
937            let secrets_controller: Arc<dyn SecretsController> = match args.secrets_controller {
938                SecretsControllerKind::Kubernetes => bail!(
939                    "SecretsControllerKind::Kubernetes is not compatible with Orchestrator::Process."
940                ),
941                SecretsControllerKind::AwsSecretsManager => Arc::new(
942                    runtime.block_on(AwsSecretsController::new(
943                        &aws_secrets_controller_prefix(&args.environment_id),
944                        &aws_secrets_controller_key_alias(&args.environment_id),
945                        args.aws_secrets_controller_tags
946                            .into_iter()
947                            .map(|tag| (tag.key, tag.value))
948                            .collect(),
949                    )),
950                ),
951                SecretsControllerKind::LocalFile => {
952                    let sc = Arc::clone(&orchestrator);
953                    let sc: Arc<dyn SecretsController> = sc;
954                    sc
955                }
956            };
957            (orchestrator, secrets_controller, None)
958        }
959    };
960    drop(entered);
961    let cloud_resource_reader = cloud_resource_controller.as_ref().map(|c| c.reader());
962    let secrets_reader = secrets_controller.reader();
963    let now = SYSTEM_TIME.clone();
964
965    let mut persist_config =
966        PersistConfig::new(&BUILD_INFO, now.clone(), mz_dyncfgs::all_dyncfgs());
967    // Start with compaction disabled, later enable it if we're not in read-only mode.
968    persist_config.disable_compaction();
969
970    let persist_pubsub_server = PersistGrpcPubSubServer::new(&persist_config, &metrics_registry);
971    let persist_pubsub_client = persist_pubsub_server.new_same_process_connection();
972
973    match args.persist_isolated_runtime_threads {
974        // Use the default.
975        None | Some(0) => (),
976        Some(x @ ..=-1) => {
977            let threads = num_cpus::get().saturating_add_signed(x).max(1);
978            persist_config.isolated_runtime_worker_threads = threads;
979        }
980        Some(x @ 1..) => {
981            let threads = usize::try_from(x).expect("pattern matched a positive value");
982            persist_config.isolated_runtime_worker_threads = threads;
983        }
984    };
985
986    let _server = runtime.spawn_named(
987        || "persist::rpc::server",
988        async move {
989            info!(
990                "listening for Persist PubSub connections on {}",
991                args.internal_persist_pubsub_listen_addr
992            );
993            // Intentionally do not bubble up errors here, we don't want to take
994            // down environmentd if there are any issues with the pubsub server.
995            let res = persist_pubsub_server
996                .serve(args.internal_persist_pubsub_listen_addr)
997                .await;
998            error!("Persist Pubsub server exited {:?}", res);
999        }
1000        .instrument(tracing::info_span!("persist::rpc::server")),
1001    );
1002
1003    let persist_clients = {
1004        // PersistClientCache may spawn tasks, so run within a tokio runtime context
1005        let _tokio_guard = runtime.enter();
1006        PersistClientCache::new(persist_config, &metrics_registry, |cfg, metrics| {
1007            let sender: Arc<dyn PubSubSender> = Arc::new(MetricsSameProcessPubSubSender::new(
1008                cfg,
1009                persist_pubsub_client.sender,
1010                metrics,
1011            ));
1012            PubSubClientConnection::new(sender, persist_pubsub_client.receiver)
1013        })
1014    };
1015
1016    let consensus_uri = args.persist_consensus_url.unwrap_or_else(|| {
1017        args.metadata_backend_url
1018            .as_ref()
1019            .map(|metadata_backend_url| {
1020                SensitiveUrl(
1021                    Url::parse_with_params(
1022                        metadata_backend_url.0.as_ref(),
1023                        &[("options", "--search_path=consensus")],
1024                    )
1025                    .unwrap(),
1026                )
1027            })
1028            .expect("either --persist-consensus-url or --metadata-backend-url must be provided")
1029    });
1030    let timestamp_oracle_url = args.timestamp_oracle_url.or_else(|| {
1031        args.metadata_backend_url
1032            .as_ref()
1033            .map(|metadata_backend_url| {
1034                SensitiveUrl(
1035                    Url::parse_with_params(
1036                        metadata_backend_url.0.as_ref(),
1037                        &[("options", "--search_path=tsoracle")],
1038                    )
1039                    .unwrap(),
1040                )
1041            })
1042    });
1043
1044    let persist_clients = Arc::new(persist_clients);
1045    let system_dyncfgs = Arc::clone(&persist_clients.cfg().configs);
1046    let connection_context = ConnectionContext::from_cli_args(
1047        args.environment_id.to_string(),
1048        &args.tracing.startup_log_filter,
1049        args.aws_external_id_prefix,
1050        args.aws_connection_role_arn,
1051        secrets_reader,
1052        cloud_resource_reader,
1053    );
1054    let orchestrator = Arc::new(TracingOrchestrator::new(orchestrator, args.tracing.clone()));
1055    let replica_http_locator = Arc::new(ReplicaHttpLocator::default());
1056    let controller = ControllerConfig {
1057        build_info: &BUILD_INFO,
1058        orchestrator,
1059        persist_location: PersistLocation {
1060            blob_uri: args.persist_blob_url,
1061            consensus_uri,
1062        },
1063        persist_clients: Arc::clone(&persist_clients),
1064        clusterd_image: args.clusterd_image.expect("clap enforced"),
1065        init_container_image: args.orchestrator_kubernetes_init_container_image,
1066        deploy_generation: args.deploy_generation,
1067        now: SYSTEM_TIME.clone(),
1068        metrics_registry: metrics_registry.clone(),
1069        persist_pubsub_url: args.persist_pubsub_url,
1070        connection_context,
1071        // When serialized to args in the controller, only the relevant flags will be passed
1072        // through, so we just set all of them
1073        secrets_args: SecretsReaderCliArgs {
1074            secrets_reader: args.secrets_controller,
1075            secrets_reader_local_file_dir: args.orchestrator_process_secrets_directory,
1076            secrets_reader_kubernetes_context: Some(args.orchestrator_kubernetes_context),
1077            secrets_reader_aws_prefix: Some(aws_secrets_controller_prefix(&args.environment_id)),
1078            secrets_reader_name_prefix: args.orchestrator_kubernetes_name_prefix.clone(),
1079        },
1080        replica_http_locator: Arc::clone(&replica_http_locator),
1081    };
1082
1083    let cluster_replica_sizes = ClusterReplicaSizeMap::parse_from_str(
1084        &args.cluster_replica_sizes,
1085        !license_key.allow_credit_consumption_override,
1086    )
1087    .context("parsing replica size map")?;
1088
1089    emit_boot_diagnostics!(&BUILD_INFO);
1090    sys::adjust_rlimits();
1091
1092    info!(
1093        "startup: envd init: preamble complete in {:?}",
1094        envd_start.elapsed()
1095    );
1096
1097    let serve_start = Instant::now();
1098    info!("startup: envd init: serving beginning");
1099    let server = runtime.block_on(async {
1100        let listeners = Listeners::bind(listeners_config).await?;
1101        let catalog_config = CatalogConfig {
1102            persist_clients,
1103            metrics: Arc::new(mz_catalog::durable::Metrics::new(&metrics_registry)),
1104        };
1105        let server = listeners
1106            .serve(crate::Config {
1107                // Special modes.
1108                unsafe_mode: args.unsafe_mode,
1109                all_features: args.all_features,
1110                // Connection options.
1111                tls,
1112                tls_reload_certs: mz_server_core::default_cert_reload_ticker(),
1113                external_login_password_mz_system: args.external_login_password_mz_system,
1114                frontegg,
1115                frontegg_oauth_issuer_url,
1116                cors_allowed_origin,
1117                cors_allowed_origin_list,
1118                egress_addresses: args.announce_egress_address,
1119                http_host_name: args.http_host_name,
1120                internal_console_redirect_url: args.internal_console_redirect_url,
1121                // Controller options.
1122                controller,
1123                secrets_controller,
1124                cloud_resource_controller,
1125                system_dyncfgs,
1126                // Storage options.
1127                storage_usage_collection_interval: args.storage_usage_collection_interval_sec,
1128                storage_usage_retention_period: args.storage_usage_retention_period,
1129                // Adapter options.
1130                catalog_config,
1131                availability_zones: args.availability_zone,
1132                cluster_replica_sizes,
1133                timestamp_oracle_url,
1134                segment_api_key: args.segment_api_key,
1135                segment_client_side: args.segment_client_side,
1136                test_only_dummy_segment_client: args.test_only_dummy_segment_client,
1137                launchdarkly_sdk_key: args.launchdarkly_sdk_key,
1138                launchdarkly_base_uri: args.launchdarkly_base_uri,
1139                launchdarkly_key_map: args
1140                    .launchdarkly_key_map
1141                    .into_iter()
1142                    .map(|kv| (kv.key, kv.value))
1143                    .collect(),
1144                config_sync_timeout: args.config_sync_timeout,
1145                config_sync_loop_interval: args.config_sync_loop_interval,
1146                config_sync_file_path: args.config_sync_file_path,
1147
1148                // Bootstrap options.
1149                environment_id: args.environment_id,
1150                bootstrap_role: args.bootstrap_role,
1151                bootstrap_default_cluster_replica_size: args.bootstrap_default_cluster_replica_size,
1152                bootstrap_default_cluster_replication_factor: args
1153                    .bootstrap_default_cluster_replication_factor,
1154                bootstrap_builtin_system_cluster_config: BootstrapBuiltinClusterConfig {
1155                    size: args.bootstrap_builtin_system_cluster_replica_size,
1156                    replication_factor: args.bootstrap_builtin_system_cluster_replication_factor,
1157                },
1158                bootstrap_builtin_catalog_server_cluster_config: BootstrapBuiltinClusterConfig {
1159                    size: args.bootstrap_builtin_catalog_server_cluster_replica_size,
1160                    replication_factor: args
1161                        .bootstrap_builtin_catalog_server_cluster_replication_factor,
1162                },
1163                bootstrap_builtin_probe_cluster_config: BootstrapBuiltinClusterConfig {
1164                    size: args.bootstrap_builtin_probe_cluster_replica_size,
1165                    replication_factor: args.bootstrap_builtin_probe_cluster_replication_factor,
1166                },
1167                bootstrap_builtin_support_cluster_config: BootstrapBuiltinClusterConfig {
1168                    size: args.bootstrap_builtin_support_cluster_replica_size,
1169                    replication_factor: args.bootstrap_builtin_support_cluster_replication_factor,
1170                },
1171                bootstrap_builtin_analytics_cluster_config: BootstrapBuiltinClusterConfig {
1172                    size: args.bootstrap_builtin_analytics_cluster_replica_size,
1173                    replication_factor: args.bootstrap_builtin_analytics_cluster_replication_factor,
1174                },
1175                system_parameter_defaults: args
1176                    .system_parameter_default
1177                    .into_iter()
1178                    .map(|kv| (kv.key, kv.value))
1179                    .collect(),
1180                helm_chart_version: args.helm_chart_version.clone(),
1181                license_key,
1182                // AWS options.
1183                aws_account_id: args.aws_account_id,
1184                aws_privatelink_availability_zones: args.aws_privatelink_availability_zones,
1185                // Observability options.
1186                metrics_registry,
1187                tracing_handle,
1188                // Testing options.
1189                now,
1190                force_builtin_schema_migration,
1191            })
1192            .await
1193            .maybe_terminate("booting server")?;
1194        Ok::<_, anyhow::Error>(server)
1195    })?;
1196    info!(
1197        "startup: envd init: serving complete in {:?}",
1198        serve_start.elapsed()
1199    );
1200
1201    let start_duration = envd_start.elapsed();
1202    metrics
1203        .start_time_environmentd
1204        .set(start_duration.as_millis().try_into().expect("must fit"));
1205    let span = span.exit();
1206    let id = span.context().span().span_context().trace_id();
1207    drop(span);
1208
1209    info!("startup: envd init: complete in {start_duration:?}");
1210
1211    println!(
1212        "environmentd {} listening...",
1213        BUILD_INFO.human_version(args.helm_chart_version)
1214    );
1215    for (name, handle) in &server.sql_listener_handles {
1216        println!("{} SQL address: {}", name, handle.local_addr);
1217    }
1218    for (name, handle) in &server.http_listener_handles {
1219        println!("{} HTTP address: {}", name, handle.local_addr);
1220    }
1221    // TODO move persist pubsub address like metrics address?
1222    println!(
1223        " Internal Persist PubSub address: {}",
1224        args.internal_persist_pubsub_listen_addr
1225    );
1226
1227    println!(" Root trace ID: {id}");
1228
1229    // Block forever.
1230    loop {
1231        thread::park();
1232    }
1233}
1234
1235fn build_info() -> Vec<String> {
1236    let openssl_version =
1237        unsafe { CStr::from_ptr(openssl_sys::OpenSSL_version(openssl_sys::OPENSSL_VERSION)) };
1238    let rdkafka_version = unsafe { CStr::from_ptr(rdkafka_sys::bindings::rd_kafka_version_str()) };
1239    vec![
1240        openssl_version.to_string_lossy().into_owned(),
1241        format!("librdkafka v{}", rdkafka_version.to_string_lossy()),
1242    ]
1243}
1244
1245#[derive(Debug, Clone)]
1246struct Metrics {
1247    pub start_time_environmentd: IntGauge,
1248}
1249
1250impl Metrics {
1251    pub fn register_into(registry: &MetricsRegistry, build_info: BuildInfo) -> Metrics {
1252        Metrics {
1253            start_time_environmentd: registry.register(metric!(
1254                name: "mz_start_time_environmentd",
1255                help: "Time in milliseconds from environmentd start until the adapter is ready.",
1256                const_labels: {
1257                    "version" => build_info.version,
1258                    "build_type" => if cfg!(release) { "release" } else { "debug" }
1259                },
1260            )),
1261        }
1262    }
1263}