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