Line data Source code
1 : use std::sync::Arc;
2 :
3 : use ::metrics::IntGauge;
4 : use bytes::{Buf, BufMut, Bytes};
5 : use pageserver_api::key::{Key, AUX_KEY_PREFIX, METADATA_KEY_SIZE};
6 : use tracing::warn;
7 :
8 : // BEGIN Copyright (c) 2017 Servo Contributors
9 :
10 : /// Const version of FNV hash.
11 : #[inline]
12 : #[must_use]
13 74 : pub const fn fnv_hash(bytes: &[u8]) -> u128 {
14 : const INITIAL_STATE: u128 = 0x6c62272e07bb014262b821756295c58d;
15 : const PRIME: u128 = 0x0000000001000000000000000000013B;
16 :
17 74 : let mut hash = INITIAL_STATE;
18 74 : let mut i = 0;
19 596 : while i < bytes.len() {
20 522 : hash ^= bytes[i] as u128;
21 522 : hash = hash.wrapping_mul(PRIME);
22 522 : i += 1;
23 522 : }
24 74 : hash
25 74 : }
26 :
27 : // END Copyright (c) 2017 Servo Contributors
28 :
29 : /// Create a metadata key from a hash, encoded as [AUX_KEY_PREFIX, 2B directory prefix, least significant 13B of FNV hash].
30 62 : fn aux_hash_to_metadata_key(dir_level1: u8, dir_level2: u8, data: &[u8]) -> Key {
31 62 : let mut key: [u8; 16] = [0; METADATA_KEY_SIZE];
32 62 : let hash = fnv_hash(data).to_be_bytes();
33 62 : key[0] = AUX_KEY_PREFIX;
34 62 : key[1] = dir_level1;
35 62 : key[2] = dir_level2;
36 62 : key[3..16].copy_from_slice(&hash[3..16]);
37 62 : Key::from_metadata_key_fixed_size(&key)
38 62 : }
39 :
40 : const AUX_DIR_PG_LOGICAL: u8 = 0x01;
41 : const AUX_DIR_PG_REPLSLOT: u8 = 0x02;
42 : const AUX_DIR_PG_UNKNOWN: u8 = 0xFF;
43 :
44 : /// Encode the aux file into a fixed-size key.
45 : ///
46 : /// The first byte is the AUX key prefix. We use the next 2 bytes of the key for the directory / aux file type.
47 : /// We have one-to-one mapping for each of the aux file that we support. We hash the remaining part of the path
48 : /// (usually a single file name, or several components) into 13-byte hash. The way we determine the 2-byte prefix
49 : /// is roughly based on the first two components of the path, one unique number for one component.
50 : ///
51 : /// * pg_logical/mappings -> 0x0101
52 : /// * pg_logical/snapshots -> 0x0102
53 : /// * pg_logical/replorigin_checkpoint -> 0x0103
54 : /// * pg_logical/others -> 0x01FF
55 : /// * pg_replslot/ -> 0x0201
56 : /// * others -> 0xFFFF
57 : ///
58 : /// If you add new AUX files to this function, please also add a test case to `test_encoding_portable`.
59 : /// The new file type must have never been written to the storage before. Otherwise, there could be data
60 : /// corruptions as the new file belongs to a new prefix but it might have been stored under the `others` prefix.
61 62 : pub fn encode_aux_file_key(path: &str) -> Key {
62 62 : if let Some(fname) = path.strip_prefix("pg_logical/mappings/") {
63 13 : aux_hash_to_metadata_key(AUX_DIR_PG_LOGICAL, 0x01, fname.as_bytes())
64 49 : } else if let Some(fname) = path.strip_prefix("pg_logical/snapshots/") {
65 5 : aux_hash_to_metadata_key(AUX_DIR_PG_LOGICAL, 0x02, fname.as_bytes())
66 44 : } else if path == "pg_logical/replorigin_checkpoint" {
67 5 : aux_hash_to_metadata_key(AUX_DIR_PG_LOGICAL, 0x03, b"")
68 39 : } else if let Some(fname) = path.strip_prefix("pg_logical/") {
69 5 : if cfg!(debug_assertions) {
70 5 : warn!(
71 0 : "unsupported pg_logical aux file type: {}, putting to 0x01FF, would affect path scanning",
72 : path
73 : );
74 0 : }
75 5 : aux_hash_to_metadata_key(AUX_DIR_PG_LOGICAL, 0xFF, fname.as_bytes())
76 34 : } else if let Some(fname) = path.strip_prefix("pg_replslot/") {
77 5 : aux_hash_to_metadata_key(AUX_DIR_PG_REPLSLOT, 0x01, fname.as_bytes())
78 : } else {
79 29 : if cfg!(debug_assertions) {
80 29 : warn!(
81 0 : "unsupported aux file type: {}, putting to 0xFFFF, would affect path scanning",
82 : path
83 : );
84 0 : }
85 29 : aux_hash_to_metadata_key(AUX_DIR_PG_UNKNOWN, 0xFF, path.as_bytes())
86 : }
87 62 : }
88 :
89 : const AUX_FILE_ENCODING_VERSION: u8 = 0x01;
90 :
91 16 : pub fn decode_file_value(val: &[u8]) -> anyhow::Result<Vec<(&str, &[u8])>> {
92 16 : let mut ptr = val;
93 16 : if ptr.is_empty() {
94 : // empty value = no files
95 4 : return Ok(Vec::new());
96 12 : }
97 12 : assert_eq!(
98 12 : ptr.get_u8(),
99 : AUX_FILE_ENCODING_VERSION,
100 0 : "unsupported aux file value"
101 : );
102 12 : let mut files = vec![];
103 28 : while ptr.has_remaining() {
104 16 : let key_len = ptr.get_u32() as usize;
105 16 : let key = &ptr[..key_len];
106 16 : ptr.advance(key_len);
107 16 : let val_len = ptr.get_u32() as usize;
108 16 : let content = &ptr[..val_len];
109 16 : ptr.advance(val_len);
110 :
111 16 : let path = std::str::from_utf8(key)?;
112 16 : files.push((path, content));
113 : }
114 12 : Ok(files)
115 16 : }
116 :
117 : /// Decode an aux file key-value pair into a list of files. The returned `Bytes` contains reference
118 : /// to the original value slice. Be cautious about memory consumption.
119 36 : pub fn decode_file_value_bytes(val: &Bytes) -> anyhow::Result<Vec<(String, Bytes)>> {
120 36 : let mut ptr = val.clone();
121 36 : if ptr.is_empty() {
122 : // empty value = no files
123 4 : return Ok(Vec::new());
124 32 : }
125 32 : assert_eq!(
126 32 : ptr.get_u8(),
127 : AUX_FILE_ENCODING_VERSION,
128 0 : "unsupported aux file value"
129 : );
130 32 : let mut files = vec![];
131 64 : while ptr.has_remaining() {
132 32 : let key_len = ptr.get_u32() as usize;
133 32 : let key = ptr.slice(..key_len);
134 32 : ptr.advance(key_len);
135 32 : let val_len = ptr.get_u32() as usize;
136 32 : let content = ptr.slice(..val_len);
137 32 : ptr.advance(val_len);
138 :
139 32 : let path = std::str::from_utf8(&key)?.to_string();
140 32 : files.push((path, content));
141 : }
142 32 : Ok(files)
143 36 : }
144 :
145 40 : pub fn encode_file_value(files: &[(&str, &[u8])]) -> anyhow::Result<Vec<u8>> {
146 40 : if files.is_empty() {
147 : // no files = empty value
148 8 : return Ok(Vec::new());
149 32 : }
150 32 : let mut encoded = vec![];
151 32 : encoded.put_u8(AUX_FILE_ENCODING_VERSION);
152 68 : for (path, content) in files {
153 36 : if path.len() > u32::MAX as usize {
154 0 : anyhow::bail!("{} exceeds path size limit", path);
155 36 : }
156 36 : encoded.put_u32(path.len() as u32);
157 36 : encoded.put_slice(path.as_bytes());
158 36 : if content.len() > u32::MAX as usize {
159 0 : anyhow::bail!("{} exceeds content size limit", path);
160 36 : }
161 36 : encoded.put_u32(content.len() as u32);
162 36 : encoded.put_slice(content);
163 : }
164 32 : Ok(encoded)
165 40 : }
166 :
167 : /// An estimation of the size of aux files.
168 : pub struct AuxFileSizeEstimator {
169 : aux_file_size_gauge: IntGauge,
170 : size: Arc<std::sync::Mutex<Option<isize>>>,
171 : }
172 :
173 : impl AuxFileSizeEstimator {
174 892 : pub fn new(aux_file_size_gauge: IntGauge) -> Self {
175 892 : Self {
176 892 : aux_file_size_gauge,
177 892 : size: Arc::new(std::sync::Mutex::new(None)),
178 892 : }
179 892 : }
180 :
181 : /// When generating base backup or doing initial logical size calculation
182 24 : pub fn on_initial(&self, new_size: usize) {
183 24 : let mut guard = self.size.lock().unwrap();
184 24 : *guard = Some(new_size as isize);
185 24 : self.report(new_size as isize);
186 24 : }
187 :
188 24 : pub fn on_add(&self, file_size: usize) {
189 24 : let mut guard = self.size.lock().unwrap();
190 24 : if let Some(size) = &mut *guard {
191 4 : *size += file_size as isize;
192 4 : self.report(*size);
193 20 : }
194 24 : }
195 :
196 4 : pub fn on_remove(&self, file_size: usize) {
197 4 : let mut guard = self.size.lock().unwrap();
198 4 : if let Some(size) = &mut *guard {
199 4 : *size -= file_size as isize;
200 4 : self.report(*size);
201 4 : }
202 4 : }
203 :
204 4 : pub fn on_update(&self, old_size: usize, new_size: usize) {
205 4 : let mut guard = self.size.lock().unwrap();
206 4 : if let Some(size) = &mut *guard {
207 4 : *size += new_size as isize - old_size as isize;
208 4 : self.report(*size);
209 4 : }
210 4 : }
211 :
212 36 : pub fn report(&self, size: isize) {
213 36 : self.aux_file_size_gauge.set(size as i64);
214 36 : }
215 : }
216 :
217 : #[cfg(test)]
218 : mod tests {
219 : use super::*;
220 :
221 : #[test]
222 4 : fn test_hash_portable() {
223 4 : // AUX file encoding requires the hash to be portable across all platforms. This test case checks
224 4 : // if the algorithm produces the same hash across different environments.
225 4 :
226 4 : assert_eq!(
227 4 : 265160408618497461376862998434862070044,
228 4 : super::fnv_hash("test1".as_bytes())
229 4 : );
230 4 : assert_eq!(
231 4 : 295486155126299629456360817749600553988,
232 4 : super::fnv_hash("test/test2".as_bytes())
233 4 : );
234 4 : assert_eq!(
235 4 : 144066263297769815596495629667062367629,
236 4 : super::fnv_hash("".as_bytes())
237 4 : );
238 4 : }
239 :
240 : #[test]
241 4 : fn test_encoding_portable() {
242 4 : // To correct retrieve AUX files, the generated keys for the same file must be the same for all versions
243 4 : // of the page server.
244 4 : assert_eq!(
245 4 : "62000001017F8B83D94F7081693471ABF91C",
246 4 : encode_aux_file_key("pg_logical/mappings/test1").to_string(),
247 4 : );
248 4 : assert_eq!(
249 4 : "62000001027F8E83D94F7081693471ABFCCD",
250 4 : encode_aux_file_key("pg_logical/snapshots/test2").to_string(),
251 4 : );
252 4 : assert_eq!(
253 4 : "62000001032E07BB014262B821756295C58D",
254 4 : encode_aux_file_key("pg_logical/replorigin_checkpoint").to_string(),
255 4 : );
256 4 : assert_eq!(
257 4 : "62000001FF4F38E1C74754E7D03C1A660178",
258 4 : encode_aux_file_key("pg_logical/unsupported").to_string(),
259 4 : );
260 4 : assert_eq!(
261 4 : "62000002017F8D83D94F7081693471ABFB92",
262 4 : encode_aux_file_key("pg_replslot/test3").to_string()
263 4 : );
264 4 : assert_eq!(
265 4 : "620000FFFF2B6ECC8AEF93F643DC44F15E03",
266 4 : encode_aux_file_key("other_file_not_supported").to_string(),
267 4 : );
268 4 : }
269 :
270 : #[test]
271 4 : fn test_value_encoding() {
272 4 : let files = vec![
273 4 : ("pg_logical/1.file", "1111".as_bytes()),
274 4 : ("pg_logical/2.file", "2222".as_bytes()),
275 4 : ];
276 4 : assert_eq!(
277 4 : files,
278 4 : decode_file_value(&encode_file_value(&files).unwrap()).unwrap()
279 4 : );
280 4 : let files = vec![];
281 4 : assert_eq!(
282 4 : files,
283 4 : decode_file_value(&encode_file_value(&files).unwrap()).unwrap()
284 4 : );
285 4 : }
286 : }
|