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