Line data Source code
1 : //! Control file serialization, deserialization and persistence.
2 :
3 : use anyhow::{bail, ensure, Context, Result};
4 : use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
5 : use camino::{Utf8Path, Utf8PathBuf};
6 : use tokio::fs::File;
7 : use tokio::io::AsyncWriteExt;
8 : use utils::crashsafe::durable_rename;
9 :
10 : use std::io::Read;
11 : use std::ops::Deref;
12 : use std::path::Path;
13 : use std::time::Instant;
14 :
15 : use crate::control_file_upgrade::downgrade_v9_to_v8;
16 : use crate::metrics::PERSIST_CONTROL_FILE_SECONDS;
17 : use crate::state::{EvictionState, TimelinePersistentState};
18 : use crate::{control_file_upgrade::upgrade_control_file, timeline::get_timeline_dir};
19 : use utils::{bin_ser::LeSer, id::TenantTimelineId};
20 :
21 : use crate::SafeKeeperConf;
22 :
23 : pub const SK_MAGIC: u32 = 0xcafeceefu32;
24 : pub const SK_FORMAT_VERSION: u32 = 9;
25 :
26 : // contains persistent metadata for safekeeper
27 : pub const CONTROL_FILE_NAME: &str = "safekeeper.control";
28 : // needed to atomically update the state using `rename`
29 : const CONTROL_FILE_NAME_PARTIAL: &str = "safekeeper.control.partial";
30 : pub const CHECKSUM_SIZE: usize = size_of::<u32>();
31 :
32 : /// Storage should keep actual state inside of it. It should implement Deref
33 : /// trait to access state fields and have persist method for updating that state.
34 : #[async_trait::async_trait]
35 : pub trait Storage: Deref<Target = TimelinePersistentState> {
36 : /// Persist safekeeper state on disk and update internal state.
37 : async fn persist(&mut self, s: &TimelinePersistentState) -> Result<()>;
38 :
39 : /// Timestamp of last persist.
40 : fn last_persist_at(&self) -> Instant;
41 : }
42 :
43 : #[derive(Debug)]
44 : pub struct FileStorage {
45 : // save timeline dir to avoid reconstructing it every time
46 : timeline_dir: Utf8PathBuf,
47 : no_sync: bool,
48 :
49 : /// Last state persisted to disk.
50 : state: TimelinePersistentState,
51 : /// Not preserved across restarts.
52 : last_persist_at: Instant,
53 : }
54 :
55 : impl FileStorage {
56 : /// Initialize storage by loading state from disk.
57 12 : pub fn restore_new(ttid: &TenantTimelineId, conf: &SafeKeeperConf) -> Result<FileStorage> {
58 12 : let timeline_dir = get_timeline_dir(conf, ttid);
59 12 : let state = Self::load_control_file_from_dir(&timeline_dir)?;
60 :
61 6 : Ok(FileStorage {
62 6 : timeline_dir,
63 6 : no_sync: conf.no_sync,
64 6 : state,
65 6 : last_persist_at: Instant::now(),
66 6 : })
67 12 : }
68 :
69 : /// Create file storage for a new timeline, but don't persist it yet.
70 12 : pub fn create_new(
71 12 : timeline_dir: Utf8PathBuf,
72 12 : conf: &SafeKeeperConf,
73 12 : state: TimelinePersistentState,
74 12 : ) -> Result<FileStorage> {
75 12 : // we don't support creating new timelines in offloaded state
76 12 : assert!(matches!(state.eviction_state, EvictionState::Present));
77 :
78 12 : let store = FileStorage {
79 12 : timeline_dir,
80 12 : no_sync: conf.no_sync,
81 12 : state,
82 12 : last_persist_at: Instant::now(),
83 12 : };
84 12 :
85 12 : Ok(store)
86 12 : }
87 :
88 : /// Check the magic/version in the on-disk data and deserialize it, if possible.
89 12 : fn deser_sk_state(buf: &mut &[u8]) -> Result<TimelinePersistentState> {
90 : // Read the version independent part
91 12 : let magic = ReadBytesExt::read_u32::<LittleEndian>(buf)?;
92 12 : if magic != SK_MAGIC {
93 0 : bail!(
94 0 : "bad control file magic: {:X}, expected {:X}",
95 0 : magic,
96 0 : SK_MAGIC
97 0 : );
98 12 : }
99 12 : let version = ReadBytesExt::read_u32::<LittleEndian>(buf)?;
100 12 : if version == SK_FORMAT_VERSION {
101 0 : let res = TimelinePersistentState::des(buf)?;
102 0 : return Ok(res);
103 12 : }
104 12 : // try to upgrade
105 12 : upgrade_control_file(buf, version)
106 12 : }
107 :
108 : /// Load control file from given directory.
109 18 : fn load_control_file_from_dir(timeline_dir: &Utf8Path) -> Result<TimelinePersistentState> {
110 18 : let path = timeline_dir.join(CONTROL_FILE_NAME);
111 18 : Self::load_control_file(path)
112 18 : }
113 :
114 : /// Read in the control file.
115 18 : pub fn load_control_file<P: AsRef<Path>>(
116 18 : control_file_path: P,
117 18 : ) -> Result<TimelinePersistentState> {
118 18 : let mut control_file = std::fs::OpenOptions::new()
119 18 : .read(true)
120 18 : .write(true)
121 18 : .open(&control_file_path)
122 18 : .with_context(|| {
123 0 : format!(
124 0 : "failed to open control file at {}",
125 0 : control_file_path.as_ref().display(),
126 0 : )
127 18 : })?;
128 :
129 18 : let mut buf = Vec::new();
130 18 : control_file
131 18 : .read_to_end(&mut buf)
132 18 : .context("failed to read control file")?;
133 :
134 18 : let calculated_checksum = crc32c::crc32c(&buf[..buf.len() - CHECKSUM_SIZE]);
135 :
136 18 : let expected_checksum_bytes: &[u8; CHECKSUM_SIZE] =
137 18 : buf[buf.len() - CHECKSUM_SIZE..].try_into()?;
138 18 : let expected_checksum = u32::from_le_bytes(*expected_checksum_bytes);
139 18 :
140 18 : ensure!(
141 18 : calculated_checksum == expected_checksum,
142 6 : format!(
143 6 : "safekeeper control file checksum mismatch: expected {} got {}",
144 6 : expected_checksum, calculated_checksum
145 6 : )
146 : );
147 :
148 12 : let state = FileStorage::deser_sk_state(&mut &buf[..buf.len() - CHECKSUM_SIZE])
149 12 : .with_context(|| {
150 0 : format!(
151 0 : "while reading control file {}",
152 0 : control_file_path.as_ref().display(),
153 0 : )
154 12 : })?;
155 12 : Ok(state)
156 18 : }
157 : }
158 :
159 : impl Deref for FileStorage {
160 : type Target = TimelinePersistentState;
161 :
162 0 : fn deref(&self) -> &Self::Target {
163 0 : &self.state
164 0 : }
165 : }
166 :
167 : impl TimelinePersistentState {
168 12 : pub(crate) fn write_to_buf(&self) -> Result<Vec<u8>> {
169 12 : let mut buf: Vec<u8> = Vec::new();
170 12 : WriteBytesExt::write_u32::<LittleEndian>(&mut buf, SK_MAGIC)?;
171 :
172 12 : if self.eviction_state == EvictionState::Present {
173 : // temp hack for forward compatibility
174 : const PREV_FORMAT_VERSION: u32 = 8;
175 12 : let prev = downgrade_v9_to_v8(self);
176 12 : WriteBytesExt::write_u32::<LittleEndian>(&mut buf, PREV_FORMAT_VERSION)?;
177 12 : prev.ser_into(&mut buf)?;
178 : } else {
179 : // otherwise, we write the current format version
180 0 : WriteBytesExt::write_u32::<LittleEndian>(&mut buf, SK_FORMAT_VERSION)?;
181 0 : self.ser_into(&mut buf)?;
182 : }
183 :
184 : // calculate checksum before resize
185 12 : let checksum = crc32c::crc32c(&buf);
186 12 : buf.extend_from_slice(&checksum.to_le_bytes());
187 12 : Ok(buf)
188 12 : }
189 : }
190 :
191 : #[async_trait::async_trait]
192 : impl Storage for FileStorage {
193 : /// Persists state durably to the underlying storage.
194 : ///
195 : /// For a description, see <https://lwn.net/Articles/457667/>.
196 12 : async fn persist(&mut self, s: &TimelinePersistentState) -> Result<()> {
197 12 : let _timer = PERSIST_CONTROL_FILE_SECONDS.start_timer();
198 12 :
199 12 : // write data to safekeeper.control.partial
200 12 : let control_partial_path = self.timeline_dir.join(CONTROL_FILE_NAME_PARTIAL);
201 12 : let mut control_partial = File::create(&control_partial_path).await.with_context(|| {
202 0 : format!(
203 0 : "failed to create partial control file at: {}",
204 0 : &control_partial_path
205 0 : )
206 12 : })?;
207 12 :
208 12 : let buf: Vec<u8> = s.write_to_buf()?;
209 12 :
210 12 : control_partial.write_all(&buf).await.with_context(|| {
211 0 : format!(
212 0 : "failed to write safekeeper state into control file at: {}",
213 0 : control_partial_path
214 0 : )
215 12 : })?;
216 12 : control_partial.flush().await.with_context(|| {
217 0 : format!(
218 0 : "failed to flush safekeeper state into control file at: {}",
219 0 : control_partial_path
220 0 : )
221 12 : })?;
222 12 :
223 12 : let control_path = self.timeline_dir.join(CONTROL_FILE_NAME);
224 76 : durable_rename(&control_partial_path, &control_path, !self.no_sync).await?;
225 12 :
226 12 : // update internal state
227 12 : self.state = s.clone();
228 12 : Ok(())
229 12 : }
230 :
231 0 : fn last_persist_at(&self) -> Instant {
232 0 : self.last_persist_at
233 0 : }
234 : }
235 :
236 : #[cfg(test)]
237 : mod test {
238 : use super::*;
239 : use tokio::fs;
240 : use utils::lsn::Lsn;
241 :
242 12 : fn stub_conf() -> SafeKeeperConf {
243 12 : let workdir = camino_tempfile::tempdir().unwrap().into_path();
244 12 : SafeKeeperConf {
245 12 : workdir,
246 12 : ..SafeKeeperConf::dummy()
247 12 : }
248 12 : }
249 :
250 12 : async fn load_from_control_file(
251 12 : conf: &SafeKeeperConf,
252 12 : ttid: &TenantTimelineId,
253 12 : ) -> Result<(FileStorage, TimelinePersistentState)> {
254 12 : let timeline_dir = get_timeline_dir(conf, ttid);
255 12 : fs::create_dir_all(&timeline_dir)
256 12 : .await
257 12 : .expect("failed to create timeline dir");
258 12 : Ok((
259 12 : FileStorage::restore_new(ttid, conf)?,
260 6 : FileStorage::load_control_file_from_dir(&timeline_dir)?,
261 : ))
262 12 : }
263 :
264 12 : async fn create(
265 12 : conf: &SafeKeeperConf,
266 12 : ttid: &TenantTimelineId,
267 12 : ) -> Result<(FileStorage, TimelinePersistentState)> {
268 12 : let timeline_dir = get_timeline_dir(conf, ttid);
269 12 : fs::create_dir_all(&timeline_dir)
270 12 : .await
271 12 : .expect("failed to create timeline dir");
272 12 : let state = TimelinePersistentState::empty();
273 12 : let storage = FileStorage::create_new(timeline_dir, conf, state.clone())?;
274 12 : Ok((storage, state))
275 12 : }
276 :
277 : #[tokio::test]
278 6 : async fn test_read_write_safekeeper_state() {
279 6 : let conf = stub_conf();
280 6 : let ttid = TenantTimelineId::generate();
281 6 : {
282 6 : let (mut storage, mut state) =
283 6 : create(&conf, &ttid).await.expect("failed to create state");
284 6 : // change something
285 6 : state.commit_lsn = Lsn(42);
286 6 : storage
287 6 : .persist(&state)
288 51 : .await
289 6 : .expect("failed to persist state");
290 6 : }
291 6 :
292 6 : let (_, state) = load_from_control_file(&conf, &ttid)
293 6 : .await
294 6 : .expect("failed to read state");
295 6 : assert_eq!(state.commit_lsn, Lsn(42));
296 6 : }
297 :
298 : #[tokio::test]
299 6 : async fn test_safekeeper_state_checksum_mismatch() {
300 6 : let conf = stub_conf();
301 6 : let ttid = TenantTimelineId::generate();
302 6 : {
303 6 : let (mut storage, mut state) =
304 6 : create(&conf, &ttid).await.expect("failed to read state");
305 6 :
306 6 : // change something
307 6 : state.commit_lsn = Lsn(42);
308 6 : storage
309 6 : .persist(&state)
310 47 : .await
311 6 : .expect("failed to persist state");
312 6 : }
313 6 : let control_path = get_timeline_dir(&conf, &ttid).join(CONTROL_FILE_NAME);
314 6 : let mut data = fs::read(&control_path).await.unwrap();
315 6 : data[0] += 1; // change the first byte of the file to fail checksum validation
316 6 : fs::write(&control_path, &data)
317 6 : .await
318 6 : .expect("failed to write control file");
319 6 :
320 6 : match load_from_control_file(&conf, &ttid).await {
321 6 : Err(err) => assert!(err
322 6 : .to_string()
323 6 : .contains("safekeeper control file checksum mismatch")),
324 6 : Ok(_) => panic!("expected error"),
325 6 : }
326 6 : }
327 : }
|