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