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