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