LCOV - code coverage report
Current view: top level - safekeeper/src/bin - safekeeper.rs (source / functions) Coverage Total Hit
Test: 4be46b1c0003aa3bbac9ade362c676b419df4c20.info Lines: 0.8 % 391 3
Test Date: 2025-07-22 17:50:06 Functions: 2.4 % 41 1

            Line data    Source code
       1              : //
       2              : // Main entry point for the safekeeper executable
       3              : //
       4              : use std::fs::{self, File};
       5              : use std::io::{ErrorKind, Write};
       6              : use std::str::FromStr;
       7              : use std::sync::Arc;
       8              : use std::time::{Duration, Instant};
       9              : 
      10              : use anyhow::{Context, Result, bail};
      11              : use camino::{Utf8Path, Utf8PathBuf};
      12              : use clap::{ArgAction, Parser};
      13              : use futures::future::BoxFuture;
      14              : use futures::stream::FuturesUnordered;
      15              : use futures::{FutureExt, StreamExt};
      16              : use http_utils::tls_certs::ReloadingCertificateResolver;
      17              : use metrics::set_build_info_metric;
      18              : use remote_storage::RemoteStorageConfig;
      19              : use safekeeper::defaults::{
      20              :     DEFAULT_CONTROL_FILE_SAVE_INTERVAL, DEFAULT_EVICTION_MIN_RESIDENT,
      21              :     DEFAULT_GLOBAL_DISK_CHECK_INTERVAL, DEFAULT_HEARTBEAT_TIMEOUT, DEFAULT_HTTP_LISTEN_ADDR,
      22              :     DEFAULT_MAX_GLOBAL_DISK_USAGE_RATIO, DEFAULT_MAX_OFFLOADER_LAG_BYTES,
      23              :     DEFAULT_MAX_REELECT_OFFLOADER_LAG_BYTES, DEFAULT_MAX_TIMELINE_DISK_USAGE_BYTES,
      24              :     DEFAULT_PARTIAL_BACKUP_CONCURRENCY, DEFAULT_PARTIAL_BACKUP_TIMEOUT, DEFAULT_PG_LISTEN_ADDR,
      25              :     DEFAULT_SSL_CERT_FILE, DEFAULT_SSL_CERT_RELOAD_PERIOD, DEFAULT_SSL_KEY_FILE,
      26              : };
      27              : use safekeeper::hadron;
      28              : use safekeeper::wal_backup::WalBackup;
      29              : use safekeeper::{
      30              :     BACKGROUND_RUNTIME, BROKER_RUNTIME, GlobalTimelines, HTTP_RUNTIME, SafeKeeperConf,
      31              :     WAL_SERVICE_RUNTIME, broker, control_file, http, wal_service,
      32              : };
      33              : use sd_notify::NotifyState;
      34              : use storage_broker::{DEFAULT_ENDPOINT, Uri};
      35              : use tokio::runtime::Handle;
      36              : use tokio::signal::unix::{SignalKind, signal};
      37              : use tokio::task::JoinError;
      38              : use tracing::*;
      39              : use utils::auth::{JwtAuth, Scope, SwappableJwtAuth};
      40              : use utils::id::NodeId;
      41              : use utils::logging::{self, LogFormat, SecretString};
      42              : use utils::metrics_collector::{METRICS_COLLECTION_INTERVAL, METRICS_COLLECTOR};
      43              : use utils::sentry_init::init_sentry;
      44              : use utils::{pid_file, project_build_tag, project_git_version, tcp_listener};
      45              : 
      46              : use safekeeper::hadron::{
      47              :     GLOBAL_DISK_LIMIT_EXCEEDED, get_filesystem_capacity, get_filesystem_usage,
      48              : };
      49              : use safekeeper::metrics::GLOBAL_DISK_UTIL_CHECK_SECONDS;
      50              : use std::sync::atomic::Ordering;
      51              : 
      52              : #[global_allocator]
      53              : static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
      54              : 
      55              : /// Configure jemalloc to profile heap allocations by sampling stack traces every 2 MB (1 << 21).
      56              : /// This adds roughly 3% overhead for allocations on average, which is acceptable considering
      57              : /// performance-sensitive code will avoid allocations as far as possible anyway.
      58              : #[allow(non_upper_case_globals)]
      59              : #[unsafe(export_name = "malloc_conf")]
      60              : pub static malloc_conf: &[u8] = b"prof:true,prof_active:true,lg_prof_sample:21\0";
      61              : 
      62              : const PID_FILE_NAME: &str = "safekeeper.pid";
      63              : const ID_FILE_NAME: &str = "safekeeper.id";
      64              : 
      65              : project_git_version!(GIT_VERSION);
      66              : project_build_tag!(BUILD_TAG);
      67              : 
      68              : const FEATURES: &[&str] = &[
      69              :     #[cfg(feature = "testing")]
      70              :     "testing",
      71              : ];
      72              : 
      73            0 : fn version() -> String {
      74            0 :     format!(
      75            0 :         "{GIT_VERSION} failpoints: {}, features: {:?}",
      76            0 :         fail::has_failpoints(),
      77              :         FEATURES,
      78              :     )
      79            0 : }
      80              : 
      81              : const ABOUT: &str = r#"
      82              : A fleet of safekeepers is responsible for reliably storing WAL received from
      83              : compute, passing it through consensus (mitigating potential computes brain
      84              : split), and serving the hardened part further downstream to pageserver(s).
      85              : "#;
      86              : 
      87              : #[derive(Parser)]
      88              : #[command(name = "Neon safekeeper", version = GIT_VERSION, about = ABOUT, long_about = None)]
      89              : struct Args {
      90              :     /// Path to the safekeeper data directory.
      91              :     #[arg(short = 'D', long, default_value = "./")]
      92              :     datadir: Utf8PathBuf,
      93              :     /// Safekeeper node id.
      94              :     #[arg(long)]
      95              :     id: Option<u64>,
      96              :     /// Initialize safekeeper with given id and exit.
      97              :     #[arg(long)]
      98              :     init: bool,
      99              :     /// Listen endpoint for receiving/sending WAL in the form host:port.
     100              :     #[arg(short, long, default_value = DEFAULT_PG_LISTEN_ADDR)]
     101              :     listen_pg: String,
     102              :     /// Listen endpoint for receiving/sending WAL in the form host:port allowing
     103              :     /// only tenant scoped auth tokens. Pointless if auth is disabled.
     104              :     #[arg(long, default_value = None, verbatim_doc_comment)]
     105              :     listen_pg_tenant_only: Option<String>,
     106              :     /// Listen http endpoint for management and metrics in the form host:port.
     107              :     #[arg(long, default_value = DEFAULT_HTTP_LISTEN_ADDR)]
     108              :     listen_http: String,
     109              :     /// Listen https endpoint for management and metrics in the form host:port.
     110              :     #[arg(long, default_value = None)]
     111              :     listen_https: Option<String>,
     112              :     /// Advertised endpoint for receiving/sending WAL in the form host:port. If not
     113              :     /// specified, listen_pg is used to advertise instead.
     114              :     #[arg(long, default_value = None)]
     115              :     advertise_pg: Option<String>,
     116              :     /// Availability zone of the safekeeper.
     117              :     #[arg(long)]
     118              :     availability_zone: Option<String>,
     119              :     /// Do not wait for changes to be written safely to disk. Unsafe.
     120              :     #[arg(short, long)]
     121              :     no_sync: bool,
     122              :     /// Dump control file at path specified by this argument and exit.
     123              :     #[arg(long)]
     124              :     dump_control_file: Option<Utf8PathBuf>,
     125              :     /// Broker endpoint for storage nodes coordination in the form
     126              :     /// http[s]://host:port. In case of https schema TLS is connection is
     127              :     /// established; plaintext otherwise.
     128              :     #[arg(long, default_value = DEFAULT_ENDPOINT, verbatim_doc_comment)]
     129              :     broker_endpoint: Uri,
     130              :     /// Broker keepalive interval.
     131              :     #[arg(long, value_parser= humantime::parse_duration, default_value = storage_broker::DEFAULT_KEEPALIVE_INTERVAL)]
     132              :     broker_keepalive_interval: Duration,
     133              :     /// Peer safekeeper is considered dead after not receiving heartbeats from
     134              :     /// it during this period passed as a human readable duration.
     135              :     #[arg(long, value_parser= humantime::parse_duration, default_value = DEFAULT_HEARTBEAT_TIMEOUT, verbatim_doc_comment)]
     136              :     heartbeat_timeout: Duration,
     137              :     /// Enable/disable peer recovery.
     138              :     #[arg(long, default_value = "false", action=ArgAction::Set)]
     139              :     peer_recovery: bool,
     140              :     /// Remote storage configuration for WAL backup (offloading to s3) as TOML
     141              :     /// inline table, e.g.
     142              :     ///   {max_concurrent_syncs = 17, max_sync_errors = 13, bucket_name = "<BUCKETNAME>", bucket_region = "<REGION>", concurrency_limit = 119}
     143              :     /// Safekeeper offloads WAL to
     144              :     ///   [prefix_in_bucket/]<tenant_id>/<timeline_id>/<segment_file>, mirroring
     145              :     /// structure on the file system.
     146              :     #[arg(long, value_parser = parse_remote_storage, verbatim_doc_comment)]
     147              :     remote_storage: Option<RemoteStorageConfig>,
     148              :     /// Safekeeper won't be elected for WAL offloading if it is lagging for more than this value in bytes
     149              :     #[arg(long, default_value_t = DEFAULT_MAX_OFFLOADER_LAG_BYTES)]
     150              :     max_offloader_lag: u64,
     151              :     /* BEGIN_HADRON */
     152              :     /// Safekeeper will re-elect a new offloader if the current backup lagging for more than this value in bytes
     153              :     #[arg(long, default_value_t = DEFAULT_MAX_REELECT_OFFLOADER_LAG_BYTES)]
     154              :     max_reelect_offloader_lag_bytes: u64,
     155              :     /// Safekeeper will stop accepting new WALs if the timeline disk usage exceeds this value in bytes.
     156              :     /// Setting this value to 0 disables the limit.
     157              :     #[arg(long, default_value_t = DEFAULT_MAX_TIMELINE_DISK_USAGE_BYTES)]
     158              :     max_timeline_disk_usage_bytes: u64,
     159              :     /* END_HADRON */
     160              :     /// Number of max parallel WAL segments to be offloaded to remote storage.
     161              :     #[arg(long, default_value = "5")]
     162              :     wal_backup_parallel_jobs: usize,
     163              :     /// Disable WAL backup to s3. When disabled, safekeeper removes WAL ignoring
     164              :     /// WAL backup horizon.
     165              :     #[arg(long)]
     166              :     disable_wal_backup: bool,
     167              :     /// If given, enables auth on incoming connections to WAL service endpoint
     168              :     /// (--listen-pg). Value specifies path to a .pem public key used for
     169              :     /// validations of JWT tokens. Empty string is allowed and means disabling
     170              :     /// auth.
     171              :     #[arg(long, verbatim_doc_comment, value_parser = opt_pathbuf_parser)]
     172              :     pg_auth_public_key_path: Option<Utf8PathBuf>,
     173              :     /// If given, enables auth on incoming connections to tenant only WAL
     174              :     /// service endpoint (--listen-pg-tenant-only). Value specifies path to a
     175              :     /// .pem public key used for validations of JWT tokens. Empty string is
     176              :     /// allowed and means disabling auth.
     177              :     #[arg(long, verbatim_doc_comment, value_parser = opt_pathbuf_parser)]
     178              :     pg_tenant_only_auth_public_key_path: Option<Utf8PathBuf>,
     179              :     /// If given, enables auth on incoming connections to http management
     180              :     /// service endpoint (--listen-http). Value specifies path to a .pem public
     181              :     /// key used for validations of JWT tokens. Empty string is allowed and
     182              :     /// means disabling auth.
     183              :     #[arg(long, verbatim_doc_comment, value_parser = opt_pathbuf_parser)]
     184              :     http_auth_public_key_path: Option<Utf8PathBuf>,
     185              :     /// Format for logging, either 'plain' or 'json'.
     186              :     #[arg(long, default_value = "plain")]
     187              :     log_format: String,
     188              :     /// Run everything in single threaded current thread runtime, might be
     189              :     /// useful for debugging.
     190              :     #[arg(long)]
     191              :     current_thread_runtime: bool,
     192              :     /// Keep horizon for walsenders, i.e. don't remove WAL segments that are
     193              :     /// still needed for existing replication connection.
     194              :     #[arg(long)]
     195              :     walsenders_keep_horizon: bool,
     196              :     /// Controls how long backup will wait until uploading the partial segment.
     197              :     #[arg(long, value_parser = humantime::parse_duration, default_value = DEFAULT_PARTIAL_BACKUP_TIMEOUT, verbatim_doc_comment)]
     198              :     partial_backup_timeout: Duration,
     199              :     /// Disable task to push messages to broker every second. Supposed to
     200              :     /// be used in tests.
     201              :     #[arg(long)]
     202              :     disable_periodic_broker_push: bool,
     203              :     /// Enable automatic switching to offloaded state.
     204              :     #[arg(long)]
     205              :     enable_offload: bool,
     206              :     /// Delete local WAL files after offloading. When disabled, they will be left on disk.
     207              :     #[arg(long)]
     208              :     delete_offloaded_wal: bool,
     209              :     /// Pending updates to control file will be automatically saved after this interval.
     210              :     #[arg(long, value_parser = humantime::parse_duration, default_value = DEFAULT_CONTROL_FILE_SAVE_INTERVAL)]
     211              :     control_file_save_interval: Duration,
     212              :     /// Number of allowed concurrent uploads of partial segments to remote storage.
     213              :     #[arg(long, default_value = DEFAULT_PARTIAL_BACKUP_CONCURRENCY)]
     214              :     partial_backup_concurrency: usize,
     215              :     /// How long a timeline must be resident before it is eligible for eviction.
     216              :     /// Usually, timeline eviction has to wait for `partial_backup_timeout` before being eligible for eviction,
     217              :     /// but if a timeline is un-evicted and then _not_ written to, it would immediately flap to evicting again,
     218              :     /// if it weren't for `eviction_min_resident` preventing that.
     219              :     ///
     220              :     /// Also defines interval for eviction retries.
     221              :     #[arg(long, value_parser = humantime::parse_duration, default_value = DEFAULT_EVICTION_MIN_RESIDENT)]
     222              :     eviction_min_resident: Duration,
     223              :     /// Enable fanning out WAL to different shards from the same reader
     224              :     #[arg(long)]
     225              :     wal_reader_fanout: bool,
     226              :     /// Only fan out the WAL reader if the absoulte delta between the new requested position
     227              :     /// and the current position of the reader is smaller than this value.
     228              :     #[arg(long)]
     229              :     max_delta_for_fanout: Option<u64>,
     230              :     /// Path to a file with certificate's private key for https API.
     231              :     #[arg(long, default_value = DEFAULT_SSL_KEY_FILE)]
     232              :     ssl_key_file: Utf8PathBuf,
     233              :     /// Path to a file with a X509 certificate for https API.
     234              :     #[arg(long, default_value = DEFAULT_SSL_CERT_FILE)]
     235              :     ssl_cert_file: Utf8PathBuf,
     236              :     /// Period to reload certificate and private key from files.
     237              :     #[arg(long, value_parser = humantime::parse_duration, default_value = DEFAULT_SSL_CERT_RELOAD_PERIOD)]
     238              :     ssl_cert_reload_period: Duration,
     239              :     /// Trusted root CA certificates to use in https APIs.
     240              :     #[arg(long)]
     241              :     ssl_ca_file: Option<Utf8PathBuf>,
     242              :     /// Flag to use https for requests to peer's safekeeper API.
     243              :     #[arg(long)]
     244              :     use_https_safekeeper_api: bool,
     245              :     /// Path to the JWT auth token used to authenticate with other safekeepers.
     246              :     #[arg(long)]
     247              :     auth_token_path: Option<Utf8PathBuf>,
     248              : 
     249              :     /// Enable TLS in WAL service API.
     250              :     /// Does not force TLS: the client negotiates TLS usage during the handshake.
     251              :     /// Uses key and certificate from ssl_key_file/ssl_cert_file.
     252              :     #[arg(long)]
     253              :     enable_tls_wal_service_api: bool,
     254              : 
     255              :     /// Controls whether to collect all metrics on each scrape or to return potentially stale
     256              :     /// results.
     257              :     #[arg(long, default_value_t = true)]
     258              :     force_metric_collection_on_scrape: bool,
     259              : 
     260              :     /// Run in development mode (disables security checks)
     261              :     #[arg(long, help = "Run in development mode (disables security checks)")]
     262              :     dev: bool,
     263              :     /* BEGIN_HADRON */
     264              :     #[arg(long)]
     265              :     enable_pull_timeline_on_startup: bool,
     266              :     /// How often to scan entire data-dir for total disk usage
     267              :     #[arg(long, value_parser=humantime::parse_duration, default_value = DEFAULT_GLOBAL_DISK_CHECK_INTERVAL)]
     268              :     global_disk_check_interval: Duration,
     269              :     /// The portion of the filesystem capacity that can be used by all timelines.
     270              :     /// A circuit breaker will trip and reject all WAL writes if the total usage
     271              :     /// exceeds this ratio.
     272              :     /// Set to 0 to disable the global disk usage limit.
     273              :     #[arg(long, default_value_t = DEFAULT_MAX_GLOBAL_DISK_USAGE_RATIO)]
     274              :     max_global_disk_usage_ratio: f64,
     275              :     /* END_HADRON */
     276              : }
     277              : 
     278              : // Like PathBufValueParser, but allows empty string.
     279            0 : fn opt_pathbuf_parser(s: &str) -> Result<Utf8PathBuf, String> {
     280            0 :     Ok(Utf8PathBuf::from_str(s).unwrap())
     281            0 : }
     282              : 
     283              : #[tokio::main(flavor = "current_thread")]
     284            0 : async fn main() -> anyhow::Result<()> {
     285              :     // We want to allow multiple occurences of the same arg (taking the last) so
     286              :     // that neon_local could generate command with defaults + overrides without
     287              :     // getting 'argument cannot be used multiple times' error. This seems to be
     288              :     // impossible with pure Derive API, so convert struct to Command, modify it,
     289              :     // parse arguments, and then fill the struct back.
     290            0 :     let cmd = <Args as clap::CommandFactory>::command()
     291            0 :         .args_override_self(true)
     292            0 :         .version(version());
     293            0 :     let mut matches = cmd.get_matches();
     294            0 :     let mut args = <Args as clap::FromArgMatches>::from_arg_matches_mut(&mut matches)?;
     295              : 
     296              :     // I failed to modify opt_pathbuf_parser to return Option<PathBuf> in
     297              :     // reasonable time, so turn empty string into option post factum.
     298            0 :     if let Some(pb) = &args.pg_auth_public_key_path {
     299            0 :         if pb.as_os_str().is_empty() {
     300            0 :             args.pg_auth_public_key_path = None;
     301            0 :         }
     302            0 :     }
     303            0 :     if let Some(pb) = &args.pg_tenant_only_auth_public_key_path {
     304            0 :         if pb.as_os_str().is_empty() {
     305            0 :             args.pg_tenant_only_auth_public_key_path = None;
     306            0 :         }
     307            0 :     }
     308            0 :     if let Some(pb) = &args.http_auth_public_key_path {
     309            0 :         if pb.as_os_str().is_empty() {
     310            0 :             args.http_auth_public_key_path = None;
     311            0 :         }
     312            0 :     }
     313              : 
     314            0 :     if let Some(addr) = args.dump_control_file {
     315            0 :         let state = control_file::FileStorage::load_control_file(addr)?;
     316            0 :         let json = serde_json::to_string(&state)?;
     317            0 :         print!("{json}");
     318            0 :         return Ok(());
     319            0 :     }
     320              : 
     321              :     // important to keep the order of:
     322              :     // 1. init logging
     323              :     // 2. tracing panic hook
     324              :     // 3. sentry
     325            0 :     logging::init(
     326            0 :         LogFormat::from_config(&args.log_format)?,
     327            0 :         logging::TracingErrorLayerEnablement::Disabled,
     328            0 :         logging::Output::Stdout,
     329            0 :     )?;
     330            0 :     logging::replace_panic_hook_with_tracing_panic_hook().forget();
     331            0 :     info!("version: {GIT_VERSION}");
     332            0 :     info!("buld_tag: {BUILD_TAG}");
     333              : 
     334            0 :     let args_workdir = &args.datadir;
     335            0 :     let workdir = args_workdir.canonicalize_utf8().with_context(|| {
     336            0 :         format!("Failed to get the absolute path for input workdir {args_workdir:?}")
     337            0 :     })?;
     338              : 
     339              :     // Change into the data directory.
     340            0 :     std::env::set_current_dir(&workdir)?;
     341              : 
     342              :     // Prevent running multiple safekeepers on the same directory
     343            0 :     let lock_file_path = workdir.join(PID_FILE_NAME);
     344            0 :     let lock_file =
     345            0 :         pid_file::claim_for_current_process(&lock_file_path).context("claim pid file")?;
     346            0 :     info!("claimed pid file at {lock_file_path:?}");
     347              :     // ensure that the lock file is held even if the main thread of the process is panics
     348              :     // we need to release the lock file only when the current process is gone
     349            0 :     std::mem::forget(lock_file);
     350              : 
     351              :     // Set or read our ID.
     352            0 :     let id = set_id(&workdir, args.id.map(NodeId))?;
     353            0 :     if args.init {
     354            0 :         return Ok(());
     355            0 :     }
     356              : 
     357            0 :     let pg_auth = match args.pg_auth_public_key_path.as_ref() {
     358              :         None => {
     359            0 :             info!("pg auth is disabled");
     360            0 :             None
     361              :         }
     362            0 :         Some(path) => {
     363            0 :             info!("loading pg auth JWT key from {path}");
     364            0 :             Some(Arc::new(
     365            0 :                 JwtAuth::from_key_path(path).context("failed to load the auth key")?,
     366              :             ))
     367              :         }
     368              :     };
     369            0 :     let pg_tenant_only_auth = match args.pg_tenant_only_auth_public_key_path.as_ref() {
     370              :         None => {
     371            0 :             info!("pg tenant only auth is disabled");
     372            0 :             None
     373              :         }
     374            0 :         Some(path) => {
     375            0 :             info!("loading pg tenant only auth JWT key from {path}");
     376            0 :             Some(Arc::new(
     377            0 :                 JwtAuth::from_key_path(path).context("failed to load the auth key")?,
     378              :             ))
     379              :         }
     380              :     };
     381            0 :     let http_auth = match args.http_auth_public_key_path.as_ref() {
     382              :         None => {
     383            0 :             info!("http auth is disabled");
     384            0 :             None
     385              :         }
     386            0 :         Some(path) => {
     387            0 :             info!("loading http auth JWT key(s) from {path}");
     388            0 :             let jwt_auth = JwtAuth::from_key_path(path).context("failed to load the auth key")?;
     389            0 :             Some(Arc::new(SwappableJwtAuth::new(jwt_auth)))
     390              :         }
     391              :     };
     392              : 
     393              :     // Load JWT auth token to connect to other safekeepers for pull_timeline.
     394            0 :     let sk_auth_token = if let Some(auth_token_path) = args.auth_token_path.as_ref() {
     395            0 :         info!("loading JWT token for authentication with safekeepers from {auth_token_path}");
     396            0 :         let auth_token = tokio::fs::read_to_string(auth_token_path).await?;
     397            0 :         Some(SecretString::from(auth_token.trim().to_owned()))
     398              :     } else {
     399            0 :         info!("no JWT token for authentication with safekeepers detected");
     400            0 :         None
     401              :     };
     402              : 
     403            0 :     let ssl_ca_certs = match args.ssl_ca_file.as_ref() {
     404            0 :         Some(ssl_ca_file) => {
     405            0 :             tracing::info!("Using ssl root CA file: {ssl_ca_file:?}");
     406            0 :             let buf = tokio::fs::read(ssl_ca_file).await?;
     407            0 :             pem::parse_many(&buf)?
     408            0 :                 .into_iter()
     409            0 :                 .filter(|pem| pem.tag() == "CERTIFICATE")
     410            0 :                 .collect()
     411              :         }
     412            0 :         None => Vec::new(),
     413              :     };
     414              : 
     415            0 :     let conf = Arc::new(SafeKeeperConf {
     416            0 :         workdir,
     417            0 :         my_id: id,
     418            0 :         listen_pg_addr: args.listen_pg,
     419            0 :         listen_pg_addr_tenant_only: args.listen_pg_tenant_only,
     420            0 :         listen_http_addr: args.listen_http,
     421            0 :         listen_https_addr: args.listen_https,
     422            0 :         advertise_pg_addr: args.advertise_pg,
     423            0 :         availability_zone: args.availability_zone,
     424            0 :         no_sync: args.no_sync,
     425            0 :         broker_endpoint: args.broker_endpoint,
     426            0 :         broker_keepalive_interval: args.broker_keepalive_interval,
     427            0 :         heartbeat_timeout: args.heartbeat_timeout,
     428            0 :         peer_recovery_enabled: args.peer_recovery,
     429            0 :         remote_storage: args.remote_storage,
     430            0 :         max_offloader_lag_bytes: args.max_offloader_lag,
     431            0 :         /* BEGIN_HADRON */
     432            0 :         max_reelect_offloader_lag_bytes: args.max_reelect_offloader_lag_bytes,
     433            0 :         max_timeline_disk_usage_bytes: args.max_timeline_disk_usage_bytes,
     434            0 :         /* END_HADRON */
     435            0 :         wal_backup_enabled: !args.disable_wal_backup,
     436            0 :         backup_parallel_jobs: args.wal_backup_parallel_jobs,
     437            0 :         pg_auth,
     438            0 :         pg_tenant_only_auth,
     439            0 :         http_auth,
     440            0 :         sk_auth_token,
     441            0 :         current_thread_runtime: args.current_thread_runtime,
     442            0 :         walsenders_keep_horizon: args.walsenders_keep_horizon,
     443            0 :         partial_backup_timeout: args.partial_backup_timeout,
     444            0 :         disable_periodic_broker_push: args.disable_periodic_broker_push,
     445            0 :         enable_offload: args.enable_offload,
     446            0 :         delete_offloaded_wal: args.delete_offloaded_wal,
     447            0 :         control_file_save_interval: args.control_file_save_interval,
     448            0 :         partial_backup_concurrency: args.partial_backup_concurrency,
     449            0 :         eviction_min_resident: args.eviction_min_resident,
     450            0 :         wal_reader_fanout: args.wal_reader_fanout,
     451            0 :         max_delta_for_fanout: args.max_delta_for_fanout,
     452            0 :         ssl_key_file: args.ssl_key_file,
     453            0 :         ssl_cert_file: args.ssl_cert_file,
     454            0 :         ssl_cert_reload_period: args.ssl_cert_reload_period,
     455            0 :         ssl_ca_certs,
     456            0 :         use_https_safekeeper_api: args.use_https_safekeeper_api,
     457            0 :         enable_tls_wal_service_api: args.enable_tls_wal_service_api,
     458            0 :         force_metric_collection_on_scrape: args.force_metric_collection_on_scrape,
     459            0 :         /* BEGIN_HADRON */
     460            0 :         advertise_pg_addr_tenant_only: None,
     461            0 :         enable_pull_timeline_on_startup: args.enable_pull_timeline_on_startup,
     462            0 :         hcc_base_url: None,
     463            0 :         global_disk_check_interval: args.global_disk_check_interval,
     464            0 :         max_global_disk_usage_ratio: args.max_global_disk_usage_ratio,
     465            0 :         /* END_HADRON */
     466            0 :     });
     467              : 
     468              :     // initialize sentry if SENTRY_DSN is provided
     469            0 :     let _sentry_guard = init_sentry(
     470            0 :         Some(GIT_VERSION.into()),
     471            0 :         &[("node_id", &conf.my_id.to_string())],
     472              :     );
     473            0 :     start_safekeeper(conf).await
     474            0 : }
     475              : 
     476              : /// Result of joining any of main tasks: upper error means task failed to
     477              : /// complete, e.g. panicked, inner is error produced by task itself.
     478              : type JoinTaskRes = Result<anyhow::Result<()>, JoinError>;
     479              : 
     480            0 : async fn start_safekeeper(conf: Arc<SafeKeeperConf>) -> Result<()> {
     481              :     // fsync the datadir to make sure we have a consistent state on disk.
     482            0 :     if !conf.no_sync {
     483            0 :         let dfd = File::open(&conf.workdir).context("open datadir for syncfs")?;
     484            0 :         let started = Instant::now();
     485            0 :         utils::crashsafe::syncfs(dfd)?;
     486            0 :         let elapsed = started.elapsed();
     487            0 :         info!(
     488            0 :             elapsed_ms = elapsed.as_millis(),
     489            0 :             "syncfs data directory done"
     490              :         );
     491            0 :     }
     492              : 
     493            0 :     info!("starting safekeeper WAL service on {}", conf.listen_pg_addr);
     494            0 :     let pg_listener = tcp_listener::bind(conf.listen_pg_addr.clone()).map_err(|e| {
     495            0 :         error!("failed to bind to address {}: {}", conf.listen_pg_addr, e);
     496            0 :         e
     497            0 :     })?;
     498              : 
     499            0 :     let pg_listener_tenant_only =
     500            0 :         if let Some(listen_pg_addr_tenant_only) = &conf.listen_pg_addr_tenant_only {
     501            0 :             info!(
     502            0 :                 "starting safekeeper tenant scoped WAL service on {}",
     503              :                 listen_pg_addr_tenant_only
     504              :             );
     505            0 :             let listener = tcp_listener::bind(listen_pg_addr_tenant_only.clone()).map_err(|e| {
     506            0 :                 error!(
     507            0 :                     "failed to bind to address {}: {}",
     508              :                     listen_pg_addr_tenant_only, e
     509              :                 );
     510            0 :                 e
     511            0 :             })?;
     512            0 :             Some(listener)
     513              :         } else {
     514            0 :             None
     515              :         };
     516              : 
     517            0 :     info!(
     518            0 :         "starting safekeeper HTTP service on {}",
     519            0 :         conf.listen_http_addr
     520              :     );
     521            0 :     let http_listener = tcp_listener::bind(conf.listen_http_addr.clone()).map_err(|e| {
     522            0 :         error!("failed to bind to address {}: {}", conf.listen_http_addr, e);
     523            0 :         e
     524            0 :     })?;
     525              : 
     526            0 :     let https_listener = match conf.listen_https_addr.as_ref() {
     527            0 :         Some(listen_https_addr) => {
     528            0 :             info!("starting safekeeper HTTPS service on {}", listen_https_addr);
     529            0 :             Some(tcp_listener::bind(listen_https_addr).map_err(|e| {
     530            0 :                 error!("failed to bind to address {}: {}", listen_https_addr, e);
     531            0 :                 e
     532            0 :             })?)
     533              :         }
     534            0 :         None => None,
     535              :     };
     536              : 
     537            0 :     let wal_backup = Arc::new(WalBackup::new(&conf).await?);
     538              : 
     539            0 :     let global_timelines = Arc::new(GlobalTimelines::new(conf.clone(), wal_backup.clone()));
     540              : 
     541              :     // Register metrics collector for active timelines. It's important to do this
     542              :     // after daemonizing, otherwise process collector will be upset.
     543            0 :     let timeline_collector = safekeeper::metrics::TimelineCollector::new(global_timelines.clone());
     544            0 :     metrics::register_internal(Box::new(timeline_collector))?;
     545              : 
     546              :     // Keep handles to main tasks to die if any of them disappears.
     547            0 :     let mut tasks_handles: FuturesUnordered<BoxFuture<(String, JoinTaskRes)>> =
     548            0 :         FuturesUnordered::new();
     549              : 
     550              :     // Start wal backup launcher before loading timelines as we'll notify it
     551              :     // through the channel about timelines which need offloading, not draining
     552              :     // the channel would cause deadlock.
     553            0 :     let current_thread_rt = conf
     554            0 :         .current_thread_runtime
     555            0 :         .then(|| Handle::try_current().expect("no runtime in main"));
     556              : 
     557              :     // Load all timelines from disk to memory.
     558            0 :     global_timelines.init().await?;
     559              : 
     560              :     /* BEGIN_HADRON */
     561            0 :     if conf.enable_pull_timeline_on_startup && global_timelines.timelines_count() == 0 {
     562            0 :         match hadron::hcc_pull_timelines(&conf, global_timelines.clone()).await {
     563              :             Ok(_) => {
     564            0 :                 info!("Successfully pulled all timelines from peer safekeepers");
     565              :             }
     566            0 :             Err(e) => {
     567            0 :                 error!("Failed to pull timelines from peer safekeepers: {:?}", e);
     568            0 :                 return Err(e);
     569              :             }
     570              :         }
     571            0 :     }
     572              :     /* END_HADRON */
     573              : 
     574              :     // Run everything in current thread rt, if asked.
     575            0 :     if conf.current_thread_runtime {
     576            0 :         info!("running in current thread runtime");
     577            0 :     }
     578              : 
     579            0 :     let tls_server_config = if conf.listen_https_addr.is_some() || conf.enable_tls_wal_service_api {
     580            0 :         let ssl_key_file = conf.ssl_key_file.clone();
     581            0 :         let ssl_cert_file = conf.ssl_cert_file.clone();
     582            0 :         let ssl_cert_reload_period = conf.ssl_cert_reload_period;
     583              : 
     584              :         // Create resolver in BACKGROUND_RUNTIME, so the background certificate reloading
     585              :         // task is run in this runtime.
     586            0 :         let cert_resolver = current_thread_rt
     587            0 :             .as_ref()
     588            0 :             .unwrap_or_else(|| BACKGROUND_RUNTIME.handle())
     589            0 :             .spawn(async move {
     590            0 :                 ReloadingCertificateResolver::new(
     591            0 :                     "main",
     592            0 :                     &ssl_key_file,
     593            0 :                     &ssl_cert_file,
     594            0 :                     ssl_cert_reload_period,
     595            0 :                 )
     596            0 :                 .await
     597            0 :             })
     598            0 :             .await??;
     599              : 
     600            0 :         let config = rustls::ServerConfig::builder()
     601            0 :             .with_no_client_auth()
     602            0 :             .with_cert_resolver(cert_resolver);
     603              : 
     604            0 :         Some(Arc::new(config))
     605              :     } else {
     606            0 :         None
     607              :     };
     608              : 
     609            0 :     let wal_service_handle = current_thread_rt
     610            0 :         .as_ref()
     611            0 :         .unwrap_or_else(|| WAL_SERVICE_RUNTIME.handle())
     612            0 :         .spawn(wal_service::task_main(
     613            0 :             conf.clone(),
     614            0 :             pg_listener,
     615            0 :             Scope::SafekeeperData,
     616            0 :             conf.enable_tls_wal_service_api
     617            0 :                 .then(|| tls_server_config.clone())
     618            0 :                 .flatten(),
     619            0 :             global_timelines.clone(),
     620              :         ))
     621              :         // wrap with task name for error reporting
     622            0 :         .map(|res| ("WAL service main".to_owned(), res));
     623            0 :     tasks_handles.push(Box::pin(wal_service_handle));
     624              : 
     625            0 :     let global_timelines_ = global_timelines.clone();
     626            0 :     let timeline_housekeeping_handle = current_thread_rt
     627            0 :         .as_ref()
     628            0 :         .unwrap_or_else(|| WAL_SERVICE_RUNTIME.handle())
     629            0 :         .spawn(async move {
     630              :             const TOMBSTONE_TTL: Duration = Duration::from_secs(3600 * 24);
     631              :             loop {
     632            0 :                 tokio::time::sleep(TOMBSTONE_TTL).await;
     633            0 :                 global_timelines_.housekeeping(&TOMBSTONE_TTL);
     634              :             }
     635              :         })
     636            0 :         .map(|res| ("Timeline map housekeeping".to_owned(), res));
     637            0 :     tasks_handles.push(Box::pin(timeline_housekeeping_handle));
     638              : 
     639              :     /* BEGIN_HADRON */
     640              :     // Spawn global disk usage watcher task, if a global disk usage limit is specified.
     641            0 :     let interval = conf.global_disk_check_interval;
     642            0 :     let data_dir = conf.workdir.clone();
     643              :     // Use the safekeeper data directory to compute filesystem capacity. This only runs once on startup, so
     644              :     // there is little point to continue if we can't have the proper protections in place.
     645            0 :     let fs_capacity_bytes = get_filesystem_capacity(data_dir.as_std_path())
     646            0 :         .expect("Failed to get filesystem capacity for data directory");
     647            0 :     let limit: u64 = (conf.max_global_disk_usage_ratio * fs_capacity_bytes as f64) as u64;
     648            0 :     if limit > 0 {
     649            0 :         let disk_usage_watch_handle = BACKGROUND_RUNTIME
     650            0 :             .handle()
     651            0 :             .spawn(async move {
     652              :                 // Use Tokio interval to preserve fixed cadence between filesystem utilization checks
     653            0 :                 let mut ticker = tokio::time::interval(interval);
     654            0 :                 ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
     655              : 
     656              :                 loop {
     657            0 :                     ticker.tick().await;
     658            0 :                     let data_dir_clone = data_dir.clone();
     659            0 :                     let check_start = Instant::now();
     660              : 
     661            0 :                     let usage = tokio::task::spawn_blocking(move || {
     662            0 :                         get_filesystem_usage(data_dir_clone.as_std_path())
     663            0 :                     })
     664            0 :                     .await
     665            0 :                     .unwrap_or(0);
     666              : 
     667            0 :                     let elapsed = check_start.elapsed().as_secs_f64();
     668            0 :                     GLOBAL_DISK_UTIL_CHECK_SECONDS.observe(elapsed);
     669            0 :                     if usage > limit {
     670            0 :                         warn!(
     671            0 :                             "Global disk usage exceeded limit. Usage: {} bytes, limit: {} bytes",
     672              :                             usage, limit
     673              :                         );
     674            0 :                     }
     675            0 :                     GLOBAL_DISK_LIMIT_EXCEEDED.store(usage > limit, Ordering::Relaxed);
     676              :                 }
     677              :             })
     678            0 :             .map(|res| ("Global disk usage watcher".to_string(), res));
     679            0 :         tasks_handles.push(Box::pin(disk_usage_watch_handle));
     680            0 :     }
     681              :     /* END_HADRON */
     682            0 :     if let Some(pg_listener_tenant_only) = pg_listener_tenant_only {
     683            0 :         let wal_service_handle = current_thread_rt
     684            0 :             .as_ref()
     685            0 :             .unwrap_or_else(|| WAL_SERVICE_RUNTIME.handle())
     686            0 :             .spawn(wal_service::task_main(
     687            0 :                 conf.clone(),
     688            0 :                 pg_listener_tenant_only,
     689            0 :                 Scope::Tenant,
     690            0 :                 conf.enable_tls_wal_service_api
     691            0 :                     .then(|| tls_server_config.clone())
     692            0 :                     .flatten(),
     693            0 :                 global_timelines.clone(),
     694              :             ))
     695              :             // wrap with task name for error reporting
     696            0 :             .map(|res| ("WAL service tenant only main".to_owned(), res));
     697            0 :         tasks_handles.push(Box::pin(wal_service_handle));
     698            0 :     }
     699              : 
     700            0 :     let http_handle = current_thread_rt
     701            0 :         .as_ref()
     702            0 :         .unwrap_or_else(|| HTTP_RUNTIME.handle())
     703            0 :         .spawn(http::task_main_http(
     704            0 :             conf.clone(),
     705            0 :             http_listener,
     706            0 :             global_timelines.clone(),
     707              :         ))
     708            0 :         .map(|res| ("HTTP service main".to_owned(), res));
     709            0 :     tasks_handles.push(Box::pin(http_handle));
     710              : 
     711            0 :     if let Some(https_listener) = https_listener {
     712            0 :         let https_handle = current_thread_rt
     713            0 :             .as_ref()
     714            0 :             .unwrap_or_else(|| HTTP_RUNTIME.handle())
     715            0 :             .spawn(http::task_main_https(
     716            0 :                 conf.clone(),
     717            0 :                 https_listener,
     718            0 :                 tls_server_config.expect("tls_server_config is set earlier if https is enabled"),
     719            0 :                 global_timelines.clone(),
     720              :             ))
     721            0 :             .map(|res| ("HTTPS service main".to_owned(), res));
     722            0 :         tasks_handles.push(Box::pin(https_handle));
     723            0 :     }
     724              : 
     725            0 :     let broker_task_handle = current_thread_rt
     726            0 :         .as_ref()
     727            0 :         .unwrap_or_else(|| BROKER_RUNTIME.handle())
     728            0 :         .spawn(
     729            0 :             broker::task_main(conf.clone(), global_timelines.clone())
     730            0 :                 .instrument(info_span!("broker")),
     731              :         )
     732            0 :         .map(|res| ("broker main".to_owned(), res));
     733            0 :     tasks_handles.push(Box::pin(broker_task_handle));
     734              : 
     735              :     /* BEGIN_HADRON */
     736            0 :     if conf.force_metric_collection_on_scrape {
     737            0 :         let metrics_handle = current_thread_rt
     738            0 :             .as_ref()
     739            0 :             .unwrap_or_else(|| BACKGROUND_RUNTIME.handle())
     740            0 :             .spawn(async move {
     741            0 :                 let mut interval: tokio::time::Interval =
     742            0 :                     tokio::time::interval(METRICS_COLLECTION_INTERVAL);
     743              :                 loop {
     744            0 :                     interval.tick().await;
     745            0 :                     tokio::task::spawn_blocking(|| {
     746            0 :                         METRICS_COLLECTOR.run_once(true);
     747            0 :                     });
     748              :                 }
     749              :             })
     750            0 :             .map(|res| ("broker main".to_owned(), res));
     751            0 :         tasks_handles.push(Box::pin(metrics_handle));
     752            0 :     }
     753              :     /* END_HADRON */
     754              : 
     755            0 :     set_build_info_metric(GIT_VERSION, BUILD_TAG);
     756              : 
     757              :     // TODO: update tokio-stream, convert to real async Stream with
     758              :     // SignalStream, map it to obtain missing signal name, combine streams into
     759              :     // single stream we can easily sit on.
     760            0 :     let mut sigquit_stream = signal(SignalKind::quit())?;
     761            0 :     let mut sigint_stream = signal(SignalKind::interrupt())?;
     762            0 :     let mut sigterm_stream = signal(SignalKind::terminate())?;
     763              : 
     764              :     // Notify systemd that we are ready. This is important as currently loading
     765              :     // timelines takes significant time (~30s in busy regions).
     766            0 :     if let Err(e) = sd_notify::notify(true, &[NotifyState::Ready]) {
     767            0 :         warn!("systemd notify failed: {:?}", e);
     768            0 :     }
     769              : 
     770            0 :     tokio::select! {
     771            0 :         Some((task_name, res)) = tasks_handles.next()=> {
     772            0 :             error!("{} task failed: {:?}, exiting", task_name, res);
     773            0 :             std::process::exit(1);
     774              :         }
     775              :         // On any shutdown signal, log receival and exit. Additionally, handling
     776              :         // SIGQUIT prevents coredump.
     777            0 :         _ = sigquit_stream.recv() => info!("received SIGQUIT, terminating"),
     778            0 :         _ = sigint_stream.recv() => info!("received SIGINT, terminating"),
     779            0 :         _ = sigterm_stream.recv() => info!("received SIGTERM, terminating")
     780              : 
     781              :     };
     782            0 :     std::process::exit(0);
     783            0 : }
     784              : 
     785              : /// Determine safekeeper id.
     786            0 : fn set_id(workdir: &Utf8Path, given_id: Option<NodeId>) -> Result<NodeId> {
     787            0 :     let id_file_path = workdir.join(ID_FILE_NAME);
     788              : 
     789              :     let my_id: NodeId;
     790              :     // If file with ID exists, read it in; otherwise set one passed.
     791            0 :     match fs::read(&id_file_path) {
     792            0 :         Ok(id_serialized) => {
     793              :             my_id = NodeId(
     794            0 :                 std::str::from_utf8(&id_serialized)
     795            0 :                     .context("failed to parse safekeeper id")?
     796            0 :                     .parse()
     797            0 :                     .context("failed to parse safekeeper id")?,
     798              :             );
     799            0 :             if let Some(given_id) = given_id {
     800            0 :                 if given_id != my_id {
     801            0 :                     bail!(
     802            0 :                         "safekeeper already initialized with id {}, can't set {}",
     803              :                         my_id,
     804              :                         given_id
     805              :                     );
     806            0 :                 }
     807            0 :             }
     808            0 :             info!("safekeeper ID {}", my_id);
     809              :         }
     810            0 :         Err(error) => match error.kind() {
     811              :             ErrorKind::NotFound => {
     812            0 :                 my_id = if let Some(given_id) = given_id {
     813            0 :                     given_id
     814              :                 } else {
     815            0 :                     bail!("safekeeper id is not specified");
     816              :                 };
     817            0 :                 let mut f = File::create(&id_file_path)
     818            0 :                     .with_context(|| format!("Failed to create id file at {id_file_path:?}"))?;
     819            0 :                 f.write_all(my_id.to_string().as_bytes())?;
     820            0 :                 f.sync_all()?;
     821            0 :                 info!("initialized safekeeper id {}", my_id);
     822              :             }
     823              :             _ => {
     824            0 :                 return Err(error.into());
     825              :             }
     826              :         },
     827              :     }
     828            0 :     Ok(my_id)
     829            0 : }
     830              : 
     831            0 : fn parse_remote_storage(storage_conf: &str) -> anyhow::Result<RemoteStorageConfig> {
     832            0 :     RemoteStorageConfig::from_toml(&storage_conf.parse()?)
     833            0 : }
     834              : 
     835              : #[test]
     836            1 : fn verify_cli() {
     837              :     use clap::CommandFactory;
     838            1 :     Args::command().debug_assert()
     839            1 : }
        

Generated by: LCOV version 2.1-beta