LCOV - code coverage report
Current view: top level - safekeeper/src - timeline_eviction.rs (source / functions) Coverage Total Hit
Test: 53437f7e869ac68c86c7d3e4c20964c0156f158c.info Lines: 0.0 % 225 0
Test Date: 2024-09-20 16:14:12 Functions: 0.0 % 33 0

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

Generated by: LCOV version 2.1-beta