Skip to main content

mz_clusterd/
lib.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::path::PathBuf;
11use std::sync::Arc;
12use std::sync::LazyLock;
13use std::time::Duration;
14
15use anyhow::Context;
16use axum::http::StatusCode;
17use axum::routing;
18use fail::FailScenario;
19use futures::future;
20use hyper_util::rt::TokioIo;
21use mz_build_info::{BuildInfo, build_info};
22use mz_cloud_resources::AwsExternalIdPrefix;
23use mz_cluster_client::client::TimelyConfig;
24use mz_compute::server::ComputeInstanceContext;
25use mz_http_util::DynamicFilterTarget;
26use mz_orchestrator_tracing::{StaticTracingConfig, TracingCliArgs};
27use mz_ore::cli::{self, CliConfig};
28use mz_ore::error::ErrorExt;
29use mz_ore::metrics::{MetricsRegistry, register_runtime_metrics};
30use mz_ore::netio::{Listener, SocketAddr};
31use mz_ore::now::SYSTEM_TIME;
32use mz_persist_client::cache::PersistClientCache;
33use mz_persist_client::cfg::PersistConfig;
34use mz_persist_client::rpc::{GrpcPubSubClient, PersistPubSubClient, PersistPubSubClientConfig};
35use mz_service::emit_boot_diagnostics;
36use mz_service::secrets::SecretsReaderCliArgs;
37use mz_service::transport;
38use mz_service::transport::ClusterServerMetrics;
39use mz_storage::storage_state::StorageInstanceContext;
40use mz_storage_types::connections::ConnectionContext;
41use mz_timely_util::capture::arc_event_link;
42use mz_txn_wal::operator::TxnsContext;
43use tokio::runtime::Handle;
44use tower::Service;
45use tracing::{Instrument, debug, error, info, info_span};
46
47mod usage_metrics;
48
49const BUILD_INFO: BuildInfo = build_info!();
50
51pub static VERSION: LazyLock<String> = LazyLock::new(|| BUILD_INFO.human_version(None));
52
53/// Independent cluster server for Materialize.
54#[derive(clap::Parser)]
55#[clap(name = "clusterd", version = VERSION.as_str())]
56struct Args {
57    // === Connection options. ===
58    /// The address on which to listen for a connection from the storage
59    /// controller.
60    #[clap(
61        long,
62        env = "STORAGE_CONTROLLER_LISTEN_ADDR",
63        value_name = "HOST:PORT",
64        default_value = "127.0.0.1:2100"
65    )]
66    storage_controller_listen_addr: SocketAddr,
67    /// The address on which to listen for a connection from the compute
68    /// controller.
69    #[clap(
70        long,
71        env = "COMPUTE_CONTROLLER_LISTEN_ADDR",
72        value_name = "HOST:PORT",
73        default_value = "127.0.0.1:2101"
74    )]
75    compute_controller_listen_addr: SocketAddr,
76    /// The address of the internal HTTP server.
77    #[clap(
78        long,
79        env = "INTERNAL_HTTP_LISTEN_ADDR",
80        value_name = "HOST:PORT",
81        default_value = "127.0.0.1:6878"
82    )]
83    internal_http_listen_addr: SocketAddr,
84    /// The FQDN of this process, for GRPC request validation.
85    ///
86    /// Not providing this value or setting it to the empty string disables host validation for
87    /// GRPC requests.
88    #[clap(long, env = "GRPC_HOST", value_name = "NAME")]
89    grpc_host: Option<String>,
90
91    // === Timely cluster options. ===
92    /// Configuration for the storage Timely cluster.
93    #[clap(long, env = "STORAGE_TIMELY_CONFIG")]
94    storage_timely_config: TimelyConfig,
95    /// Configuration for the compute Timely cluster.
96    #[clap(long, env = "COMPUTE_TIMELY_CONFIG")]
97    compute_timely_config: TimelyConfig,
98    /// The index of the process in both Timely clusters.
99    #[clap(long, env = "PROCESS")]
100    process: usize,
101
102    // === Storage options. ===
103    /// The URL for the Persist PubSub service.
104    #[clap(
105        long,
106        env = "PERSIST_PUBSUB_URL",
107        value_name = "http://HOST:PORT",
108        default_value = "http://localhost:6879"
109    )]
110    persist_pubsub_url: String,
111
112    // === Cloud options. ===
113    /// An external ID to be supplied to all AWS AssumeRole operations.
114    ///
115    /// Details: <https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html>
116    #[clap(long, env = "AWS_EXTERNAL_ID", value_name = "ID", value_parser = AwsExternalIdPrefix::new_from_cli_argument_or_environment_variable)]
117    aws_external_id_prefix: Option<AwsExternalIdPrefix>,
118
119    /// The ARN for a Materialize-controlled role to assume before assuming
120    /// a customer's requested role for an AWS connection.
121    #[clap(long, env = "AWS_CONNECTION_ROLE_ARN")]
122    aws_connection_role_arn: Option<String>,
123
124    // === Secrets reader options. ===
125    #[clap(flatten)]
126    secrets: SecretsReaderCliArgs,
127
128    // === Tracing options. ===
129    #[clap(flatten)]
130    tracing: TracingCliArgs,
131
132    // === Other options. ===
133    /// An opaque identifier for the environment in which this process is
134    /// running.
135    #[clap(long, env = "ENVIRONMENT_ID")]
136    environment_id: String,
137
138    /// A scratch directory that can be used for ephemeral storage.
139    #[clap(long, env = "SCRATCH_DIRECTORY", value_name = "PATH")]
140    scratch_directory: Option<PathBuf>,
141
142    /// Memory limit (bytes) of the cluster replica, if known.
143    ///
144    /// The limit is expected to be enforced by the orchestrator. The clusterd process only uses it
145    /// to inform configuration of backpressure mechanism.
146    #[clap(long)]
147    announce_memory_limit: Option<usize>,
148
149    /// Heap limit (bytes) of the cluster replica.
150    ///
151    /// A process heap usage is calculated as the sum of its memory and swap usage.
152    ///
153    /// In contrast to `announce_memory_limit`, this limit is enforced by the clusterd process. If
154    /// the limit is exceeded, the process terminates itself with a 167 exit code.
155    #[clap(long)]
156    heap_limit: Option<usize>,
157
158    /// Whether this size represents a modern "cc" size rather than a legacy
159    /// T-shirt size.
160    #[clap(long)]
161    is_cc: bool,
162
163    /// Set core affinity for Timely workers.
164    ///
165    /// This flag should only be set if the process is provided with exclusive access to its
166    /// supplied CPU cores. If other processes are competing over the same cores, setting core
167    /// affinity might degrade dataflow performance rather than improving it.
168    #[clap(long)]
169    worker_core_affinity: bool,
170
171    /// Forward storage's timely logging events to compute so storage operators appear in
172    /// `mz_introspection.mz_dataflow_*` tables.
173    #[clap(long)]
174    enable_storage_introspection_logs: bool,
175}
176
177/// The process ordinal for a StatefulSet pod, taken from the trailing
178/// `-`-delimited segment of its hostname (e.g.
179/// "mz5ncn-cluster-s1-replica-s1-gen-1-0" → "0"). This mirrors how
180/// orchestrator-kubernetes recovers the process id from pod names.
181///
182/// Returns `None` when the trailing segment is not a non-negative integer, so
183/// an unexpected hostname leaves `CLUSTERD_PROCESS` unset rather than set to a
184/// value that fails to parse as the process index.
185fn process_ordinal_from_hostname(hostname: &str) -> Option<&str> {
186    let ordinal = hostname.rsplit('-').next()?;
187    ordinal.parse::<usize>().ok().map(|_| ordinal)
188}
189
190pub fn main() {
191    mz_ore::panic::install_enhanced_handler();
192
193    // Pin the rustls crypto provider to aws-lc-rs. The LaunchDarkly SDK uses
194    // hyper-rustls, so building its client resolves the process-default rustls
195    // provider. The workspace also links rustls' `ring` feature (pulled by
196    // other hyper-rustls chains), and with both provider features enabled
197    // rustls cannot choose a default on its own and panics. The call is
198    // idempotent, so ignore the result.
199    let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
200
201    // Derive `CLUSTERD_PROCESS` (the process ordinal) from the pod hostname
202    // when running under Kubernetes and it was not set explicitly. The
203    // distroless image has no shell entrypoint to do this, so clusterd does it
204    // itself.
205    if std::env::var("KUBERNETES_SERVICE_HOST").is_ok()
206        && std::env::var("CLUSTERD_PROCESS").is_err()
207    {
208        if let Ok(hostname) = std::env::var("HOSTNAME") {
209            if let Some(ordinal) = process_ordinal_from_hostname(&hostname) {
210                // SAFETY: `set_var` is called before any threads are spawned.
211                // `install_enhanced_handler` above only registers a panic hook.
212                // That hook spawns a thread only on panic, which cannot happen
213                // before this call.
214                unsafe { std::env::set_var("CLUSTERD_PROCESS", ordinal) };
215            }
216        }
217    }
218
219    let args = cli::parse_args(CliConfig {
220        env_prefix: Some("CLUSTERD_"),
221        enable_version_flag: true,
222    });
223
224    let ncpus_useful = usize::max(1, std::cmp::min(num_cpus::get(), num_cpus::get_physical()));
225    let runtime = tokio::runtime::Builder::new_multi_thread()
226        .worker_threads(ncpus_useful)
227        .thread_stack_size(3 * 1024 * 1024) // 3 MiB
228        // The default thread name exceeds the Linux limit on thread name
229        // length, so pick something shorter. The maximum length is 16 including
230        // a \0 terminator. This gives us four decimals, which should be enough
231        // for most existing computers.
232        .thread_name_fn(|| {
233            use std::sync::atomic::{AtomicUsize, Ordering};
234            static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
235            let id = ATOMIC_ID.fetch_add(1, Ordering::Relaxed);
236            format!("tokio:work-{}", id)
237        })
238        .enable_all()
239        .build()
240        .unwrap();
241    if let Err(err) = runtime.block_on(run(args)) {
242        panic!("clusterd: fatal: {}", err.display_with_causes());
243    }
244}
245
246async fn run(args: Args) -> Result<(), anyhow::Error> {
247    let metrics_registry = MetricsRegistry::new();
248    let tracing_handle = args
249        .tracing
250        .configure_tracing(
251            StaticTracingConfig {
252                service_name: "clusterd",
253                build_info: BUILD_INFO,
254            },
255            metrics_registry.clone(),
256        )
257        .await?;
258
259    let tracing_handle = Arc::new(tracing_handle);
260    register_runtime_metrics("main", Handle::current().metrics(), &metrics_registry);
261
262    // Keep this _after_ the mz_ore::tracing::configure call so that its panic
263    // hook runs _before_ the one that sends things to sentry.
264    mz_timely_util::panic::halt_on_timely_communication_panic();
265
266    let _failpoint_scenario = FailScenario::setup();
267
268    emit_boot_diagnostics!(&BUILD_INFO);
269
270    mz_alloc::register_metrics_into(&metrics_registry).await;
271    mz_metrics::register_metrics_into(&metrics_registry, mz_dyncfgs::all_dyncfgs()).await;
272
273    if let Some(heap_limit) = args.heap_limit {
274        mz_compute::memory_limiter::start_limiter(heap_limit, &metrics_registry);
275    } else {
276        info!("no heap limit announced; disabling memory limiter");
277    }
278
279    let secrets_reader = args
280        .secrets
281        .load()
282        .await
283        .context("loading secrets reader")?;
284
285    let usage_collector = Arc::new(usage_metrics::Collector {
286        disk_root: args.scratch_directory.clone(),
287    });
288
289    mz_ore::task::spawn(|| "clusterd_internal_http_server", {
290        let metrics_registry = metrics_registry.clone();
291        tracing::info!(
292            "serving internal HTTP server on {}",
293            args.internal_http_listen_addr
294        );
295        let listener = Listener::bind(args.internal_http_listen_addr).await?;
296        let mut make_service = mz_prof_http::router(&BUILD_INFO)
297            .route(
298                "/api/livez",
299                routing::get(mz_http_util::handle_liveness_check),
300            )
301            .route(
302                "/metrics",
303                routing::get(move |headers: axum::http::HeaderMap| async move {
304                    mz_http_util::handle_prometheus(&metrics_registry, headers).await
305                }),
306            )
307            .route("/api/tracing", routing::get(mz_http_util::handle_tracing))
308            .route(
309                "/api/opentelemetry/config",
310                routing::put({
311                    move |_: axum::Json<DynamicFilterTarget>| async {
312                        (
313                            StatusCode::BAD_REQUEST,
314                            "This endpoint has been replaced. \
315                                Use the `opentelemetry_filter` system variable."
316                                .to_string(),
317                        )
318                    }
319                }),
320            )
321            .route(
322                "/api/stderr/config",
323                routing::put({
324                    move |_: axum::Json<DynamicFilterTarget>| async {
325                        (
326                            StatusCode::BAD_REQUEST,
327                            "This endpoint has been replaced. \
328                                Use the `log_filter` system variable."
329                                .to_string(),
330                        )
331                    }
332                }),
333            )
334            .route(
335                "/api/usage-metrics",
336                routing::get(async move || axum::Json(usage_collector.collect())),
337            )
338            .into_make_service();
339
340        // Once https://github.com/tokio-rs/axum/pull/2479 lands, this can become just a call to
341        // `axum::serve`.
342        async move {
343            loop {
344                let (conn, remote_addr) = match listener.accept().await {
345                    Ok(peer) => peer,
346                    Err(error) => {
347                        // Match hyper's AddrIncoming error handling:
348                        // connection errors are per-connection and can be
349                        // skipped immediately; all other errors (e.g., EMFILE)
350                        // sleep to avoid a tight loop on resource exhaustion.
351                        if is_connection_error(&error) {
352                            debug!("accepted connection already errored: {error:#}");
353                        } else {
354                            error!("internal_http accept error: {error:#}");
355                            tokio::time::sleep(Duration::from_secs(1)).await;
356                        }
357                        continue;
358                    }
359                };
360
361                let tower_service = make_service.call(&conn).await.expect("infallible");
362                let hyper_service =
363                    hyper::service::service_fn(move |req| tower_service.clone().call(req));
364
365                mz_ore::task::spawn(
366                    || format!("clusterd_internal_http_server:{remote_addr}"),
367                    async move {
368                        if let Err(error) = hyper::server::conn::http1::Builder::new()
369                            .serve_connection(TokioIo::new(conn), hyper_service)
370                            .await
371                        {
372                            // This can happen when the client performs an unclean shutdown, so a
373                            // high severity isn't warranted. Might even downgrade this to DEBUG if
374                            // it turns out too noisy.
375                            info!("error serving internal_http connection: {error:#}");
376                        }
377                    },
378                );
379            }
380        }
381    });
382
383    let pubsub_caller_id = std::env::var("HOSTNAME")
384        .ok()
385        .or_else(|| args.tracing.log_prefix.clone())
386        .unwrap_or_default();
387    let mut persist_cfg =
388        PersistConfig::new(&BUILD_INFO, SYSTEM_TIME.clone(), mz_dyncfgs::all_dyncfgs());
389    persist_cfg.is_cc_active = args.is_cc;
390    persist_cfg.announce_memory_limit = args.announce_memory_limit;
391    // Start with compaction disabled, will get enabled once a cluster receives AllowWrites.
392    persist_cfg.disable_compaction();
393
394    let persist_clients = Arc::new(PersistClientCache::new(
395        persist_cfg,
396        &metrics_registry,
397        |persist_cfg, metrics| {
398            let cfg = PersistPubSubClientConfig {
399                url: args.persist_pubsub_url,
400                caller_id: pubsub_caller_id,
401                persist_cfg: persist_cfg.clone(),
402            };
403            GrpcPubSubClient::connect(cfg, metrics)
404        },
405    ));
406    let txns_ctx = TxnsContext::default();
407
408    let connection_context = ConnectionContext::from_cli_args(
409        args.environment_id,
410        &args.tracing.startup_log_filter,
411        args.aws_external_id_prefix,
412        args.aws_connection_role_arn,
413        secrets_reader,
414        None,
415    );
416
417    let grpc_host = args.grpc_host.and_then(|h| (!h.is_empty()).then_some(h));
418    let cluster_server_metrics = ClusterServerMetrics::register_with(&metrics_registry);
419
420    let mut storage_timely_config = args.storage_timely_config;
421    storage_timely_config.process = args.process;
422    let mut compute_timely_config = args.compute_timely_config;
423    compute_timely_config.process = args.process;
424
425    // We assume each storage worker has a corresponding compute worker that can process its logs.
426    assert_eq!(
427        storage_timely_config.workers, compute_timely_config.workers,
428        "storage and compute must have equal workers-per-process",
429    );
430
431    // Create per-worker bridges for forwarding storage timely logging events to compute.
432    let (storage_log_writers, storage_log_readers) = if args.enable_storage_introspection_logs {
433        (0..storage_timely_config.workers)
434            .map(|_| arc_event_link())
435            .unzip()
436    } else {
437        (Vec::new(), Vec::new())
438    };
439
440    // Start storage server.
441    let storage_client_builder = mz_storage::serve(
442        storage_timely_config,
443        &metrics_registry,
444        Arc::clone(&persist_clients),
445        txns_ctx.clone(),
446        Arc::clone(&tracing_handle),
447        SYSTEM_TIME.clone(),
448        connection_context.clone(),
449        StorageInstanceContext::new(args.scratch_directory.clone(), args.announce_memory_limit),
450        storage_log_writers,
451    )
452    .await?;
453    info!(
454        "listening for storage controller connections on {}",
455        args.storage_controller_listen_addr
456    );
457    mz_ore::task::spawn(
458        || "storage_server",
459        transport::serve(
460            args.storage_controller_listen_addr,
461            BUILD_INFO.semver_version(),
462            grpc_host.clone(),
463            Duration::MAX,
464            storage_client_builder,
465            cluster_server_metrics.for_server("storage"),
466        )
467        .instrument(info_span!("ctp", name = "storage")),
468    );
469
470    // Start compute server.
471    let compute_client_builder = mz_compute::server::serve(
472        compute_timely_config,
473        &metrics_registry,
474        persist_clients,
475        txns_ctx,
476        tracing_handle,
477        ComputeInstanceContext {
478            scratch_directory: args.scratch_directory,
479            worker_core_affinity: args.worker_core_affinity,
480            connection_context,
481        },
482        storage_log_readers,
483    )
484    .await?;
485    info!(
486        "listening for compute controller connections on {}",
487        args.compute_controller_listen_addr
488    );
489    mz_ore::task::spawn(
490        || "compute_server",
491        transport::serve(
492            args.compute_controller_listen_addr,
493            BUILD_INFO.semver_version(),
494            grpc_host.clone(),
495            Duration::MAX,
496            compute_client_builder,
497            cluster_server_metrics.for_server("compute"),
498        )
499        .instrument(info_span!("ctp", name = "compute")),
500    );
501
502    // TODO: unify storage and compute servers to use one timely cluster.
503
504    // Block forever.
505    future::pending().await
506}
507
508/// Per-connection errors from `accept()` that can be skipped immediately.
509/// All other errors (e.g., EMFILE/ENFILE resource exhaustion) warrant a sleep
510/// before retrying. Mirrors hyper's `AddrIncoming` classification.
511fn is_connection_error(e: &std::io::Error) -> bool {
512    matches!(
513        e.kind(),
514        std::io::ErrorKind::ConnectionRefused
515            | std::io::ErrorKind::ConnectionAborted
516            | std::io::ErrorKind::ConnectionReset
517    )
518}
519
520#[cfg(test)]
521mod tests {
522    use super::*;
523
524    #[mz_ore::test]
525    fn test_process_ordinal_from_hostname() {
526        // A StatefulSet pod name ends in the process ordinal.
527        assert_eq!(
528            process_ordinal_from_hostname("mz5ncn-cluster-s1-replica-s1-gen-1-0"),
529            Some("0")
530        );
531        assert_eq!(
532            process_ordinal_from_hostname("mz5ncn-cluster-s1-replica-s1-gen-1-11"),
533            Some("11")
534        );
535        // A bare numeric hostname is its own ordinal.
536        assert_eq!(process_ordinal_from_hostname("7"), Some("7"));
537
538        // A trailing segment that is not a non-negative integer yields `None`,
539        // so `CLUSTERD_PROCESS` stays unset rather than being set to a value
540        // that fails to parse as the process index.
541        assert_eq!(process_ordinal_from_hostname("clusterd"), None);
542        assert_eq!(process_ordinal_from_hostname("replica-abc"), None);
543        assert_eq!(process_ordinal_from_hostname("replica-"), None);
544        assert_eq!(process_ordinal_from_hostname(""), None);
545    }
546}