LCOV - code coverage report
Current view: top level - safekeeper/src/bin - safekeeper.rs (source / functions) Coverage Total Hit
Test: 20b6afc7b7f34578dcaab2b3acdaecfe91cd8bf1.info Lines: 1.4 % 358 5
Test Date: 2024-11-25 17:48:16 Functions: 4.9 % 81 4

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

Generated by: LCOV version 2.1-beta