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