LCOV - code coverage report
Current view: top level - safekeeper/src/bin - safekeeper.rs (source / functions) Coverage Total Hit
Test: 5e392a02abbad1ab595f4dba672e219a49f7f539.info Lines: 1.0 % 417 4
Test Date: 2025-04-11 22:43:24 Functions: 2.4 % 85 2

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

Generated by: LCOV version 2.1-beta