Line data Source code
1 : use std::collections::HashMap;
2 : use std::sync::Arc;
3 :
4 : use parking_lot::Mutex;
5 : use safekeeper::state::TimelinePersistentState;
6 : use utils::id::TenantTimelineId;
7 :
8 : use super::block_storage::BlockStorage;
9 :
10 : use std::{ops::Deref, time::Instant};
11 :
12 : use anyhow::Result;
13 : use bytes::{Buf, BytesMut};
14 : use futures::future::BoxFuture;
15 : use postgres_ffi::{waldecoder::WalStreamDecoder, XLogSegNo};
16 : use safekeeper::{control_file, metrics::WalStorageMetrics, wal_storage};
17 : use tracing::{debug, info};
18 : use utils::lsn::Lsn;
19 :
20 : /// All safekeeper state that is usually saved to disk.
21 : pub struct SafekeeperDisk {
22 : pub timelines: Mutex<HashMap<TenantTimelineId, Arc<TimelineDisk>>>,
23 : }
24 :
25 : impl Default for SafekeeperDisk {
26 0 : fn default() -> Self {
27 0 : Self::new()
28 0 : }
29 : }
30 :
31 : impl SafekeeperDisk {
32 6024 : pub fn new() -> Self {
33 6024 : SafekeeperDisk {
34 6024 : timelines: Mutex::new(HashMap::new()),
35 6024 : }
36 6024 : }
37 :
38 5725 : pub fn put_state(
39 5725 : &self,
40 5725 : ttid: &TenantTimelineId,
41 5725 : state: TimelinePersistentState,
42 5725 : ) -> Arc<TimelineDisk> {
43 5725 : self.timelines
44 5725 : .lock()
45 5725 : .entry(*ttid)
46 5725 : .and_modify(|e| {
47 0 : let mut mu = e.state.lock();
48 0 : *mu = state.clone();
49 5725 : })
50 5725 : .or_insert_with(|| {
51 5725 : Arc::new(TimelineDisk {
52 5725 : state: Mutex::new(state),
53 5725 : wal: Mutex::new(BlockStorage::new()),
54 5725 : })
55 5725 : })
56 5725 : .clone()
57 5725 : }
58 : }
59 :
60 : /// Control file state and WAL storage.
61 : pub struct TimelineDisk {
62 : pub state: Mutex<TimelinePersistentState>,
63 : pub wal: Mutex<BlockStorage>,
64 : }
65 :
66 : /// Implementation of `control_file::Storage` trait.
67 : pub struct DiskStateStorage {
68 : persisted_state: TimelinePersistentState,
69 : disk: Arc<TimelineDisk>,
70 : last_persist_at: Instant,
71 : }
72 :
73 : impl DiskStateStorage {
74 35312 : pub fn new(disk: Arc<TimelineDisk>) -> Self {
75 35312 : let guard = disk.state.lock();
76 35312 : let state = guard.clone();
77 35312 : drop(guard);
78 35312 : DiskStateStorage {
79 35312 : persisted_state: state,
80 35312 : disk,
81 35312 : last_persist_at: Instant::now(),
82 35312 : }
83 35312 : }
84 : }
85 :
86 : impl control_file::Storage for DiskStateStorage {
87 : /// Persist safekeeper state on disk and update internal state.
88 15630 : async fn persist(&mut self, s: &TimelinePersistentState) -> Result<()> {
89 15630 : self.persisted_state = s.clone();
90 15630 : *self.disk.state.lock() = s.clone();
91 15630 : Ok(())
92 15630 : }
93 :
94 : /// Timestamp of last persist.
95 0 : fn last_persist_at(&self) -> Instant {
96 0 : // TODO: don't rely on it in tests
97 0 : self.last_persist_at
98 0 : }
99 : }
100 :
101 : impl Deref for DiskStateStorage {
102 : type Target = TimelinePersistentState;
103 :
104 1004625 : fn deref(&self) -> &Self::Target {
105 1004625 : &self.persisted_state
106 1004625 : }
107 : }
108 :
109 : /// Implementation of `wal_storage::Storage` trait.
110 : pub struct DiskWALStorage {
111 : /// Written to disk, but possibly still in the cache and not fully persisted.
112 : /// Also can be ahead of record_lsn, if happen to be in the middle of a WAL record.
113 : write_lsn: Lsn,
114 :
115 : /// The LSN of the last WAL record written to disk. Still can be not fully flushed.
116 : write_record_lsn: Lsn,
117 :
118 : /// The LSN of the last WAL record flushed to disk.
119 : flush_record_lsn: Lsn,
120 :
121 : /// Decoder is required for detecting boundaries of WAL records.
122 : decoder: WalStreamDecoder,
123 :
124 : /// Bytes of WAL records that are not yet written to disk.
125 : unflushed_bytes: BytesMut,
126 :
127 : /// Contains BlockStorage for WAL.
128 : disk: Arc<TimelineDisk>,
129 : }
130 :
131 : impl DiskWALStorage {
132 35312 : pub fn new(disk: Arc<TimelineDisk>, state: &TimelinePersistentState) -> Result<Self> {
133 35312 : let write_lsn = if state.commit_lsn == Lsn(0) {
134 32967 : Lsn(0)
135 : } else {
136 2345 : Self::find_end_of_wal(disk.clone(), state.commit_lsn)?
137 : };
138 :
139 35312 : let flush_lsn = write_lsn;
140 35312 : Ok(DiskWALStorage {
141 35312 : write_lsn,
142 35312 : write_record_lsn: flush_lsn,
143 35312 : flush_record_lsn: flush_lsn,
144 35312 : decoder: WalStreamDecoder::new(flush_lsn, 16),
145 35312 : unflushed_bytes: BytesMut::new(),
146 35312 : disk,
147 35312 : })
148 35312 : }
149 :
150 2345 : fn find_end_of_wal(disk: Arc<TimelineDisk>, start_lsn: Lsn) -> Result<Lsn> {
151 2345 : let mut buf = [0; 8192];
152 2345 : let mut pos = start_lsn.0;
153 2345 : let mut decoder = WalStreamDecoder::new(start_lsn, 16);
154 2345 : let mut result = start_lsn;
155 2345 : loop {
156 2345 : disk.wal.lock().read(pos, &mut buf);
157 2345 : pos += buf.len() as u64;
158 2345 : decoder.feed_bytes(&buf);
159 :
160 : loop {
161 11894 : match decoder.poll_decode() {
162 9549 : Ok(Some(record)) => result = record.0,
163 2345 : Err(e) => {
164 2345 : debug!(
165 0 : "find_end_of_wal reached end at {:?}, decode error: {:?}",
166 : result, e
167 : );
168 2345 : return Ok(result);
169 : }
170 0 : Ok(None) => break, // need more data
171 : }
172 : }
173 : }
174 2345 : }
175 : }
176 :
177 : impl wal_storage::Storage for DiskWALStorage {
178 : /// LSN of last durably stored WAL record.
179 79743 : fn flush_lsn(&self) -> Lsn {
180 79743 : self.flush_record_lsn
181 79743 : }
182 :
183 547 : async fn initialize_first_segment(&mut self, _init_lsn: Lsn) -> Result<()> {
184 547 : Ok(())
185 547 : }
186 :
187 : /// Write piece of WAL from buf to disk, but not necessarily sync it.
188 1982 : async fn write_wal(&mut self, startpos: Lsn, buf: &[u8]) -> Result<()> {
189 1982 : if self.write_lsn != startpos {
190 0 : panic!("write_wal called with wrong startpos");
191 1982 : }
192 1982 :
193 1982 : self.unflushed_bytes.extend_from_slice(buf);
194 1982 : self.write_lsn += buf.len() as u64;
195 1982 :
196 1982 : if self.decoder.available() != startpos {
197 0 : info!(
198 0 : "restart decoder from {} to {}",
199 0 : self.decoder.available(),
200 : startpos,
201 : );
202 0 : self.decoder = WalStreamDecoder::new(startpos, 16);
203 1982 : }
204 1982 : self.decoder.feed_bytes(buf);
205 : loop {
206 31430 : match self.decoder.poll_decode()? {
207 1982 : None => break, // no full record yet
208 29448 : Some((lsn, _rec)) => {
209 29448 : self.write_record_lsn = lsn;
210 29448 : }
211 : }
212 : }
213 :
214 1982 : Ok(())
215 1982 : }
216 :
217 : /// Truncate WAL at specified LSN, which must be the end of WAL record.
218 3385 : async fn truncate_wal(&mut self, end_pos: Lsn) -> Result<()> {
219 3385 : if self.write_lsn != Lsn(0) && end_pos > self.write_lsn {
220 0 : panic!(
221 0 : "truncate_wal called on non-written WAL, write_lsn={}, end_pos={}",
222 0 : self.write_lsn, end_pos
223 0 : );
224 3385 : }
225 3385 :
226 3385 : self.flush_wal().await?;
227 :
228 : // write zeroes to disk from end_pos until self.write_lsn
229 3385 : let buf = [0; 8192];
230 3385 : let mut pos = end_pos.0;
231 3398 : while pos < self.write_lsn.0 {
232 13 : self.disk.wal.lock().write(pos, &buf);
233 13 : pos += buf.len() as u64;
234 13 : }
235 :
236 3385 : self.write_lsn = end_pos;
237 3385 : self.write_record_lsn = end_pos;
238 3385 : self.flush_record_lsn = end_pos;
239 3385 : self.unflushed_bytes.clear();
240 3385 : self.decoder = WalStreamDecoder::new(end_pos, 16);
241 3385 :
242 3385 : Ok(())
243 3385 : }
244 :
245 : /// Durably store WAL on disk, up to the last written WAL record.
246 25174 : async fn flush_wal(&mut self) -> Result<()> {
247 25174 : if self.flush_record_lsn == self.write_record_lsn {
248 : // no need to do extra flush
249 23202 : return Ok(());
250 1972 : }
251 1972 :
252 1972 : let num_bytes = self.write_record_lsn.0 - self.flush_record_lsn.0;
253 1972 :
254 1972 : self.disk.wal.lock().write(
255 1972 : self.flush_record_lsn.0,
256 1972 : &self.unflushed_bytes[..num_bytes as usize],
257 1972 : );
258 1972 : self.unflushed_bytes.advance(num_bytes as usize);
259 1972 : self.flush_record_lsn = self.write_record_lsn;
260 1972 :
261 1972 : Ok(())
262 25174 : }
263 :
264 : /// Remove all segments <= given segno. Returns function doing that as we
265 : /// want to perform it without timeline lock.
266 0 : fn remove_up_to(&self, _segno_up_to: XLogSegNo) -> BoxFuture<'static, anyhow::Result<()>> {
267 0 : Box::pin(async move { Ok(()) })
268 0 : }
269 :
270 : /// Release resources associated with the storage -- technically, close FDs.
271 : /// Currently we don't remove timelines until restart (#3146), so need to
272 : /// spare descriptors. This would be useful for temporary tli detach as
273 : /// well.
274 0 : fn close(&mut self) {}
275 :
276 : /// Get metrics for this timeline.
277 0 : fn get_metrics(&self) -> WalStorageMetrics {
278 0 : WalStorageMetrics::default()
279 0 : }
280 : }
|