LCOV - code coverage report
Current view: top level - safekeeper/src - wal_backup.rs (source / functions) Coverage Total Hit
Test: 5445d246133daeceb0507e6cc0797ab7c1c70cb8.info Lines: 2.5 % 441 11
Test Date: 2025-03-12 18:05:02 Functions: 3.2 % 62 2

            Line data    Source code
       1              : use std::cmp::min;
       2              : use std::collections::HashSet;
       3              : use std::num::NonZeroU32;
       4              : use std::pin::Pin;
       5              : use std::time::Duration;
       6              : 
       7              : use anyhow::{Context, Result};
       8              : use camino::{Utf8Path, Utf8PathBuf};
       9              : use futures::StreamExt;
      10              : use futures::stream::FuturesOrdered;
      11              : use postgres_ffi::v14::xlog_utils::XLogSegNoOffsetToRecPtr;
      12              : use postgres_ffi::{PG_TLI, XLogFileName, XLogSegNo};
      13              : use remote_storage::{
      14              :     DownloadOpts, GenericRemoteStorage, ListingMode, RemotePath, StorageMetadata,
      15              : };
      16              : use safekeeper_api::models::PeerInfo;
      17              : use tokio::fs::File;
      18              : use tokio::select;
      19              : use tokio::sync::mpsc::{self, Receiver, Sender};
      20              : use tokio::sync::{OnceCell, watch};
      21              : use tokio::task::JoinHandle;
      22              : use tokio_util::sync::CancellationToken;
      23              : use tracing::*;
      24              : use utils::id::{NodeId, TenantTimelineId};
      25              : use utils::lsn::Lsn;
      26              : use utils::{backoff, pausable_failpoint};
      27              : 
      28              : use crate::metrics::{BACKED_UP_SEGMENTS, BACKUP_ERRORS, WAL_BACKUP_TASKS};
      29              : use crate::timeline::WalResidentTimeline;
      30              : use crate::timeline_manager::{Manager, StateSnapshot};
      31              : use crate::{SafeKeeperConf, WAL_BACKUP_RUNTIME};
      32              : 
      33              : const UPLOAD_FAILURE_RETRY_MIN_MS: u64 = 10;
      34              : const UPLOAD_FAILURE_RETRY_MAX_MS: u64 = 5000;
      35              : 
      36              : /// Default buffer size when interfacing with [`tokio::fs::File`].
      37              : const BUFFER_SIZE: usize = 32 * 1024;
      38              : 
      39              : pub struct WalBackupTaskHandle {
      40              :     shutdown_tx: Sender<()>,
      41              :     handle: JoinHandle<()>,
      42              : }
      43              : 
      44              : impl WalBackupTaskHandle {
      45            0 :     pub(crate) async fn join(self) {
      46            0 :         if let Err(e) = self.handle.await {
      47            0 :             error!("WAL backup task panicked: {}", e);
      48            0 :         }
      49            0 :     }
      50              : }
      51              : 
      52              : /// Do we have anything to upload to S3, i.e. should safekeepers run backup activity?
      53           35 : pub(crate) fn is_wal_backup_required(
      54           35 :     wal_seg_size: usize,
      55           35 :     num_computes: usize,
      56           35 :     state: &StateSnapshot,
      57           35 : ) -> bool {
      58           35 :     num_computes > 0 ||
      59              :     // Currently only the whole segment is offloaded, so compare segment numbers.
      60           24 :     (state.commit_lsn.segment_number(wal_seg_size) > state.backup_lsn.segment_number(wal_seg_size))
      61           35 : }
      62              : 
      63              : /// Based on peer information determine which safekeeper should offload; if it
      64              : /// is me, run (per timeline) task, if not yet. OTOH, if it is not me and task
      65              : /// is running, kill it.
      66            0 : pub(crate) async fn update_task(mgr: &mut Manager, need_backup: bool, state: &StateSnapshot) {
      67            0 :     let (offloader, election_dbg_str) =
      68            0 :         determine_offloader(&state.peers, state.backup_lsn, mgr.tli.ttid, &mgr.conf);
      69            0 :     let elected_me = Some(mgr.conf.my_id) == offloader;
      70              : 
      71            0 :     let should_task_run = need_backup && elected_me;
      72              : 
      73              :     // start or stop the task
      74            0 :     if should_task_run != (mgr.backup_task.is_some()) {
      75            0 :         if should_task_run {
      76            0 :             info!("elected for backup: {}", election_dbg_str);
      77              : 
      78            0 :             let (shutdown_tx, shutdown_rx) = mpsc::channel(1);
      79              : 
      80            0 :             let Ok(resident) = mgr.wal_resident_timeline() else {
      81            0 :                 info!("Timeline shut down");
      82            0 :                 return;
      83              :             };
      84              : 
      85            0 :             let async_task = backup_task_main(resident, mgr.conf.backup_parallel_jobs, shutdown_rx);
      86              : 
      87            0 :             let handle = if mgr.conf.current_thread_runtime {
      88            0 :                 tokio::spawn(async_task)
      89              :             } else {
      90            0 :                 WAL_BACKUP_RUNTIME.spawn(async_task)
      91              :             };
      92              : 
      93            0 :             mgr.backup_task = Some(WalBackupTaskHandle {
      94            0 :                 shutdown_tx,
      95            0 :                 handle,
      96            0 :             });
      97              :         } else {
      98            0 :             if !need_backup {
      99              :                 // don't need backup at all
     100            0 :                 info!("stepping down from backup, need_backup={}", need_backup);
     101              :             } else {
     102              :                 // someone else has been elected
     103            0 :                 info!("stepping down from backup: {}", election_dbg_str);
     104              :             }
     105            0 :             shut_down_task(&mut mgr.backup_task).await;
     106              :         }
     107            0 :     }
     108            0 : }
     109              : 
     110            0 : async fn shut_down_task(entry: &mut Option<WalBackupTaskHandle>) {
     111            0 :     if let Some(wb_handle) = entry.take() {
     112              :         // Tell the task to shutdown. Error means task exited earlier, that's ok.
     113            0 :         let _ = wb_handle.shutdown_tx.send(()).await;
     114              :         // Await the task itself. TODO: restart panicked tasks earlier.
     115            0 :         wb_handle.join().await;
     116            0 :     }
     117            0 : }
     118              : 
     119              : /// The goal is to ensure that normally only one safekeepers offloads. However,
     120              : /// it is fine (and inevitable, as s3 doesn't provide CAS) that for some short
     121              : /// time we have several ones as they PUT the same files. Also,
     122              : /// - frequently changing the offloader would be bad;
     123              : /// - electing seriously lagging safekeeper is undesirable;
     124              : ///
     125              : /// So we deterministically choose among the reasonably caught up candidates.
     126              : /// TODO: take into account failed attempts to deal with hypothetical situation
     127              : /// where s3 is unreachable only for some sks.
     128            0 : fn determine_offloader(
     129            0 :     alive_peers: &[PeerInfo],
     130            0 :     wal_backup_lsn: Lsn,
     131            0 :     ttid: TenantTimelineId,
     132            0 :     conf: &SafeKeeperConf,
     133            0 : ) -> (Option<NodeId>, String) {
     134            0 :     // TODO: remove this once we fill newly joined safekeepers since backup_lsn.
     135            0 :     let capable_peers = alive_peers
     136            0 :         .iter()
     137            0 :         .filter(|p| p.local_start_lsn <= wal_backup_lsn);
     138            0 :     match capable_peers.clone().map(|p| p.commit_lsn).max() {
     139            0 :         None => (None, "no connected peers to elect from".to_string()),
     140            0 :         Some(max_commit_lsn) => {
     141            0 :             let threshold = max_commit_lsn
     142            0 :                 .checked_sub(conf.max_offloader_lag_bytes)
     143            0 :                 .unwrap_or(Lsn(0));
     144            0 :             let mut caughtup_peers = capable_peers
     145            0 :                 .clone()
     146            0 :                 .filter(|p| p.commit_lsn >= threshold)
     147            0 :                 .collect::<Vec<_>>();
     148            0 :             caughtup_peers.sort_by(|p1, p2| p1.sk_id.cmp(&p2.sk_id));
     149            0 : 
     150            0 :             // To distribute the load, shift by timeline_id.
     151            0 :             let offloader = caughtup_peers
     152            0 :                 [(u128::from(ttid.timeline_id) % caughtup_peers.len() as u128) as usize]
     153            0 :                 .sk_id;
     154            0 : 
     155            0 :             let mut capable_peers_dbg = capable_peers
     156            0 :                 .map(|p| (p.sk_id, p.commit_lsn))
     157            0 :                 .collect::<Vec<_>>();
     158            0 :             capable_peers_dbg.sort_by(|p1, p2| p1.0.cmp(&p2.0));
     159            0 :             (
     160            0 :                 Some(offloader),
     161            0 :                 format!(
     162            0 :                     "elected {} among {:?} peers, with {} of them being caughtup",
     163            0 :                     offloader,
     164            0 :                     capable_peers_dbg,
     165            0 :                     caughtup_peers.len()
     166            0 :                 ),
     167            0 :             )
     168              :         }
     169              :     }
     170            0 : }
     171              : 
     172              : static REMOTE_STORAGE: OnceCell<Option<GenericRemoteStorage>> = OnceCell::const_new();
     173              : 
     174              : // Storage must be configured and initialized when this is called.
     175            0 : fn get_configured_remote_storage() -> &'static GenericRemoteStorage {
     176            0 :     REMOTE_STORAGE
     177            0 :         .get()
     178            0 :         .expect("failed to get remote storage")
     179            0 :         .as_ref()
     180            0 :         .unwrap()
     181            0 : }
     182              : 
     183            0 : pub async fn init_remote_storage(conf: &SafeKeeperConf) {
     184            0 :     // TODO: refactor REMOTE_STORAGE to avoid using global variables, and provide
     185            0 :     // dependencies to all tasks instead.
     186            0 :     REMOTE_STORAGE
     187            0 :         .get_or_init(|| async {
     188            0 :             if let Some(conf) = conf.remote_storage.as_ref() {
     189              :                 Some(
     190            0 :                     GenericRemoteStorage::from_config(conf)
     191            0 :                         .await
     192            0 :                         .expect("failed to create remote storage"),
     193              :                 )
     194              :             } else {
     195            0 :                 None
     196              :             }
     197            0 :         })
     198            0 :         .await;
     199            0 : }
     200              : 
     201              : struct WalBackupTask {
     202              :     timeline: WalResidentTimeline,
     203              :     timeline_dir: Utf8PathBuf,
     204              :     wal_seg_size: usize,
     205              :     parallel_jobs: usize,
     206              :     commit_lsn_watch_rx: watch::Receiver<Lsn>,
     207              : }
     208              : 
     209              : /// Offload single timeline.
     210              : #[instrument(name = "wal_backup", skip_all, fields(ttid = %tli.ttid))]
     211              : async fn backup_task_main(
     212              :     tli: WalResidentTimeline,
     213              :     parallel_jobs: usize,
     214              :     mut shutdown_rx: Receiver<()>,
     215              : ) {
     216              :     let _guard = WAL_BACKUP_TASKS.guard();
     217              :     info!("started");
     218              : 
     219              :     let cancel = tli.tli.cancel.clone();
     220              :     let mut wb = WalBackupTask {
     221              :         wal_seg_size: tli.get_wal_seg_size().await,
     222              :         commit_lsn_watch_rx: tli.get_commit_lsn_watch_rx(),
     223              :         timeline_dir: tli.get_timeline_dir(),
     224              :         timeline: tli,
     225              :         parallel_jobs,
     226              :     };
     227              : 
     228              :     // task is spinned up only when wal_seg_size already initialized
     229              :     assert!(wb.wal_seg_size > 0);
     230              : 
     231              :     let mut canceled = false;
     232              :     select! {
     233              :         _ = wb.run() => {}
     234              :         _ = shutdown_rx.recv() => {
     235              :             canceled = true;
     236              :         },
     237              :         _ = cancel.cancelled() => {
     238              :             canceled = true;
     239              :         }
     240              :     }
     241              :     info!("task {}", if canceled { "canceled" } else { "terminated" });
     242              : }
     243              : 
     244              : impl WalBackupTask {
     245              :     /// This function must be called from a select! that also respects self.timeline's
     246              :     /// cancellation token.  This is done in [`backup_task_main`].
     247              :     ///
     248              :     /// The future returned by this function is safe to drop at any time because it
     249              :     /// does not write to local disk.
     250            0 :     async fn run(&mut self) {
     251            0 :         let mut backup_lsn = Lsn(0);
     252            0 : 
     253            0 :         let mut retry_attempt = 0u32;
     254              :         // offload loop
     255            0 :         while !self.timeline.cancel.is_cancelled() {
     256            0 :             if retry_attempt == 0 {
     257              :                 // wait for new WAL to arrive
     258            0 :                 if let Err(e) = self.commit_lsn_watch_rx.changed().await {
     259              :                     // should never happen, as we hold Arc to timeline and transmitter's lifetime
     260              :                     // is within Timeline's
     261            0 :                     error!("commit_lsn watch shut down: {:?}", e);
     262            0 :                     return;
     263            0 :                 };
     264              :             } else {
     265              :                 // or just sleep if we errored previously
     266            0 :                 let mut retry_delay = UPLOAD_FAILURE_RETRY_MAX_MS;
     267            0 :                 if let Some(backoff_delay) = UPLOAD_FAILURE_RETRY_MIN_MS.checked_shl(retry_attempt)
     268            0 :                 {
     269            0 :                     retry_delay = min(retry_delay, backoff_delay);
     270            0 :                 }
     271            0 :                 tokio::time::sleep(Duration::from_millis(retry_delay)).await;
     272              :             }
     273              : 
     274            0 :             let commit_lsn = *self.commit_lsn_watch_rx.borrow();
     275            0 : 
     276            0 :             // Note that backup_lsn can be higher than commit_lsn if we
     277            0 :             // don't have much local WAL and others already uploaded
     278            0 :             // segments we don't even have.
     279            0 :             if backup_lsn.segment_number(self.wal_seg_size)
     280            0 :                 >= commit_lsn.segment_number(self.wal_seg_size)
     281              :             {
     282            0 :                 retry_attempt = 0;
     283            0 :                 continue; /* nothing to do, common case as we wake up on every commit_lsn bump */
     284            0 :             }
     285            0 :             // Perhaps peers advanced the position, check shmem value.
     286            0 :             backup_lsn = self.timeline.get_wal_backup_lsn().await;
     287            0 :             if backup_lsn.segment_number(self.wal_seg_size)
     288            0 :                 >= commit_lsn.segment_number(self.wal_seg_size)
     289              :             {
     290            0 :                 retry_attempt = 0;
     291            0 :                 continue;
     292            0 :             }
     293            0 : 
     294            0 :             match backup_lsn_range(
     295            0 :                 &self.timeline,
     296            0 :                 &mut backup_lsn,
     297            0 :                 commit_lsn,
     298            0 :                 self.wal_seg_size,
     299            0 :                 &self.timeline_dir,
     300            0 :                 self.parallel_jobs,
     301            0 :             )
     302            0 :             .await
     303              :             {
     304            0 :                 Ok(()) => {
     305            0 :                     retry_attempt = 0;
     306            0 :                 }
     307            0 :                 Err(e) => {
     308            0 :                     // We might have managed to upload some segment even though
     309            0 :                     // some later in the range failed, so log backup_lsn
     310            0 :                     // separately.
     311            0 :                     error!(
     312            0 :                         "failed while offloading range {}-{}, backup_lsn {}: {:?}",
     313              :                         backup_lsn, commit_lsn, backup_lsn, e
     314              :                     );
     315              : 
     316            0 :                     retry_attempt = retry_attempt.saturating_add(1);
     317              :                 }
     318              :             }
     319              :         }
     320            0 :     }
     321              : }
     322              : 
     323            0 : async fn backup_lsn_range(
     324            0 :     timeline: &WalResidentTimeline,
     325            0 :     backup_lsn: &mut Lsn,
     326            0 :     end_lsn: Lsn,
     327            0 :     wal_seg_size: usize,
     328            0 :     timeline_dir: &Utf8Path,
     329            0 :     parallel_jobs: usize,
     330            0 : ) -> Result<()> {
     331            0 :     if parallel_jobs < 1 {
     332            0 :         anyhow::bail!("parallel_jobs must be >= 1");
     333            0 :     }
     334            0 : 
     335            0 :     let remote_timeline_path = &timeline.remote_path;
     336            0 :     let start_lsn = *backup_lsn;
     337            0 :     let segments = get_segments(start_lsn, end_lsn, wal_seg_size);
     338            0 : 
     339            0 :     info!(
     340            0 :         "offloading segnos {:?} of range [{}-{})",
     341            0 :         segments.iter().map(|&s| s.seg_no).collect::<Vec<_>>(),
     342              :         start_lsn,
     343              :         end_lsn,
     344              :     );
     345              : 
     346              :     // Pool of concurrent upload tasks. We use `FuturesOrdered` to
     347              :     // preserve order of uploads, and update `backup_lsn` only after
     348              :     // all previous uploads are finished.
     349            0 :     let mut uploads = FuturesOrdered::new();
     350            0 :     let mut iter = segments.iter();
     351              : 
     352              :     loop {
     353            0 :         let added_task = match iter.next() {
     354            0 :             Some(s) => {
     355            0 :                 uploads.push_back(backup_single_segment(s, timeline_dir, remote_timeline_path));
     356            0 :                 true
     357              :             }
     358            0 :             None => false,
     359              :         };
     360              : 
     361              :         // Wait for the next segment to upload if we don't have any more segments,
     362              :         // or if we have too many concurrent uploads.
     363            0 :         if !added_task || uploads.len() >= parallel_jobs {
     364            0 :             let next = uploads.next().await;
     365            0 :             if let Some(res) = next {
     366              :                 // next segment uploaded
     367            0 :                 let segment = res?;
     368            0 :                 let new_backup_lsn = segment.end_lsn;
     369            0 :                 timeline
     370            0 :                     .set_wal_backup_lsn(new_backup_lsn)
     371            0 :                     .await
     372            0 :                     .context("setting wal_backup_lsn")?;
     373            0 :                 *backup_lsn = new_backup_lsn;
     374              :             } else {
     375              :                 // no more segments to upload
     376            0 :                 break;
     377              :             }
     378            0 :         }
     379              :     }
     380              : 
     381            0 :     info!(
     382            0 :         "offloaded segnos {:?} of range [{}-{})",
     383            0 :         segments.iter().map(|&s| s.seg_no).collect::<Vec<_>>(),
     384              :         start_lsn,
     385              :         end_lsn,
     386              :     );
     387            0 :     Ok(())
     388            0 : }
     389              : 
     390            0 : async fn backup_single_segment(
     391            0 :     seg: &Segment,
     392            0 :     timeline_dir: &Utf8Path,
     393            0 :     remote_timeline_path: &RemotePath,
     394            0 : ) -> Result<Segment> {
     395            0 :     let segment_file_path = seg.file_path(timeline_dir)?;
     396            0 :     let remote_segment_path = seg.remote_path(remote_timeline_path);
     397              : 
     398            0 :     let res = backup_object(&segment_file_path, &remote_segment_path, seg.size()).await;
     399            0 :     if res.is_ok() {
     400            0 :         BACKED_UP_SEGMENTS.inc();
     401            0 :     } else {
     402            0 :         BACKUP_ERRORS.inc();
     403            0 :     }
     404            0 :     res?;
     405            0 :     debug!("Backup of {} done", segment_file_path);
     406              : 
     407            0 :     Ok(*seg)
     408            0 : }
     409              : 
     410              : #[derive(Debug, Copy, Clone)]
     411              : pub struct Segment {
     412              :     seg_no: XLogSegNo,
     413              :     start_lsn: Lsn,
     414              :     end_lsn: Lsn,
     415              : }
     416              : 
     417              : impl Segment {
     418            0 :     pub fn new(seg_no: u64, start_lsn: Lsn, end_lsn: Lsn) -> Self {
     419            0 :         Self {
     420            0 :             seg_no,
     421            0 :             start_lsn,
     422            0 :             end_lsn,
     423            0 :         }
     424            0 :     }
     425              : 
     426            0 :     pub fn object_name(self) -> String {
     427            0 :         XLogFileName(PG_TLI, self.seg_no, self.size())
     428            0 :     }
     429              : 
     430            0 :     pub fn file_path(self, timeline_dir: &Utf8Path) -> Result<Utf8PathBuf> {
     431            0 :         Ok(timeline_dir.join(self.object_name()))
     432            0 :     }
     433              : 
     434            0 :     pub fn remote_path(self, remote_timeline_path: &RemotePath) -> RemotePath {
     435            0 :         remote_timeline_path.join(self.object_name())
     436            0 :     }
     437              : 
     438            0 :     pub fn size(self) -> usize {
     439            0 :         (u64::from(self.end_lsn) - u64::from(self.start_lsn)) as usize
     440            0 :     }
     441              : }
     442              : 
     443            0 : fn get_segments(start: Lsn, end: Lsn, seg_size: usize) -> Vec<Segment> {
     444            0 :     let first_seg = start.segment_number(seg_size);
     445            0 :     let last_seg = end.segment_number(seg_size);
     446            0 : 
     447            0 :     let res: Vec<Segment> = (first_seg..last_seg)
     448            0 :         .map(|s| {
     449            0 :             let start_lsn = XLogSegNoOffsetToRecPtr(s, 0, seg_size);
     450            0 :             let end_lsn = XLogSegNoOffsetToRecPtr(s + 1, 0, seg_size);
     451            0 :             Segment::new(s, Lsn::from(start_lsn), Lsn::from(end_lsn))
     452            0 :         })
     453            0 :         .collect();
     454            0 :     res
     455            0 : }
     456              : 
     457            0 : async fn backup_object(
     458            0 :     source_file: &Utf8Path,
     459            0 :     target_file: &RemotePath,
     460            0 :     size: usize,
     461            0 : ) -> Result<()> {
     462            0 :     let storage = get_configured_remote_storage();
     463              : 
     464            0 :     let file = File::open(&source_file)
     465            0 :         .await
     466            0 :         .with_context(|| format!("Failed to open file {source_file:?} for wal backup"))?;
     467              : 
     468            0 :     let file = tokio_util::io::ReaderStream::with_capacity(file, BUFFER_SIZE);
     469            0 : 
     470            0 :     let cancel = CancellationToken::new();
     471            0 : 
     472            0 :     storage
     473            0 :         .upload_storage_object(file, size, target_file, &cancel)
     474            0 :         .await
     475            0 : }
     476              : 
     477            0 : pub(crate) async fn backup_partial_segment(
     478            0 :     source_file: &Utf8Path,
     479            0 :     target_file: &RemotePath,
     480            0 :     size: usize,
     481            0 : ) -> Result<()> {
     482            0 :     let storage = get_configured_remote_storage();
     483              : 
     484            0 :     let file = File::open(&source_file)
     485            0 :         .await
     486            0 :         .with_context(|| format!("Failed to open file {source_file:?} for wal backup"))?;
     487              : 
     488              :     // limiting the file to read only the first `size` bytes
     489            0 :     let limited_file = tokio::io::AsyncReadExt::take(file, size as u64);
     490            0 : 
     491            0 :     let file = tokio_util::io::ReaderStream::with_capacity(limited_file, BUFFER_SIZE);
     492            0 : 
     493            0 :     let cancel = CancellationToken::new();
     494            0 : 
     495            0 :     storage
     496            0 :         .upload(
     497            0 :             file,
     498            0 :             size,
     499            0 :             target_file,
     500            0 :             Some(StorageMetadata::from([("sk_type", "partial_segment")])),
     501            0 :             &cancel,
     502            0 :         )
     503            0 :         .await
     504            0 : }
     505              : 
     506            0 : pub(crate) async fn copy_partial_segment(
     507            0 :     source: &RemotePath,
     508            0 :     destination: &RemotePath,
     509            0 : ) -> Result<()> {
     510            0 :     let storage = get_configured_remote_storage();
     511            0 :     let cancel = CancellationToken::new();
     512            0 : 
     513            0 :     storage.copy_object(source, destination, &cancel).await
     514            0 : }
     515              : 
     516            0 : pub async fn read_object(
     517            0 :     file_path: &RemotePath,
     518            0 :     offset: u64,
     519            0 : ) -> anyhow::Result<Pin<Box<dyn tokio::io::AsyncRead + Send + Sync>>> {
     520            0 :     let storage = REMOTE_STORAGE
     521            0 :         .get()
     522            0 :         .context("Failed to get remote storage")?
     523            0 :         .as_ref()
     524            0 :         .context("No remote storage configured")?;
     525              : 
     526            0 :     info!("segment download about to start from remote path {file_path:?} at offset {offset}");
     527              : 
     528            0 :     let cancel = CancellationToken::new();
     529            0 : 
     530            0 :     let opts = DownloadOpts {
     531            0 :         byte_start: std::ops::Bound::Included(offset),
     532            0 :         ..Default::default()
     533            0 :     };
     534            0 :     let download = storage
     535            0 :         .download(file_path, &opts, &cancel)
     536            0 :         .await
     537            0 :         .with_context(|| {
     538            0 :             format!("Failed to open WAL segment download stream for remote path {file_path:?}")
     539            0 :         })?;
     540              : 
     541            0 :     let reader = tokio_util::io::StreamReader::new(download.download_stream);
     542            0 : 
     543            0 :     let reader = tokio::io::BufReader::with_capacity(BUFFER_SIZE, reader);
     544            0 : 
     545            0 :     Ok(Box::pin(reader))
     546            0 : }
     547              : 
     548              : /// Delete WAL files for the given timeline. Remote storage must be configured
     549              : /// when called.
     550            0 : pub async fn delete_timeline(ttid: &TenantTimelineId) -> Result<()> {
     551            0 :     let storage = get_configured_remote_storage();
     552            0 :     let remote_path = remote_timeline_path(ttid)?;
     553              : 
     554              :     // see DEFAULT_MAX_KEYS_PER_LIST_RESPONSE
     555              :     // const Option unwrap is not stable, otherwise it would be const.
     556            0 :     let batch_size: NonZeroU32 = NonZeroU32::new(1000).unwrap();
     557            0 : 
     558            0 :     // A backoff::retry is used here for two reasons:
     559            0 :     // - To provide a backoff rather than busy-polling the API on errors
     560            0 :     // - To absorb transient 429/503 conditions without hitting our error
     561            0 :     //   logging path for issues deleting objects.
     562            0 :     //
     563            0 :     // Note: listing segments might take a long time if there are many of them.
     564            0 :     // We don't currently have http requests timeout cancellation, but if/once
     565            0 :     // we have listing should get streaming interface to make progress.
     566            0 : 
     567            0 :     pausable_failpoint!("sk-delete-timeline-remote-pause");
     568              : 
     569            0 :     fail::fail_point!("sk-delete-timeline-remote", |_| {
     570            0 :         Err(anyhow::anyhow!("failpoint: sk-delete-timeline-remote"))
     571            0 :     });
     572              : 
     573            0 :     let cancel = CancellationToken::new(); // not really used
     574            0 :     backoff::retry(
     575            0 :         || async {
     576              :             // Do list-delete in batch_size batches to make progress even if there a lot of files.
     577              :             // Alternatively we could make remote storage list return iterator, but it is more complicated and
     578              :             // I'm not sure deleting while iterating is expected in s3.
     579              :             loop {
     580            0 :                 let files = storage
     581            0 :                     .list(
     582            0 :                         Some(&remote_path),
     583            0 :                         ListingMode::NoDelimiter,
     584            0 :                         Some(batch_size),
     585            0 :                         &cancel,
     586            0 :                     )
     587            0 :                     .await?
     588              :                     .keys
     589            0 :                     .into_iter()
     590            0 :                     .map(|o| o.key)
     591            0 :                     .collect::<Vec<_>>();
     592            0 :                 if files.is_empty() {
     593            0 :                     return Ok(()); // done
     594            0 :                 }
     595            0 :                 // (at least) s3 results are sorted, so can log min/max:
     596            0 :                 // "List results are always returned in UTF-8 binary order."
     597            0 :                 info!(
     598            0 :                     "deleting batch of {} WAL segments [{}-{}]",
     599            0 :                     files.len(),
     600            0 :                     files.first().unwrap().object_name().unwrap_or(""),
     601            0 :                     files.last().unwrap().object_name().unwrap_or("")
     602              :                 );
     603            0 :                 storage.delete_objects(&files, &cancel).await?;
     604              :             }
     605            0 :         },
     606            0 :         // consider TimeoutOrCancel::caused_by_cancel when using cancellation
     607            0 :         |_| false,
     608            0 :         3,
     609            0 :         10,
     610            0 :         "executing WAL segments deletion batch",
     611            0 :         &cancel,
     612            0 :     )
     613            0 :     .await
     614            0 :     .ok_or_else(|| anyhow::anyhow!("canceled"))
     615            0 :     .and_then(|x| x)?;
     616              : 
     617            0 :     Ok(())
     618            0 : }
     619              : 
     620              : /// Used by wal_backup_partial.
     621            0 : pub async fn delete_objects(paths: &[RemotePath]) -> Result<()> {
     622            0 :     let cancel = CancellationToken::new(); // not really used
     623            0 :     let storage = get_configured_remote_storage();
     624            0 :     storage.delete_objects(paths, &cancel).await
     625            0 : }
     626              : 
     627              : /// Copy segments from one timeline to another. Used in copy_timeline.
     628            0 : pub async fn copy_s3_segments(
     629            0 :     wal_seg_size: usize,
     630            0 :     src_ttid: &TenantTimelineId,
     631            0 :     dst_ttid: &TenantTimelineId,
     632            0 :     from_segment: XLogSegNo,
     633            0 :     to_segment: XLogSegNo,
     634            0 : ) -> Result<()> {
     635              :     const SEGMENTS_PROGRESS_REPORT_INTERVAL: u64 = 1024;
     636              : 
     637            0 :     let storage = REMOTE_STORAGE
     638            0 :         .get()
     639            0 :         .expect("failed to get remote storage")
     640            0 :         .as_ref()
     641            0 :         .unwrap();
     642              : 
     643            0 :     let remote_dst_path = remote_timeline_path(dst_ttid)?;
     644              : 
     645            0 :     let cancel = CancellationToken::new();
     646              : 
     647            0 :     let files = storage
     648            0 :         .list(
     649            0 :             Some(&remote_dst_path),
     650            0 :             ListingMode::NoDelimiter,
     651            0 :             None,
     652            0 :             &cancel,
     653            0 :         )
     654            0 :         .await?
     655              :         .keys;
     656              : 
     657            0 :     let uploaded_segments = &files
     658            0 :         .iter()
     659            0 :         .filter_map(|o| o.key.object_name().map(ToOwned::to_owned))
     660            0 :         .collect::<HashSet<_>>();
     661            0 : 
     662            0 :     debug!(
     663            0 :         "these segments have already been uploaded: {:?}",
     664              :         uploaded_segments
     665              :     );
     666              : 
     667            0 :     for segno in from_segment..to_segment {
     668            0 :         if segno % SEGMENTS_PROGRESS_REPORT_INTERVAL == 0 {
     669            0 :             info!("copied all segments from {} until {}", from_segment, segno);
     670            0 :         }
     671              : 
     672            0 :         let segment_name = XLogFileName(PG_TLI, segno, wal_seg_size);
     673            0 :         if uploaded_segments.contains(&segment_name) {
     674            0 :             continue;
     675            0 :         }
     676            0 :         debug!("copying segment {}", segment_name);
     677              : 
     678            0 :         let from = remote_timeline_path(src_ttid)?.join(&segment_name);
     679            0 :         let to = remote_dst_path.join(&segment_name);
     680            0 : 
     681            0 :         storage.copy_object(&from, &to, &cancel).await?;
     682              :     }
     683              : 
     684            0 :     info!(
     685            0 :         "finished copying segments from {} until {}",
     686              :         from_segment, to_segment
     687              :     );
     688            0 :     Ok(())
     689            0 : }
     690              : 
     691              : /// Get S3 (remote_storage) prefix path used for timeline files.
     692           13 : pub fn remote_timeline_path(ttid: &TenantTimelineId) -> Result<RemotePath> {
     693           13 :     RemotePath::new(&Utf8Path::new(&ttid.tenant_id.to_string()).join(ttid.timeline_id.to_string()))
     694           13 : }
        

Generated by: LCOV version 2.1-beta