Line data Source code
1 : use std::{ffi::CString, sync::Arc};
2 :
3 : use byteorder::{LittleEndian, WriteBytesExt};
4 : use crc32c::crc32c_append;
5 : use parking_lot::{Mutex, MutexGuard};
6 : use postgres_ffi::{
7 : pg_constants::{
8 : RM_LOGICALMSG_ID, XLOG_LOGICAL_MESSAGE, XLP_LONG_HEADER, XLR_BLOCK_ID_DATA_LONG,
9 : XLR_BLOCK_ID_DATA_SHORT,
10 : },
11 : v16::{
12 : wal_craft_test_export::{XLogLongPageHeaderData, XLogPageHeaderData, XLOG_PAGE_MAGIC},
13 : xlog_utils::{
14 : XLogSegNoOffsetToRecPtr, XlLogicalMessage, XLOG_RECORD_CRC_OFFS,
15 : XLOG_SIZE_OF_XLOG_LONG_PHD, XLOG_SIZE_OF_XLOG_RECORD, XLOG_SIZE_OF_XLOG_SHORT_PHD,
16 : XLP_FIRST_IS_CONTRECORD,
17 : },
18 : XLogRecord,
19 : },
20 : WAL_SEGMENT_SIZE, XLOG_BLCKSZ,
21 : };
22 : use utils::lsn::Lsn;
23 :
24 : use super::block_storage::BlockStorage;
25 :
26 : /// Simulation implementation of walproposer WAL storage.
27 : pub struct DiskWalProposer {
28 : state: Mutex<State>,
29 : }
30 :
31 : impl DiskWalProposer {
32 37048 : pub fn new() -> Arc<DiskWalProposer> {
33 37048 : Arc::new(DiskWalProposer {
34 37048 : state: Mutex::new(State {
35 37048 : internal_available_lsn: Lsn(0),
36 37048 : prev_lsn: Lsn(0),
37 37048 : disk: BlockStorage::new(),
38 37048 : }),
39 37048 : })
40 37048 : }
41 :
42 41497 : pub fn lock(&self) -> MutexGuard<State> {
43 41497 : self.state.lock()
44 41497 : }
45 : }
46 :
47 : pub struct State {
48 : // flush_lsn
49 : internal_available_lsn: Lsn,
50 : // needed for WAL generation
51 : prev_lsn: Lsn,
52 : // actual WAL storage
53 : disk: BlockStorage,
54 : }
55 :
56 : impl State {
57 15693 : pub fn read(&self, pos: u64, buf: &mut [u8]) {
58 15693 : self.disk.read(pos, buf);
59 15693 : // TODO: fail on reading uninitialized data
60 15693 : }
61 :
62 69778 : pub fn write(&mut self, pos: u64, buf: &[u8]) {
63 69778 : self.disk.write(pos, buf);
64 69778 : }
65 :
66 : /// Update the internal available LSN to the given value.
67 1537 : pub fn reset_to(&mut self, lsn: Lsn) {
68 1537 : self.internal_available_lsn = lsn;
69 1537 : }
70 :
71 : /// Get current LSN.
72 6228 : pub fn flush_rec_ptr(&self) -> Lsn {
73 6228 : self.internal_available_lsn
74 6228 : }
75 :
76 : /// Generate a new WAL record at the current LSN.
77 17183 : pub fn insert_logical_message(&mut self, prefix: &str, msg: &[u8]) -> anyhow::Result<()> {
78 17183 : let prefix_cstr = CString::new(prefix)?;
79 17183 : let prefix_bytes = prefix_cstr.as_bytes_with_nul();
80 17183 :
81 17183 : let lm = XlLogicalMessage {
82 17183 : db_id: 0,
83 17183 : transactional: 0,
84 17183 : prefix_size: prefix_bytes.len() as ::std::os::raw::c_ulong,
85 17183 : message_size: msg.len() as ::std::os::raw::c_ulong,
86 17183 : };
87 17183 :
88 17183 : let record_bytes = lm.encode();
89 17183 : let rdatas: Vec<&[u8]> = vec![&record_bytes, prefix_bytes, msg];
90 17183 : insert_wal_record(self, rdatas, RM_LOGICALMSG_ID, XLOG_LOGICAL_MESSAGE)
91 17183 : }
92 : }
93 :
94 17183 : fn insert_wal_record(
95 17183 : state: &mut State,
96 17183 : rdatas: Vec<&[u8]>,
97 17183 : rmid: u8,
98 17183 : info: u8,
99 17183 : ) -> anyhow::Result<()> {
100 17183 : // bytes right after the header, in the same rdata block
101 17183 : let mut scratch = Vec::new();
102 51549 : let mainrdata_len: usize = rdatas.iter().map(|rdata| rdata.len()).sum();
103 17183 :
104 17183 : if mainrdata_len > 0 {
105 17183 : if mainrdata_len > 255 {
106 0 : scratch.push(XLR_BLOCK_ID_DATA_LONG);
107 0 : // TODO: verify endiness
108 0 : let _ = scratch.write_u32::<LittleEndian>(mainrdata_len as u32);
109 17183 : } else {
110 17183 : scratch.push(XLR_BLOCK_ID_DATA_SHORT);
111 17183 : scratch.push(mainrdata_len as u8);
112 17183 : }
113 0 : }
114 :
115 17183 : let total_len: u32 = (XLOG_SIZE_OF_XLOG_RECORD + scratch.len() + mainrdata_len) as u32;
116 17183 : let size = maxalign(total_len);
117 17183 : assert!(size as usize > XLOG_SIZE_OF_XLOG_RECORD);
118 :
119 17183 : let start_bytepos = recptr_to_bytepos(state.internal_available_lsn);
120 17183 : let end_bytepos = start_bytepos + size as u64;
121 17183 :
122 17183 : let start_recptr = bytepos_to_recptr(start_bytepos);
123 17183 : let end_recptr = bytepos_to_recptr(end_bytepos);
124 17183 :
125 17183 : assert!(recptr_to_bytepos(start_recptr) == start_bytepos);
126 17183 : assert!(recptr_to_bytepos(end_recptr) == end_bytepos);
127 :
128 17183 : let mut crc = crc32c_append(0, &scratch);
129 68732 : for rdata in &rdatas {
130 51549 : crc = crc32c_append(crc, rdata);
131 51549 : }
132 :
133 17183 : let mut header = XLogRecord {
134 17183 : xl_tot_len: total_len,
135 17183 : xl_xid: 0,
136 17183 : xl_prev: state.prev_lsn.0,
137 17183 : xl_info: info,
138 17183 : xl_rmid: rmid,
139 17183 : __bindgen_padding_0: [0u8; 2usize],
140 17183 : xl_crc: crc,
141 17183 : };
142 :
143 : // now we have the header and can finish the crc
144 17183 : let header_bytes = header.encode()?;
145 17183 : let crc = crc32c_append(crc, &header_bytes[0..XLOG_RECORD_CRC_OFFS]);
146 17183 : header.xl_crc = crc;
147 :
148 17183 : let mut header_bytes = header.encode()?.to_vec();
149 17183 : assert!(header_bytes.len() == XLOG_SIZE_OF_XLOG_RECORD);
150 :
151 17183 : header_bytes.extend_from_slice(&scratch);
152 17183 :
153 17183 : // finish rdatas
154 17183 : let mut rdatas = rdatas;
155 17183 : rdatas.insert(0, &header_bytes);
156 17183 :
157 17183 : write_walrecord_to_disk(state, total_len as u64, rdatas, start_recptr, end_recptr)?;
158 :
159 17183 : state.internal_available_lsn = end_recptr;
160 17183 : state.prev_lsn = start_recptr;
161 17183 : Ok(())
162 17183 : }
163 :
164 17183 : fn write_walrecord_to_disk(
165 17183 : state: &mut State,
166 17183 : total_len: u64,
167 17183 : rdatas: Vec<&[u8]>,
168 17183 : start: Lsn,
169 17183 : end: Lsn,
170 17183 : ) -> anyhow::Result<()> {
171 17183 : let mut curr_ptr = start;
172 17183 : let mut freespace = insert_freespace(curr_ptr);
173 17183 : let mut written: usize = 0;
174 17183 :
175 17183 : assert!(freespace >= size_of::<u32>());
176 :
177 85915 : for mut rdata in rdatas {
178 68827 : while rdata.len() >= freespace {
179 95 : assert!(
180 95 : curr_ptr.segment_offset(WAL_SEGMENT_SIZE) >= XLOG_SIZE_OF_XLOG_SHORT_PHD
181 0 : || freespace == 0
182 : );
183 :
184 95 : state.write(curr_ptr.0, &rdata[..freespace]);
185 95 : rdata = &rdata[freespace..];
186 95 : written += freespace;
187 95 : curr_ptr = Lsn(curr_ptr.0 + freespace as u64);
188 95 :
189 95 : let mut new_page = XLogPageHeaderData {
190 95 : xlp_magic: XLOG_PAGE_MAGIC as u16,
191 95 : xlp_info: XLP_BKP_REMOVABLE,
192 95 : xlp_tli: 1,
193 95 : xlp_pageaddr: curr_ptr.0,
194 95 : xlp_rem_len: (total_len - written as u64) as u32,
195 95 : ..Default::default() // Put 0 in padding fields.
196 95 : };
197 95 : if new_page.xlp_rem_len > 0 {
198 86 : new_page.xlp_info |= XLP_FIRST_IS_CONTRECORD;
199 86 : }
200 :
201 95 : if curr_ptr.segment_offset(WAL_SEGMENT_SIZE) == 0 {
202 0 : new_page.xlp_info |= XLP_LONG_HEADER;
203 0 : let long_page = XLogLongPageHeaderData {
204 0 : std: new_page,
205 0 : xlp_sysid: 0,
206 0 : xlp_seg_size: WAL_SEGMENT_SIZE as u32,
207 0 : xlp_xlog_blcksz: XLOG_BLCKSZ as u32,
208 0 : };
209 0 : let header_bytes = long_page.encode()?;
210 0 : assert!(header_bytes.len() == XLOG_SIZE_OF_XLOG_LONG_PHD);
211 0 : state.write(curr_ptr.0, &header_bytes);
212 0 : curr_ptr = Lsn(curr_ptr.0 + header_bytes.len() as u64);
213 : } else {
214 95 : let header_bytes = new_page.encode()?;
215 95 : assert!(header_bytes.len() == XLOG_SIZE_OF_XLOG_SHORT_PHD);
216 95 : state.write(curr_ptr.0, &header_bytes);
217 95 : curr_ptr = Lsn(curr_ptr.0 + header_bytes.len() as u64);
218 : }
219 95 : freespace = insert_freespace(curr_ptr);
220 : }
221 :
222 68732 : assert!(
223 68732 : curr_ptr.segment_offset(WAL_SEGMENT_SIZE) >= XLOG_SIZE_OF_XLOG_SHORT_PHD
224 0 : || rdata.is_empty()
225 : );
226 68732 : state.write(curr_ptr.0, rdata);
227 68732 : curr_ptr = Lsn(curr_ptr.0 + rdata.len() as u64);
228 68732 : written += rdata.len();
229 68732 : freespace -= rdata.len();
230 : }
231 :
232 17183 : assert!(written == total_len as usize);
233 17183 : curr_ptr.0 = maxalign(curr_ptr.0);
234 17183 : assert!(curr_ptr == end);
235 17183 : Ok(())
236 17183 : }
237 :
238 34366 : fn maxalign<T>(size: T) -> T
239 34366 : where
240 34366 : T: std::ops::BitAnd<Output = T>
241 34366 : + std::ops::Add<Output = T>
242 34366 : + std::ops::Not<Output = T>
243 34366 : + From<u8>,
244 34366 : {
245 34366 : (size + T::from(7)) & !T::from(7)
246 34366 : }
247 :
248 17278 : fn insert_freespace(ptr: Lsn) -> usize {
249 17278 : if ptr.block_offset() == 0 {
250 0 : 0
251 : } else {
252 17278 : (XLOG_BLCKSZ as u64 - ptr.block_offset()) as usize
253 : }
254 17278 : }
255 :
256 : const XLP_BKP_REMOVABLE: u16 = 0x0004;
257 : const USABLE_BYTES_IN_PAGE: u64 = (XLOG_BLCKSZ - XLOG_SIZE_OF_XLOG_SHORT_PHD) as u64;
258 : const USABLE_BYTES_IN_SEGMENT: u64 = ((WAL_SEGMENT_SIZE / XLOG_BLCKSZ) as u64
259 : * USABLE_BYTES_IN_PAGE)
260 : - (XLOG_SIZE_OF_XLOG_RECORD - XLOG_SIZE_OF_XLOG_SHORT_PHD) as u64;
261 :
262 34366 : fn bytepos_to_recptr(bytepos: u64) -> Lsn {
263 34366 : let fullsegs = bytepos / USABLE_BYTES_IN_SEGMENT;
264 34366 : let mut bytesleft = bytepos % USABLE_BYTES_IN_SEGMENT;
265 :
266 34366 : let seg_offset = if bytesleft < (XLOG_BLCKSZ - XLOG_SIZE_OF_XLOG_SHORT_PHD) as u64 {
267 : // fits on first page of segment
268 0 : bytesleft + XLOG_SIZE_OF_XLOG_SHORT_PHD as u64
269 : } else {
270 : // account for the first page on segment with long header
271 34366 : bytesleft -= (XLOG_BLCKSZ - XLOG_SIZE_OF_XLOG_SHORT_PHD) as u64;
272 34366 : let fullpages = bytesleft / USABLE_BYTES_IN_PAGE;
273 34366 : bytesleft %= USABLE_BYTES_IN_PAGE;
274 34366 :
275 34366 : XLOG_BLCKSZ as u64
276 34366 : + fullpages * XLOG_BLCKSZ as u64
277 34366 : + bytesleft
278 34366 : + XLOG_SIZE_OF_XLOG_SHORT_PHD as u64
279 : };
280 :
281 34366 : Lsn(XLogSegNoOffsetToRecPtr(
282 34366 : fullsegs,
283 34366 : seg_offset as u32,
284 34366 : WAL_SEGMENT_SIZE,
285 34366 : ))
286 34366 : }
287 :
288 51549 : fn recptr_to_bytepos(ptr: Lsn) -> u64 {
289 51549 : let fullsegs = ptr.segment_number(WAL_SEGMENT_SIZE);
290 51549 : let offset = ptr.segment_offset(WAL_SEGMENT_SIZE) as u64;
291 51549 :
292 51549 : let fullpages = offset / XLOG_BLCKSZ as u64;
293 51549 : let offset = offset % XLOG_BLCKSZ as u64;
294 51549 :
295 51549 : if fullpages == 0 {
296 0 : fullsegs * USABLE_BYTES_IN_SEGMENT
297 0 : + if offset > 0 {
298 0 : assert!(offset >= XLOG_SIZE_OF_XLOG_SHORT_PHD as u64);
299 0 : offset - XLOG_SIZE_OF_XLOG_SHORT_PHD as u64
300 : } else {
301 0 : 0
302 : }
303 : } else {
304 51549 : fullsegs * USABLE_BYTES_IN_SEGMENT
305 51549 : + (XLOG_BLCKSZ - XLOG_SIZE_OF_XLOG_SHORT_PHD) as u64
306 51549 : + (fullpages - 1) * USABLE_BYTES_IN_PAGE
307 51549 : + if offset > 0 {
308 51549 : assert!(offset >= XLOG_SIZE_OF_XLOG_SHORT_PHD as u64);
309 51549 : offset - XLOG_SIZE_OF_XLOG_SHORT_PHD as u64
310 : } else {
311 0 : 0
312 : }
313 : }
314 51549 : }
|