LCOV - code coverage report
Current view: top level - safekeeper/src - copy_timeline.rs (source / functions) Coverage Total Hit
Test: a43a77853355b937a79c57b07a8f05607cf29e6c.info Lines: 0.0 % 164 0
Test Date: 2024-09-19 12:04:32 Functions: 0.0 % 6 0

            Line data    Source code
       1              : use std::sync::Arc;
       2              : 
       3              : use anyhow::{bail, Result};
       4              : use camino::Utf8PathBuf;
       5              : 
       6              : use postgres_ffi::{MAX_SEND_SIZE, WAL_SEGMENT_SIZE};
       7              : use tokio::{
       8              :     fs::OpenOptions,
       9              :     io::{AsyncSeekExt, AsyncWriteExt},
      10              : };
      11              : use tracing::{info, warn};
      12              : use utils::{id::TenantTimelineId, lsn::Lsn};
      13              : 
      14              : use crate::{
      15              :     control_file::{FileStorage, Storage},
      16              :     pull_timeline::{create_temp_timeline_dir, load_temp_timeline, validate_temp_timeline},
      17              :     state::TimelinePersistentState,
      18              :     timeline::{Timeline, TimelineError, WalResidentTimeline},
      19              :     wal_backup::copy_s3_segments,
      20              :     wal_storage::{wal_file_paths, WalReader},
      21              :     GlobalTimelines,
      22              : };
      23              : 
      24              : // we don't want to have more than 10 segments on disk after copy, because they take space
      25              : const MAX_BACKUP_LAG: u64 = 10 * WAL_SEGMENT_SIZE as u64;
      26              : 
      27              : pub struct Request {
      28              :     pub source: Arc<Timeline>,
      29              :     pub until_lsn: Lsn,
      30              :     pub destination_ttid: TenantTimelineId,
      31              : }
      32              : 
      33            0 : pub async fn handle_request(request: Request) -> Result<()> {
      34            0 :     // TODO: request.until_lsn MUST be a valid LSN, and we cannot check it :(
      35            0 :     //   if LSN will point to the middle of a WAL record, timeline will be in "broken" state
      36            0 : 
      37            0 :     match GlobalTimelines::get(request.destination_ttid) {
      38              :         // timeline already exists. would be good to check that this timeline is the copy
      39              :         // of the source timeline, but it isn't obvious how to do that
      40            0 :         Ok(_) => return Ok(()),
      41              :         // timeline not found, we are going to create it
      42            0 :         Err(TimelineError::NotFound(_)) => {}
      43              :         // error, probably timeline was deleted
      44            0 :         res => {
      45            0 :             res?;
      46              :         }
      47              :     }
      48              : 
      49            0 :     let source_tli = request.source.wal_residence_guard().await?;
      50              : 
      51            0 :     let conf = &GlobalTimelines::get_global_config();
      52            0 :     let ttid = request.destination_ttid;
      53              : 
      54            0 :     let (_tmp_dir, tli_dir_path) = create_temp_timeline_dir(conf, ttid).await?;
      55              : 
      56            0 :     let (mem_state, state) = source_tli.get_state().await;
      57            0 :     let start_lsn = state.timeline_start_lsn;
      58            0 :     if start_lsn == Lsn::INVALID {
      59            0 :         bail!("timeline is not initialized");
      60            0 :     }
      61            0 :     let backup_lsn = mem_state.backup_lsn;
      62            0 : 
      63            0 :     {
      64            0 :         let commit_lsn = mem_state.commit_lsn;
      65            0 :         let flush_lsn = source_tli.get_flush_lsn().await;
      66              : 
      67            0 :         info!(
      68            0 :             "collected info about source timeline: start_lsn={}, backup_lsn={}, commit_lsn={}, flush_lsn={}",
      69              :             start_lsn, backup_lsn, commit_lsn, flush_lsn
      70              :         );
      71              : 
      72            0 :         assert!(backup_lsn >= start_lsn);
      73            0 :         assert!(commit_lsn >= start_lsn);
      74            0 :         assert!(flush_lsn >= start_lsn);
      75              : 
      76            0 :         if request.until_lsn > flush_lsn {
      77            0 :             bail!(format!(
      78            0 :                 "requested LSN {} is beyond the end of the timeline {}",
      79            0 :                 request.until_lsn, flush_lsn
      80            0 :             ));
      81            0 :         }
      82            0 :         if request.until_lsn < start_lsn {
      83            0 :             bail!(format!(
      84            0 :                 "requested LSN {} is before the start of the timeline {}",
      85            0 :                 request.until_lsn, start_lsn
      86            0 :             ));
      87            0 :         }
      88            0 : 
      89            0 :         if request.until_lsn > commit_lsn {
      90            0 :             warn!("copy_timeline WAL is not fully committed");
      91            0 :         }
      92              : 
      93            0 :         if backup_lsn < request.until_lsn && request.until_lsn.0 - backup_lsn.0 > MAX_BACKUP_LAG {
      94              :             // we have a lot of segments that are not backed up. we can try to wait here until
      95              :             // segments will be backed up to remote storage, but it's not clear how long to wait
      96            0 :             bail!("too many segments are not backed up");
      97            0 :         }
      98            0 :     }
      99            0 : 
     100            0 :     let wal_seg_size = state.server.wal_seg_size as usize;
     101            0 :     if wal_seg_size == 0 {
     102            0 :         bail!("wal_seg_size is not set");
     103            0 :     }
     104            0 : 
     105            0 :     let first_segment = start_lsn.segment_number(wal_seg_size);
     106            0 :     let last_segment = request.until_lsn.segment_number(wal_seg_size);
     107              : 
     108            0 :     let new_backup_lsn = {
     109              :         // we can't have new backup_lsn greater than existing backup_lsn or start of the last segment
     110            0 :         let max_backup_lsn = backup_lsn.min(Lsn(last_segment * wal_seg_size as u64));
     111            0 : 
     112            0 :         if max_backup_lsn <= start_lsn {
     113              :             // probably we are starting from the first segment, which was not backed up yet.
     114              :             // note that start_lsn can be in the middle of the segment
     115            0 :             start_lsn
     116              :         } else {
     117              :             // we have some segments backed up, so we will assume all WAL below max_backup_lsn is backed up
     118            0 :             assert!(max_backup_lsn.segment_offset(wal_seg_size) == 0);
     119            0 :             max_backup_lsn
     120              :         }
     121              :     };
     122              : 
     123              :     // all previous segments will be copied inside S3
     124            0 :     let first_ondisk_segment = new_backup_lsn.segment_number(wal_seg_size);
     125            0 :     assert!(first_ondisk_segment <= last_segment);
     126            0 :     assert!(first_ondisk_segment >= first_segment);
     127              : 
     128            0 :     copy_s3_segments(
     129            0 :         wal_seg_size,
     130            0 :         &request.source.ttid,
     131            0 :         &request.destination_ttid,
     132            0 :         first_segment,
     133            0 :         first_ondisk_segment,
     134            0 :     )
     135            0 :     .await?;
     136              : 
     137            0 :     copy_disk_segments(
     138            0 :         &source_tli,
     139            0 :         wal_seg_size,
     140            0 :         new_backup_lsn,
     141            0 :         request.until_lsn,
     142            0 :         &tli_dir_path,
     143            0 :     )
     144            0 :     .await?;
     145              : 
     146            0 :     let mut new_state = TimelinePersistentState::new(
     147            0 :         &request.destination_ttid,
     148            0 :         state.server.clone(),
     149            0 :         vec![],
     150            0 :         request.until_lsn,
     151            0 :         start_lsn,
     152            0 :     );
     153            0 :     new_state.timeline_start_lsn = start_lsn;
     154            0 :     new_state.peer_horizon_lsn = request.until_lsn;
     155            0 :     new_state.backup_lsn = new_backup_lsn;
     156              : 
     157            0 :     let mut file_storage = FileStorage::create_new(tli_dir_path.clone(), conf, new_state.clone())?;
     158            0 :     file_storage.persist(&new_state).await?;
     159              : 
     160              :     // now we have a ready timeline in a temp directory
     161            0 :     validate_temp_timeline(conf, request.destination_ttid, &tli_dir_path).await?;
     162            0 :     load_temp_timeline(conf, request.destination_ttid, &tli_dir_path).await?;
     163              : 
     164            0 :     Ok(())
     165            0 : }
     166              : 
     167            0 : async fn copy_disk_segments(
     168            0 :     tli: &WalResidentTimeline,
     169            0 :     wal_seg_size: usize,
     170            0 :     start_lsn: Lsn,
     171            0 :     end_lsn: Lsn,
     172            0 :     tli_dir_path: &Utf8PathBuf,
     173            0 : ) -> Result<()> {
     174            0 :     let mut wal_reader = tli.get_walreader(start_lsn).await?;
     175              : 
     176            0 :     let mut buf = [0u8; MAX_SEND_SIZE];
     177            0 : 
     178            0 :     let first_segment = start_lsn.segment_number(wal_seg_size);
     179            0 :     let last_segment = end_lsn.segment_number(wal_seg_size);
     180              : 
     181            0 :     for segment in first_segment..=last_segment {
     182            0 :         let segment_start = segment * wal_seg_size as u64;
     183            0 :         let segment_end = segment_start + wal_seg_size as u64;
     184            0 : 
     185            0 :         let copy_start = segment_start.max(start_lsn.0);
     186            0 :         let copy_end = segment_end.min(end_lsn.0);
     187            0 : 
     188            0 :         let copy_start = copy_start - segment_start;
     189            0 :         let copy_end = copy_end - segment_start;
     190              : 
     191            0 :         let wal_file_path = {
     192            0 :             let (normal, partial) = wal_file_paths(tli_dir_path, segment, wal_seg_size);
     193            0 : 
     194            0 :             if segment == last_segment {
     195            0 :                 partial
     196              :             } else {
     197            0 :                 normal
     198              :             }
     199              :         };
     200              : 
     201            0 :         write_segment(
     202            0 :             &mut buf,
     203            0 :             &wal_file_path,
     204            0 :             wal_seg_size as u64,
     205            0 :             copy_start,
     206            0 :             copy_end,
     207            0 :             &mut wal_reader,
     208            0 :         )
     209            0 :         .await?;
     210              :     }
     211              : 
     212            0 :     Ok(())
     213            0 : }
     214              : 
     215            0 : async fn write_segment(
     216            0 :     buf: &mut [u8],
     217            0 :     file_path: &Utf8PathBuf,
     218            0 :     wal_seg_size: u64,
     219            0 :     from: u64,
     220            0 :     to: u64,
     221            0 :     reader: &mut WalReader,
     222            0 : ) -> Result<()> {
     223            0 :     assert!(from <= to);
     224            0 :     assert!(to <= wal_seg_size);
     225              : 
     226              :     #[allow(clippy::suspicious_open_options)]
     227            0 :     let mut file = OpenOptions::new()
     228            0 :         .create(true)
     229            0 :         .write(true)
     230            0 :         .open(&file_path)
     231            0 :         .await?;
     232              : 
     233              :     // maybe fill with zeros, as in wal_storage.rs?
     234            0 :     file.set_len(wal_seg_size).await?;
     235            0 :     file.seek(std::io::SeekFrom::Start(from)).await?;
     236              : 
     237            0 :     let mut bytes_left = to - from;
     238            0 :     while bytes_left > 0 {
     239            0 :         let len = bytes_left as usize;
     240            0 :         let len = len.min(buf.len());
     241            0 :         let len = reader.read(&mut buf[..len]).await?;
     242            0 :         file.write_all(&buf[..len]).await?;
     243            0 :         bytes_left -= len as u64;
     244              :     }
     245              : 
     246            0 :     file.flush().await?;
     247            0 :     file.sync_all().await?;
     248            0 :     Ok(())
     249            0 : }
        

Generated by: LCOV version 2.1-beta