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 = std::mem::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 4 : pub fn restore_new(ttid: &TenantTimelineId, conf: &SafeKeeperConf) -> Result<FileStorage> {
58 4 : let timeline_dir = get_timeline_dir(conf, ttid);
59 4 : let state = Self::load_control_file_from_dir(&timeline_dir)?;
60 :
61 2 : Ok(FileStorage {
62 2 : timeline_dir,
63 2 : no_sync: conf.no_sync,
64 2 : state,
65 2 : last_persist_at: Instant::now(),
66 2 : })
67 4 : }
68 :
69 : /// Create file storage for a new timeline, but don't persist it yet.
70 4 : pub fn create_new(
71 4 : timeline_dir: Utf8PathBuf,
72 4 : conf: &SafeKeeperConf,
73 4 : state: TimelinePersistentState,
74 4 : ) -> Result<FileStorage> {
75 4 : // we don't support creating new timelines in offloaded state
76 4 : assert!(matches!(state.eviction_state, EvictionState::Present));
77 :
78 4 : let store = FileStorage {
79 4 : timeline_dir,
80 4 : no_sync: conf.no_sync,
81 4 : state,
82 4 : last_persist_at: Instant::now(),
83 4 : };
84 4 :
85 4 : Ok(store)
86 4 : }
87 :
88 : /// Check the magic/version in the on-disk data and deserialize it, if possible.
89 4 : fn deser_sk_state(buf: &mut &[u8]) -> Result<TimelinePersistentState> {
90 : // Read the version independent part
91 4 : let magic = ReadBytesExt::read_u32::<LittleEndian>(buf)?;
92 4 : 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 4 : }
99 4 : let version = ReadBytesExt::read_u32::<LittleEndian>(buf)?;
100 4 : if version == SK_FORMAT_VERSION {
101 0 : let res = TimelinePersistentState::des(buf)?;
102 0 : return Ok(res);
103 4 : }
104 4 : // try to upgrade
105 4 : upgrade_control_file(buf, version)
106 4 : }
107 :
108 : /// Load control file from given directory.
109 6 : fn load_control_file_from_dir(timeline_dir: &Utf8Path) -> Result<TimelinePersistentState> {
110 6 : let path = timeline_dir.join(CONTROL_FILE_NAME);
111 6 : Self::load_control_file(path)
112 6 : }
113 :
114 : /// Read in the control file.
115 6 : pub fn load_control_file<P: AsRef<Path>>(
116 6 : control_file_path: P,
117 6 : ) -> Result<TimelinePersistentState> {
118 6 : let mut control_file = std::fs::OpenOptions::new()
119 6 : .read(true)
120 6 : .write(true)
121 6 : .open(&control_file_path)
122 6 : .with_context(|| {
123 0 : format!(
124 0 : "failed to open control file at {}",
125 0 : control_file_path.as_ref().display(),
126 0 : )
127 6 : })?;
128 :
129 6 : let mut buf = Vec::new();
130 6 : control_file
131 6 : .read_to_end(&mut buf)
132 6 : .context("failed to read control file")?;
133 :
134 6 : let calculated_checksum = crc32c::crc32c(&buf[..buf.len() - CHECKSUM_SIZE]);
135 :
136 6 : let expected_checksum_bytes: &[u8; CHECKSUM_SIZE] =
137 6 : buf[buf.len() - CHECKSUM_SIZE..].try_into()?;
138 6 : let expected_checksum = u32::from_le_bytes(*expected_checksum_bytes);
139 6 :
140 6 : ensure!(
141 6 : calculated_checksum == expected_checksum,
142 2 : format!(
143 2 : "safekeeper control file checksum mismatch: expected {} got {}",
144 2 : expected_checksum, calculated_checksum
145 2 : )
146 : );
147 :
148 4 : let state = FileStorage::deser_sk_state(&mut &buf[..buf.len() - CHECKSUM_SIZE])
149 4 : .with_context(|| {
150 0 : format!(
151 0 : "while reading control file {}",
152 0 : control_file_path.as_ref().display(),
153 0 : )
154 4 : })?;
155 4 : Ok(state)
156 6 : }
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 : #[async_trait::async_trait]
168 : impl Storage for FileStorage {
169 : /// Persists state durably to the underlying storage.
170 : ///
171 : /// For a description, see <https://lwn.net/Articles/457667/>.
172 4 : async fn persist(&mut self, s: &TimelinePersistentState) -> Result<()> {
173 4 : let _timer = PERSIST_CONTROL_FILE_SECONDS.start_timer();
174 4 :
175 4 : // write data to safekeeper.control.partial
176 4 : let control_partial_path = self.timeline_dir.join(CONTROL_FILE_NAME_PARTIAL);
177 4 : let mut control_partial = File::create(&control_partial_path).await.with_context(|| {
178 0 : format!(
179 0 : "failed to create partial control file at: {}",
180 0 : &control_partial_path
181 0 : )
182 4 : })?;
183 4 : let mut buf: Vec<u8> = Vec::new();
184 4 : WriteBytesExt::write_u32::<LittleEndian>(&mut buf, SK_MAGIC)?;
185 4 :
186 4 : if s.eviction_state == EvictionState::Present {
187 4 : // temp hack for forward compatibility
188 4 : const PREV_FORMAT_VERSION: u32 = 8;
189 4 : let prev = downgrade_v9_to_v8(s);
190 4 : WriteBytesExt::write_u32::<LittleEndian>(&mut buf, PREV_FORMAT_VERSION)?;
191 4 : prev.ser_into(&mut buf)?;
192 4 : } else {
193 4 : // otherwise, we write the current format version
194 4 : WriteBytesExt::write_u32::<LittleEndian>(&mut buf, SK_FORMAT_VERSION)?;
195 4 : s.ser_into(&mut buf)?;
196 4 : }
197 4 :
198 4 : // calculate checksum before resize
199 4 : let checksum = crc32c::crc32c(&buf);
200 4 : buf.extend_from_slice(&checksum.to_le_bytes());
201 4 :
202 4 : control_partial.write_all(&buf).await.with_context(|| {
203 0 : format!(
204 0 : "failed to write safekeeper state into control file at: {}",
205 0 : control_partial_path
206 0 : )
207 4 : })?;
208 4 : control_partial.flush().await.with_context(|| {
209 0 : format!(
210 0 : "failed to flush safekeeper state into control file at: {}",
211 0 : control_partial_path
212 0 : )
213 4 : })?;
214 4 :
215 4 : let control_path = self.timeline_dir.join(CONTROL_FILE_NAME);
216 28 : durable_rename(&control_partial_path, &control_path, !self.no_sync).await?;
217 4 :
218 4 : // update internal state
219 4 : self.state = s.clone();
220 4 : Ok(())
221 4 : }
222 :
223 0 : fn last_persist_at(&self) -> Instant {
224 0 : self.last_persist_at
225 0 : }
226 : }
227 :
228 : #[cfg(test)]
229 : mod test {
230 : use super::*;
231 : use tokio::fs;
232 : use utils::lsn::Lsn;
233 :
234 4 : fn stub_conf() -> SafeKeeperConf {
235 4 : let workdir = camino_tempfile::tempdir().unwrap().into_path();
236 4 : SafeKeeperConf {
237 4 : workdir,
238 4 : ..SafeKeeperConf::dummy()
239 4 : }
240 4 : }
241 :
242 4 : async fn load_from_control_file(
243 4 : conf: &SafeKeeperConf,
244 4 : ttid: &TenantTimelineId,
245 4 : ) -> Result<(FileStorage, TimelinePersistentState)> {
246 4 : let timeline_dir = get_timeline_dir(conf, ttid);
247 4 : fs::create_dir_all(&timeline_dir)
248 4 : .await
249 4 : .expect("failed to create timeline dir");
250 4 : Ok((
251 4 : FileStorage::restore_new(ttid, conf)?,
252 2 : FileStorage::load_control_file_from_dir(&timeline_dir)?,
253 : ))
254 4 : }
255 :
256 4 : async fn create(
257 4 : conf: &SafeKeeperConf,
258 4 : ttid: &TenantTimelineId,
259 4 : ) -> Result<(FileStorage, TimelinePersistentState)> {
260 4 : let timeline_dir = get_timeline_dir(conf, ttid);
261 4 : fs::create_dir_all(&timeline_dir)
262 4 : .await
263 4 : .expect("failed to create timeline dir");
264 4 : let state = TimelinePersistentState::empty();
265 4 : let storage = FileStorage::create_new(timeline_dir, conf, state.clone())?;
266 4 : Ok((storage, state))
267 4 : }
268 :
269 : #[tokio::test]
270 2 : async fn test_read_write_safekeeper_state() {
271 2 : let conf = stub_conf();
272 2 : let ttid = TenantTimelineId::generate();
273 2 : {
274 2 : let (mut storage, mut state) =
275 2 : create(&conf, &ttid).await.expect("failed to create state");
276 2 : // change something
277 2 : state.commit_lsn = Lsn(42);
278 2 : storage
279 2 : .persist(&state)
280 18 : .await
281 2 : .expect("failed to persist state");
282 2 : }
283 2 :
284 2 : let (_, state) = load_from_control_file(&conf, &ttid)
285 2 : .await
286 2 : .expect("failed to read state");
287 2 : assert_eq!(state.commit_lsn, Lsn(42));
288 2 : }
289 :
290 : #[tokio::test]
291 2 : async fn test_safekeeper_state_checksum_mismatch() {
292 2 : let conf = stub_conf();
293 2 : let ttid = TenantTimelineId::generate();
294 2 : {
295 2 : let (mut storage, mut state) =
296 2 : create(&conf, &ttid).await.expect("failed to read state");
297 2 :
298 2 : // change something
299 2 : state.commit_lsn = Lsn(42);
300 2 : storage
301 2 : .persist(&state)
302 18 : .await
303 2 : .expect("failed to persist state");
304 2 : }
305 2 : let control_path = get_timeline_dir(&conf, &ttid).join(CONTROL_FILE_NAME);
306 2 : let mut data = fs::read(&control_path).await.unwrap();
307 2 : data[0] += 1; // change the first byte of the file to fail checksum validation
308 2 : fs::write(&control_path, &data)
309 2 : .await
310 2 : .expect("failed to write control file");
311 2 :
312 2 : match load_from_control_file(&conf, &ttid).await {
313 2 : Err(err) => assert!(err
314 2 : .to_string()
315 2 : .contains("safekeeper control file checksum mismatch")),
316 2 : Ok(_) => panic!("expected error"),
317 2 : }
318 2 : }
319 : }
|