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