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