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