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