LCOV - code coverage report
Current view: top level - safekeeper/src - timeline.rs (source / functions) Coverage Total Hit
Test: 4be46b1c0003aa3bbac9ade362c676b419df4c20.info Lines: 34.2 % 748 256
Test Date: 2025-07-22 17:50:06 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         2576 :     pub fn flush_lsn(&self) -> Lsn {
     156         2576 :         match self {
     157         2576 :             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         2576 :     }
     165              : 
     166              :     /// Get a reference to the control file's timeline state.
     167         2609 :     pub fn state(&self) -> &TimelineState<control_file::FileStorage> {
     168         2609 :         match self {
     169         2609 :             StateSK::Loaded(sk) => &sk.state,
     170            0 :             StateSK::Offloaded(s) => s,
     171            0 :             StateSK::Empty => unreachable!(),
     172              :         }
     173         2609 :     }
     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         1288 :     pub fn last_log_term(&self) -> Term {
     184         1288 :         self.state()
     185         1288 :             .acceptor_state
     186         1288 :             .get_last_log_term(self.flush_lsn())
     187         1288 :     }
     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           34 :     pub(crate) fn get_peers(&self, heartbeat_timeout: Duration) -> Vec<PeerInfo> {
     392           34 :         let now = Instant::now();
     393           34 :         self.peers_info
     394           34 :             .0
     395           34 :             .iter()
     396              :             // Regard peer as absent if we haven't heard from it within heartbeat_timeout.
     397           34 :             .filter(|p| now.duration_since(p.ts) <= heartbeat_timeout)
     398           34 :             .cloned()
     399           34 :             .collect()
     400           34 :     }
     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 :             TimelineError::Deleted(ttid) => {
     431            0 :                 ApiError::NotFound(anyhow!("timeline {} deleted", ttid).into())
     432              :             }
     433            0 :             _ => ApiError::InternalServerError(anyhow!("{}", te)),
     434              :         }
     435            0 :     }
     436              : }
     437              : 
     438              : /// We run remote deletion in a background task, this is how it sends its results back.
     439              : type RemoteDeletionReceiver = tokio::sync::watch::Receiver<Option<anyhow::Result<()>>>;
     440              : 
     441              : /// Timeline struct manages lifecycle (creation, deletion, restore) of a safekeeper timeline.
     442              : /// It also holds SharedState and provides mutually exclusive access to it.
     443              : pub struct Timeline {
     444              :     pub ttid: TenantTimelineId,
     445              :     pub remote_path: RemotePath,
     446              : 
     447              :     /// Used to broadcast commit_lsn updates to all background jobs.
     448              :     commit_lsn_watch_tx: watch::Sender<Lsn>,
     449              :     commit_lsn_watch_rx: watch::Receiver<Lsn>,
     450              : 
     451              :     /// Broadcasts (current term, flush_lsn) updates, walsender is interested in
     452              :     /// them when sending in recovery mode (to walproposer or peers). Note: this
     453              :     /// is just a notification, WAL reading should always done with lock held as
     454              :     /// term can change otherwise.
     455              :     term_flush_lsn_watch_tx: watch::Sender<TermLsn>,
     456              :     term_flush_lsn_watch_rx: watch::Receiver<TermLsn>,
     457              : 
     458              :     /// Broadcasts shared state updates.
     459              :     shared_state_version_tx: watch::Sender<usize>,
     460              :     shared_state_version_rx: watch::Receiver<usize>,
     461              : 
     462              :     /// Safekeeper and other state, that should remain consistent and
     463              :     /// synchronized with the disk. This is tokio mutex as we write WAL to disk
     464              :     /// while holding it, ensuring that consensus checks are in order.
     465              :     mutex: RwLock<SharedState>,
     466              :     walsenders: Arc<WalSenders>,
     467              :     walreceivers: Arc<WalReceivers>,
     468              :     timeline_dir: Utf8PathBuf,
     469              :     manager_ctl: ManagerCtl,
     470              :     conf: Arc<SafeKeeperConf>,
     471              : 
     472              :     pub(crate) wal_backup: Arc<WalBackup>,
     473              : 
     474              :     remote_deletion: std::sync::Mutex<Option<RemoteDeletionReceiver>>,
     475              : 
     476              :     /// Hold this gate from code that depends on the Timeline's non-shut-down state.  While holding
     477              :     /// this gate, you must respect [`Timeline::cancel`]
     478              :     pub(crate) gate: Gate,
     479              : 
     480              :     /// Delete/cancel will trigger this, background tasks should drop out as soon as it fires
     481              :     pub(crate) cancel: CancellationToken,
     482              : 
     483              :     // timeline_manager controlled state
     484              :     pub(crate) broker_active: AtomicBool,
     485              :     pub(crate) wal_backup_active: AtomicBool,
     486              :     pub(crate) last_removed_segno: AtomicU64,
     487              :     pub(crate) mgr_status: AtomicStatus,
     488              : }
     489              : 
     490              : impl Timeline {
     491              :     /// Constructs a new timeline.
     492            5 :     pub fn new(
     493            5 :         ttid: TenantTimelineId,
     494            5 :         timeline_dir: &Utf8Path,
     495            5 :         remote_path: &RemotePath,
     496            5 :         shared_state: SharedState,
     497            5 :         conf: Arc<SafeKeeperConf>,
     498            5 :         wal_backup: Arc<WalBackup>,
     499            5 :     ) -> Arc<Self> {
     500            5 :         let (commit_lsn_watch_tx, commit_lsn_watch_rx) =
     501            5 :             watch::channel(shared_state.sk.state().commit_lsn);
     502            5 :         let (term_flush_lsn_watch_tx, term_flush_lsn_watch_rx) = watch::channel(TermLsn::from((
     503            5 :             shared_state.sk.last_log_term(),
     504            5 :             shared_state.sk.flush_lsn(),
     505            5 :         )));
     506            5 :         let (shared_state_version_tx, shared_state_version_rx) = watch::channel(0);
     507              : 
     508            5 :         let walreceivers = WalReceivers::new();
     509              : 
     510            5 :         Arc::new(Self {
     511            5 :             ttid,
     512            5 :             remote_path: remote_path.to_owned(),
     513            5 :             timeline_dir: timeline_dir.to_owned(),
     514            5 :             commit_lsn_watch_tx,
     515            5 :             commit_lsn_watch_rx,
     516            5 :             term_flush_lsn_watch_tx,
     517            5 :             term_flush_lsn_watch_rx,
     518            5 :             shared_state_version_tx,
     519            5 :             shared_state_version_rx,
     520            5 :             mutex: RwLock::new(shared_state),
     521            5 :             walsenders: WalSenders::new(walreceivers.clone()),
     522            5 :             walreceivers,
     523            5 :             gate: Default::default(),
     524            5 :             cancel: CancellationToken::default(),
     525            5 :             remote_deletion: std::sync::Mutex::new(None),
     526            5 :             manager_ctl: ManagerCtl::new(),
     527            5 :             conf,
     528            5 :             broker_active: AtomicBool::new(false),
     529            5 :             wal_backup_active: AtomicBool::new(false),
     530            5 :             last_removed_segno: AtomicU64::new(0),
     531            5 :             mgr_status: AtomicStatus::new(),
     532            5 :             wal_backup,
     533            5 :         })
     534            5 :     }
     535              : 
     536              :     /// Load existing timeline from disk.
     537            0 :     pub fn load_timeline(
     538            0 :         conf: Arc<SafeKeeperConf>,
     539            0 :         ttid: TenantTimelineId,
     540            0 :         wal_backup: Arc<WalBackup>,
     541            0 :     ) -> Result<Arc<Timeline>> {
     542            0 :         let _enter = info_span!("load_timeline", timeline = %ttid.timeline_id).entered();
     543              : 
     544            0 :         let shared_state = SharedState::restore(conf.as_ref(), &ttid)?;
     545            0 :         let timeline_dir = get_timeline_dir(conf.as_ref(), &ttid);
     546            0 :         let remote_path = remote_timeline_path(&ttid)?;
     547              : 
     548            0 :         Ok(Timeline::new(
     549            0 :             ttid,
     550            0 :             &timeline_dir,
     551            0 :             &remote_path,
     552            0 :             shared_state,
     553            0 :             conf,
     554            0 :             wal_backup,
     555            0 :         ))
     556            0 :     }
     557              : 
     558              :     /// Bootstrap new or existing timeline starting background tasks.
     559            5 :     pub fn bootstrap(
     560            5 :         self: &Arc<Timeline>,
     561            5 :         _shared_state: &mut WriteGuardSharedState<'_>,
     562            5 :         conf: &SafeKeeperConf,
     563            5 :         broker_active_set: Arc<TimelinesSet>,
     564            5 :         partial_backup_rate_limiter: RateLimiter,
     565            5 :         wal_backup: Arc<WalBackup>,
     566            5 :     ) {
     567            5 :         let (tx, rx) = self.manager_ctl.bootstrap_manager();
     568              : 
     569            5 :         let Ok(gate_guard) = self.gate.enter() else {
     570              :             // Init raced with shutdown
     571            0 :             return;
     572              :         };
     573              : 
     574              :         // Start manager task which will monitor timeline state and update
     575              :         // background tasks.
     576            5 :         tokio::spawn({
     577            5 :             let this = self.clone();
     578            5 :             let conf = conf.clone();
     579            5 :             async move {
     580            5 :                 let _gate_guard = gate_guard;
     581            5 :                 timeline_manager::main_task(
     582            5 :                     ManagerTimeline { tli: this },
     583            5 :                     conf,
     584            5 :                     broker_active_set,
     585            5 :                     tx,
     586            5 :                     rx,
     587            5 :                     partial_backup_rate_limiter,
     588            5 :                     wal_backup,
     589            5 :                 )
     590            5 :                 .await
     591            0 :             }
     592              :         });
     593            5 :     }
     594              : 
     595              :     /// Cancel the timeline, requesting background activity to stop. Closing
     596              :     /// the `self.gate` waits for that.
     597            0 :     pub async fn cancel(&self) {
     598            0 :         info!("timeline {} shutting down", self.ttid);
     599            0 :         self.cancel.cancel();
     600            0 :     }
     601              : 
     602              :     /// Background timeline activities (which hold Timeline::gate) will no
     603              :     /// longer run once this function completes. `Self::cancel` must have been
     604              :     /// already called.
     605            0 :     pub async fn close(&self) {
     606            0 :         assert!(self.cancel.is_cancelled());
     607              : 
     608              :         // Wait for any concurrent tasks to stop using this timeline, to avoid e.g. attempts
     609              :         // to read deleted files.
     610            0 :         self.gate.close().await;
     611            0 :     }
     612              : 
     613              :     /// Delete timeline from disk completely, by removing timeline directory.
     614              :     ///
     615              :     /// Also deletes WAL in s3. Might fail if e.g. s3 is unavailable, but
     616              :     /// deletion API endpoint is retriable.
     617              :     ///
     618              :     /// Timeline must be in shut-down state (i.e. call [`Self::close`] first)
     619            0 :     pub async fn delete(
     620            0 :         &self,
     621            0 :         shared_state: &mut WriteGuardSharedState<'_>,
     622            0 :         only_local: bool,
     623            0 :     ) -> Result<bool> {
     624              :         // Assert that [`Self::close`] was already called
     625            0 :         assert!(self.cancel.is_cancelled());
     626            0 :         assert!(self.gate.close_complete());
     627              : 
     628            0 :         info!("deleting timeline {} from disk", self.ttid);
     629              : 
     630              :         // Close associated FDs. Nobody will be able to touch timeline data once
     631              :         // it is cancelled, so WAL storage won't be opened again.
     632            0 :         shared_state.sk.close_wal_store();
     633              : 
     634            0 :         if !only_local {
     635            0 :             self.remote_delete().await?;
     636            0 :         }
     637              : 
     638            0 :         let dir_existed = delete_dir(&self.timeline_dir).await?;
     639            0 :         Ok(dir_existed)
     640            0 :     }
     641              : 
     642              :     /// Delete timeline content from remote storage.  If the returned future is dropped,
     643              :     /// deletion will continue in the background.
     644              :     ///
     645              :     /// This function ordinarily spawns a task and stashes a result receiver into [`Self::remote_deletion`].  If
     646              :     /// deletion is already happening, it may simply wait for an existing task's result.
     647              :     ///
     648              :     /// Note: we concurrently delete remote storage data from multiple
     649              :     /// safekeepers. That's ok, s3 replies 200 if object doesn't exist and we
     650              :     /// do some retries anyway.
     651            0 :     async fn remote_delete(&self) -> Result<()> {
     652              :         // We will start a background task to do the deletion, so that it proceeds even if our
     653              :         // API request is dropped.  Future requests will see the existing deletion task and wait
     654              :         // for it to complete.
     655            0 :         let mut result_rx = {
     656            0 :             let mut remote_deletion_state = self.remote_deletion.lock().unwrap();
     657            0 :             let result_rx = if let Some(result_rx) = remote_deletion_state.as_ref() {
     658            0 :                 if let Some(result) = result_rx.borrow().as_ref() {
     659            0 :                     if let Err(e) = result {
     660              :                         // A previous remote deletion failed: we will start a new one
     661            0 :                         tracing::error!("remote deletion failed, will retry ({e})");
     662            0 :                         None
     663              :                     } else {
     664              :                         // A previous remote deletion call already succeeded
     665            0 :                         return Ok(());
     666              :                     }
     667              :                 } else {
     668              :                     // Remote deletion is still in flight
     669            0 :                     Some(result_rx.clone())
     670              :                 }
     671              :             } else {
     672              :                 // Remote deletion was not attempted yet, start it now.
     673            0 :                 None
     674              :             };
     675              : 
     676            0 :             match result_rx {
     677            0 :                 Some(result_rx) => result_rx,
     678            0 :                 None => self.start_remote_delete(&mut remote_deletion_state),
     679              :             }
     680              :         };
     681              : 
     682              :         // Wait for a result
     683            0 :         let Ok(result) = result_rx.wait_for(|v| v.is_some()).await else {
     684              :             // Unexpected: sender should always send a result before dropping the channel, even if it has an error
     685            0 :             return Err(anyhow::anyhow!(
     686            0 :                 "remote deletion task future was dropped without sending a result"
     687            0 :             ));
     688              :         };
     689              : 
     690            0 :         result
     691            0 :             .as_ref()
     692            0 :             .expect("We did a wait_for on this being Some above")
     693            0 :             .as_ref()
     694            0 :             .map(|_| ())
     695            0 :             .map_err(|e| anyhow::anyhow!("remote deletion failed: {e}"))
     696            0 :     }
     697              : 
     698              :     /// Spawn background task to do remote deletion, return a receiver for its outcome
     699            0 :     fn start_remote_delete(
     700            0 :         &self,
     701            0 :         guard: &mut std::sync::MutexGuard<Option<RemoteDeletionReceiver>>,
     702            0 :     ) -> RemoteDeletionReceiver {
     703            0 :         tracing::info!("starting remote deletion");
     704            0 :         let storage = self.wal_backup.get_storage().clone();
     705            0 :         let (result_tx, result_rx) = tokio::sync::watch::channel(None);
     706            0 :         let ttid = self.ttid;
     707            0 :         tokio::task::spawn(
     708            0 :             async move {
     709            0 :                 let r = if let Some(storage) = storage {
     710            0 :                     wal_backup::delete_timeline(&storage, &ttid).await
     711              :                 } else {
     712            0 :                     tracing::info!(
     713            0 :                         "skipping remote deletion because no remote storage is configured; this effectively leaks the objects in remote storage"
     714              :                     );
     715            0 :                     Ok(())
     716              :                 };
     717              : 
     718            0 :                 if let Err(e) = &r {
     719              :                     // Log error here in case nobody ever listens for our result (e.g. dropped API request)
     720            0 :                     tracing::error!("remote deletion failed: {e}");
     721            0 :                 }
     722              : 
     723              :                 // Ignore send results: it's legal for the Timeline to give up waiting for us.
     724            0 :                 let _ = result_tx.send(Some(r));
     725            0 :             }
     726            0 :             .instrument(info_span!("remote_delete", timeline = %self.ttid)),
     727              :         );
     728              : 
     729            0 :         **guard = Some(result_rx.clone());
     730              : 
     731            0 :         result_rx
     732            0 :     }
     733              : 
     734              :     /// Returns if timeline is cancelled.
     735         2505 :     pub fn is_cancelled(&self) -> bool {
     736         2505 :         self.cancel.is_cancelled()
     737         2505 :     }
     738              : 
     739              :     /// Take a writing mutual exclusive lock on timeline shared_state.
     740         1249 :     pub async fn write_shared_state(self: &Arc<Self>) -> WriteGuardSharedState<'_> {
     741         1249 :         WriteGuardSharedState::new(self.clone(), self.mutex.write().await)
     742         1249 :     }
     743              : 
     744           53 :     pub async fn read_shared_state(&self) -> ReadGuardSharedState {
     745           53 :         self.mutex.read().await
     746           53 :     }
     747              : 
     748              :     /// Returns commit_lsn watch channel.
     749            5 :     pub fn get_commit_lsn_watch_rx(&self) -> watch::Receiver<Lsn> {
     750            5 :         self.commit_lsn_watch_rx.clone()
     751            5 :     }
     752              : 
     753              :     /// Returns term_flush_lsn watch channel.
     754            0 :     pub fn get_term_flush_lsn_watch_rx(&self) -> watch::Receiver<TermLsn> {
     755            0 :         self.term_flush_lsn_watch_rx.clone()
     756            0 :     }
     757              : 
     758              :     /// Returns watch channel for SharedState update version.
     759            5 :     pub fn get_state_version_rx(&self) -> watch::Receiver<usize> {
     760            5 :         self.shared_state_version_rx.clone()
     761            5 :     }
     762              : 
     763              :     /// Returns wal_seg_size.
     764            5 :     pub async fn get_wal_seg_size(&self) -> usize {
     765            5 :         self.read_shared_state().await.get_wal_seg_size()
     766            5 :     }
     767              : 
     768              :     /// Returns state of the timeline.
     769            9 :     pub async fn get_state(&self) -> (TimelineMemState, TimelinePersistentState) {
     770            9 :         let state = self.read_shared_state().await;
     771            9 :         (
     772            9 :             state.sk.state().inmem.clone(),
     773            9 :             TimelinePersistentState::clone(state.sk.state()),
     774            9 :         )
     775            9 :     }
     776              : 
     777              :     /// Returns latest backup_lsn.
     778            0 :     pub async fn get_wal_backup_lsn(&self) -> Lsn {
     779            0 :         self.read_shared_state().await.sk.state().inmem.backup_lsn
     780            0 :     }
     781              : 
     782              :     /// Sets backup_lsn to the given value.
     783            0 :     pub async fn set_wal_backup_lsn(self: &Arc<Self>, backup_lsn: Lsn) -> Result<()> {
     784            0 :         if self.is_cancelled() {
     785            0 :             bail!(TimelineError::Cancelled(self.ttid));
     786            0 :         }
     787              : 
     788            0 :         let mut state = self.write_shared_state().await;
     789            0 :         state.sk.state_mut().inmem.backup_lsn = max(state.sk.state().inmem.backup_lsn, backup_lsn);
     790              :         // we should check whether to shut down offloader, but this will be done
     791              :         // soon by peer communication anyway.
     792            0 :         Ok(())
     793            0 :     }
     794              : 
     795              :     /// Get safekeeper info for broadcasting to broker and other peers.
     796            0 :     pub async fn get_safekeeper_info(&self, conf: &SafeKeeperConf) -> SafekeeperTimelineInfo {
     797            0 :         let standby_apply_lsn = self.walsenders.get_hotstandby().reply.apply_lsn;
     798            0 :         let shared_state = self.read_shared_state().await;
     799            0 :         shared_state.get_safekeeper_info(&self.ttid, conf, standby_apply_lsn)
     800            0 :     }
     801              : 
     802              :     /// Update timeline state with peer safekeeper data.
     803            0 :     pub async fn record_safekeeper_info(
     804            0 :         self: &Arc<Self>,
     805            0 :         sk_info: SafekeeperTimelineInfo,
     806            0 :     ) -> Result<()> {
     807              :         {
     808            0 :             let mut shared_state = self.write_shared_state().await;
     809            0 :             shared_state.sk.record_safekeeper_info(&sk_info).await?;
     810            0 :             let peer_info = peer_info_from_sk_info(&sk_info, Instant::now());
     811            0 :             shared_state.peers_info.upsert(&peer_info);
     812              :         }
     813            0 :         Ok(())
     814            0 :     }
     815              : 
     816            0 :     pub async fn get_peers(&self, conf: &SafeKeeperConf) -> Vec<PeerInfo> {
     817            0 :         let shared_state = self.read_shared_state().await;
     818            0 :         shared_state.get_peers(conf.heartbeat_timeout)
     819            0 :     }
     820              : 
     821            5 :     pub fn get_walsenders(&self) -> &Arc<WalSenders> {
     822            5 :         &self.walsenders
     823            5 :     }
     824              : 
     825           15 :     pub fn get_walreceivers(&self) -> &Arc<WalReceivers> {
     826           15 :         &self.walreceivers
     827           15 :     }
     828              : 
     829              :     /// Returns flush_lsn.
     830            0 :     pub async fn get_flush_lsn(&self) -> Lsn {
     831            0 :         self.read_shared_state().await.sk.flush_lsn()
     832            0 :     }
     833              : 
     834              :     /// Gather timeline data for metrics.
     835            0 :     pub async fn info_for_metrics(&self) -> Option<FullTimelineInfo> {
     836            0 :         if self.is_cancelled() {
     837            0 :             return None;
     838            0 :         }
     839              : 
     840              :         let WalSendersTimelineMetricValues {
     841            0 :             ps_feedback_counter,
     842            0 :             last_ps_feedback,
     843            0 :             interpreted_wal_reader_tasks,
     844            0 :         } = self.walsenders.info_for_metrics();
     845              : 
     846            0 :         let state = self.read_shared_state().await;
     847            0 :         Some(FullTimelineInfo {
     848            0 :             ttid: self.ttid,
     849            0 :             ps_feedback_count: ps_feedback_counter,
     850            0 :             last_ps_feedback,
     851            0 :             wal_backup_active: self.wal_backup_active.load(Ordering::Relaxed),
     852            0 :             timeline_is_active: self.broker_active.load(Ordering::Relaxed),
     853            0 :             num_computes: self.walreceivers.get_num() as u32,
     854            0 :             last_removed_segno: self.last_removed_segno.load(Ordering::Relaxed),
     855            0 :             interpreted_wal_reader_tasks,
     856            0 :             epoch_start_lsn: state.sk.term_start_lsn(),
     857            0 :             mem_state: state.sk.state().inmem.clone(),
     858            0 :             persisted_state: TimelinePersistentState::clone(state.sk.state()),
     859            0 :             flush_lsn: state.sk.flush_lsn(),
     860            0 :             wal_storage: state.sk.wal_storage_metrics(),
     861            0 :         })
     862            0 :     }
     863              : 
     864              :     /// Returns in-memory timeline state to build a full debug dump.
     865            0 :     pub async fn memory_dump(&self) -> debug_dump::Memory {
     866            0 :         let state = self.read_shared_state().await;
     867              : 
     868            0 :         let (write_lsn, write_record_lsn, flush_lsn, file_open) =
     869            0 :             state.sk.wal_storage_internal_state();
     870              : 
     871            0 :         debug_dump::Memory {
     872            0 :             is_cancelled: self.is_cancelled(),
     873            0 :             peers_info_len: state.peers_info.0.len(),
     874            0 :             walsenders: self.walsenders.get_all_public(),
     875            0 :             wal_backup_active: self.wal_backup_active.load(Ordering::Relaxed),
     876            0 :             active: self.broker_active.load(Ordering::Relaxed),
     877            0 :             num_computes: self.walreceivers.get_num() as u32,
     878            0 :             last_removed_segno: self.last_removed_segno.load(Ordering::Relaxed),
     879            0 :             epoch_start_lsn: state.sk.term_start_lsn(),
     880            0 :             mem_state: state.sk.state().inmem.clone(),
     881            0 :             mgr_status: self.mgr_status.get(),
     882            0 :             write_lsn,
     883            0 :             write_record_lsn,
     884            0 :             flush_lsn,
     885            0 :             file_open,
     886            0 :         }
     887            0 :     }
     888              : 
     889              :     /// Apply a function to the control file state and persist it.
     890            0 :     pub async fn map_control_file<T>(
     891            0 :         self: &Arc<Self>,
     892            0 :         f: impl FnOnce(&mut TimelinePersistentState) -> Result<T>,
     893            0 :     ) -> Result<T> {
     894            0 :         let mut state = self.write_shared_state().await;
     895            0 :         let mut persistent_state = state.sk.state_mut().start_change();
     896              :         // If f returns error, we abort the change and don't persist anything.
     897            0 :         let res = f(&mut persistent_state)?;
     898              :         // If persisting fails, we abort the change and return error.
     899            0 :         state
     900            0 :             .sk
     901            0 :             .state_mut()
     902            0 :             .finish_change(&persistent_state)
     903            0 :             .await?;
     904            0 :         Ok(res)
     905            0 :     }
     906              : 
     907            0 :     pub async fn term_bump(self: &Arc<Self>, to: Option<Term>) -> Result<TimelineTermBumpResponse> {
     908            0 :         let mut state = self.write_shared_state().await;
     909            0 :         state.sk.term_bump(to).await
     910            0 :     }
     911              : 
     912            0 :     pub async fn membership_switch(
     913            0 :         self: &Arc<Self>,
     914            0 :         to: Configuration,
     915            0 :     ) -> Result<TimelineMembershipSwitchResponse> {
     916            0 :         let mut state = self.write_shared_state().await;
     917            0 :         state.sk.membership_switch(to).await
     918            0 :     }
     919              : 
     920              :     /// Guts of [`Self::wal_residence_guard`] and [`Self::try_wal_residence_guard`]
     921           10 :     async fn do_wal_residence_guard(
     922           10 :         self: &Arc<Self>,
     923           10 :         block: bool,
     924           10 :     ) -> Result<Option<WalResidentTimeline>> {
     925           10 :         let op_label = if block {
     926           10 :             "wal_residence_guard"
     927              :         } else {
     928            0 :             "try_wal_residence_guard"
     929              :         };
     930              : 
     931           10 :         if self.is_cancelled() {
     932            0 :             bail!(TimelineError::Cancelled(self.ttid));
     933           10 :         }
     934              : 
     935           10 :         debug!("requesting WalResidentTimeline guard");
     936           10 :         let started_at = Instant::now();
     937           10 :         let status_before = self.mgr_status.get();
     938              : 
     939              :         // Wait 30 seconds for the guard to be acquired. It can time out if someone is
     940              :         // holding the lock (e.g. during `SafeKeeper::process_msg()`) or manager task
     941              :         // is stuck.
     942           10 :         let res = tokio::time::timeout_at(started_at + Duration::from_secs(30), async {
     943           10 :             if block {
     944           10 :                 self.manager_ctl.wal_residence_guard().await.map(Some)
     945              :             } else {
     946            0 :                 self.manager_ctl.try_wal_residence_guard().await
     947              :             }
     948           10 :         })
     949           10 :         .await;
     950              : 
     951           10 :         let guard = match res {
     952           10 :             Ok(Ok(guard)) => {
     953           10 :                 let finished_at = Instant::now();
     954           10 :                 let elapsed = finished_at - started_at;
     955           10 :                 MISC_OPERATION_SECONDS
     956           10 :                     .with_label_values(&[op_label])
     957           10 :                     .observe(elapsed.as_secs_f64());
     958              : 
     959           10 :                 guard
     960              :             }
     961            0 :             Ok(Err(e)) => {
     962            0 :                 warn!(
     963            0 :                     "error acquiring in {op_label}, statuses {:?} => {:?}",
     964              :                     status_before,
     965            0 :                     self.mgr_status.get()
     966              :                 );
     967            0 :                 return Err(e);
     968              :             }
     969              :             Err(_) => {
     970            0 :                 warn!(
     971            0 :                     "timeout acquiring in {op_label} guard, statuses {:?} => {:?}",
     972              :                     status_before,
     973            0 :                     self.mgr_status.get()
     974              :                 );
     975            0 :                 anyhow::bail!("timeout while acquiring WalResidentTimeline guard");
     976              :             }
     977              :         };
     978              : 
     979           10 :         Ok(guard.map(|g| WalResidentTimeline::new(self.clone(), g)))
     980           10 :     }
     981              : 
     982              :     /// Get the timeline guard for reading/writing WAL files.
     983              :     /// If WAL files are not present on disk (evicted), they will be automatically
     984              :     /// downloaded from remote storage. This is done in the manager task, which is
     985              :     /// responsible for issuing all guards.
     986              :     ///
     987              :     /// NB: don't use this function from timeline_manager, it will deadlock.
     988              :     /// NB: don't use this function while holding shared_state lock.
     989           10 :     pub async fn wal_residence_guard(self: &Arc<Self>) -> Result<WalResidentTimeline> {
     990           10 :         self.do_wal_residence_guard(true)
     991           10 :             .await
     992           10 :             .map(|m| m.expect("Always get Some in block=true mode"))
     993           10 :     }
     994              : 
     995              :     /// Get the timeline guard for reading/writing WAL files if the timeline is resident,
     996              :     /// else return None
     997            0 :     pub(crate) async fn try_wal_residence_guard(
     998            0 :         self: &Arc<Self>,
     999            0 :     ) -> Result<Option<WalResidentTimeline>> {
    1000            0 :         self.do_wal_residence_guard(false).await
    1001            0 :     }
    1002              : 
    1003            0 :     pub async fn backup_partial_reset(self: &Arc<Self>) -> Result<Vec<String>> {
    1004            0 :         self.manager_ctl.backup_partial_reset().await
    1005            0 :     }
    1006              : }
    1007              : 
    1008              : /// This is a guard that allows to read/write disk timeline state.
    1009              : /// All tasks that are trying to read/write WAL from disk should use this guard.
    1010              : pub struct WalResidentTimeline {
    1011              :     pub tli: Arc<Timeline>,
    1012              :     _guard: ResidenceGuard,
    1013              : }
    1014              : 
    1015              : impl WalResidentTimeline {
    1016           15 :     pub fn new(tli: Arc<Timeline>, _guard: ResidenceGuard) -> Self {
    1017           15 :         WalResidentTimeline { tli, _guard }
    1018           15 :     }
    1019              : }
    1020              : 
    1021              : impl Deref for WalResidentTimeline {
    1022              :     type Target = Arc<Timeline>;
    1023              : 
    1024         6911 :     fn deref(&self) -> &Self::Target {
    1025         6911 :         &self.tli
    1026         6911 :     }
    1027              : }
    1028              : 
    1029              : impl WalResidentTimeline {
    1030              :     /// Returns true if walsender should stop sending WAL to pageserver. We
    1031              :     /// terminate it if remote_consistent_lsn reached commit_lsn and there is no
    1032              :     /// computes. While there might be nothing to stream already, we learn about
    1033              :     /// remote_consistent_lsn update through replication feedback, and we want
    1034              :     /// to stop pushing to the broker if pageserver is fully caughtup.
    1035            0 :     pub async fn should_walsender_stop(&self, reported_remote_consistent_lsn: Lsn) -> bool {
    1036            0 :         if self.is_cancelled() {
    1037            0 :             return true;
    1038            0 :         }
    1039            0 :         let shared_state = self.read_shared_state().await;
    1040            0 :         if self.walreceivers.get_num() == 0 {
    1041            0 :             return shared_state.sk.state().inmem.commit_lsn == Lsn(0) || // no data at all yet
    1042            0 :             reported_remote_consistent_lsn >= shared_state.sk.state().inmem.commit_lsn;
    1043            0 :         }
    1044            0 :         false
    1045            0 :     }
    1046              : 
    1047              :     /// Ensure that current term is t, erroring otherwise, and lock the state.
    1048            0 :     pub async fn acquire_term(&self, t: Term) -> Result<ReadGuardSharedState> {
    1049            0 :         let ss = self.read_shared_state().await;
    1050            0 :         if ss.sk.state().acceptor_state.term != t {
    1051            0 :             bail!(
    1052            0 :                 "failed to acquire term {}, current term {}",
    1053              :                 t,
    1054            0 :                 ss.sk.state().acceptor_state.term
    1055              :             );
    1056            0 :         }
    1057            0 :         Ok(ss)
    1058            0 :     }
    1059              : 
    1060              :     // BEGIN HADRON
    1061              :     // Check if disk usage by WAL segment files for this timeline exceeds the configured limit.
    1062         1240 :     fn hadron_check_disk_usage(
    1063         1240 :         &self,
    1064         1240 :         shared_state_locked: &mut WriteGuardSharedState<'_>,
    1065         1240 :     ) -> Result<()> {
    1066              :         // The disk usage is calculated based on the number of segments between `last_removed_segno`
    1067              :         // and the current flush LSN segment number. `last_removed_segno` is advanced after
    1068              :         // unneeded WAL files are physically removed from disk (see `update_wal_removal_end()`
    1069              :         // in `timeline_manager.rs`).
    1070         1240 :         let max_timeline_disk_usage_bytes = self.conf.max_timeline_disk_usage_bytes;
    1071         1240 :         if max_timeline_disk_usage_bytes > 0 {
    1072            0 :             let last_removed_segno = self.last_removed_segno.load(Ordering::Relaxed);
    1073            0 :             let flush_lsn = shared_state_locked.sk.flush_lsn();
    1074            0 :             let wal_seg_size = shared_state_locked.sk.state().server.wal_seg_size as u64;
    1075            0 :             let current_segno = flush_lsn.segment_number(wal_seg_size as usize);
    1076              : 
    1077            0 :             let segno_count = current_segno - last_removed_segno;
    1078            0 :             let disk_usage_bytes = segno_count * wal_seg_size;
    1079              : 
    1080            0 :             if disk_usage_bytes > max_timeline_disk_usage_bytes {
    1081            0 :                 WAL_STORAGE_LIMIT_ERRORS.inc();
    1082            0 :                 bail!(
    1083            0 :                     "WAL storage utilization exceeds configured limit of {} bytes: current disk usage: {} bytes",
    1084              :                     max_timeline_disk_usage_bytes,
    1085              :                     disk_usage_bytes
    1086              :                 );
    1087            0 :             }
    1088         1240 :         }
    1089              : 
    1090         1240 :         if GLOBAL_DISK_LIMIT_EXCEEDED.load(Ordering::Relaxed) {
    1091            0 :             bail!("Global disk usage exceeded limit");
    1092         1240 :         }
    1093              : 
    1094         1240 :         Ok(())
    1095         1240 :     }
    1096              :     // END HADRON
    1097              : 
    1098              :     /// Pass arrived message to the safekeeper.
    1099         1240 :     pub async fn process_msg(
    1100         1240 :         &self,
    1101         1240 :         msg: &ProposerAcceptorMessage,
    1102         1240 :     ) -> Result<Option<AcceptorProposerMessage>> {
    1103         1240 :         if self.is_cancelled() {
    1104            0 :             bail!(TimelineError::Cancelled(self.ttid));
    1105         1240 :         }
    1106              : 
    1107              :         let mut rmsg: Option<AcceptorProposerMessage>;
    1108              :         {
    1109         1240 :             let mut shared_state = self.write_shared_state().await;
    1110              :             // BEGIN HADRON
    1111              :             // Errors from the `hadron_check_disk_usage()` function fail the process_msg() function, which
    1112              :             // gets propagated upward and terminates the entire WalAcceptor. This will cause postgres to
    1113              :             // disconnect from the safekeeper and reestablish another connection. Postgres will keep retrying
    1114              :             // safekeeper connections every second until it can successfully propose WAL to the SK again.
    1115         1240 :             self.hadron_check_disk_usage(&mut shared_state)?;
    1116              :             // END HADRON
    1117         1240 :             rmsg = shared_state.sk.safekeeper().process_msg(msg).await?;
    1118              : 
    1119              :             // if this is AppendResponse, fill in proper hot standby feedback.
    1120          620 :             if let Some(AcceptorProposerMessage::AppendResponse(ref mut resp)) = rmsg {
    1121          620 :                 resp.hs_feedback = self.walsenders.get_hotstandby().hs_feedback;
    1122          620 :             }
    1123              :         }
    1124         1240 :         Ok(rmsg)
    1125         1240 :     }
    1126              : 
    1127            9 :     pub async fn get_walreader(&self, start_lsn: Lsn) -> Result<WalReader> {
    1128            9 :         let (_, persisted_state) = self.get_state().await;
    1129              : 
    1130            9 :         WalReader::new(
    1131            9 :             &self.ttid,
    1132            9 :             self.timeline_dir.clone(),
    1133            9 :             &persisted_state,
    1134            9 :             start_lsn,
    1135            9 :             self.wal_backup.clone(),
    1136              :         )
    1137            9 :     }
    1138              : 
    1139            0 :     pub fn get_timeline_dir(&self) -> Utf8PathBuf {
    1140            0 :         self.timeline_dir.clone()
    1141            0 :     }
    1142              : 
    1143              :     /// Update in memory remote consistent lsn.
    1144            0 :     pub async fn update_remote_consistent_lsn(&self, candidate: Lsn) {
    1145            0 :         let mut shared_state = self.write_shared_state().await;
    1146            0 :         shared_state.sk.state_mut().inmem.remote_consistent_lsn = max(
    1147            0 :             shared_state.sk.state().inmem.remote_consistent_lsn,
    1148            0 :             candidate,
    1149            0 :         );
    1150            0 :     }
    1151              : }
    1152              : 
    1153              : /// This struct contains methods that are used by timeline manager task.
    1154              : pub(crate) struct ManagerTimeline {
    1155              :     pub(crate) tli: Arc<Timeline>,
    1156              : }
    1157              : 
    1158              : impl Deref for ManagerTimeline {
    1159              :     type Target = Arc<Timeline>;
    1160              : 
    1161          366 :     fn deref(&self) -> &Self::Target {
    1162          366 :         &self.tli
    1163          366 :     }
    1164              : }
    1165              : 
    1166              : impl ManagerTimeline {
    1167            0 :     pub(crate) fn timeline_dir(&self) -> &Utf8PathBuf {
    1168            0 :         &self.tli.timeline_dir
    1169            0 :     }
    1170              : 
    1171              :     /// Manager requests this state on startup.
    1172            5 :     pub(crate) async fn bootstrap_mgr(&self) -> (bool, Option<PartialRemoteSegment>) {
    1173            5 :         let shared_state = self.read_shared_state().await;
    1174            5 :         let is_offloaded = matches!(
    1175            5 :             shared_state.sk.state().eviction_state,
    1176              :             EvictionState::Offloaded(_)
    1177              :         );
    1178            5 :         let partial_backup_uploaded = shared_state.sk.state().partial_backup.uploaded_segment();
    1179              : 
    1180            5 :         (is_offloaded, partial_backup_uploaded)
    1181            5 :     }
    1182              : 
    1183              :     /// Try to switch state Present->Offloaded.
    1184            0 :     pub(crate) async fn switch_to_offloaded(
    1185            0 :         &self,
    1186            0 :         partial: &PartialRemoteSegment,
    1187            0 :     ) -> anyhow::Result<()> {
    1188            0 :         let mut shared = self.write_shared_state().await;
    1189              : 
    1190              :         // updating control file
    1191            0 :         let mut pstate = shared.sk.state_mut().start_change();
    1192              : 
    1193            0 :         if !matches!(pstate.eviction_state, EvictionState::Present) {
    1194            0 :             bail!(
    1195            0 :                 "cannot switch to offloaded state, current state is {:?}",
    1196              :                 pstate.eviction_state
    1197              :             );
    1198            0 :         }
    1199              : 
    1200            0 :         if partial.flush_lsn != shared.sk.flush_lsn() {
    1201            0 :             bail!(
    1202            0 :                 "flush_lsn mismatch in partial backup, expected {}, got {}",
    1203            0 :                 shared.sk.flush_lsn(),
    1204              :                 partial.flush_lsn
    1205              :             );
    1206            0 :         }
    1207              : 
    1208            0 :         if partial.commit_lsn != pstate.commit_lsn {
    1209            0 :             bail!(
    1210            0 :                 "commit_lsn mismatch in partial backup, expected {}, got {}",
    1211              :                 pstate.commit_lsn,
    1212              :                 partial.commit_lsn
    1213              :             );
    1214            0 :         }
    1215              : 
    1216            0 :         if partial.term != shared.sk.last_log_term() {
    1217            0 :             bail!(
    1218            0 :                 "term mismatch in partial backup, expected {}, got {}",
    1219            0 :                 shared.sk.last_log_term(),
    1220              :                 partial.term
    1221              :             );
    1222            0 :         }
    1223              : 
    1224            0 :         pstate.eviction_state = EvictionState::Offloaded(shared.sk.flush_lsn());
    1225            0 :         shared.sk.state_mut().finish_change(&pstate).await?;
    1226              :         // control file is now switched to Offloaded state
    1227              : 
    1228              :         // now we can switch shared.sk to Offloaded, shouldn't fail
    1229            0 :         let prev_sk = std::mem::replace(&mut shared.sk, StateSK::Empty);
    1230            0 :         let cfile_state = prev_sk.take_state();
    1231            0 :         shared.sk = StateSK::Offloaded(Box::new(cfile_state));
    1232              : 
    1233            0 :         Ok(())
    1234            0 :     }
    1235              : 
    1236              :     /// Try to switch state Offloaded->Present.
    1237            0 :     pub(crate) async fn switch_to_present(&self) -> anyhow::Result<()> {
    1238            0 :         let mut shared = self.write_shared_state().await;
    1239              : 
    1240              :         // trying to restore WAL storage
    1241            0 :         let wal_store = wal_storage::PhysicalStorage::new(
    1242            0 :             &self.ttid,
    1243            0 :             &self.timeline_dir,
    1244            0 :             shared.sk.state(),
    1245            0 :             self.conf.no_sync,
    1246            0 :         )?;
    1247              : 
    1248              :         // updating control file
    1249            0 :         let mut pstate = shared.sk.state_mut().start_change();
    1250              : 
    1251            0 :         if !matches!(pstate.eviction_state, EvictionState::Offloaded(_)) {
    1252            0 :             bail!(
    1253            0 :                 "cannot switch to present state, current state is {:?}",
    1254              :                 pstate.eviction_state
    1255              :             );
    1256            0 :         }
    1257              : 
    1258            0 :         if wal_store.flush_lsn() != shared.sk.flush_lsn() {
    1259            0 :             bail!(
    1260            0 :                 "flush_lsn mismatch in restored WAL, expected {}, got {}",
    1261            0 :                 shared.sk.flush_lsn(),
    1262            0 :                 wal_store.flush_lsn()
    1263              :             );
    1264            0 :         }
    1265              : 
    1266            0 :         pstate.eviction_state = EvictionState::Present;
    1267            0 :         shared.sk.state_mut().finish_change(&pstate).await?;
    1268              : 
    1269              :         // now we can switch shared.sk to Present, shouldn't fail
    1270            0 :         let prev_sk = std::mem::replace(&mut shared.sk, StateSK::Empty);
    1271            0 :         let cfile_state = prev_sk.take_state();
    1272            0 :         shared.sk = StateSK::Loaded(SafeKeeper::new(cfile_state, wal_store, self.conf.my_id)?);
    1273              : 
    1274            0 :         Ok(())
    1275            0 :     }
    1276              : 
    1277              :     /// Update current manager state, useful for debugging manager deadlocks.
    1278          192 :     pub(crate) fn set_status(&self, status: timeline_manager::Status) {
    1279          192 :         self.mgr_status.store(status, Ordering::Relaxed);
    1280          192 :     }
    1281              : }
    1282              : 
    1283              : /// Deletes directory and it's contents. Returns false if directory does not exist.
    1284            0 : pub async fn delete_dir(path: &Utf8PathBuf) -> Result<bool> {
    1285            0 :     match fs::remove_dir_all(path).await {
    1286            0 :         Ok(_) => Ok(true),
    1287            0 :         Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
    1288            0 :         Err(e) => Err(e.into()),
    1289              :     }
    1290            0 : }
    1291              : 
    1292              : /// Get a path to the tenant directory. If you just need to get a timeline directory,
    1293              : /// use WalResidentTimeline::get_timeline_dir instead.
    1294           10 : pub fn get_tenant_dir(conf: &SafeKeeperConf, tenant_id: &TenantId) -> Utf8PathBuf {
    1295           10 :     conf.workdir.join(tenant_id.to_string())
    1296           10 : }
    1297              : 
    1298              : /// Get a path to the timeline directory. If you need to read WAL files from disk,
    1299              : /// use WalResidentTimeline::get_timeline_dir instead. This function does not check
    1300              : /// timeline eviction status and WAL files might not be present on disk.
    1301           10 : pub fn get_timeline_dir(conf: &SafeKeeperConf, ttid: &TenantTimelineId) -> Utf8PathBuf {
    1302           10 :     get_tenant_dir(conf, &ttid.tenant_id).join(ttid.timeline_id.to_string())
    1303           10 : }
        

Generated by: LCOV version 2.1-beta