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