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