Line data Source code
1 : //! This module has everything to deal with WAL -- reading and writing to disk.
2 : //!
3 : //! Safekeeper WAL is stored in the timeline directory, in format similar to pg_wal.
4 : //! PG timeline is always 1, so WAL segments are usually have names like this:
5 : //! - 000000010000000000000001
6 : //! - 000000010000000000000002.partial
7 : //!
8 : //! Note that last file has `.partial` suffix, that's different from postgres.
9 :
10 : use anyhow::{bail, Context, Result};
11 : use bytes::Bytes;
12 : use camino::{Utf8Path, Utf8PathBuf};
13 : use futures::future::BoxFuture;
14 : use postgres_ffi::v14::xlog_utils::{IsPartialXLogFileName, IsXLogFileName, XLogFromFileName};
15 : use postgres_ffi::{dispatch_pgversion, XLogSegNo, PG_TLI};
16 : use remote_storage::RemotePath;
17 : use std::cmp::{max, min};
18 : use std::future::Future;
19 : use std::io::{self, SeekFrom};
20 : use std::pin::Pin;
21 : use tokio::fs::{self, remove_file, File, OpenOptions};
22 : use tokio::io::{AsyncRead, AsyncWriteExt};
23 : use tokio::io::{AsyncReadExt, AsyncSeekExt};
24 : use tracing::*;
25 : use utils::crashsafe::durable_rename;
26 :
27 : use crate::metrics::{
28 : time_io_closure, WalStorageMetrics, REMOVED_WAL_SEGMENTS, WAL_STORAGE_OPERATION_SECONDS,
29 : };
30 : use crate::state::TimelinePersistentState;
31 : use crate::wal_backup::{read_object, remote_timeline_path};
32 : use postgres_ffi::waldecoder::WalStreamDecoder;
33 : use postgres_ffi::XLogFileName;
34 : use pq_proto::SystemId;
35 : use utils::{id::TenantTimelineId, lsn::Lsn};
36 :
37 : pub trait Storage {
38 : // Last written LSN.
39 : fn write_lsn(&self) -> Lsn;
40 : /// LSN of last durably stored WAL record.
41 : fn flush_lsn(&self) -> Lsn;
42 :
43 : /// Initialize segment by creating proper long header at the beginning of
44 : /// the segment and short header at the page of given LSN. This is only used
45 : /// for timeline initialization because compute will stream data only since
46 : /// init_lsn. Other segment headers are included in compute stream.
47 : fn initialize_first_segment(
48 : &mut self,
49 : init_lsn: Lsn,
50 : ) -> impl Future<Output = Result<()>> + Send;
51 :
52 : /// Write piece of WAL from buf to disk, but not necessarily sync it.
53 : fn write_wal(&mut self, startpos: Lsn, buf: &[u8]) -> impl Future<Output = Result<()>> + Send;
54 :
55 : /// Truncate WAL at specified LSN, which must be the end of WAL record.
56 : fn truncate_wal(&mut self, end_pos: Lsn) -> impl Future<Output = Result<()>> + Send;
57 :
58 : /// Durably store WAL on disk, up to the last written WAL record.
59 : fn flush_wal(&mut self) -> impl Future<Output = Result<()>> + Send;
60 :
61 : /// Remove all segments <= given segno. Returns function doing that as we
62 : /// want to perform it without timeline lock.
63 : fn remove_up_to(&self, segno_up_to: XLogSegNo) -> BoxFuture<'static, anyhow::Result<()>>;
64 :
65 : /// Release resources associated with the storage -- technically, close FDs.
66 : /// Currently we don't remove timelines until restart (#3146), so need to
67 : /// spare descriptors. This would be useful for temporary tli detach as
68 : /// well.
69 0 : fn close(&mut self) {}
70 :
71 : /// Get metrics for this timeline.
72 : fn get_metrics(&self) -> WalStorageMetrics;
73 : }
74 :
75 : /// PhysicalStorage is a storage that stores WAL on disk. Writes are separated from flushes
76 : /// for better performance. Storage is initialized in the constructor.
77 : ///
78 : /// WAL is stored in segments, each segment is a file. Last segment has ".partial" suffix in
79 : /// its filename and may be not fully flushed.
80 : ///
81 : /// Relationship of LSNs:
82 : /// `write_lsn` >= `write_record_lsn` >= `flush_record_lsn`
83 : ///
84 : /// When storage is created first time, all LSNs are zeroes and there are no segments on disk.
85 : pub struct PhysicalStorage {
86 : metrics: WalStorageMetrics,
87 : timeline_dir: Utf8PathBuf,
88 :
89 : /// Disables fsync if true.
90 : no_sync: bool,
91 :
92 : /// Size of WAL segment in bytes.
93 : wal_seg_size: usize,
94 : pg_version: u32,
95 : system_id: u64,
96 :
97 : /// Written to disk, but possibly still in the cache and not fully persisted.
98 : /// Also can be ahead of record_lsn, if happen to be in the middle of a WAL record.
99 : write_lsn: Lsn,
100 :
101 : /// The LSN of the last WAL record written to disk. Still can be not fully
102 : /// flushed.
103 : ///
104 : /// Note: Normally it (and flush_record_lsn) is <= write_lsn, but after xlog
105 : /// switch ingest the reverse is true because we don't bump write_lsn up to
106 : /// the next segment: WAL stream from the compute doesn't have the gap and
107 : /// for simplicity / as a sanity check we disallow any non-sequential
108 : /// writes, so write zeros as is.
109 : ///
110 : /// Similar effect is in theory possible due to LSN alignment: if record
111 : /// ends at *2, decoder will report end lsn as *8 even though we haven't
112 : /// written these zeros yet. In practice compute likely never sends
113 : /// non-aligned chunks of data.
114 : write_record_lsn: Lsn,
115 :
116 : /// The LSN of the last WAL record flushed to disk.
117 : flush_record_lsn: Lsn,
118 :
119 : /// Decoder is required for detecting boundaries of WAL records.
120 : decoder: WalStreamDecoder,
121 :
122 : /// Cached open file for the last segment.
123 : ///
124 : /// If Some(file) is open, then it always:
125 : /// - has ".partial" suffix
126 : /// - points to write_lsn, so no seek is needed for writing
127 : /// - doesn't point to the end of the segment
128 : file: Option<File>,
129 :
130 : /// When true, WAL truncation potentially has been interrupted and we need
131 : /// to finish it before allowing WAL writes; see truncate_wal for details.
132 : /// In this case [`write_lsn`] can be less than actually written WAL on
133 : /// disk. In particular, there can be a case with unexpected .partial file.
134 : ///
135 : /// Imagine the following:
136 : /// - 000000010000000000000001
137 : /// - it was fully written, but the last record is split between 2
138 : /// segments
139 : /// - after restart, `find_end_of_wal()` returned 0/1FFFFF0, which is in
140 : /// the end of this segment
141 : /// - `write_lsn`, `write_record_lsn` and `flush_record_lsn` were
142 : /// initialized to 0/1FFFFF0
143 : /// - 000000010000000000000002.partial
144 : /// - it has only 1 byte written, which is not enough to make a full WAL
145 : /// record
146 : ///
147 : /// Partial segment 002 has no WAL records, and it will be removed by the
148 : /// next truncate_wal(). This flag will be set to true after the first
149 : /// truncate_wal() call.
150 : ///
151 : /// [`write_lsn`]: Self::write_lsn
152 : pending_wal_truncation: bool,
153 : }
154 :
155 : impl PhysicalStorage {
156 : /// Create new storage. If commit_lsn is not zero, flush_lsn is tried to be restored from
157 : /// the disk. Otherwise, all LSNs are set to zero.
158 0 : pub fn new(
159 0 : ttid: &TenantTimelineId,
160 0 : timeline_dir: &Utf8Path,
161 0 : state: &TimelinePersistentState,
162 0 : no_sync: bool,
163 0 : ) -> Result<PhysicalStorage> {
164 0 : let wal_seg_size = state.server.wal_seg_size as usize;
165 :
166 : // Find out where stored WAL ends, starting at commit_lsn which is a
167 : // known recent record boundary (unless we don't have WAL at all).
168 : //
169 : // NB: find_end_of_wal MUST be backwards compatible with the previously
170 : // written WAL. If find_end_of_wal fails to read any WAL written by an
171 : // older version of the code, we could lose data forever.
172 0 : let write_lsn = if state.commit_lsn == Lsn(0) {
173 0 : Lsn(0)
174 : } else {
175 0 : let version = state.server.pg_version / 10000;
176 0 :
177 0 : dispatch_pgversion!(
178 0 : version,
179 0 : pgv::xlog_utils::find_end_of_wal(
180 0 : timeline_dir.as_std_path(),
181 0 : wal_seg_size,
182 0 : state.commit_lsn,
183 0 : )?,
184 0 : bail!("unsupported postgres version: {}", version)
185 : )
186 : };
187 :
188 : // note: this assumes we fsync'ed whole datadir on start.
189 0 : let flush_lsn = write_lsn;
190 0 :
191 0 : debug!(
192 0 : "initialized storage for timeline {}, flush_lsn={}, commit_lsn={}, peer_horizon_lsn={}",
193 : ttid.timeline_id, flush_lsn, state.commit_lsn, state.peer_horizon_lsn,
194 : );
195 0 : if flush_lsn < state.commit_lsn {
196 0 : bail!("timeline {} potential data loss: flush_lsn {} by find_end_of_wal is less than commit_lsn {} from control file", ttid.timeline_id, flush_lsn, state.commit_lsn);
197 0 : }
198 0 : if flush_lsn < state.peer_horizon_lsn {
199 0 : warn!(
200 0 : "timeline {}: flush_lsn {} is less than cfile peer_horizon_lsn {}",
201 : ttid.timeline_id, flush_lsn, state.peer_horizon_lsn
202 : );
203 0 : }
204 :
205 0 : Ok(PhysicalStorage {
206 0 : metrics: WalStorageMetrics::default(),
207 0 : timeline_dir: timeline_dir.to_path_buf(),
208 0 : no_sync,
209 0 : wal_seg_size,
210 0 : pg_version: state.server.pg_version,
211 0 : system_id: state.server.system_id,
212 0 : write_lsn,
213 0 : write_record_lsn: write_lsn,
214 0 : flush_record_lsn: flush_lsn,
215 0 : decoder: WalStreamDecoder::new(write_lsn, state.server.pg_version / 10000),
216 0 : file: None,
217 0 : pending_wal_truncation: true,
218 0 : })
219 0 : }
220 :
221 : /// Get all known state of the storage.
222 0 : pub fn internal_state(&self) -> (Lsn, Lsn, Lsn, bool) {
223 0 : (
224 0 : self.write_lsn,
225 0 : self.write_record_lsn,
226 0 : self.flush_record_lsn,
227 0 : self.file.is_some(),
228 0 : )
229 0 : }
230 :
231 : /// Call fsync if config requires so.
232 0 : async fn fsync_file(&mut self, file: &File) -> Result<()> {
233 0 : if !self.no_sync {
234 0 : self.metrics
235 0 : .observe_flush_seconds(time_io_closure(file.sync_all()).await?);
236 0 : }
237 0 : Ok(())
238 0 : }
239 :
240 : /// Call fdatasync if config requires so.
241 0 : async fn fdatasync_file(&mut self, file: &File) -> Result<()> {
242 0 : if !self.no_sync {
243 0 : self.metrics
244 0 : .observe_flush_seconds(time_io_closure(file.sync_data()).await?);
245 0 : }
246 0 : Ok(())
247 0 : }
248 :
249 : /// Open or create WAL segment file. Caller must call seek to the wanted position.
250 : /// Returns `file` and `is_partial`.
251 0 : async fn open_or_create(&mut self, segno: XLogSegNo) -> Result<(File, bool)> {
252 0 : let (wal_file_path, wal_file_partial_path) =
253 0 : wal_file_paths(&self.timeline_dir, segno, self.wal_seg_size);
254 :
255 : // Try to open already completed segment
256 0 : if let Ok(file) = OpenOptions::new().write(true).open(&wal_file_path).await {
257 0 : Ok((file, false))
258 0 : } else if let Ok(file) = OpenOptions::new()
259 0 : .write(true)
260 0 : .open(&wal_file_partial_path)
261 0 : .await
262 : {
263 : // Try to open existing partial file
264 0 : Ok((file, true))
265 : } else {
266 0 : let _timer = WAL_STORAGE_OPERATION_SECONDS
267 0 : .with_label_values(&["initialize_segment"])
268 0 : .start_timer();
269 0 : // Create and fill new partial file
270 0 : //
271 0 : // We're using fdatasync during WAL writing, so file size must not
272 0 : // change; to this end it is filled with zeros here. To avoid using
273 0 : // half initialized segment, first bake it under tmp filename and
274 0 : // then rename.
275 0 : let tmp_path = self.timeline_dir.join("waltmp");
276 0 : let file = File::create(&tmp_path)
277 0 : .await
278 0 : .with_context(|| format!("Failed to open tmp wal file {:?}", &tmp_path))?;
279 :
280 0 : fail::fail_point!("sk-zero-segment", |_| {
281 0 : info!("sk-zero-segment failpoint hit");
282 0 : Err(anyhow::anyhow!("failpoint: sk-zero-segment"))
283 0 : });
284 0 : file.set_len(self.wal_seg_size as u64).await?;
285 :
286 0 : if let Err(e) = durable_rename(&tmp_path, &wal_file_partial_path, !self.no_sync).await {
287 : // Probably rename succeeded, but fsync of it failed. Remove
288 : // the file then to avoid using it.
289 0 : remove_file(wal_file_partial_path)
290 0 : .await
291 0 : .or_else(utils::fs_ext::ignore_not_found)?;
292 0 : return Err(e.into());
293 0 : }
294 0 : Ok((file, true))
295 : }
296 0 : }
297 :
298 : /// Write WAL bytes, which are known to be located in a single WAL segment.
299 0 : async fn write_in_segment(&mut self, segno: u64, xlogoff: usize, buf: &[u8]) -> Result<()> {
300 0 : let mut file = if let Some(file) = self.file.take() {
301 0 : file
302 : } else {
303 0 : let (mut file, is_partial) = self.open_or_create(segno).await?;
304 0 : assert!(is_partial, "unexpected write into non-partial segment file");
305 0 : file.seek(SeekFrom::Start(xlogoff as u64)).await?;
306 0 : file
307 : };
308 :
309 0 : file.write_all(buf).await?;
310 : // Note: flush just ensures write above reaches the OS (this is not
311 : // needed in case of sync IO as Write::write there calls directly write
312 : // syscall, but needed in case of async). It does *not* fsyncs the file.
313 0 : file.flush().await?;
314 :
315 0 : if xlogoff + buf.len() == self.wal_seg_size {
316 : // If we reached the end of a WAL segment, flush and close it.
317 0 : self.fdatasync_file(&file).await?;
318 :
319 : // Rename partial file to completed file
320 0 : let (wal_file_path, wal_file_partial_path) =
321 0 : wal_file_paths(&self.timeline_dir, segno, self.wal_seg_size);
322 0 : fs::rename(wal_file_partial_path, wal_file_path).await?;
323 0 : } else {
324 0 : // otherwise, file can be reused later
325 0 : self.file = Some(file);
326 0 : }
327 :
328 0 : Ok(())
329 0 : }
330 :
331 : /// Writes WAL to the segment files, until everything is writed. If some segments
332 : /// are fully written, they are flushed to disk. The last (partial) segment can
333 : /// be flushed separately later.
334 : ///
335 : /// Updates `write_lsn`.
336 0 : async fn write_exact(&mut self, pos: Lsn, mut buf: &[u8]) -> Result<()> {
337 0 : if self.write_lsn != pos {
338 : // need to flush the file before discarding it
339 0 : if let Some(file) = self.file.take() {
340 0 : self.fdatasync_file(&file).await?;
341 0 : }
342 :
343 0 : self.write_lsn = pos;
344 0 : }
345 :
346 0 : while !buf.is_empty() {
347 : // Extract WAL location for this block
348 0 : let xlogoff = self.write_lsn.segment_offset(self.wal_seg_size);
349 0 : let segno = self.write_lsn.segment_number(self.wal_seg_size);
350 :
351 : // If crossing a WAL boundary, only write up until we reach wal segment size.
352 0 : let bytes_write = if xlogoff + buf.len() > self.wal_seg_size {
353 0 : self.wal_seg_size - xlogoff
354 : } else {
355 0 : buf.len()
356 : };
357 :
358 0 : self.write_in_segment(segno, xlogoff, &buf[..bytes_write])
359 0 : .await?;
360 0 : self.write_lsn += bytes_write as u64;
361 0 : buf = &buf[bytes_write..];
362 : }
363 :
364 0 : Ok(())
365 0 : }
366 : }
367 :
368 : impl Storage for PhysicalStorage {
369 : // Last written LSN.
370 0 : fn write_lsn(&self) -> Lsn {
371 0 : self.write_lsn
372 0 : }
373 : /// flush_lsn returns LSN of last durably stored WAL record.
374 0 : fn flush_lsn(&self) -> Lsn {
375 0 : self.flush_record_lsn
376 0 : }
377 :
378 0 : async fn initialize_first_segment(&mut self, init_lsn: Lsn) -> Result<()> {
379 0 : let _timer = WAL_STORAGE_OPERATION_SECONDS
380 0 : .with_label_values(&["initialize_first_segment"])
381 0 : .start_timer();
382 0 :
383 0 : let segno = init_lsn.segment_number(self.wal_seg_size);
384 0 : let (mut file, _) = self.open_or_create(segno).await?;
385 0 : let major_pg_version = self.pg_version / 10000;
386 0 : let wal_seg =
387 0 : postgres_ffi::generate_wal_segment(segno, self.system_id, major_pg_version, init_lsn)?;
388 0 : file.seek(SeekFrom::Start(0)).await?;
389 0 : file.write_all(&wal_seg).await?;
390 0 : file.flush().await?;
391 0 : info!("initialized segno {} at lsn {}", segno, init_lsn);
392 : // note: file is *not* fsynced
393 0 : Ok(())
394 0 : }
395 :
396 : /// Write WAL to disk.
397 0 : async fn write_wal(&mut self, startpos: Lsn, buf: &[u8]) -> Result<()> {
398 0 : // Disallow any non-sequential writes, which can result in gaps or overwrites.
399 0 : // If we need to move the pointer, use truncate_wal() instead.
400 0 : if self.write_lsn > startpos {
401 0 : bail!(
402 0 : "write_wal rewrites WAL written before, write_lsn={}, startpos={}",
403 0 : self.write_lsn,
404 0 : startpos
405 0 : );
406 0 : }
407 0 : if self.write_lsn < startpos && self.write_lsn != Lsn(0) {
408 0 : bail!(
409 0 : "write_wal creates gap in written WAL, write_lsn={}, startpos={}",
410 0 : self.write_lsn,
411 0 : startpos
412 0 : );
413 0 : }
414 0 : if self.pending_wal_truncation {
415 0 : bail!(
416 0 : "write_wal called with pending WAL truncation, write_lsn={}, startpos={}",
417 0 : self.write_lsn,
418 0 : startpos
419 0 : );
420 0 : }
421 :
422 0 : let write_seconds = time_io_closure(self.write_exact(startpos, buf)).await?;
423 : // WAL is written, updating write metrics
424 0 : self.metrics.observe_write_seconds(write_seconds);
425 0 : self.metrics.observe_write_bytes(buf.len());
426 0 :
427 0 : // figure out last record's end lsn for reporting (if we got the
428 0 : // whole record)
429 0 : if self.decoder.available() != startpos {
430 0 : info!(
431 0 : "restart decoder from {} to {}",
432 0 : self.decoder.available(),
433 : startpos,
434 : );
435 0 : let pg_version = self.decoder.pg_version;
436 0 : self.decoder = WalStreamDecoder::new(startpos, pg_version);
437 0 : }
438 0 : self.decoder.feed_bytes(buf);
439 : loop {
440 0 : match self.decoder.poll_decode()? {
441 0 : None => break, // no full record yet
442 0 : Some((lsn, _rec)) => {
443 0 : self.write_record_lsn = lsn;
444 0 : }
445 : }
446 : }
447 :
448 0 : Ok(())
449 0 : }
450 :
451 0 : async fn flush_wal(&mut self) -> Result<()> {
452 0 : if self.flush_record_lsn == self.write_record_lsn {
453 : // no need to do extra flush
454 0 : return Ok(());
455 0 : }
456 :
457 0 : if let Some(unflushed_file) = self.file.take() {
458 0 : self.fdatasync_file(&unflushed_file).await?;
459 0 : self.file = Some(unflushed_file);
460 : } else {
461 : // We have unflushed data (write_lsn != flush_lsn), but no file.
462 : // This should only happen if last file was fully written and flushed,
463 : // but haven't updated flush_lsn yet.
464 0 : if self.write_lsn.segment_offset(self.wal_seg_size) != 0 {
465 0 : bail!(
466 0 : "unexpected unflushed data with no open file, write_lsn={}, flush_lsn={}",
467 0 : self.write_lsn,
468 0 : self.flush_record_lsn
469 0 : );
470 0 : }
471 : }
472 :
473 : // everything is flushed now, let's update flush_lsn
474 0 : self.flush_record_lsn = self.write_record_lsn;
475 0 : Ok(())
476 0 : }
477 :
478 : /// Truncate written WAL by removing all WAL segments after the given LSN.
479 : /// end_pos must point to the end of the WAL record.
480 0 : async fn truncate_wal(&mut self, end_pos: Lsn) -> Result<()> {
481 0 : let _timer = WAL_STORAGE_OPERATION_SECONDS
482 0 : .with_label_values(&["truncate_wal"])
483 0 : .start_timer();
484 0 :
485 0 : // Streaming must not create a hole, so truncate cannot be called on
486 0 : // non-written lsn.
487 0 : if self.write_record_lsn != Lsn(0) && end_pos > self.write_record_lsn {
488 0 : bail!(
489 0 : "truncate_wal called on non-written WAL, write_record_lsn={}, end_pos={}",
490 0 : self.write_record_lsn,
491 0 : end_pos
492 0 : );
493 0 : }
494 0 :
495 0 : // Quick exit if nothing to do and we know that the state is clean to
496 0 : // avoid writing up to 16 MiB of zeros on disk (this happens on each
497 0 : // connect).
498 0 : if !self.pending_wal_truncation
499 0 : && end_pos == self.write_lsn
500 0 : && end_pos == self.flush_record_lsn
501 : {
502 0 : return Ok(());
503 0 : }
504 0 :
505 0 : // Atomicity: we start with LSNs reset because once on disk deletion is
506 0 : // started it can't be reversed. However, we might crash/error in the
507 0 : // middle, leaving garbage above the truncation point. In theory,
508 0 : // concatenated with previous records it might form bogus WAL (though
509 0 : // very unlikely in practice because CRC would guard from that). To
510 0 : // protect, set pending_wal_truncation flag before beginning: it means
511 0 : // truncation must be retried and WAL writes are prohibited until it
512 0 : // succeeds. Flag is also set on boot because we don't know if the last
513 0 : // state was clean.
514 0 : //
515 0 : // Protocol (HandleElected before first AppendRequest) ensures we'll
516 0 : // always try to ensure clean truncation before any writes.
517 0 : self.pending_wal_truncation = true;
518 0 :
519 0 : self.write_lsn = end_pos;
520 0 : self.write_record_lsn = end_pos;
521 0 : self.flush_record_lsn = end_pos;
522 :
523 : // Close previously opened file, if any
524 0 : if let Some(unflushed_file) = self.file.take() {
525 0 : self.fdatasync_file(&unflushed_file).await?;
526 0 : }
527 :
528 0 : let xlogoff = end_pos.segment_offset(self.wal_seg_size);
529 0 : let segno = end_pos.segment_number(self.wal_seg_size);
530 0 :
531 0 : // Remove all segments after the given LSN.
532 0 : remove_segments_from_disk(&self.timeline_dir, self.wal_seg_size, |x| x > segno).await?;
533 :
534 0 : let (file, is_partial) = self.open_or_create(segno).await?;
535 :
536 : // Fill end with zeroes
537 0 : file.set_len(xlogoff as u64).await?;
538 0 : file.set_len(self.wal_seg_size as u64).await?;
539 0 : self.fsync_file(&file).await?;
540 :
541 0 : if !is_partial {
542 : // Make segment partial once again
543 0 : let (wal_file_path, wal_file_partial_path) =
544 0 : wal_file_paths(&self.timeline_dir, segno, self.wal_seg_size);
545 0 : fs::rename(wal_file_path, wal_file_partial_path).await?;
546 0 : }
547 :
548 0 : self.pending_wal_truncation = false;
549 0 : Ok(())
550 0 : }
551 :
552 0 : fn remove_up_to(&self, segno_up_to: XLogSegNo) -> BoxFuture<'static, anyhow::Result<()>> {
553 0 : let timeline_dir = self.timeline_dir.clone();
554 0 : let wal_seg_size = self.wal_seg_size;
555 0 : Box::pin(async move {
556 0 : remove_segments_from_disk(&timeline_dir, wal_seg_size, |x| x <= segno_up_to).await
557 0 : })
558 0 : }
559 :
560 0 : fn close(&mut self) {
561 0 : // close happens in destructor
562 0 : let _open_file = self.file.take();
563 0 : }
564 :
565 0 : fn get_metrics(&self) -> WalStorageMetrics {
566 0 : self.metrics.clone()
567 0 : }
568 : }
569 :
570 : /// Remove all WAL segments in timeline_dir that match the given predicate.
571 0 : async fn remove_segments_from_disk(
572 0 : timeline_dir: &Utf8Path,
573 0 : wal_seg_size: usize,
574 0 : remove_predicate: impl Fn(XLogSegNo) -> bool,
575 0 : ) -> Result<()> {
576 0 : let _timer = WAL_STORAGE_OPERATION_SECONDS
577 0 : .with_label_values(&["remove_segments_from_disk"])
578 0 : .start_timer();
579 0 :
580 0 : let mut n_removed = 0;
581 0 : let mut min_removed = u64::MAX;
582 0 : let mut max_removed = u64::MIN;
583 :
584 0 : let mut entries = fs::read_dir(timeline_dir).await?;
585 0 : while let Some(entry) = entries.next_entry().await? {
586 0 : let entry_path = entry.path();
587 0 : let fname = entry_path.file_name().unwrap();
588 0 : /* Ignore files that are not XLOG segments */
589 0 : if !IsXLogFileName(fname) && !IsPartialXLogFileName(fname) {
590 0 : continue;
591 0 : }
592 0 : let (segno, _) = XLogFromFileName(fname, wal_seg_size)?;
593 0 : if remove_predicate(segno) {
594 0 : remove_file(entry_path).await?;
595 0 : n_removed += 1;
596 0 : min_removed = min(min_removed, segno);
597 0 : max_removed = max(max_removed, segno);
598 0 : REMOVED_WAL_SEGMENTS.inc();
599 0 : }
600 : }
601 :
602 0 : if n_removed > 0 {
603 0 : info!(
604 0 : "removed {} WAL segments [{}; {}]",
605 : n_removed, min_removed, max_removed
606 : );
607 0 : }
608 0 : Ok(())
609 0 : }
610 :
611 : pub struct WalReader {
612 : remote_path: RemotePath,
613 : timeline_dir: Utf8PathBuf,
614 : wal_seg_size: usize,
615 : pos: Lsn,
616 : wal_segment: Option<Pin<Box<dyn AsyncRead + Send + Sync>>>,
617 :
618 : // S3 will be used to read WAL if LSN is not available locally
619 : enable_remote_read: bool,
620 :
621 : // We don't have WAL locally if LSN is less than local_start_lsn
622 : local_start_lsn: Lsn,
623 : // We will respond with zero-ed bytes before this Lsn as long as
624 : // pos is in the same segment as timeline_start_lsn.
625 : timeline_start_lsn: Lsn,
626 : // integer version number of PostgreSQL, e.g. 14; 15; 16
627 : pg_version: u32,
628 : system_id: SystemId,
629 : timeline_start_segment: Option<Bytes>,
630 : }
631 :
632 : impl WalReader {
633 0 : pub fn new(
634 0 : ttid: &TenantTimelineId,
635 0 : timeline_dir: Utf8PathBuf,
636 0 : state: &TimelinePersistentState,
637 0 : start_pos: Lsn,
638 0 : enable_remote_read: bool,
639 0 : ) -> Result<Self> {
640 0 : if state.server.wal_seg_size == 0 || state.local_start_lsn == Lsn(0) {
641 0 : bail!("state uninitialized, no data to read");
642 0 : }
643 0 :
644 0 : // TODO: Upgrade to bail!() once we know this couldn't possibly happen
645 0 : if state.timeline_start_lsn == Lsn(0) {
646 0 : warn!("timeline_start_lsn uninitialized before initializing wal reader");
647 0 : }
648 :
649 0 : if start_pos
650 0 : < state
651 0 : .timeline_start_lsn
652 0 : .segment_lsn(state.server.wal_seg_size as usize)
653 : {
654 0 : bail!(
655 0 : "Requested streaming from {}, which is before the start of the timeline {}, and also doesn't start at the first segment of that timeline",
656 0 : start_pos,
657 0 : state.timeline_start_lsn
658 0 : );
659 0 : }
660 0 :
661 0 : Ok(Self {
662 0 : remote_path: remote_timeline_path(ttid)?,
663 0 : timeline_dir,
664 0 : wal_seg_size: state.server.wal_seg_size as usize,
665 0 : pos: start_pos,
666 0 : wal_segment: None,
667 0 : enable_remote_read,
668 0 : local_start_lsn: state.local_start_lsn,
669 0 : timeline_start_lsn: state.timeline_start_lsn,
670 0 : pg_version: state.server.pg_version / 10000,
671 0 : system_id: state.server.system_id,
672 0 : timeline_start_segment: None,
673 : })
674 0 : }
675 :
676 : /// Read WAL at current position into provided buf, returns number of bytes
677 : /// read. It can be smaller than buf size only if segment boundary is
678 : /// reached.
679 0 : pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
680 0 : // If this timeline is new, we may not have a full segment yet, so
681 0 : // we pad the first bytes of the timeline's first WAL segment with 0s
682 0 : if self.pos < self.timeline_start_lsn {
683 0 : debug_assert_eq!(
684 0 : self.pos.segment_number(self.wal_seg_size),
685 0 : self.timeline_start_lsn.segment_number(self.wal_seg_size)
686 : );
687 :
688 : // All bytes after timeline_start_lsn are in WAL, but those before
689 : // are not, so we manually construct an empty segment for the bytes
690 : // not available in this timeline.
691 0 : if self.timeline_start_segment.is_none() {
692 0 : let it = postgres_ffi::generate_wal_segment(
693 0 : self.timeline_start_lsn.segment_number(self.wal_seg_size),
694 0 : self.system_id,
695 0 : self.pg_version,
696 0 : self.timeline_start_lsn,
697 0 : )?;
698 0 : self.timeline_start_segment = Some(it);
699 0 : }
700 :
701 0 : assert!(self.timeline_start_segment.is_some());
702 0 : let segment = self.timeline_start_segment.take().unwrap();
703 0 :
704 0 : let seg_bytes = &segment[..];
705 0 :
706 0 : // How much of the current segment have we already consumed?
707 0 : let pos_seg_offset = self.pos.segment_offset(self.wal_seg_size);
708 0 :
709 0 : // How many bytes may we consume in total?
710 0 : let tl_start_seg_offset = self.timeline_start_lsn.segment_offset(self.wal_seg_size);
711 0 :
712 0 : debug_assert!(seg_bytes.len() > pos_seg_offset);
713 0 : debug_assert!(seg_bytes.len() > tl_start_seg_offset);
714 :
715 : // Copy as many bytes as possible into the buffer
716 0 : let len = (tl_start_seg_offset - pos_seg_offset).min(buf.len());
717 0 : buf[0..len].copy_from_slice(&seg_bytes[pos_seg_offset..pos_seg_offset + len]);
718 0 :
719 0 : self.pos += len as u64;
720 0 :
721 0 : // If we're done with the segment, we can release it's memory.
722 0 : // However, if we're not yet done, store it so that we don't have to
723 0 : // construct the segment the next time this function is called.
724 0 : if self.pos < self.timeline_start_lsn {
725 0 : self.timeline_start_segment = Some(segment);
726 0 : }
727 :
728 0 : return Ok(len);
729 0 : }
730 :
731 0 : let mut wal_segment = match self.wal_segment.take() {
732 0 : Some(reader) => reader,
733 0 : None => self.open_segment().await?,
734 : };
735 :
736 : // How much to read and send in message? We cannot cross the WAL file
737 : // boundary, and we don't want send more than provided buffer.
738 0 : let xlogoff = self.pos.segment_offset(self.wal_seg_size);
739 0 : let send_size = min(buf.len(), self.wal_seg_size - xlogoff);
740 0 :
741 0 : // Read some data from the file.
742 0 : let buf = &mut buf[0..send_size];
743 0 : let send_size = wal_segment.read_exact(buf).await?;
744 0 : self.pos += send_size as u64;
745 0 :
746 0 : // Decide whether to reuse this file. If we don't set wal_segment here
747 0 : // a new reader will be opened next time.
748 0 : if self.pos.segment_offset(self.wal_seg_size) != 0 {
749 0 : self.wal_segment = Some(wal_segment);
750 0 : }
751 :
752 0 : Ok(send_size)
753 0 : }
754 :
755 : /// Open WAL segment at the current position of the reader.
756 0 : async fn open_segment(&self) -> Result<Pin<Box<dyn AsyncRead + Send + Sync>>> {
757 0 : let xlogoff = self.pos.segment_offset(self.wal_seg_size);
758 0 : let segno = self.pos.segment_number(self.wal_seg_size);
759 0 : let wal_file_name = XLogFileName(PG_TLI, segno, self.wal_seg_size);
760 0 :
761 0 : // Try to open local file, if we may have WAL locally
762 0 : if self.pos >= self.local_start_lsn {
763 0 : let res = open_wal_file(&self.timeline_dir, segno, self.wal_seg_size).await;
764 0 : match res {
765 0 : Ok((mut file, _)) => {
766 0 : file.seek(SeekFrom::Start(xlogoff as u64)).await?;
767 0 : return Ok(Box::pin(file));
768 : }
769 0 : Err(e) => {
770 0 : let is_not_found = e.chain().any(|e| {
771 0 : if let Some(e) = e.downcast_ref::<io::Error>() {
772 0 : e.kind() == io::ErrorKind::NotFound
773 : } else {
774 0 : false
775 : }
776 0 : });
777 0 : if !is_not_found {
778 0 : return Err(e);
779 0 : }
780 : // NotFound is expected, fall through to remote read
781 : }
782 : };
783 0 : }
784 :
785 : // Try to open remote file, if remote reads are enabled
786 0 : if self.enable_remote_read {
787 0 : let remote_wal_file_path = self.remote_path.join(&wal_file_name);
788 0 : return read_object(&remote_wal_file_path, xlogoff as u64).await;
789 0 : }
790 0 :
791 0 : bail!("WAL segment is not found")
792 0 : }
793 : }
794 :
795 : /// Helper function for opening WAL segment `segno` in `dir`. Returns file and
796 : /// whether it is .partial.
797 0 : pub(crate) async fn open_wal_file(
798 0 : timeline_dir: &Utf8Path,
799 0 : segno: XLogSegNo,
800 0 : wal_seg_size: usize,
801 0 : ) -> Result<(tokio::fs::File, bool)> {
802 0 : let (wal_file_path, wal_file_partial_path) = wal_file_paths(timeline_dir, segno, wal_seg_size);
803 0 :
804 0 : // First try to open the .partial file.
805 0 : let mut partial_path = wal_file_path.to_owned();
806 0 : partial_path.set_extension("partial");
807 0 : if let Ok(opened_file) = tokio::fs::File::open(&wal_file_partial_path).await {
808 0 : return Ok((opened_file, true));
809 0 : }
810 :
811 : // If that failed, try it without the .partial extension.
812 0 : let pf = tokio::fs::File::open(&wal_file_path)
813 0 : .await
814 0 : .with_context(|| format!("failed to open WAL file {:#}", wal_file_path))
815 0 : .map_err(|e| {
816 0 : warn!("{}", e);
817 0 : e
818 0 : })?;
819 :
820 0 : Ok((pf, false))
821 0 : }
822 :
823 : /// Helper returning full path to WAL segment file and its .partial brother.
824 0 : pub fn wal_file_paths(
825 0 : timeline_dir: &Utf8Path,
826 0 : segno: XLogSegNo,
827 0 : wal_seg_size: usize,
828 0 : ) -> (Utf8PathBuf, Utf8PathBuf) {
829 0 : let wal_file_name = XLogFileName(PG_TLI, segno, wal_seg_size);
830 0 : let wal_file_path = timeline_dir.join(wal_file_name.clone());
831 0 : let wal_file_partial_path = timeline_dir.join(wal_file_name + ".partial");
832 0 : (wal_file_path, wal_file_partial_path)
833 0 : }
|