LCOV - code coverage report
Current view: top level - safekeeper/src - timeline_eviction.rs (source / functions) Coverage Total Hit
Test: 42f947419473a288706e86ecdf7c2863d760d5d7.info Lines: 0.0 % 236 0
Test Date: 2024-08-02 21:34:27 Functions: 0.0 % 33 0

            Line data    Source code
       1              : //! Code related to evicting WAL files to remote storage. The actual upload is done by the
       2              : //! partial WAL backup code. This file has code to delete and re-download WAL files,
       3              : //! cross-validate with partial WAL backup if local file is still present.
       4              : 
       5              : use anyhow::Context;
       6              : use camino::Utf8PathBuf;
       7              : use remote_storage::RemotePath;
       8              : use tokio::{
       9              :     fs::File,
      10              :     io::{AsyncRead, AsyncWriteExt},
      11              : };
      12              : use tracing::{debug, info, instrument, warn};
      13              : use utils::crashsafe::durable_rename;
      14              : 
      15              : use crate::{
      16              :     metrics::{EvictionEvent, EVICTION_EVENTS_COMPLETED, EVICTION_EVENTS_STARTED},
      17              :     rate_limit::rand_duration,
      18              :     timeline_manager::{Manager, StateSnapshot},
      19              :     wal_backup,
      20              :     wal_backup_partial::{self, PartialRemoteSegment},
      21              :     wal_storage::wal_file_paths,
      22              : };
      23              : 
      24              : impl Manager {
      25              :     /// Returns true if the timeline is ready for eviction.
      26              :     /// Current criteria:
      27              :     /// - no active tasks
      28              :     /// - control file is flushed (no next event scheduled)
      29              :     /// - no WAL residence guards
      30              :     /// - no pushes to the broker
      31              :     /// - partial WAL backup is uploaded
      32            0 :     pub(crate) fn ready_for_eviction(
      33            0 :         &self,
      34            0 :         next_event: &Option<tokio::time::Instant>,
      35            0 :         state: &StateSnapshot,
      36            0 :     ) -> bool {
      37            0 :         self.backup_task.is_none()
      38            0 :             && self.recovery_task.is_none()
      39            0 :             && self.wal_removal_task.is_none()
      40            0 :             && self.partial_backup_task.is_none()
      41            0 :             && self.partial_backup_uploaded.is_some()
      42            0 :             && next_event.is_none()
      43            0 :             && self.access_service.is_empty()
      44            0 :             && !self.tli_broker_active.get()
      45            0 :             && !wal_backup_partial::needs_uploading(state, &self.partial_backup_uploaded)
      46            0 :             && self
      47            0 :                 .partial_backup_uploaded
      48            0 :                 .as_ref()
      49            0 :                 .unwrap()
      50            0 :                 .flush_lsn
      51            0 :                 .segment_number(self.wal_seg_size)
      52            0 :                 == self.last_removed_segno + 1
      53            0 :     }
      54              : 
      55              :     /// Evict the timeline to remote storage.
      56            0 :     #[instrument(name = "evict_timeline", skip_all)]
      57              :     pub(crate) async fn evict_timeline(&mut self) {
      58              :         assert!(!self.is_offloaded);
      59              :         let partial_backup_uploaded = match &self.partial_backup_uploaded {
      60              :             Some(p) => p.clone(),
      61              :             None => {
      62              :                 warn!("no partial backup uploaded, skipping eviction");
      63              :                 return;
      64              :             }
      65              :         };
      66              : 
      67              :         info!("starting eviction, using {:?}", partial_backup_uploaded);
      68              : 
      69              :         EVICTION_EVENTS_STARTED
      70              :             .with_label_values(&[EvictionEvent::Evict.into()])
      71              :             .inc();
      72            0 :         let _guard = scopeguard::guard((), |_| {
      73            0 :             EVICTION_EVENTS_COMPLETED
      74            0 :                 .with_label_values(&[EvictionEvent::Evict.into()])
      75            0 :                 .inc();
      76            0 :         });
      77              : 
      78              :         if let Err(e) = do_eviction(self, &partial_backup_uploaded).await {
      79              :             warn!("failed to evict timeline: {:?}", e);
      80              :             return;
      81              :         }
      82              : 
      83              :         info!("successfully evicted timeline");
      84              :     }
      85              : 
      86              :     /// Restore evicted timeline from remote storage.
      87            0 :     #[instrument(name = "unevict_timeline", skip_all)]
      88              :     pub(crate) async fn unevict_timeline(&mut self) {
      89              :         assert!(self.is_offloaded);
      90              :         let partial_backup_uploaded = match &self.partial_backup_uploaded {
      91              :             Some(p) => p.clone(),
      92              :             None => {
      93              :                 warn!("no partial backup uploaded, cannot unevict");
      94              :                 return;
      95              :             }
      96              :         };
      97              : 
      98              :         info!("starting uneviction, using {:?}", partial_backup_uploaded);
      99              : 
     100              :         EVICTION_EVENTS_STARTED
     101              :             .with_label_values(&[EvictionEvent::Restore.into()])
     102              :             .inc();
     103            0 :         let _guard = scopeguard::guard((), |_| {
     104            0 :             EVICTION_EVENTS_COMPLETED
     105            0 :                 .with_label_values(&[EvictionEvent::Restore.into()])
     106            0 :                 .inc();
     107            0 :         });
     108              : 
     109              :         if let Err(e) = do_uneviction(self, &partial_backup_uploaded).await {
     110              :             warn!("failed to unevict timeline: {:?}", e);
     111              :             return;
     112              :         }
     113              : 
     114              :         self.evict_not_before =
     115              :             tokio::time::Instant::now() + rand_duration(&self.conf.eviction_min_resident);
     116              : 
     117              :         info!("successfully restored evicted timeline");
     118              :     }
     119              : }
     120              : 
     121              : /// Ensure that content matches the remote partial backup, if local segment exists.
     122              : /// Then change state in control file and in-memory. If `delete_offloaded_wal` is set,
     123              : /// delete the local segment.
     124            0 : async fn do_eviction(mgr: &mut Manager, partial: &PartialRemoteSegment) -> anyhow::Result<()> {
     125            0 :     compare_local_segment_with_remote(mgr, partial).await?;
     126              : 
     127            0 :     mgr.tli.switch_to_offloaded(partial).await?;
     128              :     // switch manager state as soon as possible
     129            0 :     mgr.is_offloaded = true;
     130            0 : 
     131            0 :     if mgr.conf.delete_offloaded_wal {
     132            0 :         delete_local_segment(mgr, partial).await?;
     133            0 :     }
     134              : 
     135            0 :     Ok(())
     136            0 : }
     137              : 
     138              : /// Ensure that content matches the remote partial backup, if local segment exists.
     139              : /// Then download segment to local disk and change state in control file and in-memory.
     140            0 : async fn do_uneviction(mgr: &mut Manager, partial: &PartialRemoteSegment) -> anyhow::Result<()> {
     141            0 :     // if the local segment is present, validate it
     142            0 :     compare_local_segment_with_remote(mgr, partial).await?;
     143              : 
     144              :     // atomically download the partial segment
     145            0 :     redownload_partial_segment(mgr, partial).await?;
     146              : 
     147            0 :     mgr.tli.switch_to_present().await?;
     148              :     // switch manager state as soon as possible
     149            0 :     mgr.is_offloaded = false;
     150            0 : 
     151            0 :     Ok(())
     152            0 : }
     153              : 
     154              : /// Delete local WAL segment.
     155            0 : async fn delete_local_segment(mgr: &Manager, partial: &PartialRemoteSegment) -> anyhow::Result<()> {
     156            0 :     let local_path = local_segment_path(mgr, partial);
     157            0 : 
     158            0 :     info!("deleting WAL file to evict: {}", local_path);
     159            0 :     tokio::fs::remove_file(&local_path).await?;
     160            0 :     Ok(())
     161            0 : }
     162              : 
     163              : /// Redownload partial segment from remote storage.
     164              : /// The segment is downloaded to a temporary file and then renamed to the final path.
     165            0 : async fn redownload_partial_segment(
     166            0 :     mgr: &Manager,
     167            0 :     partial: &PartialRemoteSegment,
     168            0 : ) -> anyhow::Result<()> {
     169            0 :     let tmp_file = mgr.tli.timeline_dir().join("remote_partial.tmp");
     170            0 :     let remote_segfile = remote_segment_path(mgr, partial)?;
     171              : 
     172            0 :     debug!(
     173            0 :         "redownloading partial segment: {} -> {}",
     174              :         remote_segfile, tmp_file
     175              :     );
     176              : 
     177            0 :     let mut reader = wal_backup::read_object(&remote_segfile, 0).await?;
     178            0 :     let mut file = File::create(&tmp_file).await?;
     179              : 
     180            0 :     let actual_len = tokio::io::copy(&mut reader, &mut file).await?;
     181            0 :     let expected_len = partial.flush_lsn.segment_offset(mgr.wal_seg_size);
     182            0 : 
     183            0 :     if actual_len != expected_len as u64 {
     184            0 :         anyhow::bail!(
     185            0 :             "partial downloaded {} bytes, expected {}",
     186            0 :             actual_len,
     187            0 :             expected_len
     188            0 :         );
     189            0 :     }
     190            0 : 
     191            0 :     if actual_len > mgr.wal_seg_size as u64 {
     192            0 :         anyhow::bail!(
     193            0 :             "remote segment is too long: {} bytes, expected {}",
     194            0 :             actual_len,
     195            0 :             mgr.wal_seg_size
     196            0 :         );
     197            0 :     }
     198            0 :     file.set_len(mgr.wal_seg_size as u64).await?;
     199            0 :     file.flush().await?;
     200              : 
     201            0 :     let final_path = local_segment_path(mgr, partial);
     202            0 :     info!("downloaded {actual_len} bytes, renaming to {final_path}");
     203            0 :     if let Err(e) = durable_rename(&tmp_file, &final_path, !mgr.conf.no_sync).await {
     204              :         // Probably rename succeeded, but fsync of it failed. Remove
     205              :         // the file then to avoid using it.
     206            0 :         tokio::fs::remove_file(tmp_file)
     207            0 :             .await
     208            0 :             .or_else(utils::fs_ext::ignore_not_found)?;
     209            0 :         return Err(e.into());
     210            0 :     }
     211            0 : 
     212            0 :     Ok(())
     213            0 : }
     214              : 
     215              : /// Compare local WAL segment with partial WAL backup in remote storage.
     216              : /// If the local segment is not present, the function does nothing.
     217              : /// If the local segment is present, it compares the local segment with the remote one.
     218            0 : async fn compare_local_segment_with_remote(
     219            0 :     mgr: &Manager,
     220            0 :     partial: &PartialRemoteSegment,
     221            0 : ) -> anyhow::Result<()> {
     222            0 :     let local_path = local_segment_path(mgr, partial);
     223            0 : 
     224            0 :     match File::open(&local_path).await {
     225            0 :         Ok(mut local_file) => do_validation(mgr, &mut local_file, mgr.wal_seg_size, partial)
     226            0 :             .await
     227            0 :             .context("validation failed"),
     228              :         Err(_) => {
     229            0 :             info!(
     230            0 :                 "local WAL file {} is not present, skipping validation",
     231              :                 local_path
     232              :             );
     233            0 :             Ok(())
     234              :         }
     235              :     }
     236            0 : }
     237              : 
     238              : /// Compare opened local WAL segment with partial WAL backup in remote storage.
     239              : /// Validate full content of both files.
     240            0 : async fn do_validation(
     241            0 :     mgr: &Manager,
     242            0 :     file: &mut File,
     243            0 :     wal_seg_size: usize,
     244            0 :     partial: &PartialRemoteSegment,
     245            0 : ) -> anyhow::Result<()> {
     246            0 :     let local_size = file.metadata().await?.len() as usize;
     247            0 :     if local_size != wal_seg_size {
     248            0 :         anyhow::bail!(
     249            0 :             "local segment size is invalid: found {}, expected {}",
     250            0 :             local_size,
     251            0 :             wal_seg_size
     252            0 :         );
     253            0 :     }
     254              : 
     255            0 :     let remote_segfile = remote_segment_path(mgr, partial)?;
     256            0 :     let mut remote_reader: std::pin::Pin<Box<dyn AsyncRead + Send + Sync>> =
     257            0 :         wal_backup::read_object(&remote_segfile, 0).await?;
     258              : 
     259              :     // remote segment should have bytes excatly up to `flush_lsn`
     260            0 :     let expected_remote_size = partial.flush_lsn.segment_offset(mgr.wal_seg_size);
     261            0 :     // let's compare the first `expected_remote_size` bytes
     262            0 :     compare_n_bytes(&mut remote_reader, file, expected_remote_size).await?;
     263              :     // and check that the remote segment ends here
     264            0 :     check_end(&mut remote_reader).await?;
     265              : 
     266              :     // if local segment is longer, the rest should be zeroes
     267            0 :     read_n_zeroes(file, mgr.wal_seg_size - expected_remote_size).await?;
     268              :     // and check that the local segment ends here
     269            0 :     check_end(file).await?;
     270              : 
     271            0 :     Ok(())
     272            0 : }
     273              : 
     274            0 : fn local_segment_path(mgr: &Manager, partial: &PartialRemoteSegment) -> Utf8PathBuf {
     275            0 :     let flush_lsn = partial.flush_lsn;
     276            0 :     let segno = flush_lsn.segment_number(mgr.wal_seg_size);
     277            0 :     let (_, local_partial_segfile) =
     278            0 :         wal_file_paths(mgr.tli.timeline_dir(), segno, mgr.wal_seg_size);
     279            0 :     local_partial_segfile
     280            0 : }
     281              : 
     282            0 : fn remote_segment_path(
     283            0 :     mgr: &Manager,
     284            0 :     partial: &PartialRemoteSegment,
     285            0 : ) -> anyhow::Result<RemotePath> {
     286            0 :     let remote_timeline_path = wal_backup::remote_timeline_path(&mgr.tli.ttid)?;
     287            0 :     Ok(partial.remote_path(&remote_timeline_path))
     288            0 : }
     289              : 
     290              : /// Compare first `n` bytes of two readers. If the bytes differ, return an error.
     291              : /// If the readers are shorter than `n`, return an error.
     292            0 : async fn compare_n_bytes<R1, R2>(reader1: &mut R1, reader2: &mut R2, n: usize) -> anyhow::Result<()>
     293            0 : where
     294            0 :     R1: AsyncRead + Unpin,
     295            0 :     R2: AsyncRead + Unpin,
     296            0 : {
     297            0 :     use tokio::io::AsyncReadExt;
     298            0 : 
     299            0 :     const BUF_SIZE: usize = 32 * 1024;
     300            0 : 
     301            0 :     let mut buffer1 = vec![0u8; BUF_SIZE];
     302            0 :     let mut buffer2 = vec![0u8; BUF_SIZE];
     303            0 : 
     304            0 :     let mut offset = 0;
     305              : 
     306            0 :     while offset < n {
     307            0 :         let bytes_to_read = std::cmp::min(BUF_SIZE, n - offset);
     308              : 
     309            0 :         let bytes_read1 = reader1
     310            0 :             .read(&mut buffer1[..bytes_to_read])
     311            0 :             .await
     312            0 :             .with_context(|| format!("failed to read from reader1 at offset {}", offset))?;
     313            0 :         if bytes_read1 == 0 {
     314            0 :             anyhow::bail!("unexpected EOF from reader1 at offset {}", offset);
     315            0 :         }
     316              : 
     317            0 :         let bytes_read2 = reader2
     318            0 :             .read_exact(&mut buffer2[..bytes_read1])
     319            0 :             .await
     320            0 :             .with_context(|| {
     321            0 :                 format!(
     322            0 :                     "failed to read {} bytes from reader2 at offset {}",
     323            0 :                     bytes_read1, offset
     324            0 :                 )
     325            0 :             })?;
     326            0 :         assert!(bytes_read2 == bytes_read1);
     327              : 
     328            0 :         if buffer1[..bytes_read1] != buffer2[..bytes_read2] {
     329            0 :             let diff_offset = buffer1[..bytes_read1]
     330            0 :                 .iter()
     331            0 :                 .zip(buffer2[..bytes_read2].iter())
     332            0 :                 .position(|(a, b)| a != b)
     333            0 :                 .expect("mismatched buffers, but no difference found");
     334            0 :             anyhow::bail!("mismatch at offset {}", offset + diff_offset);
     335            0 :         }
     336            0 : 
     337            0 :         offset += bytes_read1;
     338              :     }
     339              : 
     340            0 :     Ok(())
     341            0 : }
     342              : 
     343            0 : async fn check_end<R>(mut reader: R) -> anyhow::Result<()>
     344            0 : where
     345            0 :     R: AsyncRead + Unpin,
     346            0 : {
     347            0 :     use tokio::io::AsyncReadExt;
     348            0 : 
     349            0 :     let mut buffer = [0u8; 1];
     350            0 :     let bytes_read = reader.read(&mut buffer).await?;
     351            0 :     if bytes_read != 0 {
     352            0 :         anyhow::bail!("expected EOF, found bytes");
     353            0 :     }
     354            0 :     Ok(())
     355            0 : }
     356              : 
     357            0 : async fn read_n_zeroes<R>(reader: &mut R, n: usize) -> anyhow::Result<()>
     358            0 : where
     359            0 :     R: AsyncRead + Unpin,
     360            0 : {
     361            0 :     use tokio::io::AsyncReadExt;
     362            0 : 
     363            0 :     const BUF_SIZE: usize = 32 * 1024;
     364            0 :     let mut buffer = vec![0u8; BUF_SIZE];
     365            0 :     let mut offset = 0;
     366              : 
     367            0 :     while offset < n {
     368            0 :         let bytes_to_read = std::cmp::min(BUF_SIZE, n - offset);
     369              : 
     370            0 :         let bytes_read = reader
     371            0 :             .read(&mut buffer[..bytes_to_read])
     372            0 :             .await
     373            0 :             .context("expected zeroes, got read error")?;
     374            0 :         if bytes_read == 0 {
     375            0 :             anyhow::bail!("expected zeroes, got EOF");
     376            0 :         }
     377            0 : 
     378            0 :         if buffer[..bytes_read].iter().all(|&b| b == 0) {
     379            0 :             offset += bytes_read;
     380            0 :         } else {
     381            0 :             anyhow::bail!("non-zero byte found");
     382              :         }
     383              :     }
     384              : 
     385            0 :     Ok(())
     386            0 : }
        

Generated by: LCOV version 2.1-beta