Line data Source code
1 : //! This module implements Timeline lifecycle management and has all necessary code
2 : //! to glue together SafeKeeper and all other background services.
3 :
4 : use anyhow::{anyhow, bail, Result};
5 : use camino::{Utf8Path, Utf8PathBuf};
6 : use remote_storage::RemotePath;
7 : use safekeeper_api::membership::Configuration;
8 : use safekeeper_api::models::{
9 : PeerInfo, TimelineMembershipSwitchResponse, TimelineTermBumpResponse,
10 : };
11 : use safekeeper_api::Term;
12 : use tokio::fs::{self};
13 : use tokio_util::sync::CancellationToken;
14 : use utils::id::TenantId;
15 : use utils::sync::gate::Gate;
16 :
17 : use std::cmp::max;
18 : use std::ops::{Deref, DerefMut};
19 : use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
20 : use std::sync::Arc;
21 : use std::time::Duration;
22 : use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
23 : use tokio::{sync::watch, time::Instant};
24 : use tracing::*;
25 : use utils::http::error::ApiError;
26 : use utils::{
27 : id::{NodeId, TenantTimelineId},
28 : lsn::Lsn,
29 : };
30 :
31 : use storage_broker::proto::SafekeeperTimelineInfo;
32 : use storage_broker::proto::TenantTimelineId as ProtoTenantTimelineId;
33 :
34 : use crate::control_file;
35 : use crate::rate_limit::RateLimiter;
36 : use crate::receive_wal::WalReceivers;
37 : use crate::safekeeper::{AcceptorProposerMessage, ProposerAcceptorMessage, SafeKeeper, TermLsn};
38 : use crate::send_wal::{WalSenders, WalSendersTimelineMetricValues};
39 : use crate::state::{EvictionState, TimelineMemState, TimelinePersistentState, TimelineState};
40 : use crate::timeline_guard::ResidenceGuard;
41 : use crate::timeline_manager::{AtomicStatus, ManagerCtl};
42 : use crate::timelines_set::TimelinesSet;
43 : use crate::wal_backup::{self, remote_timeline_path};
44 : use crate::wal_backup_partial::PartialRemoteSegment;
45 :
46 : use crate::metrics::{FullTimelineInfo, WalStorageMetrics, MISC_OPERATION_SECONDS};
47 : use crate::wal_storage::{Storage as wal_storage_iface, WalReader};
48 : use crate::SafeKeeperConf;
49 : use crate::{debug_dump, timeline_manager, wal_storage};
50 :
51 0 : fn peer_info_from_sk_info(sk_info: &SafekeeperTimelineInfo, ts: Instant) -> PeerInfo {
52 0 : PeerInfo {
53 0 : sk_id: NodeId(sk_info.safekeeper_id),
54 0 : term: sk_info.term,
55 0 : last_log_term: sk_info.last_log_term,
56 0 : flush_lsn: Lsn(sk_info.flush_lsn),
57 0 : commit_lsn: Lsn(sk_info.commit_lsn),
58 0 : local_start_lsn: Lsn(sk_info.local_start_lsn),
59 0 : pg_connstr: sk_info.safekeeper_connstr.clone(),
60 0 : http_connstr: sk_info.http_connstr.clone(),
61 0 : ts,
62 0 : }
63 0 : }
64 :
65 : // vector-based node id -> peer state map with very limited functionality we
66 : // need.
67 : #[derive(Debug, Clone, Default)]
68 : pub struct PeersInfo(pub Vec<PeerInfo>);
69 :
70 : impl PeersInfo {
71 0 : fn get(&mut self, id: NodeId) -> Option<&mut PeerInfo> {
72 0 : self.0.iter_mut().find(|p| p.sk_id == id)
73 0 : }
74 :
75 0 : fn upsert(&mut self, p: &PeerInfo) {
76 0 : match self.get(p.sk_id) {
77 0 : Some(rp) => *rp = p.clone(),
78 0 : None => self.0.push(p.clone()),
79 : }
80 0 : }
81 : }
82 :
83 : pub type ReadGuardSharedState<'a> = RwLockReadGuard<'a, SharedState>;
84 :
85 : /// WriteGuardSharedState is a wrapper around `RwLockWriteGuard<SharedState>` that
86 : /// automatically updates `watch::Sender` channels with state on drop.
87 : pub struct WriteGuardSharedState<'a> {
88 : tli: Arc<Timeline>,
89 : guard: RwLockWriteGuard<'a, SharedState>,
90 : }
91 :
92 : impl<'a> WriteGuardSharedState<'a> {
93 1206 : fn new(tli: Arc<Timeline>, guard: RwLockWriteGuard<'a, SharedState>) -> Self {
94 1206 : WriteGuardSharedState { tli, guard }
95 1206 : }
96 : }
97 :
98 : impl Deref for WriteGuardSharedState<'_> {
99 : type Target = SharedState;
100 :
101 0 : fn deref(&self) -> &Self::Target {
102 0 : &self.guard
103 0 : }
104 : }
105 :
106 : impl DerefMut for WriteGuardSharedState<'_> {
107 1203 : fn deref_mut(&mut self) -> &mut Self::Target {
108 1203 : &mut self.guard
109 1203 : }
110 : }
111 :
112 : impl Drop for WriteGuardSharedState<'_> {
113 1206 : fn drop(&mut self) {
114 1206 : let term_flush_lsn =
115 1206 : TermLsn::from((self.guard.sk.last_log_term(), self.guard.sk.flush_lsn()));
116 1206 : let commit_lsn = self.guard.sk.state().inmem.commit_lsn;
117 1206 :
118 1206 : let _ = self.tli.term_flush_lsn_watch_tx.send_if_modified(|old| {
119 1206 : if *old != term_flush_lsn {
120 600 : *old = term_flush_lsn;
121 600 : true
122 : } else {
123 606 : false
124 : }
125 1206 : });
126 1206 :
127 1206 : let _ = self.tli.commit_lsn_watch_tx.send_if_modified(|old| {
128 1206 : if *old != commit_lsn {
129 597 : *old = commit_lsn;
130 597 : true
131 : } else {
132 609 : false
133 : }
134 1206 : });
135 1206 :
136 1206 : // send notification about shared state update
137 1206 : self.tli.shared_state_version_tx.send_modify(|old| {
138 1206 : *old += 1;
139 1206 : });
140 1206 : }
141 : }
142 :
143 : /// This structure is stored in shared state and represents the state of the timeline.
144 : ///
145 : /// Usually it holds SafeKeeper, but it also supports offloaded timeline state. In this
146 : /// case, SafeKeeper is not available (because WAL is not present on disk) and all
147 : /// operations can be done only with control file.
148 : pub enum StateSK {
149 : Loaded(SafeKeeper<control_file::FileStorage, wal_storage::PhysicalStorage>),
150 : Offloaded(Box<TimelineState<control_file::FileStorage>>),
151 : // Not used, required for moving between states.
152 : Empty,
153 : }
154 :
155 : impl StateSK {
156 2464 : pub fn flush_lsn(&self) -> Lsn {
157 2464 : match self {
158 2464 : StateSK::Loaded(sk) => sk.wal_store.flush_lsn(),
159 0 : StateSK::Offloaded(state) => match state.eviction_state {
160 0 : EvictionState::Offloaded(flush_lsn) => flush_lsn,
161 0 : _ => panic!("StateSK::Offloaded mismatches with eviction_state from control_file"),
162 : },
163 0 : StateSK::Empty => unreachable!(),
164 : }
165 2464 : }
166 :
167 : /// Get a reference to the control file's timeline state.
168 2483 : pub fn state(&self) -> &TimelineState<control_file::FileStorage> {
169 2483 : match self {
170 2483 : StateSK::Loaded(sk) => &sk.state,
171 0 : StateSK::Offloaded(ref s) => s,
172 0 : StateSK::Empty => unreachable!(),
173 : }
174 2483 : }
175 :
176 3 : pub fn state_mut(&mut self) -> &mut TimelineState<control_file::FileStorage> {
177 3 : match self {
178 3 : StateSK::Loaded(sk) => &mut sk.state,
179 0 : StateSK::Offloaded(ref mut s) => s,
180 0 : StateSK::Empty => unreachable!(),
181 : }
182 3 : }
183 :
184 1232 : pub fn last_log_term(&self) -> Term {
185 1232 : self.state()
186 1232 : .acceptor_state
187 1232 : .get_last_log_term(self.flush_lsn())
188 1232 : }
189 :
190 0 : pub async fn term_bump(&mut self, to: Option<Term>) -> Result<TimelineTermBumpResponse> {
191 0 : self.state_mut().term_bump(to).await
192 0 : }
193 :
194 0 : pub async fn membership_switch(
195 0 : &mut self,
196 0 : to: Configuration,
197 0 : ) -> Result<TimelineMembershipSwitchResponse> {
198 0 : self.state_mut().membership_switch(to).await
199 0 : }
200 :
201 : /// Close open WAL files to release FDs.
202 0 : fn close_wal_store(&mut self) {
203 0 : if let StateSK::Loaded(sk) = self {
204 0 : sk.wal_store.close();
205 0 : }
206 0 : }
207 :
208 : /// Update timeline state with peer safekeeper data.
209 0 : pub async fn record_safekeeper_info(&mut self, sk_info: &SafekeeperTimelineInfo) -> Result<()> {
210 0 : // update commit_lsn if safekeeper is loaded
211 0 : match self {
212 0 : StateSK::Loaded(sk) => sk.record_safekeeper_info(sk_info).await?,
213 0 : StateSK::Offloaded(_) => {}
214 0 : StateSK::Empty => unreachable!(),
215 : }
216 :
217 : // update everything else, including remote_consistent_lsn and backup_lsn
218 0 : let mut sync_control_file = false;
219 0 : let state = self.state_mut();
220 0 : let wal_seg_size = state.server.wal_seg_size as u64;
221 0 :
222 0 : state.inmem.backup_lsn = max(Lsn(sk_info.backup_lsn), state.inmem.backup_lsn);
223 0 : sync_control_file |= state.backup_lsn + wal_seg_size < state.inmem.backup_lsn;
224 0 :
225 0 : state.inmem.remote_consistent_lsn = max(
226 0 : Lsn(sk_info.remote_consistent_lsn),
227 0 : state.inmem.remote_consistent_lsn,
228 0 : );
229 0 : sync_control_file |=
230 0 : state.remote_consistent_lsn + wal_seg_size < state.inmem.remote_consistent_lsn;
231 0 :
232 0 : state.inmem.peer_horizon_lsn =
233 0 : max(Lsn(sk_info.peer_horizon_lsn), state.inmem.peer_horizon_lsn);
234 0 : sync_control_file |= state.peer_horizon_lsn + wal_seg_size < state.inmem.peer_horizon_lsn;
235 0 :
236 0 : if sync_control_file {
237 0 : state.flush().await?;
238 0 : }
239 0 : Ok(())
240 0 : }
241 :
242 : /// Previously known as epoch_start_lsn. Needed only for reference in some APIs.
243 0 : pub fn term_start_lsn(&self) -> Lsn {
244 0 : match self {
245 0 : StateSK::Loaded(sk) => sk.term_start_lsn,
246 0 : StateSK::Offloaded(_) => Lsn(0),
247 0 : StateSK::Empty => unreachable!(),
248 : }
249 0 : }
250 :
251 : /// Used for metrics only.
252 0 : pub fn wal_storage_metrics(&self) -> WalStorageMetrics {
253 0 : match self {
254 0 : StateSK::Loaded(sk) => sk.wal_store.get_metrics(),
255 0 : StateSK::Offloaded(_) => WalStorageMetrics::default(),
256 0 : StateSK::Empty => unreachable!(),
257 : }
258 0 : }
259 :
260 : /// Returns WAL storage internal LSNs for debug dump.
261 0 : pub fn wal_storage_internal_state(&self) -> (Lsn, Lsn, Lsn, bool) {
262 0 : match self {
263 0 : StateSK::Loaded(sk) => sk.wal_store.internal_state(),
264 : StateSK::Offloaded(_) => {
265 0 : let flush_lsn = self.flush_lsn();
266 0 : (flush_lsn, flush_lsn, flush_lsn, false)
267 : }
268 0 : StateSK::Empty => unreachable!(),
269 : }
270 0 : }
271 :
272 : /// Access to SafeKeeper object. Panics if offloaded, should be good to use from WalResidentTimeline.
273 1200 : pub fn safekeeper(
274 1200 : &mut self,
275 1200 : ) -> &mut SafeKeeper<control_file::FileStorage, wal_storage::PhysicalStorage> {
276 1200 : match self {
277 1200 : StateSK::Loaded(sk) => sk,
278 : StateSK::Offloaded(_) => {
279 0 : panic!("safekeeper is offloaded, cannot be used")
280 : }
281 0 : StateSK::Empty => unreachable!(),
282 : }
283 1200 : }
284 :
285 : /// Moves control file's state structure out of the enum. Used to switch states.
286 0 : fn take_state(self) -> TimelineState<control_file::FileStorage> {
287 0 : match self {
288 0 : StateSK::Loaded(sk) => sk.state,
289 0 : StateSK::Offloaded(state) => *state,
290 0 : StateSK::Empty => unreachable!(),
291 : }
292 0 : }
293 : }
294 :
295 : /// Shared state associated with database instance
296 : pub struct SharedState {
297 : /// Safekeeper object
298 : pub(crate) sk: StateSK,
299 : /// In memory list containing state of peers sent in latest messages from them.
300 : pub(crate) peers_info: PeersInfo,
301 : // True value hinders old WAL removal; this is used by snapshotting. We
302 : // could make it a counter, but there is no need to.
303 : pub(crate) wal_removal_on_hold: bool,
304 : }
305 :
306 : impl SharedState {
307 : /// Creates a new SharedState.
308 3 : pub fn new(sk: StateSK) -> Self {
309 3 : Self {
310 3 : sk,
311 3 : peers_info: PeersInfo(vec![]),
312 3 : wal_removal_on_hold: false,
313 3 : }
314 3 : }
315 :
316 : /// Restore SharedState from control file. If file doesn't exist, bails out.
317 0 : pub fn restore(conf: &SafeKeeperConf, ttid: &TenantTimelineId) -> Result<Self> {
318 0 : let timeline_dir = get_timeline_dir(conf, ttid);
319 0 : let control_store = control_file::FileStorage::restore_new(&timeline_dir, conf.no_sync)?;
320 0 : if control_store.server.wal_seg_size == 0 {
321 0 : bail!(TimelineError::UninitializedWalSegSize(*ttid));
322 0 : }
323 :
324 0 : let sk = match control_store.eviction_state {
325 : EvictionState::Present => {
326 0 : let wal_store = wal_storage::PhysicalStorage::new(
327 0 : ttid,
328 0 : &timeline_dir,
329 0 : &control_store,
330 0 : conf.no_sync,
331 0 : )?;
332 0 : StateSK::Loaded(SafeKeeper::new(
333 0 : TimelineState::new(control_store),
334 0 : wal_store,
335 0 : conf.my_id,
336 0 : )?)
337 : }
338 : EvictionState::Offloaded(_) => {
339 0 : StateSK::Offloaded(Box::new(TimelineState::new(control_store)))
340 : }
341 : };
342 :
343 0 : Ok(Self::new(sk))
344 0 : }
345 :
346 3 : pub(crate) fn get_wal_seg_size(&self) -> usize {
347 3 : self.sk.state().server.wal_seg_size as usize
348 3 : }
349 :
350 0 : fn get_safekeeper_info(
351 0 : &self,
352 0 : ttid: &TenantTimelineId,
353 0 : conf: &SafeKeeperConf,
354 0 : standby_apply_lsn: Lsn,
355 0 : ) -> SafekeeperTimelineInfo {
356 0 : SafekeeperTimelineInfo {
357 0 : safekeeper_id: conf.my_id.0,
358 0 : tenant_timeline_id: Some(ProtoTenantTimelineId {
359 0 : tenant_id: ttid.tenant_id.as_ref().to_owned(),
360 0 : timeline_id: ttid.timeline_id.as_ref().to_owned(),
361 0 : }),
362 0 : term: self.sk.state().acceptor_state.term,
363 0 : last_log_term: self.sk.last_log_term(),
364 0 : flush_lsn: self.sk.flush_lsn().0,
365 0 : // note: this value is not flushed to control file yet and can be lost
366 0 : commit_lsn: self.sk.state().inmem.commit_lsn.0,
367 0 : remote_consistent_lsn: self.sk.state().inmem.remote_consistent_lsn.0,
368 0 : peer_horizon_lsn: self.sk.state().inmem.peer_horizon_lsn.0,
369 0 : safekeeper_connstr: conf
370 0 : .advertise_pg_addr
371 0 : .to_owned()
372 0 : .unwrap_or(conf.listen_pg_addr.clone()),
373 0 : http_connstr: conf.listen_http_addr.to_owned(),
374 0 : backup_lsn: self.sk.state().inmem.backup_lsn.0,
375 0 : local_start_lsn: self.sk.state().local_start_lsn.0,
376 0 : availability_zone: conf.availability_zone.clone(),
377 0 : standby_horizon: standby_apply_lsn.0,
378 0 : }
379 0 : }
380 :
381 : /// Get our latest view of alive peers status on the timeline.
382 : /// We pass our own info through the broker as well, so when we don't have connection
383 : /// to the broker returned vec is empty.
384 23 : pub(crate) fn get_peers(&self, heartbeat_timeout: Duration) -> Vec<PeerInfo> {
385 23 : let now = Instant::now();
386 23 : self.peers_info
387 23 : .0
388 23 : .iter()
389 23 : // Regard peer as absent if we haven't heard from it within heartbeat_timeout.
390 23 : .filter(|p| now.duration_since(p.ts) <= heartbeat_timeout)
391 23 : .cloned()
392 23 : .collect()
393 23 : }
394 : }
395 :
396 : #[derive(Debug, thiserror::Error)]
397 : pub enum TimelineError {
398 : #[error("Timeline {0} was cancelled and cannot be used anymore")]
399 : Cancelled(TenantTimelineId),
400 : #[error("Timeline {0} was not found in global map")]
401 : NotFound(TenantTimelineId),
402 : #[error("Timeline {0} creation is in progress")]
403 : CreationInProgress(TenantTimelineId),
404 : #[error("Timeline {0} exists on disk, but wasn't loaded on startup")]
405 : Invalid(TenantTimelineId),
406 : #[error("Timeline {0} is already exists")]
407 : AlreadyExists(TenantTimelineId),
408 : #[error("Timeline {0} is not initialized, wal_seg_size is zero")]
409 : UninitializedWalSegSize(TenantTimelineId),
410 : #[error("Timeline {0} is not initialized, pg_version is unknown")]
411 : UninitialinzedPgVersion(TenantTimelineId),
412 : }
413 :
414 : // Convert to HTTP API error.
415 : impl From<TimelineError> for ApiError {
416 0 : fn from(te: TimelineError) -> ApiError {
417 0 : match te {
418 0 : TimelineError::NotFound(ttid) => {
419 0 : ApiError::NotFound(anyhow!("timeline {} not found", ttid).into())
420 : }
421 0 : _ => ApiError::InternalServerError(anyhow!("{}", te)),
422 : }
423 0 : }
424 : }
425 :
426 : /// Timeline struct manages lifecycle (creation, deletion, restore) of a safekeeper timeline.
427 : /// It also holds SharedState and provides mutually exclusive access to it.
428 : pub struct Timeline {
429 : pub ttid: TenantTimelineId,
430 : pub remote_path: RemotePath,
431 :
432 : /// Used to broadcast commit_lsn updates to all background jobs.
433 : commit_lsn_watch_tx: watch::Sender<Lsn>,
434 : commit_lsn_watch_rx: watch::Receiver<Lsn>,
435 :
436 : /// Broadcasts (current term, flush_lsn) updates, walsender is interested in
437 : /// them when sending in recovery mode (to walproposer or peers). Note: this
438 : /// is just a notification, WAL reading should always done with lock held as
439 : /// term can change otherwise.
440 : term_flush_lsn_watch_tx: watch::Sender<TermLsn>,
441 : term_flush_lsn_watch_rx: watch::Receiver<TermLsn>,
442 :
443 : /// Broadcasts shared state updates.
444 : shared_state_version_tx: watch::Sender<usize>,
445 : shared_state_version_rx: watch::Receiver<usize>,
446 :
447 : /// Safekeeper and other state, that should remain consistent and
448 : /// synchronized with the disk. This is tokio mutex as we write WAL to disk
449 : /// while holding it, ensuring that consensus checks are in order.
450 : mutex: RwLock<SharedState>,
451 : walsenders: Arc<WalSenders>,
452 : walreceivers: Arc<WalReceivers>,
453 : timeline_dir: Utf8PathBuf,
454 : manager_ctl: ManagerCtl,
455 : conf: Arc<SafeKeeperConf>,
456 :
457 : /// Hold this gate from code that depends on the Timeline's non-shut-down state. While holding
458 : /// this gate, you must respect [`Timeline::cancel`]
459 : pub(crate) gate: Gate,
460 :
461 : /// Delete/cancel will trigger this, background tasks should drop out as soon as it fires
462 : pub(crate) cancel: CancellationToken,
463 :
464 : // timeline_manager controlled state
465 : pub(crate) broker_active: AtomicBool,
466 : pub(crate) wal_backup_active: AtomicBool,
467 : pub(crate) last_removed_segno: AtomicU64,
468 : pub(crate) mgr_status: AtomicStatus,
469 : }
470 :
471 : impl Timeline {
472 : /// Constructs a new timeline.
473 3 : pub fn new(
474 3 : ttid: TenantTimelineId,
475 3 : timeline_dir: &Utf8Path,
476 3 : remote_path: &RemotePath,
477 3 : shared_state: SharedState,
478 3 : conf: Arc<SafeKeeperConf>,
479 3 : ) -> Arc<Self> {
480 3 : let (commit_lsn_watch_tx, commit_lsn_watch_rx) =
481 3 : watch::channel(shared_state.sk.state().commit_lsn);
482 3 : let (term_flush_lsn_watch_tx, term_flush_lsn_watch_rx) = watch::channel(TermLsn::from((
483 3 : shared_state.sk.last_log_term(),
484 3 : shared_state.sk.flush_lsn(),
485 3 : )));
486 3 : let (shared_state_version_tx, shared_state_version_rx) = watch::channel(0);
487 3 :
488 3 : let walreceivers = WalReceivers::new();
489 3 :
490 3 : Arc::new(Self {
491 3 : ttid,
492 3 : remote_path: remote_path.to_owned(),
493 3 : timeline_dir: timeline_dir.to_owned(),
494 3 : commit_lsn_watch_tx,
495 3 : commit_lsn_watch_rx,
496 3 : term_flush_lsn_watch_tx,
497 3 : term_flush_lsn_watch_rx,
498 3 : shared_state_version_tx,
499 3 : shared_state_version_rx,
500 3 : mutex: RwLock::new(shared_state),
501 3 : walsenders: WalSenders::new(walreceivers.clone()),
502 3 : walreceivers,
503 3 : gate: Default::default(),
504 3 : cancel: CancellationToken::default(),
505 3 : manager_ctl: ManagerCtl::new(),
506 3 : conf,
507 3 : broker_active: AtomicBool::new(false),
508 3 : wal_backup_active: AtomicBool::new(false),
509 3 : last_removed_segno: AtomicU64::new(0),
510 3 : mgr_status: AtomicStatus::new(),
511 3 : })
512 3 : }
513 :
514 : /// Load existing timeline from disk.
515 0 : pub fn load_timeline(
516 0 : conf: Arc<SafeKeeperConf>,
517 0 : ttid: TenantTimelineId,
518 0 : ) -> Result<Arc<Timeline>> {
519 0 : let _enter = info_span!("load_timeline", timeline = %ttid.timeline_id).entered();
520 :
521 0 : let shared_state = SharedState::restore(conf.as_ref(), &ttid)?;
522 0 : let timeline_dir = get_timeline_dir(conf.as_ref(), &ttid);
523 0 : let remote_path = remote_timeline_path(&ttid)?;
524 :
525 0 : Ok(Timeline::new(
526 0 : ttid,
527 0 : &timeline_dir,
528 0 : &remote_path,
529 0 : shared_state,
530 0 : conf,
531 0 : ))
532 0 : }
533 :
534 : /// Bootstrap new or existing timeline starting background tasks.
535 3 : pub fn bootstrap(
536 3 : self: &Arc<Timeline>,
537 3 : _shared_state: &mut WriteGuardSharedState<'_>,
538 3 : conf: &SafeKeeperConf,
539 3 : broker_active_set: Arc<TimelinesSet>,
540 3 : partial_backup_rate_limiter: RateLimiter,
541 3 : ) {
542 3 : let (tx, rx) = self.manager_ctl.bootstrap_manager();
543 :
544 3 : let Ok(gate_guard) = self.gate.enter() else {
545 : // Init raced with shutdown
546 0 : return;
547 : };
548 :
549 : // Start manager task which will monitor timeline state and update
550 : // background tasks.
551 3 : tokio::spawn({
552 3 : let this = self.clone();
553 3 : let conf = conf.clone();
554 3 : async move {
555 3 : let _gate_guard = gate_guard;
556 3 : timeline_manager::main_task(
557 3 : ManagerTimeline { tli: this },
558 3 : conf,
559 3 : broker_active_set,
560 3 : tx,
561 3 : rx,
562 3 : partial_backup_rate_limiter,
563 3 : )
564 3 : .await
565 3 : }
566 3 : });
567 3 : }
568 :
569 : /// Background timeline activities (which hold Timeline::gate) will no
570 : /// longer run once this function completes.
571 0 : pub async fn shutdown(&self) {
572 0 : info!("timeline {} shutting down", self.ttid);
573 0 : self.cancel.cancel();
574 0 :
575 0 : // Wait for any concurrent tasks to stop using this timeline, to avoid e.g. attempts
576 0 : // to read deleted files.
577 0 : self.gate.close().await;
578 0 : }
579 :
580 : /// Delete timeline from disk completely, by removing timeline directory.
581 : ///
582 : /// Also deletes WAL in s3. Might fail if e.g. s3 is unavailable, but
583 : /// deletion API endpoint is retriable.
584 : ///
585 : /// Timeline must be in shut-down state (i.e. call [`Self::shutdown`] first)
586 0 : pub async fn delete(
587 0 : &self,
588 0 : shared_state: &mut WriteGuardSharedState<'_>,
589 0 : only_local: bool,
590 0 : ) -> Result<bool> {
591 0 : // Assert that [`Self::shutdown`] was already called
592 0 : assert!(self.cancel.is_cancelled());
593 0 : assert!(self.gate.close_complete());
594 :
595 : // Close associated FDs. Nobody will be able to touch timeline data once
596 : // it is cancelled, so WAL storage won't be opened again.
597 0 : shared_state.sk.close_wal_store();
598 0 :
599 0 : if !only_local && self.conf.is_wal_backup_enabled() {
600 : // Note: we concurrently delete remote storage data from multiple
601 : // safekeepers. That's ok, s3 replies 200 if object doesn't exist and we
602 : // do some retries anyway.
603 0 : wal_backup::delete_timeline(&self.ttid).await?;
604 0 : }
605 0 : let dir_existed = delete_dir(&self.timeline_dir).await?;
606 0 : Ok(dir_existed)
607 0 : }
608 :
609 : /// Returns if timeline is cancelled.
610 2415 : pub fn is_cancelled(&self) -> bool {
611 2415 : self.cancel.is_cancelled()
612 2415 : }
613 :
614 : /// Take a writing mutual exclusive lock on timeline shared_state.
615 1206 : pub async fn write_shared_state<'a>(self: &'a Arc<Self>) -> WriteGuardSharedState<'a> {
616 1206 : WriteGuardSharedState::new(self.clone(), self.mutex.write().await)
617 1206 : }
618 :
619 34 : pub async fn read_shared_state(&self) -> ReadGuardSharedState {
620 34 : self.mutex.read().await
621 34 : }
622 :
623 : /// Returns commit_lsn watch channel.
624 3 : pub fn get_commit_lsn_watch_rx(&self) -> watch::Receiver<Lsn> {
625 3 : self.commit_lsn_watch_rx.clone()
626 3 : }
627 :
628 : /// Returns term_flush_lsn watch channel.
629 0 : pub fn get_term_flush_lsn_watch_rx(&self) -> watch::Receiver<TermLsn> {
630 0 : self.term_flush_lsn_watch_rx.clone()
631 0 : }
632 :
633 : /// Returns watch channel for SharedState update version.
634 3 : pub fn get_state_version_rx(&self) -> watch::Receiver<usize> {
635 3 : self.shared_state_version_rx.clone()
636 3 : }
637 :
638 : /// Returns wal_seg_size.
639 3 : pub async fn get_wal_seg_size(&self) -> usize {
640 3 : self.read_shared_state().await.get_wal_seg_size()
641 3 : }
642 :
643 : /// Returns state of the timeline.
644 5 : pub async fn get_state(&self) -> (TimelineMemState, TimelinePersistentState) {
645 5 : let state = self.read_shared_state().await;
646 5 : (
647 5 : state.sk.state().inmem.clone(),
648 5 : TimelinePersistentState::clone(state.sk.state()),
649 5 : )
650 5 : }
651 :
652 : /// Returns latest backup_lsn.
653 0 : pub async fn get_wal_backup_lsn(&self) -> Lsn {
654 0 : self.read_shared_state().await.sk.state().inmem.backup_lsn
655 0 : }
656 :
657 : /// Sets backup_lsn to the given value.
658 0 : pub async fn set_wal_backup_lsn(self: &Arc<Self>, backup_lsn: Lsn) -> Result<()> {
659 0 : if self.is_cancelled() {
660 0 : bail!(TimelineError::Cancelled(self.ttid));
661 0 : }
662 :
663 0 : let mut state = self.write_shared_state().await;
664 0 : state.sk.state_mut().inmem.backup_lsn = max(state.sk.state().inmem.backup_lsn, backup_lsn);
665 0 : // we should check whether to shut down offloader, but this will be done
666 0 : // soon by peer communication anyway.
667 0 : Ok(())
668 0 : }
669 :
670 : /// Get safekeeper info for broadcasting to broker and other peers.
671 0 : pub async fn get_safekeeper_info(&self, conf: &SafeKeeperConf) -> SafekeeperTimelineInfo {
672 0 : let standby_apply_lsn = self.walsenders.get_hotstandby().reply.apply_lsn;
673 0 : let shared_state = self.read_shared_state().await;
674 0 : shared_state.get_safekeeper_info(&self.ttid, conf, standby_apply_lsn)
675 0 : }
676 :
677 : /// Update timeline state with peer safekeeper data.
678 0 : pub async fn record_safekeeper_info(
679 0 : self: &Arc<Self>,
680 0 : sk_info: SafekeeperTimelineInfo,
681 0 : ) -> Result<()> {
682 : {
683 0 : let mut shared_state = self.write_shared_state().await;
684 0 : shared_state.sk.record_safekeeper_info(&sk_info).await?;
685 0 : let peer_info = peer_info_from_sk_info(&sk_info, Instant::now());
686 0 : shared_state.peers_info.upsert(&peer_info);
687 0 : }
688 0 : Ok(())
689 0 : }
690 :
691 0 : pub async fn get_peers(&self, conf: &SafeKeeperConf) -> Vec<PeerInfo> {
692 0 : let shared_state = self.read_shared_state().await;
693 0 : shared_state.get_peers(conf.heartbeat_timeout)
694 0 : }
695 :
696 3 : pub fn get_walsenders(&self) -> &Arc<WalSenders> {
697 3 : &self.walsenders
698 3 : }
699 :
700 9 : pub fn get_walreceivers(&self) -> &Arc<WalReceivers> {
701 9 : &self.walreceivers
702 9 : }
703 :
704 : /// Returns flush_lsn.
705 0 : pub async fn get_flush_lsn(&self) -> Lsn {
706 0 : self.read_shared_state().await.sk.flush_lsn()
707 0 : }
708 :
709 : /// Gather timeline data for metrics.
710 0 : pub async fn info_for_metrics(&self) -> Option<FullTimelineInfo> {
711 0 : if self.is_cancelled() {
712 0 : return None;
713 0 : }
714 0 :
715 0 : let WalSendersTimelineMetricValues {
716 0 : ps_feedback_counter,
717 0 : last_ps_feedback,
718 0 : interpreted_wal_reader_tasks,
719 0 : } = self.walsenders.info_for_metrics();
720 :
721 0 : let state = self.read_shared_state().await;
722 0 : Some(FullTimelineInfo {
723 0 : ttid: self.ttid,
724 0 : ps_feedback_count: ps_feedback_counter,
725 0 : last_ps_feedback,
726 0 : wal_backup_active: self.wal_backup_active.load(Ordering::Relaxed),
727 0 : timeline_is_active: self.broker_active.load(Ordering::Relaxed),
728 0 : num_computes: self.walreceivers.get_num() as u32,
729 0 : last_removed_segno: self.last_removed_segno.load(Ordering::Relaxed),
730 0 : interpreted_wal_reader_tasks,
731 0 : epoch_start_lsn: state.sk.term_start_lsn(),
732 0 : mem_state: state.sk.state().inmem.clone(),
733 0 : persisted_state: TimelinePersistentState::clone(state.sk.state()),
734 0 : flush_lsn: state.sk.flush_lsn(),
735 0 : wal_storage: state.sk.wal_storage_metrics(),
736 0 : })
737 0 : }
738 :
739 : /// Returns in-memory timeline state to build a full debug dump.
740 0 : pub async fn memory_dump(&self) -> debug_dump::Memory {
741 0 : let state = self.read_shared_state().await;
742 :
743 0 : let (write_lsn, write_record_lsn, flush_lsn, file_open) =
744 0 : state.sk.wal_storage_internal_state();
745 0 :
746 0 : debug_dump::Memory {
747 0 : is_cancelled: self.is_cancelled(),
748 0 : peers_info_len: state.peers_info.0.len(),
749 0 : walsenders: self.walsenders.get_all_public(),
750 0 : wal_backup_active: self.wal_backup_active.load(Ordering::Relaxed),
751 0 : active: self.broker_active.load(Ordering::Relaxed),
752 0 : num_computes: self.walreceivers.get_num() as u32,
753 0 : last_removed_segno: self.last_removed_segno.load(Ordering::Relaxed),
754 0 : epoch_start_lsn: state.sk.term_start_lsn(),
755 0 : mem_state: state.sk.state().inmem.clone(),
756 0 : mgr_status: self.mgr_status.get(),
757 0 : write_lsn,
758 0 : write_record_lsn,
759 0 : flush_lsn,
760 0 : file_open,
761 0 : }
762 0 : }
763 :
764 : /// Apply a function to the control file state and persist it.
765 0 : pub async fn map_control_file<T>(
766 0 : self: &Arc<Self>,
767 0 : f: impl FnOnce(&mut TimelinePersistentState) -> Result<T>,
768 0 : ) -> Result<T> {
769 0 : let mut state = self.write_shared_state().await;
770 0 : let mut persistent_state = state.sk.state_mut().start_change();
771 : // If f returns error, we abort the change and don't persist anything.
772 0 : let res = f(&mut persistent_state)?;
773 : // If persisting fails, we abort the change and return error.
774 0 : state
775 0 : .sk
776 0 : .state_mut()
777 0 : .finish_change(&persistent_state)
778 0 : .await?;
779 0 : Ok(res)
780 0 : }
781 :
782 0 : pub async fn term_bump(self: &Arc<Self>, to: Option<Term>) -> Result<TimelineTermBumpResponse> {
783 0 : let mut state = self.write_shared_state().await;
784 0 : state.sk.term_bump(to).await
785 0 : }
786 :
787 0 : pub async fn membership_switch(
788 0 : self: &Arc<Self>,
789 0 : to: Configuration,
790 0 : ) -> Result<TimelineMembershipSwitchResponse> {
791 0 : let mut state = self.write_shared_state().await;
792 0 : state.sk.membership_switch(to).await
793 0 : }
794 :
795 : /// Guts of [`Self::wal_residence_guard`] and [`Self::try_wal_residence_guard`]
796 6 : async fn do_wal_residence_guard(
797 6 : self: &Arc<Self>,
798 6 : block: bool,
799 6 : ) -> Result<Option<WalResidentTimeline>> {
800 6 : let op_label = if block {
801 6 : "wal_residence_guard"
802 : } else {
803 0 : "try_wal_residence_guard"
804 : };
805 :
806 6 : if self.is_cancelled() {
807 0 : bail!(TimelineError::Cancelled(self.ttid));
808 6 : }
809 6 :
810 6 : debug!("requesting WalResidentTimeline guard");
811 6 : let started_at = Instant::now();
812 6 : let status_before = self.mgr_status.get();
813 :
814 : // Wait 30 seconds for the guard to be acquired. It can time out if someone is
815 : // holding the lock (e.g. during `SafeKeeper::process_msg()`) or manager task
816 : // is stuck.
817 6 : let res = tokio::time::timeout_at(started_at + Duration::from_secs(30), async {
818 6 : if block {
819 6 : self.manager_ctl.wal_residence_guard().await.map(Some)
820 : } else {
821 0 : self.manager_ctl.try_wal_residence_guard().await
822 : }
823 6 : })
824 6 : .await;
825 :
826 6 : let guard = match res {
827 6 : Ok(Ok(guard)) => {
828 6 : let finished_at = Instant::now();
829 6 : let elapsed = finished_at - started_at;
830 6 : MISC_OPERATION_SECONDS
831 6 : .with_label_values(&[op_label])
832 6 : .observe(elapsed.as_secs_f64());
833 6 :
834 6 : guard
835 : }
836 0 : Ok(Err(e)) => {
837 0 : warn!(
838 0 : "error acquiring in {op_label}, statuses {:?} => {:?}",
839 0 : status_before,
840 0 : self.mgr_status.get()
841 : );
842 0 : return Err(e);
843 : }
844 : Err(_) => {
845 0 : warn!(
846 0 : "timeout acquiring in {op_label} guard, statuses {:?} => {:?}",
847 0 : status_before,
848 0 : self.mgr_status.get()
849 : );
850 0 : anyhow::bail!("timeout while acquiring WalResidentTimeline guard");
851 : }
852 : };
853 :
854 6 : Ok(guard.map(|g| WalResidentTimeline::new(self.clone(), g)))
855 6 : }
856 :
857 : /// Get the timeline guard for reading/writing WAL files.
858 : /// If WAL files are not present on disk (evicted), they will be automatically
859 : /// downloaded from remote storage. This is done in the manager task, which is
860 : /// responsible for issuing all guards.
861 : ///
862 : /// NB: don't use this function from timeline_manager, it will deadlock.
863 : /// NB: don't use this function while holding shared_state lock.
864 6 : pub async fn wal_residence_guard(self: &Arc<Self>) -> Result<WalResidentTimeline> {
865 6 : self.do_wal_residence_guard(true)
866 6 : .await
867 6 : .map(|m| m.expect("Always get Some in block=true mode"))
868 6 : }
869 :
870 : /// Get the timeline guard for reading/writing WAL files if the timeline is resident,
871 : /// else return None
872 0 : pub(crate) async fn try_wal_residence_guard(
873 0 : self: &Arc<Self>,
874 0 : ) -> Result<Option<WalResidentTimeline>> {
875 0 : self.do_wal_residence_guard(false).await
876 0 : }
877 :
878 0 : pub async fn backup_partial_reset(self: &Arc<Self>) -> Result<Vec<String>> {
879 0 : self.manager_ctl.backup_partial_reset().await
880 0 : }
881 : }
882 :
883 : /// This is a guard that allows to read/write disk timeline state.
884 : /// All tasks that are trying to read/write WAL from disk should use this guard.
885 : pub struct WalResidentTimeline {
886 : pub tli: Arc<Timeline>,
887 : _guard: ResidenceGuard,
888 : }
889 :
890 : impl WalResidentTimeline {
891 9 : pub fn new(tli: Arc<Timeline>, _guard: ResidenceGuard) -> Self {
892 9 : WalResidentTimeline { tli, _guard }
893 9 : }
894 : }
895 :
896 : impl Deref for WalResidentTimeline {
897 : type Target = Arc<Timeline>;
898 :
899 5450 : fn deref(&self) -> &Self::Target {
900 5450 : &self.tli
901 5450 : }
902 : }
903 :
904 : impl WalResidentTimeline {
905 : /// Returns true if walsender should stop sending WAL to pageserver. We
906 : /// terminate it if remote_consistent_lsn reached commit_lsn and there is no
907 : /// computes. While there might be nothing to stream already, we learn about
908 : /// remote_consistent_lsn update through replication feedback, and we want
909 : /// to stop pushing to the broker if pageserver is fully caughtup.
910 0 : pub async fn should_walsender_stop(&self, reported_remote_consistent_lsn: Lsn) -> bool {
911 0 : if self.is_cancelled() {
912 0 : return true;
913 0 : }
914 0 : let shared_state = self.read_shared_state().await;
915 0 : if self.walreceivers.get_num() == 0 {
916 0 : return shared_state.sk.state().inmem.commit_lsn == Lsn(0) || // no data at all yet
917 0 : reported_remote_consistent_lsn >= shared_state.sk.state().inmem.commit_lsn;
918 0 : }
919 0 : false
920 0 : }
921 :
922 : /// Ensure that current term is t, erroring otherwise, and lock the state.
923 0 : pub async fn acquire_term(&self, t: Term) -> Result<ReadGuardSharedState> {
924 0 : let ss = self.read_shared_state().await;
925 0 : if ss.sk.state().acceptor_state.term != t {
926 0 : bail!(
927 0 : "failed to acquire term {}, current term {}",
928 0 : t,
929 0 : ss.sk.state().acceptor_state.term
930 0 : );
931 0 : }
932 0 : Ok(ss)
933 0 : }
934 :
935 : /// Pass arrived message to the safekeeper.
936 1200 : pub async fn process_msg(
937 1200 : &self,
938 1200 : msg: &ProposerAcceptorMessage,
939 1200 : ) -> Result<Option<AcceptorProposerMessage>> {
940 1200 : if self.is_cancelled() {
941 0 : bail!(TimelineError::Cancelled(self.ttid));
942 1200 : }
943 :
944 : let mut rmsg: Option<AcceptorProposerMessage>;
945 : {
946 1200 : let mut shared_state = self.write_shared_state().await;
947 1200 : rmsg = shared_state.sk.safekeeper().process_msg(msg).await?;
948 :
949 : // if this is AppendResponse, fill in proper hot standby feedback.
950 600 : if let Some(AcceptorProposerMessage::AppendResponse(ref mut resp)) = rmsg {
951 600 : resp.hs_feedback = self.walsenders.get_hotstandby().hs_feedback;
952 600 : }
953 : }
954 1200 : Ok(rmsg)
955 1200 : }
956 :
957 5 : pub async fn get_walreader(&self, start_lsn: Lsn) -> Result<WalReader> {
958 5 : let (_, persisted_state) = self.get_state().await;
959 5 : let enable_remote_read = self.conf.is_wal_backup_enabled();
960 5 :
961 5 : WalReader::new(
962 5 : &self.ttid,
963 5 : self.timeline_dir.clone(),
964 5 : &persisted_state,
965 5 : start_lsn,
966 5 : enable_remote_read,
967 5 : )
968 5 : }
969 :
970 0 : pub fn get_timeline_dir(&self) -> Utf8PathBuf {
971 0 : self.timeline_dir.clone()
972 0 : }
973 :
974 : /// Update in memory remote consistent lsn.
975 0 : pub async fn update_remote_consistent_lsn(&self, candidate: Lsn) {
976 0 : let mut shared_state = self.write_shared_state().await;
977 0 : shared_state.sk.state_mut().inmem.remote_consistent_lsn = max(
978 0 : shared_state.sk.state().inmem.remote_consistent_lsn,
979 0 : candidate,
980 0 : );
981 0 : }
982 : }
983 :
984 : /// This struct contains methods that are used by timeline manager task.
985 : pub(crate) struct ManagerTimeline {
986 : pub(crate) tli: Arc<Timeline>,
987 : }
988 :
989 : impl Deref for ManagerTimeline {
990 : type Target = Arc<Timeline>;
991 :
992 250 : fn deref(&self) -> &Self::Target {
993 250 : &self.tli
994 250 : }
995 : }
996 :
997 : impl ManagerTimeline {
998 0 : pub(crate) fn timeline_dir(&self) -> &Utf8PathBuf {
999 0 : &self.tli.timeline_dir
1000 0 : }
1001 :
1002 : /// Manager requests this state on startup.
1003 3 : pub(crate) async fn bootstrap_mgr(&self) -> (bool, Option<PartialRemoteSegment>) {
1004 3 : let shared_state = self.read_shared_state().await;
1005 3 : let is_offloaded = matches!(
1006 3 : shared_state.sk.state().eviction_state,
1007 : EvictionState::Offloaded(_)
1008 : );
1009 3 : let partial_backup_uploaded = shared_state.sk.state().partial_backup.uploaded_segment();
1010 3 :
1011 3 : (is_offloaded, partial_backup_uploaded)
1012 3 : }
1013 :
1014 : /// Try to switch state Present->Offloaded.
1015 0 : pub(crate) async fn switch_to_offloaded(
1016 0 : &self,
1017 0 : partial: &PartialRemoteSegment,
1018 0 : ) -> anyhow::Result<()> {
1019 0 : let mut shared = self.write_shared_state().await;
1020 :
1021 : // updating control file
1022 0 : let mut pstate = shared.sk.state_mut().start_change();
1023 :
1024 0 : if !matches!(pstate.eviction_state, EvictionState::Present) {
1025 0 : bail!(
1026 0 : "cannot switch to offloaded state, current state is {:?}",
1027 0 : pstate.eviction_state
1028 0 : );
1029 0 : }
1030 0 :
1031 0 : if partial.flush_lsn != shared.sk.flush_lsn() {
1032 0 : bail!(
1033 0 : "flush_lsn mismatch in partial backup, expected {}, got {}",
1034 0 : shared.sk.flush_lsn(),
1035 0 : partial.flush_lsn
1036 0 : );
1037 0 : }
1038 0 :
1039 0 : if partial.commit_lsn != pstate.commit_lsn {
1040 0 : bail!(
1041 0 : "commit_lsn mismatch in partial backup, expected {}, got {}",
1042 0 : pstate.commit_lsn,
1043 0 : partial.commit_lsn
1044 0 : );
1045 0 : }
1046 0 :
1047 0 : if partial.term != shared.sk.last_log_term() {
1048 0 : bail!(
1049 0 : "term mismatch in partial backup, expected {}, got {}",
1050 0 : shared.sk.last_log_term(),
1051 0 : partial.term
1052 0 : );
1053 0 : }
1054 0 :
1055 0 : pstate.eviction_state = EvictionState::Offloaded(shared.sk.flush_lsn());
1056 0 : shared.sk.state_mut().finish_change(&pstate).await?;
1057 : // control file is now switched to Offloaded state
1058 :
1059 : // now we can switch shared.sk to Offloaded, shouldn't fail
1060 0 : let prev_sk = std::mem::replace(&mut shared.sk, StateSK::Empty);
1061 0 : let cfile_state = prev_sk.take_state();
1062 0 : shared.sk = StateSK::Offloaded(Box::new(cfile_state));
1063 0 :
1064 0 : Ok(())
1065 0 : }
1066 :
1067 : /// Try to switch state Offloaded->Present.
1068 0 : pub(crate) async fn switch_to_present(&self) -> anyhow::Result<()> {
1069 0 : let mut shared = self.write_shared_state().await;
1070 :
1071 : // trying to restore WAL storage
1072 0 : let wal_store = wal_storage::PhysicalStorage::new(
1073 0 : &self.ttid,
1074 0 : &self.timeline_dir,
1075 0 : shared.sk.state(),
1076 0 : self.conf.no_sync,
1077 0 : )?;
1078 :
1079 : // updating control file
1080 0 : let mut pstate = shared.sk.state_mut().start_change();
1081 :
1082 0 : if !matches!(pstate.eviction_state, EvictionState::Offloaded(_)) {
1083 0 : bail!(
1084 0 : "cannot switch to present state, current state is {:?}",
1085 0 : pstate.eviction_state
1086 0 : );
1087 0 : }
1088 0 :
1089 0 : if wal_store.flush_lsn() != shared.sk.flush_lsn() {
1090 0 : bail!(
1091 0 : "flush_lsn mismatch in restored WAL, expected {}, got {}",
1092 0 : shared.sk.flush_lsn(),
1093 0 : wal_store.flush_lsn()
1094 0 : );
1095 0 : }
1096 0 :
1097 0 : pstate.eviction_state = EvictionState::Present;
1098 0 : shared.sk.state_mut().finish_change(&pstate).await?;
1099 :
1100 : // now we can switch shared.sk to Present, shouldn't fail
1101 0 : let prev_sk = std::mem::replace(&mut shared.sk, StateSK::Empty);
1102 0 : let cfile_state = prev_sk.take_state();
1103 0 : shared.sk = StateSK::Loaded(SafeKeeper::new(cfile_state, wal_store, self.conf.my_id)?);
1104 :
1105 0 : Ok(())
1106 0 : }
1107 :
1108 : /// Update current manager state, useful for debugging manager deadlocks.
1109 134 : pub(crate) fn set_status(&self, status: timeline_manager::Status) {
1110 134 : self.mgr_status.store(status, Ordering::Relaxed);
1111 134 : }
1112 : }
1113 :
1114 : /// Deletes directory and it's contents. Returns false if directory does not exist.
1115 0 : async fn delete_dir(path: &Utf8PathBuf) -> Result<bool> {
1116 0 : match fs::remove_dir_all(path).await {
1117 0 : Ok(_) => Ok(true),
1118 0 : Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
1119 0 : Err(e) => Err(e.into()),
1120 : }
1121 0 : }
1122 :
1123 : /// Get a path to the tenant directory. If you just need to get a timeline directory,
1124 : /// use WalResidentTimeline::get_timeline_dir instead.
1125 6 : pub fn get_tenant_dir(conf: &SafeKeeperConf, tenant_id: &TenantId) -> Utf8PathBuf {
1126 6 : conf.workdir.join(tenant_id.to_string())
1127 6 : }
1128 :
1129 : /// Get a path to the timeline directory. If you need to read WAL files from disk,
1130 : /// use WalResidentTimeline::get_timeline_dir instead. This function does not check
1131 : /// timeline eviction status and WAL files might not be present on disk.
1132 6 : pub fn get_timeline_dir(conf: &SafeKeeperConf, ttid: &TenantTimelineId) -> Utf8PathBuf {
1133 6 : get_tenant_dir(conf, &ttid.tenant_id).join(ttid.timeline_id.to_string())
1134 6 : }
|