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;
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#[derive(clap::Parser)]
55#[clap(name = "clusterd", version = VERSION.as_str())]
56struct Args {
57 #[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 #[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 #[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 #[clap(long, env = "GRPC_HOST", value_name = "NAME")]
89 grpc_host: Option<String>,
90
91 #[clap(long, env = "STORAGE_TIMELY_CONFIG")]
94 storage_timely_config: TimelyConfig,
95 #[clap(long, env = "COMPUTE_TIMELY_CONFIG")]
97 compute_timely_config: TimelyConfig,
98 #[clap(long, env = "PROCESS")]
100 process: usize,
101
102 #[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 #[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 #[clap(long, env = "AWS_CONNECTION_ROLE_ARN")]
122 aws_connection_role_arn: Option<String>,
123
124 #[clap(flatten)]
126 secrets: SecretsReaderCliArgs,
127
128 #[clap(flatten)]
130 tracing: TracingCliArgs,
131
132 #[clap(long, env = "ENVIRONMENT_ID")]
136 environment_id: String,
137
138 #[clap(long, env = "SCRATCH_DIRECTORY", value_name = "PATH")]
140 scratch_directory: Option<PathBuf>,
141
142 #[clap(long)]
147 announce_memory_limit: Option<usize>,
148
149 #[clap(long)]
156 heap_limit: Option<usize>,
157
158 #[clap(long)]
161 is_cc: bool,
162
163 #[clap(long)]
169 worker_core_affinity: bool,
170
171 #[clap(long)]
174 enable_storage_introspection_logs: bool,
175}
176
177fn 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 let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
200
201 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 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) .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 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 async move {
343 loop {
344 let (conn, remote_addr) = match listener.accept().await {
345 Ok(peer) => peer,
346 Err(error) => {
347 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 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 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 assert_eq!(
427 storage_timely_config.workers, compute_timely_config.workers,
428 "storage and compute must have equal workers-per-process",
429 );
430
431 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 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 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 future::pending().await
506}
507
508fn 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 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 assert_eq!(process_ordinal_from_hostname("7"), Some("7"));
537
538 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}