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