LCOV - code coverage report
Current view: top level - safekeeper/src - wal_backup_partial.rs (source / functions) Coverage Total Hit
Test: 42f947419473a288706e86ecdf7c2863d760d5d7.info Lines: 0.8 % 126 1
Test Date: 2024-08-02 21:34:27 Functions: 1.9 % 52 1

            Line data    Source code
       1              : //! Safekeeper timeline has a background task which is subscribed to `commit_lsn`
       2              : //! and `flush_lsn` updates. After the partial segment was updated (`flush_lsn`
       3              : //! was changed), the segment will be uploaded to S3 in about 15 minutes.
       4              : //!
       5              : //! The filename format for partial segments is
       6              : //! `Segment_Term_Flush_Commit_skNN.partial`, where:
       7              : //! - `Segment` – the segment name, like `000000010000000000000001`
       8              : //! - `Term` – current term
       9              : //! - `Flush` – flush_lsn in hex format `{:016X}`, e.g. `00000000346BC568`
      10              : //! - `Commit` – commit_lsn in the same hex format
      11              : //! - `NN` – safekeeper_id, like `1`
      12              : //!
      13              : //! The full object name example:
      14              : //! `000000010000000000000002_2_0000000002534868_0000000002534410_sk1.partial`
      15              : //!
      16              : //! Each safekeeper will keep info about remote partial segments in its control
      17              : //! file. Code updates state in the control file before doing any S3 operations.
      18              : //! This way control file stores information about all potentially existing
      19              : //! remote partial segments and can clean them up after uploading a newer version.
      20              : 
      21              : use camino::Utf8PathBuf;
      22              : use postgres_ffi::{XLogFileName, XLogSegNo, PG_TLI};
      23              : use remote_storage::RemotePath;
      24              : use serde::{Deserialize, Serialize};
      25              : 
      26              : use tracing::{debug, error, info, instrument, warn};
      27              : use utils::lsn::Lsn;
      28              : 
      29              : use crate::{
      30              :     metrics::{MISC_OPERATION_SECONDS, PARTIAL_BACKUP_UPLOADED_BYTES, PARTIAL_BACKUP_UPLOADS},
      31              :     rate_limit::{rand_duration, RateLimiter},
      32              :     safekeeper::Term,
      33              :     timeline::WalResidentTimeline,
      34              :     timeline_manager::StateSnapshot,
      35              :     wal_backup::{self, remote_timeline_path},
      36              :     SafeKeeperConf,
      37              : };
      38              : 
      39            0 : #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
      40              : pub enum UploadStatus {
      41              :     /// Upload is in progress. This status should be used only for garbage collection,
      42              :     /// don't read data from the remote storage with this status.
      43              :     InProgress,
      44              :     /// Upload is finished. There is always at most one segment with this status.
      45              :     /// It means that the segment is actual and can be used.
      46              :     Uploaded,
      47              :     /// Deletion is in progress. This status should be used only for garbage collection,
      48              :     /// don't read data from the remote storage with this status.
      49              :     Deleting,
      50              : }
      51              : 
      52            0 : #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
      53              : pub struct PartialRemoteSegment {
      54              :     pub status: UploadStatus,
      55              :     pub name: String,
      56              :     pub commit_lsn: Lsn,
      57              :     pub flush_lsn: Lsn,
      58              :     // We should use last_log_term here, otherwise it's possible to have inconsistent data in the
      59              :     // remote storage.
      60              :     //
      61              :     // More info here: https://github.com/neondatabase/neon/pull/8022#discussion_r1654738405
      62              :     pub term: Term,
      63              : }
      64              : 
      65              : impl PartialRemoteSegment {
      66            0 :     fn eq_without_status(&self, other: &Self) -> bool {
      67            0 :         self.name == other.name
      68            0 :             && self.commit_lsn == other.commit_lsn
      69            0 :             && self.flush_lsn == other.flush_lsn
      70            0 :             && self.term == other.term
      71            0 :     }
      72              : 
      73            0 :     pub(crate) fn remote_path(&self, remote_timeline_path: &RemotePath) -> RemotePath {
      74            0 :         remote_timeline_path.join(&self.name)
      75            0 :     }
      76              : }
      77              : 
      78              : // NB: these structures are a part of a control_file, you can't change them without
      79              : // changing the control file format version.
      80            6 : #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
      81              : pub struct State {
      82              :     pub segments: Vec<PartialRemoteSegment>,
      83              : }
      84              : 
      85              : impl State {
      86              :     /// Find an Uploaded segment. There should be only one Uploaded segment at a time.
      87            0 :     pub(crate) fn uploaded_segment(&self) -> Option<PartialRemoteSegment> {
      88            0 :         self.segments
      89            0 :             .iter()
      90            0 :             .find(|seg| seg.status == UploadStatus::Uploaded)
      91            0 :             .cloned()
      92            0 :     }
      93              : }
      94              : 
      95              : struct PartialBackup {
      96              :     wal_seg_size: usize,
      97              :     tli: WalResidentTimeline,
      98              :     conf: SafeKeeperConf,
      99              :     local_prefix: Utf8PathBuf,
     100              :     remote_timeline_path: RemotePath,
     101              : 
     102              :     state: State,
     103              : }
     104              : 
     105              : // Read-only methods for getting segment names
     106              : impl PartialBackup {
     107            0 :     fn segno(&self, lsn: Lsn) -> XLogSegNo {
     108            0 :         lsn.segment_number(self.wal_seg_size)
     109            0 :     }
     110              : 
     111            0 :     fn segment_name(&self, segno: u64) -> String {
     112            0 :         XLogFileName(PG_TLI, segno, self.wal_seg_size)
     113            0 :     }
     114              : 
     115            0 :     fn remote_segment_name(
     116            0 :         &self,
     117            0 :         segno: u64,
     118            0 :         term: u64,
     119            0 :         commit_lsn: Lsn,
     120            0 :         flush_lsn: Lsn,
     121            0 :     ) -> String {
     122            0 :         format!(
     123            0 :             "{}_{}_{:016X}_{:016X}_sk{}.partial",
     124            0 :             self.segment_name(segno),
     125            0 :             term,
     126            0 :             flush_lsn.0,
     127            0 :             commit_lsn.0,
     128            0 :             self.conf.my_id.0,
     129            0 :         )
     130            0 :     }
     131              : 
     132            0 :     fn local_segment_name(&self, segno: u64) -> String {
     133            0 :         format!("{}.partial", self.segment_name(segno))
     134            0 :     }
     135              : }
     136              : 
     137              : impl PartialBackup {
     138              :     /// Takes a lock to read actual safekeeper state and returns a segment that should be uploaded.
     139            0 :     async fn prepare_upload(&self) -> PartialRemoteSegment {
     140              :         // this operation takes a lock to get the actual state
     141            0 :         let sk_info = self.tli.get_safekeeper_info(&self.conf).await;
     142            0 :         let flush_lsn = Lsn(sk_info.flush_lsn);
     143            0 :         let commit_lsn = Lsn(sk_info.commit_lsn);
     144            0 :         let last_log_term = sk_info.last_log_term;
     145            0 :         let segno = self.segno(flush_lsn);
     146            0 : 
     147            0 :         let name = self.remote_segment_name(segno, last_log_term, commit_lsn, flush_lsn);
     148            0 : 
     149            0 :         PartialRemoteSegment {
     150            0 :             status: UploadStatus::InProgress,
     151            0 :             name,
     152            0 :             commit_lsn,
     153            0 :             flush_lsn,
     154            0 :             term: last_log_term,
     155            0 :         }
     156            0 :     }
     157              : 
     158              :     /// Reads segment from disk and uploads it to the remote storage.
     159            0 :     async fn upload_segment(&mut self, prepared: PartialRemoteSegment) -> anyhow::Result<()> {
     160            0 :         let flush_lsn = prepared.flush_lsn;
     161            0 :         let segno = self.segno(flush_lsn);
     162            0 : 
     163            0 :         // We're going to backup bytes from the start of the segment up to flush_lsn.
     164            0 :         let backup_bytes = flush_lsn.segment_offset(self.wal_seg_size);
     165            0 : 
     166            0 :         let local_path = self.local_prefix.join(self.local_segment_name(segno));
     167            0 :         let remote_path = prepared.remote_path(&self.remote_timeline_path);
     168            0 : 
     169            0 :         // Upload first `backup_bytes` bytes of the segment to the remote storage.
     170            0 :         wal_backup::backup_partial_segment(&local_path, &remote_path, backup_bytes).await?;
     171            0 :         PARTIAL_BACKUP_UPLOADED_BYTES.inc_by(backup_bytes as u64);
     172              : 
     173              :         // We uploaded the segment, now let's verify that the data is still actual.
     174              :         // If the term changed, we cannot guarantee the validity of the uploaded data.
     175              :         // If the term is the same, we know the data is not corrupted.
     176            0 :         let sk_info = self.tli.get_safekeeper_info(&self.conf).await;
     177            0 :         if sk_info.last_log_term != prepared.term {
     178            0 :             anyhow::bail!("term changed during upload");
     179            0 :         }
     180            0 :         assert!(prepared.commit_lsn <= Lsn(sk_info.commit_lsn));
     181            0 :         assert!(prepared.flush_lsn <= Lsn(sk_info.flush_lsn));
     182              : 
     183            0 :         Ok(())
     184            0 :     }
     185              : 
     186              :     /// Write new state to disk. If in-memory and on-disk states diverged, returns an error.
     187            0 :     async fn commit_state(&mut self, new_state: State) -> anyhow::Result<()> {
     188            0 :         self.tli
     189            0 :             .map_control_file(|cf| {
     190            0 :                 if cf.partial_backup != self.state {
     191            0 :                     let memory = self.state.clone();
     192            0 :                     self.state = cf.partial_backup.clone();
     193            0 :                     anyhow::bail!(
     194            0 :                         "partial backup state diverged, memory={:?}, disk={:?}",
     195            0 :                         memory,
     196            0 :                         cf.partial_backup
     197            0 :                     );
     198            0 :                 }
     199            0 : 
     200            0 :                 cf.partial_backup = new_state.clone();
     201            0 :                 Ok(())
     202            0 :             })
     203            0 :             .await?;
     204              :         // update in-memory state
     205            0 :         self.state = new_state;
     206            0 :         Ok(())
     207            0 :     }
     208              : 
     209              :     /// Upload the latest version of the partial segment and garbage collect older versions.
     210            0 :     #[instrument(name = "upload", skip_all, fields(name = %prepared.name))]
     211              :     async fn do_upload(&mut self, prepared: &PartialRemoteSegment) -> anyhow::Result<()> {
     212              :         let _timer = MISC_OPERATION_SECONDS
     213              :             .with_label_values(&["partial_do_upload"])
     214              :             .start_timer();
     215              :         info!("starting upload {:?}", prepared);
     216              : 
     217              :         let state_0 = self.state.clone();
     218              :         let state_1 = {
     219              :             let mut state = state_0.clone();
     220              :             state.segments.push(prepared.clone());
     221              :             state
     222              :         };
     223              : 
     224              :         // we're going to upload a new segment, let's write it to disk to make GC later
     225              :         self.commit_state(state_1).await?;
     226              : 
     227              :         self.upload_segment(prepared.clone()).await?;
     228              : 
     229              :         let state_2 = {
     230              :             let mut state = state_0.clone();
     231              :             for seg in state.segments.iter_mut() {
     232              :                 seg.status = UploadStatus::Deleting;
     233              :             }
     234              :             let mut actual_remote_segment = prepared.clone();
     235              :             actual_remote_segment.status = UploadStatus::Uploaded;
     236              :             state.segments.push(actual_remote_segment);
     237              :             state
     238              :         };
     239              : 
     240              :         // we've uploaded new segment, it's actual, all other segments should be GCed
     241              :         self.commit_state(state_2).await?;
     242              :         self.gc().await?;
     243              : 
     244              :         Ok(())
     245              :     }
     246              : 
     247              :     /// Delete all non-Uploaded segments from the remote storage. There should be only one
     248              :     /// Uploaded segment at a time.
     249            0 :     #[instrument(name = "gc", skip_all)]
     250              :     async fn gc(&mut self) -> anyhow::Result<()> {
     251              :         let mut segments_to_delete = vec![];
     252              : 
     253              :         let new_segments: Vec<PartialRemoteSegment> = self
     254              :             .state
     255              :             .segments
     256              :             .iter()
     257            0 :             .filter_map(|seg| {
     258            0 :                 if seg.status == UploadStatus::Uploaded {
     259            0 :                     Some(seg.clone())
     260              :                 } else {
     261            0 :                     segments_to_delete.push(seg.name.clone());
     262            0 :                     None
     263              :                 }
     264            0 :             })
     265              :             .collect();
     266              : 
     267              :         if new_segments.len() == 1 {
     268              :             // we have an uploaded segment, it must not be deleted from remote storage
     269            0 :             segments_to_delete.retain(|name| name != &new_segments[0].name);
     270              :         } else {
     271              :             // there should always be zero or one uploaded segment
     272              :             assert!(
     273              :                 new_segments.is_empty(),
     274              :                 "too many uploaded segments: {:?}",
     275              :                 new_segments
     276              :             );
     277              :         }
     278              : 
     279              :         info!("deleting objects: {:?}", segments_to_delete);
     280              :         let mut objects_to_delete = vec![];
     281              :         for seg in segments_to_delete.iter() {
     282              :             let remote_path = self.remote_timeline_path.join(seg);
     283              :             objects_to_delete.push(remote_path);
     284              :         }
     285              : 
     286              :         // removing segments from remote storage
     287              :         wal_backup::delete_objects(&objects_to_delete).await?;
     288              : 
     289              :         // now we can update the state on disk
     290              :         let new_state = {
     291              :             let mut state = self.state.clone();
     292              :             state.segments = new_segments;
     293              :             state
     294              :         };
     295              :         self.commit_state(new_state).await?;
     296              : 
     297              :         Ok(())
     298              :     }
     299              : }
     300              : 
     301              : /// Check if everything is uploaded and partial backup task doesn't need to run.
     302            0 : pub(crate) fn needs_uploading(
     303            0 :     state: &StateSnapshot,
     304            0 :     uploaded: &Option<PartialRemoteSegment>,
     305            0 : ) -> bool {
     306            0 :     match uploaded {
     307            0 :         Some(uploaded) => {
     308            0 :             uploaded.status != UploadStatus::Uploaded
     309            0 :                 || uploaded.flush_lsn != state.flush_lsn
     310            0 :                 || uploaded.commit_lsn != state.commit_lsn
     311            0 :                 || uploaded.term != state.last_log_term
     312              :         }
     313            0 :         None => true,
     314              :     }
     315            0 : }
     316              : 
     317              : /// Main task for partial backup. It waits for the flush_lsn to change and then uploads the
     318              : /// partial segment to the remote storage. It also does garbage collection of old segments.
     319              : ///
     320              : /// When there is nothing more to do and the last segment was successfully uploaded, the task
     321              : /// returns PartialRemoteSegment, to signal readiness for offloading the timeline.
     322            0 : #[instrument(name = "Partial backup", skip_all, fields(ttid = %tli.ttid))]
     323              : pub async fn main_task(
     324              :     tli: WalResidentTimeline,
     325              :     conf: SafeKeeperConf,
     326              :     limiter: RateLimiter,
     327              : ) -> Option<PartialRemoteSegment> {
     328              :     debug!("started");
     329              :     let await_duration = conf.partial_backup_timeout;
     330              :     let mut first_iteration = true;
     331              : 
     332              :     let (_, persistent_state) = tli.get_state().await;
     333              :     let mut commit_lsn_rx = tli.get_commit_lsn_watch_rx();
     334              :     let mut flush_lsn_rx = tli.get_term_flush_lsn_watch_rx();
     335              :     let wal_seg_size = tli.get_wal_seg_size().await;
     336              : 
     337              :     let local_prefix = tli.get_timeline_dir();
     338              :     let remote_timeline_path = match remote_timeline_path(&tli.ttid) {
     339              :         Ok(path) => path,
     340              :         Err(e) => {
     341              :             error!("failed to create remote path: {:?}", e);
     342              :             return None;
     343              :         }
     344              :     };
     345              : 
     346              :     let mut backup = PartialBackup {
     347              :         wal_seg_size,
     348              :         tli,
     349              :         state: persistent_state.partial_backup,
     350              :         conf,
     351              :         local_prefix,
     352              :         remote_timeline_path,
     353              :     };
     354              : 
     355              :     debug!("state: {:?}", backup.state);
     356              : 
     357              :     // The general idea is that each safekeeper keeps only one partial segment
     358              :     // both in remote storage and in local state. If this is not true, something
     359              :     // went wrong.
     360              :     const MAX_SIMULTANEOUS_SEGMENTS: usize = 10;
     361              : 
     362              :     'outer: loop {
     363              :         if backup.state.segments.len() > MAX_SIMULTANEOUS_SEGMENTS {
     364              :             warn!(
     365              :                 "too many segments in control_file state, running gc: {}",
     366              :                 backup.state.segments.len()
     367              :             );
     368              : 
     369            0 :             backup.gc().await.unwrap_or_else(|e| {
     370            0 :                 error!("failed to run gc: {:#}", e);
     371            0 :             });
     372              :         }
     373              : 
     374              :         // wait until we have something to upload
     375              :         let uploaded_segment = backup.state.uploaded_segment();
     376              :         if let Some(seg) = &uploaded_segment {
     377              :             // check if uploaded segment matches the current state
     378              :             if flush_lsn_rx.borrow().lsn == seg.flush_lsn
     379              :                 && *commit_lsn_rx.borrow() == seg.commit_lsn
     380              :                 && flush_lsn_rx.borrow().term == seg.term
     381              :             {
     382              :                 // we have nothing to do, the last segment is already uploaded
     383              :                 return Some(seg.clone());
     384              :             }
     385              :         }
     386              : 
     387              :         // if we don't have any data and zero LSNs, wait for something
     388              :         while flush_lsn_rx.borrow().lsn == Lsn(0) {
     389              :             tokio::select! {
     390              :                 _ = backup.tli.cancel.cancelled() => {
     391              :                     info!("timeline canceled");
     392              :                     return None;
     393              :                 }
     394              :                 _ = flush_lsn_rx.changed() => {}
     395              :             }
     396              :         }
     397              : 
     398              :         // smoothing the load after restart, by sleeping for a random time.
     399              :         // if this is not the first iteration, we will wait for the full await_duration
     400              :         let await_duration = if first_iteration {
     401              :             first_iteration = false;
     402              :             rand_duration(&await_duration)
     403              :         } else {
     404              :             await_duration
     405              :         };
     406              : 
     407              :         // fixing the segno and waiting some time to prevent reuploading the same segment too often
     408              :         let pending_segno = backup.segno(flush_lsn_rx.borrow().lsn);
     409              :         let timeout = tokio::time::sleep(await_duration);
     410              :         tokio::pin!(timeout);
     411              :         let mut timeout_expired = false;
     412              : 
     413              :         // waiting until timeout expires OR segno changes
     414              :         'inner: loop {
     415              :             tokio::select! {
     416              :                 _ = backup.tli.cancel.cancelled() => {
     417              :                     info!("timeline canceled");
     418              :                     return None;
     419              :                 }
     420              :                 _ = commit_lsn_rx.changed() => {}
     421              :                 _ = flush_lsn_rx.changed() => {
     422              :                     let segno = backup.segno(flush_lsn_rx.borrow().lsn);
     423              :                     if segno != pending_segno {
     424              :                         // previous segment is no longer partial, aborting the wait
     425              :                         break 'inner;
     426              :                     }
     427              :                 }
     428              :                 _ = &mut timeout => {
     429              :                     // timeout expired, now we are ready for upload
     430              :                     timeout_expired = true;
     431              :                     break 'inner;
     432              :                 }
     433              :             }
     434              :         }
     435              : 
     436              :         if !timeout_expired {
     437              :             // likely segno has changed, let's try again in the next iteration
     438              :             continue 'outer;
     439              :         }
     440              : 
     441              :         // limit concurrent uploads
     442              :         let _upload_permit = limiter.acquire_partial_backup().await;
     443              : 
     444              :         let prepared = backup.prepare_upload().await;
     445              :         if let Some(seg) = &uploaded_segment {
     446              :             if seg.eq_without_status(&prepared) {
     447              :                 // we already uploaded this segment, nothing to do
     448              :                 continue 'outer;
     449              :             }
     450              :         }
     451              : 
     452              :         match backup.do_upload(&prepared).await {
     453              :             Ok(()) => {
     454              :                 debug!(
     455              :                     "uploaded {} up to flush_lsn {}",
     456              :                     prepared.name, prepared.flush_lsn
     457              :                 );
     458              :                 PARTIAL_BACKUP_UPLOADS.with_label_values(&["ok"]).inc();
     459              :             }
     460              :             Err(e) => {
     461              :                 info!("failed to upload {}: {:#}", prepared.name, e);
     462              :                 PARTIAL_BACKUP_UPLOADS.with_label_values(&["error"]).inc();
     463              :             }
     464              :         }
     465              :     }
     466              : }
        

Generated by: LCOV version 2.1-beta