LCOV - code coverage report
Current view: top level - safekeeper/src - state.rs (source / functions) Coverage Total Hit
Test: 2a9d99866121f170b43760bd62e1e2431e597707.info Lines: 98.9 % 91 90
Test Date: 2024-09-02 14:10:37 Functions: 40.2 % 92 37

            Line data    Source code
       1              : //! Defines per timeline data stored persistently (SafeKeeperPersistentState)
       2              : //! and its wrapper with in memory layer (SafekeeperState).
       3              : 
       4              : use std::ops::Deref;
       5              : 
       6              : use anyhow::Result;
       7              : use serde::{Deserialize, Serialize};
       8              : use utils::{
       9              :     id::{NodeId, TenantId, TenantTimelineId, TimelineId},
      10              :     lsn::Lsn,
      11              : };
      12              : 
      13              : use crate::{
      14              :     control_file,
      15              :     safekeeper::{AcceptorState, PersistedPeerInfo, PgUuid, ServerInfo, TermHistory},
      16              :     wal_backup_partial::{self},
      17              : };
      18              : 
      19              : /// Persistent information stored on safekeeper node about timeline.
      20              : /// On disk data is prefixed by magic and format version and followed by checksum.
      21            6 : #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
      22              : pub struct TimelinePersistentState {
      23              :     #[serde(with = "hex")]
      24              :     pub tenant_id: TenantId,
      25              :     #[serde(with = "hex")]
      26              :     pub timeline_id: TimelineId,
      27              :     /// persistent acceptor state
      28              :     pub acceptor_state: AcceptorState,
      29              :     /// information about server
      30              :     pub server: ServerInfo,
      31              :     /// Unique id of the last *elected* proposer we dealt with. Not needed
      32              :     /// for correctness, exists for monitoring purposes.
      33              :     #[serde(with = "hex")]
      34              :     pub proposer_uuid: PgUuid,
      35              :     /// Since which LSN this timeline generally starts. Safekeeper might have
      36              :     /// joined later.
      37              :     pub timeline_start_lsn: Lsn,
      38              :     /// Since which LSN safekeeper has (had) WAL for this timeline.
      39              :     /// All WAL segments next to one containing local_start_lsn are
      40              :     /// filled with data from the beginning.
      41              :     pub local_start_lsn: Lsn,
      42              :     /// Part of WAL acknowledged by quorum *and available locally*. Always points
      43              :     /// to record boundary.
      44              :     pub commit_lsn: Lsn,
      45              :     /// LSN that points to the end of the last backed up segment. Useful to
      46              :     /// persist to avoid finding out offloading progress on boot.
      47              :     pub backup_lsn: Lsn,
      48              :     /// Minimal LSN which may be needed for recovery of some safekeeper (end_lsn
      49              :     /// of last record streamed to everyone). Persisting it helps skipping
      50              :     /// recovery in walproposer, generally we compute it from peers. In
      51              :     /// walproposer proto called 'truncate_lsn'. Updates are currently drived
      52              :     /// only by walproposer.
      53              :     pub peer_horizon_lsn: Lsn,
      54              :     /// LSN of the oldest known checkpoint made by pageserver and successfully
      55              :     /// pushed to s3. We don't remove WAL beyond it. Persisted only for
      56              :     /// informational purposes, we receive it from pageserver (or broker).
      57              :     pub remote_consistent_lsn: Lsn,
      58              :     /// Peers and their state as we remember it. Knowing peers themselves is
      59              :     /// fundamental; but state is saved here only for informational purposes and
      60              :     /// obviously can be stale. (Currently not saved at all, but let's provision
      61              :     /// place to have less file version upgrades).
      62              :     pub peers: PersistedPeers,
      63              :     /// Holds names of partial segments uploaded to remote storage. Used to
      64              :     /// clean up old objects without leaving garbage in remote storage.
      65              :     pub partial_backup: wal_backup_partial::State,
      66              :     /// Eviction state of the timeline. If it's Offloaded, we should download
      67              :     /// WAL files from remote storage to serve the timeline.
      68              :     pub eviction_state: EvictionState,
      69              : }
      70              : 
      71            4 : #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
      72              : pub struct PersistedPeers(pub Vec<(NodeId, PersistedPeerInfo)>);
      73              : 
      74              : /// State of the local WAL files. Used to track current timeline state,
      75              : /// that can be either WAL files are present on disk or last partial segment
      76              : /// is offloaded to remote storage.
      77            2 : #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
      78              : pub enum EvictionState {
      79              :     /// WAL files are present on disk.
      80              :     Present,
      81              :     /// Last partial segment is offloaded to remote storage.
      82              :     /// Contains flush_lsn of the last offloaded segment.
      83              :     Offloaded(Lsn),
      84              : }
      85              : 
      86              : impl TimelinePersistentState {
      87         5729 :     pub fn new(
      88         5729 :         ttid: &TenantTimelineId,
      89         5729 :         server_info: ServerInfo,
      90         5729 :         peers: Vec<NodeId>,
      91         5729 :         commit_lsn: Lsn,
      92         5729 :         local_start_lsn: Lsn,
      93         5729 :     ) -> TimelinePersistentState {
      94         5729 :         TimelinePersistentState {
      95         5729 :             tenant_id: ttid.tenant_id,
      96         5729 :             timeline_id: ttid.timeline_id,
      97         5729 :             acceptor_state: AcceptorState {
      98         5729 :                 term: 0,
      99         5729 :                 term_history: TermHistory::empty(),
     100         5729 :             },
     101         5729 :             server: server_info,
     102         5729 :             proposer_uuid: [0; 16],
     103         5729 :             timeline_start_lsn: Lsn(0),
     104         5729 :             local_start_lsn,
     105         5729 :             commit_lsn,
     106         5729 :             backup_lsn: local_start_lsn,
     107         5729 :             peer_horizon_lsn: local_start_lsn,
     108         5729 :             remote_consistent_lsn: Lsn(0),
     109         5729 :             peers: PersistedPeers(
     110         5729 :                 peers
     111         5729 :                     .iter()
     112         5729 :                     .map(|p| (*p, PersistedPeerInfo::new()))
     113         5729 :                     .collect(),
     114         5729 :             ),
     115         5729 :             partial_backup: wal_backup_partial::State::default(),
     116         5729 :             eviction_state: EvictionState::Present,
     117         5729 :         }
     118         5729 :     }
     119              : 
     120              :     #[cfg(test)]
     121            4 :     pub fn empty() -> Self {
     122            4 :         use crate::safekeeper::UNKNOWN_SERVER_VERSION;
     123            4 : 
     124            4 :         TimelinePersistentState::new(
     125            4 :             &TenantTimelineId::empty(),
     126            4 :             ServerInfo {
     127            4 :                 pg_version: UNKNOWN_SERVER_VERSION, /* Postgres server version */
     128            4 :                 system_id: 0,                       /* Postgres system identifier */
     129            4 :                 wal_seg_size: 0,
     130            4 :             },
     131            4 :             vec![],
     132            4 :             Lsn::INVALID,
     133            4 :             Lsn::INVALID,
     134            4 :         )
     135            4 :     }
     136              : }
     137              : 
     138            0 : #[derive(Debug, Clone, Serialize, Deserialize)]
     139              : // In memory safekeeper state. Fields mirror ones in `SafeKeeperPersistentState`; values
     140              : // are not flushed yet.
     141              : pub struct TimelineMemState {
     142              :     pub commit_lsn: Lsn,
     143              :     pub backup_lsn: Lsn,
     144              :     pub peer_horizon_lsn: Lsn,
     145              :     pub remote_consistent_lsn: Lsn,
     146              :     #[serde(with = "hex")]
     147              :     pub proposer_uuid: PgUuid,
     148              : }
     149              : 
     150              : /// Safekeeper persistent state plus in memory layer, to avoid frequent fsyncs
     151              : /// when we update fields like commit_lsn which don't need immediate
     152              : /// persistence. Provides transactional like API to atomically update the state.
     153              : ///
     154              : /// Implements Deref into *persistent* part.
     155              : pub struct TimelineState<CTRL: control_file::Storage> {
     156              :     pub inmem: TimelineMemState,
     157              :     pub pers: CTRL, // persistent
     158              : }
     159              : 
     160              : impl<CTRL> TimelineState<CTRL>
     161              : where
     162              :     CTRL: control_file::Storage,
     163              : {
     164        35315 :     pub fn new(state: CTRL) -> Self {
     165        35315 :         TimelineState {
     166        35315 :             inmem: TimelineMemState {
     167        35315 :                 commit_lsn: state.commit_lsn,
     168        35315 :                 backup_lsn: state.backup_lsn,
     169        35315 :                 peer_horizon_lsn: state.peer_horizon_lsn,
     170        35315 :                 remote_consistent_lsn: state.remote_consistent_lsn,
     171        35315 :                 proposer_uuid: state.proposer_uuid,
     172        35315 :             },
     173        35315 :             pers: state,
     174        35315 :         }
     175        35315 :     }
     176              : 
     177              :     /// Start atomic change. Returns SafeKeeperPersistentState with in memory
     178              :     /// values applied; the protocol is to 1) change returned struct as desired
     179              :     /// 2) atomically persist it with finish_change.
     180        15824 :     pub fn start_change(&self) -> TimelinePersistentState {
     181        15824 :         let mut s = self.pers.clone();
     182        15824 :         s.commit_lsn = self.inmem.commit_lsn;
     183        15824 :         s.backup_lsn = self.inmem.backup_lsn;
     184        15824 :         s.peer_horizon_lsn = self.inmem.peer_horizon_lsn;
     185        15824 :         s.remote_consistent_lsn = self.inmem.remote_consistent_lsn;
     186        15824 :         s.proposer_uuid = self.inmem.proposer_uuid;
     187        15824 :         s
     188        15824 :     }
     189              : 
     190              :     /// Persist given state. c.f. start_change.
     191        15824 :     pub async fn finish_change(&mut self, s: &TimelinePersistentState) -> Result<()> {
     192        15824 :         if s.eq(&*self.pers) {
     193          191 :             // nothing to do if state didn't change
     194          191 :         } else {
     195        15633 :             self.pers.persist(s).await?;
     196              :         }
     197              : 
     198              :         // keep in memory values up to date
     199        15824 :         self.inmem.commit_lsn = s.commit_lsn;
     200        15824 :         self.inmem.backup_lsn = s.backup_lsn;
     201        15824 :         self.inmem.peer_horizon_lsn = s.peer_horizon_lsn;
     202        15824 :         self.inmem.remote_consistent_lsn = s.remote_consistent_lsn;
     203        15824 :         self.inmem.proposer_uuid = s.proposer_uuid;
     204        15824 :         Ok(())
     205        15824 :     }
     206              : 
     207              :     /// Flush in memory values.
     208          432 :     pub async fn flush(&mut self) -> Result<()> {
     209          432 :         let s = self.start_change();
     210          432 :         self.finish_change(&s).await
     211          432 :     }
     212              : }
     213              : 
     214              : impl<CTRL> Deref for TimelineState<CTRL>
     215              : where
     216              :     CTRL: control_file::Storage,
     217              : {
     218              :     type Target = TimelinePersistentState;
     219              : 
     220       761154 :     fn deref(&self) -> &Self::Target {
     221       761154 :         &self.pers
     222       761154 :     }
     223              : }
        

Generated by: LCOV version 2.1-beta