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