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