LCOV - code coverage report
Current view: top level - safekeeper/src - timeline.rs (source / functions) Coverage Total Hit
Test: 9ea6db2ee0fa9d49a3b75230199d5aaf7b855d49.info Lines: 34.3 % 746 256
Test Date: 2025-07-18 08:04:09 Functions: 39.7 % 126 50

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

Generated by: LCOV version 2.1-beta