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    /// Memory limit (bytes) of the cluster replica, if known.
142    ///
143    /// The limit is expected to be enforced by the orchestrator. The clusterd process only uses it
144    /// to inform configuration of backpressure mechanism.
145    #[clap(long)]
146    announce_memory_limit: Option<usize>,
147
148    /// Heap limit (bytes) of the cluster replica.
149    ///
150    /// A process heap usage is calculated as the sum of its memory and swap usage.
151    ///
152    /// In contrast to `announce_memory_limit`, this limit is enforced by the clusterd process. If
153    /// the limit is exceeded, the process terminates itself with a 167 exit code.
154    #[clap(long)]
155    heap_limit: Option<usize>,
156
157    /// Whether this size represents a modern "cc" size rather than a legacy
158    /// T-shirt size.
159    #[clap(long)]
160    is_cc: bool,
161
162    /// Set core affinity for Timely workers.
163    ///
164    /// This flag should only be set if the process is provided with exclusive access to its
165    /// supplied CPU cores. If other processes are competing over the same cores, setting core
166    /// affinity might degrade dataflow performance rather than improving it.
167    #[clap(long)]
168    worker_core_affinity: bool,
169
170    /// Host storage objects on the compute Timely cluster instead of building a separate
171    /// storage Timely cluster. The storage and compute controller protocols are served
172    /// unchanged, from the same cluster.
173    #[clap(long, env = "UNIFIED_CLUSTER")]
174    unified_cluster: 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(
272        &metrics_registry,
273        mz_dyncfgs::all_dyncfgs(),
274        args.scratch_directory.clone(),
275    )
276    .await;
277
278    if let Some(heap_limit) = args.heap_limit {
279        mz_compute::memory_limiter::start_limiter(heap_limit, &metrics_registry);
280    } else {
281        info!("no heap limit announced; disabling memory limiter");
282    }
283
284    let secrets_reader = mz_secrets_loader::load(args.secrets)
285        .await
286        .context("loading secrets reader")?;
287
288    let usage_collector = Arc::new(usage_metrics::Collector {
289        disk_root: args.scratch_directory.clone(),
290    });
291
292    mz_ore::task::spawn(|| "clusterd_internal_http_server", {
293        let metrics_registry = metrics_registry.clone();
294        tracing::info!(
295            "serving internal HTTP server on {}",
296            args.internal_http_listen_addr
297        );
298        let listener = Listener::bind(args.internal_http_listen_addr).await?;
299        let mut make_service = mz_prof_http::router(&BUILD_INFO)
300            .route(
301                "/api/livez",
302                routing::get(mz_http_util::handle_liveness_check),
303            )
304            .route(
305                "/metrics",
306                routing::get(move |headers: axum::http::HeaderMap| async move {
307                    mz_http_util::handle_prometheus(&metrics_registry, headers).await
308                }),
309            )
310            .route("/api/tracing", routing::get(mz_http_util::handle_tracing))
311            .route(
312                "/api/opentelemetry/config",
313                routing::put({
314                    move |_: axum::Json<DynamicFilterTarget>| async {
315                        (
316                            StatusCode::BAD_REQUEST,
317                            "This endpoint has been replaced. \
318                                Use the `opentelemetry_filter` system variable."
319                                .to_string(),
320                        )
321                    }
322                }),
323            )
324            .route(
325                "/api/stderr/config",
326                routing::put({
327                    move |_: axum::Json<DynamicFilterTarget>| async {
328                        (
329                            StatusCode::BAD_REQUEST,
330                            "This endpoint has been replaced. \
331                                Use the `log_filter` system variable."
332                                .to_string(),
333                        )
334                    }
335                }),
336            )
337            .route(
338                "/api/usage-metrics",
339                routing::get(async move || axum::Json(usage_collector.collect())),
340            )
341            .into_make_service();
342
343        // Once https://github.com/tokio-rs/axum/pull/2479 lands, this can become just a call to
344        // `axum::serve`.
345        async move {
346            loop {
347                let (conn, remote_addr) = match listener.accept().await {
348                    Ok(peer) => peer,
349                    Err(error) => {
350                        // Match hyper's AddrIncoming error handling:
351                        // connection errors are per-connection and can be
352                        // skipped immediately; all other errors (e.g., EMFILE)
353                        // sleep to avoid a tight loop on resource exhaustion.
354                        if is_connection_error(&error) {
355                            debug!("accepted connection already errored: {error:#}");
356                        } else {
357                            error!("internal_http accept error: {error:#}");
358                            tokio::time::sleep(Duration::from_secs(1)).await;
359                        }
360                        continue;
361                    }
362                };
363
364                let tower_service = make_service.call(&conn).await.expect("infallible");
365                let hyper_service =
366                    hyper::service::service_fn(move |req| tower_service.clone().call(req));
367
368                mz_ore::task::spawn(
369                    || format!("clusterd_internal_http_server:{remote_addr}"),
370                    async move {
371                        if let Err(error) = hyper::server::conn::http1::Builder::new()
372                            .serve_connection(TokioIo::new(conn), hyper_service)
373                            .await
374                        {
375                            // This can happen when the client performs an unclean shutdown, so a
376                            // high severity isn't warranted. Might even downgrade this to DEBUG if
377                            // it turns out too noisy.
378                            info!("error serving internal_http connection: {error:#}");
379                        }
380                    },
381                );
382            }
383        }
384    });
385
386    let pubsub_caller_id = std::env::var("HOSTNAME")
387        .ok()
388        .or_else(|| args.tracing.log_prefix.clone())
389        .unwrap_or_default();
390    let mut persist_cfg =
391        PersistConfig::new(&BUILD_INFO, SYSTEM_TIME.clone(), mz_dyncfgs::all_dyncfgs());
392    persist_cfg.is_cc_active = args.is_cc;
393    persist_cfg.announce_memory_limit = args.announce_memory_limit;
394    // Start with compaction disabled, will get enabled once a cluster receives AllowWrites.
395    persist_cfg.disable_compaction();
396
397    let persist_clients = Arc::new(PersistClientCache::new(
398        persist_cfg,
399        &metrics_registry,
400        |persist_cfg, metrics| {
401            let cfg = PersistPubSubClientConfig {
402                url: args.persist_pubsub_url,
403                caller_id: pubsub_caller_id,
404                persist_cfg: persist_cfg.clone(),
405            };
406            GrpcPubSubClient::connect(cfg, metrics)
407        },
408    ));
409    let txns_ctx = TxnsContext::default();
410
411    let connection_context = ConnectionContext::from_cli_args(
412        args.environment_id,
413        &args.tracing.startup_log_filter,
414        args.aws_external_id_prefix,
415        args.aws_connection_role_arn,
416        secrets_reader,
417        None,
418    );
419
420    let grpc_host = args.grpc_host.and_then(|h| (!h.is_empty()).then_some(h));
421    let cluster_server_metrics = ClusterServerMetrics::register_with(&metrics_registry);
422
423    let mut storage_timely_config = args.storage_timely_config;
424    storage_timely_config.process = args.process;
425    let mut compute_timely_config = args.compute_timely_config;
426    compute_timely_config.process = args.process;
427
428    // We assume each storage worker has a corresponding compute worker that can process its logs.
429    assert_eq!(
430        storage_timely_config.workers, compute_timely_config.workers,
431        "storage and compute must have equal workers-per-process",
432    );
433
434    if args.unified_cluster {
435        info!("running with a unified timely cluster");
436
437        let (compute_client_builder, storage_client_builder) = mz_compute::server::serve_unified(
438            compute_timely_config,
439            ComputeRuntimeRole::Solo,
440            &metrics_registry,
441            persist_clients,
442            txns_ctx,
443            tracing_handle,
444            ComputeInstanceContext {
445                scratch_directory: args.scratch_directory.clone(),
446                worker_core_affinity: args.worker_core_affinity,
447                connection_context: connection_context.clone(),
448            },
449            SYSTEM_TIME.clone(),
450            connection_context,
451            StorageInstanceContext::new(args.scratch_directory, args.announce_memory_limit),
452        )
453        .await?;
454
455        info!(
456            "listening for storage controller connections on {}",
457            args.storage_controller_listen_addr
458        );
459        mz_ore::task::spawn(
460            || "storage_server",
461            transport::serve(
462                args.storage_controller_listen_addr,
463                BUILD_INFO.semver_version(),
464                grpc_host.clone(),
465                Duration::MAX,
466                storage_client_builder,
467                cluster_server_metrics.for_server("storage"),
468            )
469            .instrument(info_span!("ctp", name = "storage")),
470        );
471
472        info!(
473            "listening for compute controller connections on {}",
474            args.compute_controller_listen_addr
475        );
476        mz_ore::task::spawn(
477            || "compute_server",
478            transport::serve(
479                args.compute_controller_listen_addr,
480                BUILD_INFO.semver_version(),
481                grpc_host,
482                Duration::MAX,
483                compute_client_builder,
484                cluster_server_metrics.for_server("compute"),
485            )
486            .instrument(info_span!("ctp", name = "compute")),
487        );
488
489        // Block forever.
490        return future::pending().await;
491    }
492
493    // Start storage server.
494    let storage_client_builder = mz_storage::serve(
495        storage_timely_config,
496        &metrics_registry,
497        Arc::clone(&persist_clients),
498        txns_ctx.clone(),
499        Arc::clone(&tracing_handle),
500        SYSTEM_TIME.clone(),
501        connection_context.clone(),
502        StorageInstanceContext::new(args.scratch_directory.clone(), args.announce_memory_limit),
503    )
504    .await?;
505    info!(
506        "listening for storage controller connections on {}",
507        args.storage_controller_listen_addr
508    );
509    mz_ore::task::spawn(
510        || "storage_server",
511        transport::serve(
512            args.storage_controller_listen_addr,
513            BUILD_INFO.semver_version(),
514            grpc_host.clone(),
515            Duration::MAX,
516            storage_client_builder,
517            cluster_server_metrics.for_server("storage"),
518        )
519        .instrument(info_span!("ctp", name = "storage")),
520    );
521
522    // Start compute server.
523    let compute_client_builder = mz_compute::server::serve(
524        compute_timely_config,
525        ComputeRuntimeRole::Solo,
526        &metrics_registry,
527        persist_clients,
528        txns_ctx,
529        tracing_handle,
530        ComputeInstanceContext {
531            scratch_directory: args.scratch_directory,
532            worker_core_affinity: args.worker_core_affinity,
533            connection_context,
534        },
535    )
536    .await?;
537    info!(
538        "listening for compute controller connections on {}",
539        args.compute_controller_listen_addr
540    );
541    mz_ore::task::spawn(
542        || "compute_server",
543        transport::serve(
544            args.compute_controller_listen_addr,
545            BUILD_INFO.semver_version(),
546            grpc_host.clone(),
547            Duration::MAX,
548            compute_client_builder,
549            cluster_server_metrics.for_server("compute"),
550        )
551        .instrument(info_span!("ctp", name = "compute")),
552    );
553
554    // TODO: retire this two-cluster topology once the unified cluster has production mileage.
555
556    // Block forever.
557    future::pending().await
558}
559
560/// Per-connection errors from `accept()` that can be skipped immediately.
561/// All other errors (e.g., EMFILE/ENFILE resource exhaustion) warrant a sleep
562/// before retrying. Mirrors hyper's `AddrIncoming` classification.
563fn is_connection_error(e: &std::io::Error) -> bool {
564    matches!(
565        e.kind(),
566        std::io::ErrorKind::ConnectionRefused
567            | std::io::ErrorKind::ConnectionAborted
568            | std::io::ErrorKind::ConnectionReset
569    )
570}
571
572#[cfg(test)]
573mod tests {
574    use super::*;
575
576    #[mz_ore::test]
577    fn test_process_ordinal_from_hostname() {
578        // A StatefulSet pod name ends in the process ordinal.
579        assert_eq!(
580            process_ordinal_from_hostname("mz5ncn-cluster-s1-replica-s1-gen-1-0"),
581            Some("0")
582        );
583        assert_eq!(
584            process_ordinal_from_hostname("mz5ncn-cluster-s1-replica-s1-gen-1-11"),
585            Some("11")
586        );
587        // A bare numeric hostname is its own ordinal.
588        assert_eq!(process_ordinal_from_hostname("7"), Some("7"));
589
590        // A trailing segment that is not a non-negative integer yields `None`,
591        // so `CLUSTERD_PROCESS` stays unset rather than being set to a value
592        // that fails to parse as the process index.
593        assert_eq!(process_ordinal_from_hostname("clusterd"), None);
594        assert_eq!(process_ordinal_from_hostname("replica-abc"), None);
595        assert_eq!(process_ordinal_from_hostname("replica-"), None);
596        assert_eq!(process_ordinal_from_hostname(""), None);
597    }
598}