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 sample allocations for profiles every 1 MB (1 << 20).
55 : // TODO: disabled because concurrent CPU profiles cause seg faults. See:
56 : // https://github.com/neondatabase/neon/issues/10225.
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:20\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 : }
211 :
212 : // Like PathBufValueParser, but allows empty string.
213 0 : fn opt_pathbuf_parser(s: &str) -> Result<Utf8PathBuf, String> {
214 0 : Ok(Utf8PathBuf::from_str(s).unwrap())
215 0 : }
216 :
217 : #[tokio::main(flavor = "current_thread")]
218 0 : async fn main() -> anyhow::Result<()> {
219 0 : // We want to allow multiple occurences of the same arg (taking the last) so
220 0 : // that neon_local could generate command with defaults + overrides without
221 0 : // getting 'argument cannot be used multiple times' error. This seems to be
222 0 : // impossible with pure Derive API, so convert struct to Command, modify it,
223 0 : // parse arguments, and then fill the struct back.
224 0 : let cmd = <Args as clap::CommandFactory>::command()
225 0 : .args_override_self(true)
226 0 : .version(version());
227 0 : let mut matches = cmd.get_matches();
228 0 : let mut args = <Args as clap::FromArgMatches>::from_arg_matches_mut(&mut matches)?;
229 0 :
230 0 : // I failed to modify opt_pathbuf_parser to return Option<PathBuf> in
231 0 : // reasonable time, so turn empty string into option post factum.
232 0 : if let Some(pb) = &args.pg_auth_public_key_path {
233 0 : if pb.as_os_str().is_empty() {
234 0 : args.pg_auth_public_key_path = None;
235 0 : }
236 0 : }
237 0 : if let Some(pb) = &args.pg_tenant_only_auth_public_key_path {
238 0 : if pb.as_os_str().is_empty() {
239 0 : args.pg_tenant_only_auth_public_key_path = None;
240 0 : }
241 0 : }
242 0 : if let Some(pb) = &args.http_auth_public_key_path {
243 0 : if pb.as_os_str().is_empty() {
244 0 : args.http_auth_public_key_path = None;
245 0 : }
246 0 : }
247 0 :
248 0 : if let Some(addr) = args.dump_control_file {
249 0 : let state = control_file::FileStorage::load_control_file(addr)?;
250 0 : let json = serde_json::to_string(&state)?;
251 0 : print!("{json}");
252 0 : return Ok(());
253 0 : }
254 0 :
255 0 : // important to keep the order of:
256 0 : // 1. init logging
257 0 : // 2. tracing panic hook
258 0 : // 3. sentry
259 0 : logging::init(
260 0 : LogFormat::from_config(&args.log_format)?,
261 0 : logging::TracingErrorLayerEnablement::Disabled,
262 0 : logging::Output::Stdout,
263 0 : )?;
264 0 : logging::replace_panic_hook_with_tracing_panic_hook().forget();
265 0 : info!("version: {GIT_VERSION}");
266 0 : info!("buld_tag: {BUILD_TAG}");
267 0 :
268 0 : let args_workdir = &args.datadir;
269 0 : let workdir = args_workdir.canonicalize_utf8().with_context(|| {
270 0 : format!("Failed to get the absolute path for input workdir {args_workdir:?}")
271 0 : })?;
272 0 :
273 0 : // Change into the data directory.
274 0 : std::env::set_current_dir(&workdir)?;
275 0 :
276 0 : // Prevent running multiple safekeepers on the same directory
277 0 : let lock_file_path = workdir.join(PID_FILE_NAME);
278 0 : let lock_file =
279 0 : pid_file::claim_for_current_process(&lock_file_path).context("claim pid file")?;
280 0 : info!("claimed pid file at {lock_file_path:?}");
281 0 : // ensure that the lock file is held even if the main thread of the process is panics
282 0 : // we need to release the lock file only when the current process is gone
283 0 : std::mem::forget(lock_file);
284 0 :
285 0 : // Set or read our ID.
286 0 : let id = set_id(&workdir, args.id.map(NodeId))?;
287 0 : if args.init {
288 0 : return Ok(());
289 0 : }
290 0 :
291 0 : let pg_auth = match args.pg_auth_public_key_path.as_ref() {
292 0 : None => {
293 0 : info!("pg auth is disabled");
294 0 : None
295 0 : }
296 0 : Some(path) => {
297 0 : info!("loading pg auth JWT key from {path}");
298 0 : Some(Arc::new(
299 0 : JwtAuth::from_key_path(path).context("failed to load the auth key")?,
300 0 : ))
301 0 : }
302 0 : };
303 0 : let pg_tenant_only_auth = match args.pg_tenant_only_auth_public_key_path.as_ref() {
304 0 : None => {
305 0 : info!("pg tenant only auth is disabled");
306 0 : None
307 0 : }
308 0 : Some(path) => {
309 0 : info!("loading pg tenant only auth JWT key from {path}");
310 0 : Some(Arc::new(
311 0 : JwtAuth::from_key_path(path).context("failed to load the auth key")?,
312 0 : ))
313 0 : }
314 0 : };
315 0 : let http_auth = match args.http_auth_public_key_path.as_ref() {
316 0 : None => {
317 0 : info!("http auth is disabled");
318 0 : None
319 0 : }
320 0 : Some(path) => {
321 0 : info!("loading http auth JWT key(s) from {path}");
322 0 : let jwt_auth = JwtAuth::from_key_path(path).context("failed to load the auth key")?;
323 0 : Some(Arc::new(SwappableJwtAuth::new(jwt_auth)))
324 0 : }
325 0 : };
326 0 :
327 0 : // Load JWT auth token to connect to other safekeepers for pull_timeline.
328 0 : let sk_auth_token = match var("SAFEKEEPER_AUTH_TOKEN") {
329 0 : Ok(v) => {
330 0 : info!("loaded JWT token for authentication with safekeepers");
331 0 : Some(SecretString::from(v))
332 0 : }
333 0 : Err(VarError::NotPresent) => {
334 0 : info!("no JWT token for authentication with safekeepers detected");
335 0 : None
336 0 : }
337 0 : Err(_) => {
338 0 : warn!("JWT token for authentication with safekeepers is not unicode");
339 0 : None
340 0 : }
341 0 : };
342 0 :
343 0 : let conf = Arc::new(SafeKeeperConf {
344 0 : workdir,
345 0 : my_id: id,
346 0 : listen_pg_addr: args.listen_pg,
347 0 : listen_pg_addr_tenant_only: args.listen_pg_tenant_only,
348 0 : listen_http_addr: args.listen_http,
349 0 : advertise_pg_addr: args.advertise_pg,
350 0 : availability_zone: args.availability_zone,
351 0 : no_sync: args.no_sync,
352 0 : broker_endpoint: args.broker_endpoint,
353 0 : broker_keepalive_interval: args.broker_keepalive_interval,
354 0 : heartbeat_timeout: args.heartbeat_timeout,
355 0 : peer_recovery_enabled: args.peer_recovery,
356 0 : remote_storage: args.remote_storage,
357 0 : max_offloader_lag_bytes: args.max_offloader_lag,
358 0 : wal_backup_enabled: !args.disable_wal_backup,
359 0 : backup_parallel_jobs: args.wal_backup_parallel_jobs,
360 0 : pg_auth,
361 0 : pg_tenant_only_auth,
362 0 : http_auth,
363 0 : sk_auth_token,
364 0 : current_thread_runtime: args.current_thread_runtime,
365 0 : walsenders_keep_horizon: args.walsenders_keep_horizon,
366 0 : partial_backup_timeout: args.partial_backup_timeout,
367 0 : disable_periodic_broker_push: args.disable_periodic_broker_push,
368 0 : enable_offload: args.enable_offload,
369 0 : delete_offloaded_wal: args.delete_offloaded_wal,
370 0 : control_file_save_interval: args.control_file_save_interval,
371 0 : partial_backup_concurrency: args.partial_backup_concurrency,
372 0 : eviction_min_resident: args.eviction_min_resident,
373 0 : });
374 0 :
375 0 : // initialize sentry if SENTRY_DSN is provided
376 0 : let _sentry_guard = init_sentry(
377 0 : Some(GIT_VERSION.into()),
378 0 : &[("node_id", &conf.my_id.to_string())],
379 0 : );
380 0 : start_safekeeper(conf).await
381 0 : }
382 :
383 : /// Result of joining any of main tasks: upper error means task failed to
384 : /// complete, e.g. panicked, inner is error produced by task itself.
385 : type JoinTaskRes = Result<anyhow::Result<()>, JoinError>;
386 :
387 0 : async fn start_safekeeper(conf: Arc<SafeKeeperConf>) -> Result<()> {
388 0 : // fsync the datadir to make sure we have a consistent state on disk.
389 0 : if !conf.no_sync {
390 0 : let dfd = File::open(&conf.workdir).context("open datadir for syncfs")?;
391 0 : let started = Instant::now();
392 0 : utils::crashsafe::syncfs(dfd)?;
393 0 : let elapsed = started.elapsed();
394 0 : info!(
395 0 : elapsed_ms = elapsed.as_millis(),
396 0 : "syncfs data directory done"
397 : );
398 0 : }
399 :
400 0 : info!("starting safekeeper WAL service on {}", conf.listen_pg_addr);
401 0 : let pg_listener = tcp_listener::bind(conf.listen_pg_addr.clone()).map_err(|e| {
402 0 : error!("failed to bind to address {}: {}", conf.listen_pg_addr, e);
403 0 : e
404 0 : })?;
405 :
406 0 : let pg_listener_tenant_only =
407 0 : if let Some(listen_pg_addr_tenant_only) = &conf.listen_pg_addr_tenant_only {
408 0 : info!(
409 0 : "starting safekeeper tenant scoped WAL service on {}",
410 : listen_pg_addr_tenant_only
411 : );
412 0 : let listener = tcp_listener::bind(listen_pg_addr_tenant_only.clone()).map_err(|e| {
413 0 : error!(
414 0 : "failed to bind to address {}: {}",
415 : listen_pg_addr_tenant_only, e
416 : );
417 0 : e
418 0 : })?;
419 0 : Some(listener)
420 : } else {
421 0 : None
422 : };
423 :
424 0 : info!(
425 0 : "starting safekeeper HTTP service on {}",
426 0 : conf.listen_http_addr
427 : );
428 0 : let http_listener = tcp_listener::bind(conf.listen_http_addr.clone()).map_err(|e| {
429 0 : error!("failed to bind to address {}: {}", conf.listen_http_addr, e);
430 0 : e
431 0 : })?;
432 :
433 0 : let global_timelines = Arc::new(GlobalTimelines::new(conf.clone()));
434 0 :
435 0 : // Register metrics collector for active timelines. It's important to do this
436 0 : // after daemonizing, otherwise process collector will be upset.
437 0 : let timeline_collector = safekeeper::metrics::TimelineCollector::new(global_timelines.clone());
438 0 : metrics::register_internal(Box::new(timeline_collector))?;
439 :
440 0 : wal_backup::init_remote_storage(&conf).await;
441 :
442 : // Keep handles to main tasks to die if any of them disappears.
443 0 : let mut tasks_handles: FuturesUnordered<BoxFuture<(String, JoinTaskRes)>> =
444 0 : FuturesUnordered::new();
445 0 :
446 0 : // Start wal backup launcher before loading timelines as we'll notify it
447 0 : // through the channel about timelines which need offloading, not draining
448 0 : // the channel would cause deadlock.
449 0 : let current_thread_rt = conf
450 0 : .current_thread_runtime
451 0 : .then(|| Handle::try_current().expect("no runtime in main"));
452 0 :
453 0 : // Load all timelines from disk to memory.
454 0 : global_timelines.init().await?;
455 :
456 : // Run everything in current thread rt, if asked.
457 0 : if conf.current_thread_runtime {
458 0 : info!("running in current thread runtime");
459 0 : }
460 :
461 0 : let wal_service_handle = current_thread_rt
462 0 : .as_ref()
463 0 : .unwrap_or_else(|| WAL_SERVICE_RUNTIME.handle())
464 0 : .spawn(wal_service::task_main(
465 0 : conf.clone(),
466 0 : pg_listener,
467 0 : Scope::SafekeeperData,
468 0 : global_timelines.clone(),
469 0 : ))
470 0 : // wrap with task name for error reporting
471 0 : .map(|res| ("WAL service main".to_owned(), res));
472 0 : tasks_handles.push(Box::pin(wal_service_handle));
473 0 :
474 0 : let global_timelines_ = global_timelines.clone();
475 0 : let timeline_housekeeping_handle = current_thread_rt
476 0 : .as_ref()
477 0 : .unwrap_or_else(|| WAL_SERVICE_RUNTIME.handle())
478 0 : .spawn(async move {
479 : const TOMBSTONE_TTL: Duration = Duration::from_secs(3600 * 24);
480 : loop {
481 0 : tokio::time::sleep(TOMBSTONE_TTL).await;
482 0 : global_timelines_.housekeeping(&TOMBSTONE_TTL);
483 : }
484 0 : })
485 0 : .map(|res| ("Timeline map housekeeping".to_owned(), res));
486 0 : tasks_handles.push(Box::pin(timeline_housekeeping_handle));
487 :
488 0 : if let Some(pg_listener_tenant_only) = pg_listener_tenant_only {
489 0 : let wal_service_handle = current_thread_rt
490 0 : .as_ref()
491 0 : .unwrap_or_else(|| WAL_SERVICE_RUNTIME.handle())
492 0 : .spawn(wal_service::task_main(
493 0 : conf.clone(),
494 0 : pg_listener_tenant_only,
495 0 : Scope::Tenant,
496 0 : global_timelines.clone(),
497 0 : ))
498 0 : // wrap with task name for error reporting
499 0 : .map(|res| ("WAL service tenant only main".to_owned(), res));
500 0 : tasks_handles.push(Box::pin(wal_service_handle));
501 0 : }
502 :
503 0 : let http_handle = current_thread_rt
504 0 : .as_ref()
505 0 : .unwrap_or_else(|| HTTP_RUNTIME.handle())
506 0 : .spawn(http::task_main(
507 0 : conf.clone(),
508 0 : http_listener,
509 0 : global_timelines.clone(),
510 0 : ))
511 0 : .map(|res| ("HTTP service main".to_owned(), res));
512 0 : tasks_handles.push(Box::pin(http_handle));
513 :
514 0 : let broker_task_handle = current_thread_rt
515 0 : .as_ref()
516 0 : .unwrap_or_else(|| BROKER_RUNTIME.handle())
517 0 : .spawn(
518 0 : broker::task_main(conf.clone(), global_timelines.clone())
519 0 : .instrument(info_span!("broker")),
520 : )
521 0 : .map(|res| ("broker main".to_owned(), res));
522 0 : tasks_handles.push(Box::pin(broker_task_handle));
523 0 :
524 0 : set_build_info_metric(GIT_VERSION, BUILD_TAG);
525 :
526 : // TODO: update tokio-stream, convert to real async Stream with
527 : // SignalStream, map it to obtain missing signal name, combine streams into
528 : // single stream we can easily sit on.
529 0 : let mut sigquit_stream = signal(SignalKind::quit())?;
530 0 : let mut sigint_stream = signal(SignalKind::interrupt())?;
531 0 : let mut sigterm_stream = signal(SignalKind::terminate())?;
532 :
533 : // Notify systemd that we are ready. This is important as currently loading
534 : // timelines takes significant time (~30s in busy regions).
535 0 : if let Err(e) = sd_notify::notify(true, &[NotifyState::Ready]) {
536 0 : warn!("systemd notify failed: {:?}", e);
537 0 : }
538 :
539 0 : tokio::select! {
540 0 : Some((task_name, res)) = tasks_handles.next()=> {
541 0 : error!("{} task failed: {:?}, exiting", task_name, res);
542 0 : std::process::exit(1);
543 : }
544 : // On any shutdown signal, log receival and exit. Additionally, handling
545 : // SIGQUIT prevents coredump.
546 0 : _ = sigquit_stream.recv() => info!("received SIGQUIT, terminating"),
547 0 : _ = sigint_stream.recv() => info!("received SIGINT, terminating"),
548 0 : _ = sigterm_stream.recv() => info!("received SIGTERM, terminating")
549 :
550 : };
551 0 : std::process::exit(0);
552 0 : }
553 :
554 : /// Determine safekeeper id.
555 0 : fn set_id(workdir: &Utf8Path, given_id: Option<NodeId>) -> Result<NodeId> {
556 0 : let id_file_path = workdir.join(ID_FILE_NAME);
557 0 :
558 0 : let my_id: NodeId;
559 0 : // If file with ID exists, read it in; otherwise set one passed.
560 0 : match fs::read(&id_file_path) {
561 0 : Ok(id_serialized) => {
562 0 : my_id = NodeId(
563 0 : std::str::from_utf8(&id_serialized)
564 0 : .context("failed to parse safekeeper id")?
565 0 : .parse()
566 0 : .context("failed to parse safekeeper id")?,
567 : );
568 0 : if let Some(given_id) = given_id {
569 0 : if given_id != my_id {
570 0 : bail!(
571 0 : "safekeeper already initialized with id {}, can't set {}",
572 0 : my_id,
573 0 : given_id
574 0 : );
575 0 : }
576 0 : }
577 0 : info!("safekeeper ID {}", my_id);
578 : }
579 0 : Err(error) => match error.kind() {
580 : ErrorKind::NotFound => {
581 0 : my_id = if let Some(given_id) = given_id {
582 0 : given_id
583 : } else {
584 0 : bail!("safekeeper id is not specified");
585 : };
586 0 : let mut f = File::create(&id_file_path)
587 0 : .with_context(|| format!("Failed to create id file at {id_file_path:?}"))?;
588 0 : f.write_all(my_id.to_string().as_bytes())?;
589 0 : f.sync_all()?;
590 0 : info!("initialized safekeeper id {}", my_id);
591 : }
592 : _ => {
593 0 : return Err(error.into());
594 : }
595 : },
596 : }
597 0 : Ok(my_id)
598 0 : }
599 :
600 0 : fn parse_remote_storage(storage_conf: &str) -> anyhow::Result<RemoteStorageConfig> {
601 0 : RemoteStorageConfig::from_toml(&storage_conf.parse()?)
602 0 : }
603 :
604 : #[test]
605 1 : fn verify_cli() {
606 : use clap::CommandFactory;
607 1 : Args::command().debug_assert()
608 1 : }
|