1use 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#[derive(clap::Parser)]
54#[clap(name = "clusterd", version = VERSION.as_str())]
55struct Args {
56 #[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 #[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 #[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 #[clap(long, env = "GRPC_HOST", value_name = "NAME")]
88 grpc_host: Option<String>,
89
90 #[clap(long, env = "STORAGE_TIMELY_CONFIG")]
93 storage_timely_config: TimelyConfig,
94 #[clap(long, env = "COMPUTE_TIMELY_CONFIG")]
96 compute_timely_config: TimelyConfig,
97 #[clap(long, env = "PROCESS")]
99 process: usize,
100
101 #[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 #[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 #[clap(long, env = "AWS_CONNECTION_ROLE_ARN")]
121 aws_connection_role_arn: Option<String>,
122
123 #[clap(flatten)]
125 secrets: SecretsReaderCliArgs,
126
127 #[clap(flatten)]
129 tracing: TracingCliArgs,
130
131 #[clap(long, env = "ENVIRONMENT_ID")]
135 environment_id: String,
136
137 #[clap(long, env = "SCRATCH_DIRECTORY", value_name = "PATH")]
139 scratch_directory: Option<PathBuf>,
140
141 #[clap(long, env = "ADDITIONAL_TRUST_BUNDLE", value_name = "PATH")]
144 additional_trust_bundle: Option<PathBuf>,
145
146 #[clap(long)]
148 no_swap: bool,
149
150 #[clap(long)]
155 announce_memory_limit: Option<usize>,
156
157 #[clap(long)]
164 heap_limit: Option<usize>,
165
166 #[clap(long)]
169 is_cc: bool,
170
171 #[clap(long)]
177 worker_core_affinity: bool,
178
179 #[clap(long, env = "UNIFIED_CLUSTER")]
183 unified_cluster: bool,
184}
185
186fn 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 let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
209
210 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 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 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) .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 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 async move {
366 loop {
367 let (conn, remote_addr) = match listener.accept().await {
368 Ok(peer) => peer,
369 Err(error) => {
370 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 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 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 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 return future::pending().await;
516 }
517
518 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 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 future::pending().await
588}
589
590fn 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 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 assert_eq!(process_ordinal_from_hostname("7"), Some("7"));
619
620 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}