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