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