LCOV - code coverage report
Current view: top level - safekeeper/src/bin - safekeeper.rs (source / functions) Coverage Total Hit
Test: 2620485e474b48c32427149a5d91ef8fc2cd649e.info Lines: 0.9 % 437 4
Test Date: 2025-05-01 22:50:11 Functions: 2.1 % 94 2

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

Generated by: LCOV version 2.1-beta