Debian Codegraph @

third_party/rust/rkv/src/backend/impl_lmdb/arch_migrator.rs

raw
1 // Copyright 2018-2019 Mozilla
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4 // this file except in compliance with the License. You may obtain a copy of the
5 // License at http://www.apache.org/licenses/LICENSE-2.0
6 // Unless required by applicable law or agreed to in writing, software distributed
7 // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
8 // CONDITIONS OF ANY KIND, either express or implied. See the License for the
9 // specific language governing permissions and limitations under the License.
10 #![allow(dead_code)] // TODO: Get rid of unused struct members
11 #![allow(clippy::upper_case_acronyms)] // TODO: Consider renaming things like `BRANCH`
12
13 //! A utility for migrating data from one LMDB environment to another. Notably, this tool
14 //! can migrate data from an enviroment created with a different bit-depth than the
15 //! current rkv consumer, which enables the consumer to retrieve data from an environment
16 //! that can't be read directly using the rkv APIs.
17 //!
18 //! The utility supports both 32-bit and 64-bit LMDB source environments, and it
19 //! automatically migrates data in both the default database and any named (sub)
20 //! databases. It also migrates the source environment's "map size" and "max DBs"
21 //! configuration options to the destination environment.
22 //!
23 //! The destination environment must be at the rkv consumer's bit depth and should be
24 //! empty of data. It can be an empty directory, in which case the utility will create a
25 //! new LMDB environment within the directory.
26 //!
27 //! The tool currently has these limitations:
28 //!
29 //! 1. It doesn't support migration from environments created with
30 //! `EnvironmentFlags::NO_SUB_DIR`. To migrate such an environment, create a
31 //! temporary directory, copy the environment's data file to a file called data.mdb in
32 //! the temporary directory, then migrate the temporary directory as the source
33 //! environment.
34 //! 2. It doesn't support migration from databases created with DatabaseFlags::DUP_SORT`
35 //! (with or without `DatabaseFlags::DUP_FIXED`).
36 //! 3. It doesn't account for existing data in the destination environment, which means
37 //! that it can overwrite data (causing data loss) or fail to migrate data if the
38 //! destination environment contains existing data.
39 //!
40 //! ## Basic Usage
41 //!
42 //! Call `Migrator::new()` with the path to the source environment to create a `Migrator`
43 //! instance; then call the instance's `migrate()` method with the path to the destination
44 //! environment to migrate data from the source to the destination environment. For
45 //! example, this snippet migrates data from the tests/envs/ref_env_32 environment to a
46 //! new environment in a temporary directory:
47 //!
48 //! ```
49 //! use rkv::migrator::LmdbArchMigrator as Migrator;
50 //! use std::path::Path;
51 //! use tempfile::tempdir;
52 //! let mut migrator = Migrator::new(Path::new("tests/envs/ref_env_32")).unwrap();
53 //! migrator.migrate(&tempdir().unwrap().path()).unwrap();
54 //! ```
55 //!
56 //! Both `Migrator::new()` and `migrate()` return a `MigrateResult` that is either an
57 //! `Ok()` result or an `Err<MigrateError>`, where `MigrateError` is an enum whose
58 //! variants identify specific kinds of migration failures.
59
60 use std::{
61 collections::{BTreeMap, HashMap},
62 convert::TryFrom,
63 fs::File,
64 io::{Cursor, Read, Seek, SeekFrom, Write},
65 path::{Path, PathBuf},
66 rc::Rc,
67 str,
68 };
69
70 use bitflags::bitflags;
71 use byteorder::{LittleEndian, ReadBytesExt};
72 use lmdb::{DatabaseFlags, Environment, Transaction, WriteFlags};
73
74 pub use super::arch_migrator_error::MigrateError;
75
76 const PAGESIZE: u16 = 4096;
77
78 // The magic number is 0xBEEFC0DE, which is 0xDEC0EFBE in little-endian. It appears at
79 // offset 12 on 32-bit systems and 16 on 64-bit systems. We don't support big-endian
80 // migration, but presumably we could do so by detecting the order of the bytes.
81 const MAGIC: [u8; 4] = [0xDE, 0xC0, 0xEF, 0xBE];
82
83 pub type MigrateResult<T> = Result<T, MigrateError>;
84
85 bitflags! {
86 #[derive(Default, PartialEq, Eq, Debug, Clone, Copy)]
87 struct PageFlags: u16 {
88 const BRANCH = 0x01;
89 const LEAF = 0x02;
90 const OVERFLOW = 0x04;
91 const META = 0x08;
92 const DIRTY = 0x10;
93 const LEAF2 = 0x20;
94 const SUBP = 0x40;
95 const LOOSE = 0x4000;
96 const KEEP = 0x8000;
97 }
98 }
99
100 bitflags! {
101 #[derive(Default, PartialEq, Eq, Debug, Clone, Copy)]
102 struct NodeFlags: u16 {
103 const BIGDATA = 0x01;
104 const SUBDATA = 0x02;
105 const DUPDATA = 0x04;
106 }
107 }
108
109 // The bit depth of the executable that created an LMDB environment. The Migrator
110 // determines this automatically based on the location of the magic number in data.mdb.
111 #[derive(Clone, Copy, PartialEq)]
112 enum Bits {
113 U32,
114 U64,
115 }
116
117 impl Bits {
118 // The size of usize for the bit-depth represented by the enum variant.
119 fn size(self) -> usize {
120 match self {
121 Bits::U32 => 4,
122 Bits::U64 => 8,
123 }
124 }
125 }
126
127 // The equivalent of PAGEHDRSZ in LMDB, except that this one varies by bits.
128 fn page_header_size(bits: Bits) -> u64 {
129 match bits {
130 Bits::U32 => 12,
131 Bits::U64 => 16,
132 }
133 }
134
135 // The equivalent of P_INVALID in LMDB, except that this one varies by bits.
136 fn validate_page_num(page_num: u64, bits: Bits) -> MigrateResult<()> {
137 let invalid_page_num = match bits {
138 Bits::U32 => u64::from(!0u32),
139 Bits::U64 => !0u64,
140 };
141
142 if page_num == invalid_page_num {
143 return Err(MigrateError::InvalidPageNum);
144 }
145
146 Ok(())
147 }
148
149 #[derive(Clone, Debug, Default)]
150 struct Database {
151 md_pad: u32,
152 md_flags: DatabaseFlags,
153 md_depth: u16,
154 md_branch_pages: u64,
155 md_leaf_pages: u64,
156 md_overflow_pages: u64,
157 md_entries: u64,
158 md_root: u64,
159 }
160
161 impl Database {
162 fn new(cursor: &mut Cursor<&[u8]>, bits: Bits) -> MigrateResult<Database> {
163 Ok(Database {
164 md_pad: cursor.read_u32::<LittleEndian>()?,
165 md_flags: DatabaseFlags::from_bits(cursor.read_u16::<LittleEndian>()?.into())
166 .ok_or(MigrateError::InvalidDatabaseBits)?,
167 md_depth: cursor.read_u16::<LittleEndian>()?,
168 md_branch_pages: cursor.read_uint::<LittleEndian>(bits.size())?,
169 md_leaf_pages: cursor.read_uint::<LittleEndian>(bits.size())?,
170 md_overflow_pages: cursor.read_uint::<LittleEndian>(bits.size())?,
171 md_entries: cursor.read_uint::<LittleEndian>(bits.size())?,
172 md_root: cursor.read_uint::<LittleEndian>(bits.size())?,
173 })
174 }
175 }
176
177 #[derive(Debug, Default)]
178 struct Databases {
179 free: Database,
180 main: Database,
181 }
182
183 #[derive(Debug, Default)]
184 struct MetaData {
185 mm_magic: u32,
186 mm_version: u32,
187 mm_address: u64,
188 mm_mapsize: u64,
189 mm_dbs: Databases,
190 mm_last_pg: u64,
191 mm_txnid: u64,
192 }
193
194 #[derive(Debug)]
195 enum LeafNode {
196 Regular {
197 mn_lo: u16,
198 mn_hi: u16,
199 mn_flags: NodeFlags,
200 mn_ksize: u16,
201 mv_size: u32,
202 key: Vec<u8>,
203 value: Vec<u8>,
204 },
205 BigData {
206 mn_lo: u16,
207 mn_hi: u16,
208 mn_flags: NodeFlags,
209 mn_ksize: u16,
210 mv_size: u32,
211 key: Vec<u8>,
212 overflow_pgno: u64,
213 },
214 SubData {
215 mn_lo: u16,
216 mn_hi: u16,
217 mn_flags: NodeFlags,
218 mn_ksize: u16,
219 mv_size: u32,
220 key: Vec<u8>,
221 value: Vec<u8>,
222 db: Database,
223 },
224 }
225
226 #[derive(Debug, Default)]
227 struct BranchNode {
228 mp_pgno: u64,
229 mn_ksize: u16,
230 mn_data: Vec<u8>,
231 }
232
233 #[derive(Debug)]
234 enum PageHeader {
235 Regular {
236 mp_pgno: u64,
237 mp_flags: PageFlags,
238 pb_lower: u16,
239 pb_upper: u16,
240 },
241 Overflow {
242 mp_pgno: u64,
243 mp_flags: PageFlags,
244 pb_pages: u32,
245 },
246 }
247
248 #[derive(Debug)]
249 enum Page {
250 META(MetaData),
251 LEAF(Vec<LeafNode>),
252 BRANCH(Vec<BranchNode>),
253 }
254
255 impl Page {
256 fn new(buf: Vec<u8>, bits: Bits) -> MigrateResult<Page> {
257 let mut cursor = std::io::Cursor::new(&buf[..]);
258
259 match Self::parse_page_header(&mut cursor, bits)? {
260 PageHeader::Regular {
261 mp_flags, pb_lower, ..
262 } => {
263 if mp_flags.contains(PageFlags::LEAF2) || mp_flags.contains(PageFlags::SUBP) {
264 // We don't yet support DUPFIXED and DUPSORT databases.
265 return Err(MigrateError::UnsupportedPageHeaderVariant);
266 }
267
268 if mp_flags.contains(PageFlags::META) {
269 let meta_data = Self::parse_meta_data(&mut cursor, bits)?;
270 Ok(Page::META(meta_data))
271 } else if mp_flags.contains(PageFlags::LEAF) {
272 let nodes = Self::parse_leaf_nodes(&mut cursor, pb_lower, bits)?;
273 Ok(Page::LEAF(nodes))
274 } else if mp_flags.contains(PageFlags::BRANCH) {
275 let nodes = Self::parse_branch_nodes(&mut cursor, pb_lower, bits)?;
276 Ok(Page::BRANCH(nodes))
277 } else {
278 Err(MigrateError::UnexpectedPageHeaderVariant)
279 }
280 }
281 PageHeader::Overflow { .. } => {
282 // There isn't anything to do, nor should we try to instantiate
283 // a page of this type, as we only access them when reading
284 // a value that is too large to fit into a leaf node.
285 Err(MigrateError::UnexpectedPageHeaderVariant)
286 }
287 }
288 }
289
290 fn parse_page_header(cursor: &mut Cursor<&[u8]>, bits: Bits) -> MigrateResult<PageHeader> {
291 let mp_pgno = cursor.read_uint::<LittleEndian>(bits.size())?;
292 let _mp_pad = cursor.read_u16::<LittleEndian>()?;
293 let mp_flags = PageFlags::from_bits(cursor.read_u16::<LittleEndian>()?)
294 .ok_or(MigrateError::InvalidPageBits)?;
295
296 if mp_flags.contains(PageFlags::OVERFLOW) {
297 let pb_pages = cursor.read_u32::<LittleEndian>()?;
298 Ok(PageHeader::Overflow {
299 mp_pgno,
300 mp_flags,
301 pb_pages,
302 })
303 } else {
304 let pb_lower = cursor.read_u16::<LittleEndian>()?;
305 let pb_upper = cursor.read_u16::<LittleEndian>()?;
306 Ok(PageHeader::Regular {
307 mp_pgno,
308 mp_flags,
309 pb_lower,
310 pb_upper,
311 })
312 }
313 }
314
315 fn parse_meta_data(cursor: &mut Cursor<&[u8]>, bits: Bits) -> MigrateResult<MetaData> {
316 cursor.seek(SeekFrom::Start(page_header_size(bits)))?;
317
318 Ok(MetaData {
319 mm_magic: cursor.read_u32::<LittleEndian>()?,
320 mm_version: cursor.read_u32::<LittleEndian>()?,
321 mm_address: cursor.read_uint::<LittleEndian>(bits.size())?,
322 mm_mapsize: cursor.read_uint::<LittleEndian>(bits.size())?,
323 mm_dbs: Databases {
324 free: Database::new(cursor, bits)?,
325 main: Database::new(cursor, bits)?,
326 },
327 mm_last_pg: cursor.read_uint::<LittleEndian>(bits.size())?,
328 mm_txnid: cursor.read_uint::<LittleEndian>(bits.size())?,
329 })
330 }
331
332 fn parse_leaf_nodes(
333 cursor: &mut Cursor<&[u8]>,
334 pb_lower: u16,
335 bits: Bits,
336 ) -> MigrateResult<Vec<LeafNode>> {
337 cursor.set_position(page_header_size(bits));
338 let num_keys = Self::num_keys(pb_lower, bits);
339 let mp_ptrs = Self::parse_mp_ptrs(cursor, num_keys)?;
340
341 let mut leaf_nodes = Vec::with_capacity(num_keys as usize);
342
343 for mp_ptr in mp_ptrs {
344 cursor.set_position(u64::from(mp_ptr));
345 leaf_nodes.push(Self::parse_leaf_node(cursor, bits)?);
346 }
347
348 Ok(leaf_nodes)
349 }
350
351 fn parse_leaf_node(cursor: &mut Cursor<&[u8]>, bits: Bits) -> MigrateResult<LeafNode> {
352 // The order of the mn_lo and mn_hi fields is endian-dependent and would be
353 // reversed in an LMDB environment created on a big-endian system.
354 let mn_lo = cursor.read_u16::<LittleEndian>()?;
355 let mn_hi = cursor.read_u16::<LittleEndian>()?;
356
357 let mn_flags = NodeFlags::from_bits(cursor.read_u16::<LittleEndian>()?)
358 .ok_or(MigrateError::InvalidNodeBits)?;
359 let mn_ksize = cursor.read_u16::<LittleEndian>()?;
360
361 let start = usize::try_from(cursor.position())?;
362 let end = usize::try_from(cursor.position() + u64::from(mn_ksize))?;
363 let key = cursor.get_ref()[start..end].to_vec();
364 cursor.set_position(end as u64);
365
366 let mv_size = Self::leaf_node_size(mn_lo, mn_hi);
367 if mn_flags.contains(NodeFlags::BIGDATA) {
368 let overflow_pgno = cursor.read_uint::<LittleEndian>(bits.size())?;
369 Ok(LeafNode::BigData {
370 mn_lo,
371 mn_hi,
372 mn_flags,
373 mn_ksize,
374 mv_size,
375 key,
376 overflow_pgno,
377 })
378 } else if mn_flags.contains(NodeFlags::SUBDATA) {
379 let start = usize::try_from(cursor.position())?;
380 let end = usize::try_from(cursor.position() + u64::from(mv_size))?;
381 let value = cursor.get_ref()[start..end].to_vec();
382 let mut cursor = std::io::Cursor::new(&value[..]);
383 let db = Database::new(&mut cursor, bits)?;
384 validate_page_num(db.md_root, bits)?;
385 Ok(LeafNode::SubData {
386 mn_lo,
387 mn_hi,
388 mn_flags,
389 mn_ksize,
390 mv_size,
391 key,
392 value,
393 db,
394 })
395 } else {
396 let start = usize::try_from(cursor.position())?;
397 let end = usize::try_from(cursor.position() + u64::from(mv_size))?;
398 let value = cursor.get_ref()[start..end].to_vec();
399 Ok(LeafNode::Regular {
400 mn_lo,
401 mn_hi,
402 mn_flags,
403 mn_ksize,
404 mv_size,
405 key,
406 value,
407 })
408 }
409 }
410
411 fn leaf_node_size(mn_lo: u16, mn_hi: u16) -> u32 {
412 u32::from(mn_lo) + ((u32::from(mn_hi)) << 16)
413 }
414
415 fn parse_branch_nodes(
416 cursor: &mut Cursor<&[u8]>,
417 pb_lower: u16,
418 bits: Bits,
419 ) -> MigrateResult<Vec<BranchNode>> {
420 let num_keys = Self::num_keys(pb_lower, bits);
421 let mp_ptrs = Self::parse_mp_ptrs(cursor, num_keys)?;
422
423 let mut branch_nodes = Vec::with_capacity(num_keys as usize);
424
425 for mp_ptr in mp_ptrs {
426 cursor.set_position(u64::from(mp_ptr));
427 branch_nodes.push(Self::parse_branch_node(cursor, bits)?)
428 }
429
430 Ok(branch_nodes)
431 }
432
433 fn parse_branch_node(cursor: &mut Cursor<&[u8]>, bits: Bits) -> MigrateResult<BranchNode> {
434 // The order of the mn_lo and mn_hi fields is endian-dependent and would be
435 // reversed in an LMDB environment created on a big-endian system.
436 let mn_lo = cursor.read_u16::<LittleEndian>()?;
437 let mn_hi = cursor.read_u16::<LittleEndian>()?;
438
439 let mn_flags = cursor.read_u16::<LittleEndian>()?;
440
441 // Branch nodes overload the mn_lo, mn_hi, and mn_flags fields to store the page
442 // number, so we derive the number from those fields.
443 let mp_pgno = Self::branch_node_page_num(mn_lo, mn_hi, mn_flags, bits);
444
445 let mn_ksize = cursor.read_u16::<LittleEndian>()?;
446
447 let position = cursor.position();
448 let start = usize::try_from(position)?;
449 let end = usize::try_from(position + u64::from(mn_ksize))?;
450 let mn_data = cursor.get_ref()[start..end].to_vec();
451 cursor.set_position(end as u64);
452
453 Ok(BranchNode {
454 mp_pgno,
455 mn_ksize,
456 mn_data,
457 })
458 }
459
460 fn branch_node_page_num(mn_lo: u16, mn_hi: u16, mn_flags: u16, bits: Bits) -> u64 {
461 let mut page_num = u64::from(u32::from(mn_lo) + (u32::from(mn_hi) << 16));
462 if bits == Bits::U64 {
463 page_num += u64::from(mn_flags) << 32;
464 }
465 page_num
466 }
467
468 fn parse_mp_ptrs(cursor: &mut Cursor<&[u8]>, num_keys: u64) -> MigrateResult<Vec<u16>> {
469 let mut mp_ptrs = Vec::with_capacity(num_keys as usize);
470 for _ in 0..num_keys {
471 mp_ptrs.push(cursor.read_u16::<LittleEndian>()?);
472 }
473 Ok(mp_ptrs)
474 }
475
476 fn num_keys(pb_lower: u16, bits: Bits) -> u64 {
477 (u64::from(pb_lower) - page_header_size(bits)) >> 1
478 }
479 }
480
481 pub struct Migrator {
482 file: File,
483 bits: Bits,
484 }
485
486 impl Migrator {
487 /// Create a new Migrator for the LMDB environment at the given path. This tries to
488 /// open the data.mdb file in the environment and determine the bit depth of the
489 /// executable that created it, so it can fail and return an Err if the file can't be
490 /// opened or the depth determined.
491 pub fn new(path: &Path) -> MigrateResult<Migrator> {
492 let mut path = PathBuf::from(path);
493 path.push("data.mdb");
494 let mut file = File::open(&path)?;
495
496 file.seek(SeekFrom::Start(page_header_size(Bits::U32)))?;
497 let mut buf = [0; 4];
498 file.read_exact(&mut buf)?;
499
500 let bits = if buf == MAGIC {
501 Bits::U32
502 } else {
503 file.seek(SeekFrom::Start(page_header_size(Bits::U64)))?;
504 file.read_exact(&mut buf)?;
505 if buf == MAGIC {
506 Bits::U64
507 } else {
508 return Err(MigrateError::IndeterminateBitDepth);
509 }
510 };
511
512 Ok(Migrator { file, bits })
513 }
514
515 /// Dump the data in one of the databases in the LMDB environment. If the `database`
516 /// paremeter is None, then we dump the data in the main database. If it's the name
517 /// of a subdatabase, then we dump the data in that subdatabase.
518 ///
519 /// Note that the output isn't identical to that of the `mdb_dump` utility, since
520 /// `mdb_dump` includes subdatabase key/value pairs when dumping the main database,
521 /// and those values are architecture-dependent, since they contain pointer-sized
522 /// data.
523 ///
524 /// If we wanted to support identical output, we could parameterize inclusion of
525 /// subdatabase pairs in get_pairs() and include them when dumping data, while
526 /// continuing to exclude them when migrating data.
527 pub fn dump<T: Write>(&mut self, database: Option<&str>, mut out: T) -> MigrateResult<()> {
528 let meta_data = self.get_meta_data()?;
529 let root_page_num = meta_data.mm_dbs.main.md_root;
530 let root_page = Rc::new(self.get_page(root_page_num)?);
531
532 let pairs;
533 if let Some(database) = database {
534 let subdbs = self.get_subdbs(root_page)?;
535 let database = subdbs
536 .get(database.as_bytes())
537 .ok_or_else(|| MigrateError::DatabaseNotFound(database.to_string()))?;
538 let root_page_num = database.md_root;
539 let root_page = Rc::new(self.get_page(root_page_num)?);
540 pairs = self.get_pairs(root_page)?;
541 } else {
542 pairs = self.get_pairs(root_page)?;
543 }
544
545 out.write_all(b"VERSION=3\n")?;
546 out.write_all(b"format=bytevalue\n")?;
547 if let Some(database) = database {
548 writeln!(out, "database={database}")?;
549 }
550 out.write_all(b"type=btree\n")?;
551 writeln!(out, "mapsize={}", meta_data.mm_mapsize)?;
552 out.write_all(b"maxreaders=126\n")?;
553 out.write_all(b"db_pagesize=4096\n")?;
554 out.write_all(b"HEADER=END\n")?;
555
556 for (key, value) in pairs {
557 out.write_all(b" ")?;
558 for byte in key {
559 write!(out, "{byte:02x}")?;
560 }
561 out.write_all(b"\n")?;
562 out.write_all(b" ")?;
563 for byte in value {
564 write!(out, "{byte:02x}")?;
565 }
566 out.write_all(b"\n")?;
567 }
568
569 out.write_all(b"DATA=END\n")?;
570
571 Ok(())
572 }
573
574 /// Migrate all data in all of databases in the existing LMDB environment to a new
575 /// environment. This includes all key/value pairs in the main database that aren't
576 /// metadata about subdatabases and all key/value pairs in all subdatabases.
577 ///
578 /// We also set the map size and maximum databases of the new environment to their
579 /// values for the existing environment. But we don't set other metadata, and we
580 /// don't check that the new environment is empty before migrating data.
581 ///
582 /// Thus it's possible for this to overwrite existing data or fail to migrate data if
583 /// the new environment isn't empty. It's the consumer's responsibility to ensure
584 /// that data can be safely migrated to the new environment. In general, this means
585 /// that environment should be empty.
586 pub fn migrate(&mut self, dest: &Path) -> MigrateResult<()> {
587 let meta_data = self.get_meta_data()?;
588 let root_page_num = meta_data.mm_dbs.main.md_root;
589 validate_page_num(root_page_num, self.bits)?;
590 let root_page = Rc::new(self.get_page(root_page_num)?);
591 let subdbs = self.get_subdbs(Rc::clone(&root_page))?;
592
593 let env = Environment::new()
594 .set_map_size(meta_data.mm_mapsize as usize)
595 .set_max_dbs(subdbs.len() as u32)
596 .open(dest)?;
597
598 // Create the databases before we open a read-write transaction, since database
599 // creation requires its own read-write transaction, which would hang while
600 // awaiting completion of an existing one.
601 env.create_db(None, meta_data.mm_dbs.main.md_flags)?;
602 for (subdb_name, subdb_info) in &subdbs {
603 env.create_db(Some(str::from_utf8(subdb_name)?), subdb_info.md_flags)?;
604 }
605
606 // Now open the read-write transaction that we'll use to migrate all the data.
607 let mut txn = env.begin_rw_txn()?;
608
609 // Migrate the main database.
610 let pairs = self.get_pairs(root_page)?;
611 let db = env.open_db(None)?;
612 for (key, value) in pairs {
613 // If we knew that the target database was empty, we could specify
614 // WriteFlags::APPEND to speed up the migration.
615 txn.put(db, &key, &value, WriteFlags::empty())?;
616 }
617
618 // Migrate subdatabases.
619 for (subdb_name, subdb_info) in &subdbs {
620 let root_page = Rc::new(self.get_page(subdb_info.md_root)?);
621 let pairs = self.get_pairs(root_page)?;
622 let db = env.open_db(Some(str::from_utf8(subdb_name)?))?;
623 for (key, value) in pairs {
624 // If we knew that the target database was empty, we could specify
625 // WriteFlags::APPEND to speed up the migration.
626 txn.put(db, &key, &value, WriteFlags::empty())?;
627 }
628 }
629
630 txn.commit()?;
631
632 Ok(())
633 }
634
635 fn get_subdbs(&mut self, root_page: Rc<Page>) -> MigrateResult<HashMap<Vec<u8>, Database>> {
636 let mut subdbs = HashMap::new();
637 let mut pages = vec![root_page];
638
639 while let Some(page) = pages.pop() {
640 match &*page {
641 Page::BRANCH(nodes) => {
642 for branch in nodes {
643 pages.push(Rc::new(self.get_page(branch.mp_pgno)?));
644 }
645 }
646 Page::LEAF(nodes) => {
647 for leaf in nodes {
648 if let LeafNode::SubData { key, db, .. } = leaf {
649 subdbs.insert(key.to_vec(), db.clone());
650 };
651 }
652 }
653 _ => {
654 return Err(MigrateError::UnexpectedPageVariant);
655 }
656 }
657 }
658
659 Ok(subdbs)
660 }
661
662 fn get_pairs(&mut self, root_page: Rc<Page>) -> MigrateResult<BTreeMap<Vec<u8>, Vec<u8>>> {
663 let mut pairs = BTreeMap::new();
664 let mut pages = vec![root_page];
665
666 while let Some(page) = pages.pop() {
667 match &*page {
668 Page::BRANCH(nodes) => {
669 for branch in nodes {
670 pages.push(Rc::new(self.get_page(branch.mp_pgno)?));
671 }
672 }
673 Page::LEAF(nodes) => {
674 for leaf in nodes {
675 match leaf {
676 LeafNode::Regular { key, value, .. } => {
677 pairs.insert(key.to_vec(), value.to_vec());
678 }
679 LeafNode::BigData {
680 mv_size,
681 key,
682 overflow_pgno,
683 ..
684 } => {
685 // Perhaps we could reduce memory consumption during a
686 // migration by waiting to read big data until it's time
687 // to write it to the new database.
688 let value = self.read_data(
689 *overflow_pgno * u64::from(PAGESIZE)
690 + page_header_size(self.bits),
691 *mv_size as usize,
692 )?;
693 pairs.insert(key.to_vec(), value);
694 }
695 LeafNode::SubData { .. } => {
696 // We don't include subdatabase leaves in pairs, since
697 // there's no architecture-neutral representation of them,
698 // and in any case they're meta-data that should get
699 // recreated when we migrate the subdatabases themselves.
700 //
701 // If we wanted to create identical dumps to those
702 // produced by `mdb_dump`, however, we could allow
703 // consumers to specify that they'd like to include these
704 // records.
705 }
706 };
707 }
708 }
709 _ => {
710 return Err(MigrateError::UnexpectedPageVariant);
711 }
712 }
713 }
714
715 Ok(pairs)
716 }
717
718 fn read_data(&mut self, offset: u64, size: usize) -> MigrateResult<Vec<u8>> {
719 self.file.seek(SeekFrom::Start(offset))?;
720 let mut buf: Vec<u8> = vec![0; size];
721 self.file.read_exact(&mut buf[0..size])?;
722 Ok(buf.to_vec())
723 }
724
725 fn get_page(&mut self, page_no: u64) -> MigrateResult<Page> {
726 Page::new(
727 self.read_data(page_no * u64::from(PAGESIZE), usize::from(PAGESIZE))?,
728 self.bits,
729 )
730 }
731
732 fn get_meta_data(&mut self) -> MigrateResult<MetaData> {
733 let (page0, page1) = (self.get_page(0)?, self.get_page(1)?);
734
735 match (page0, page1) {
736 (Page::META(meta0), Page::META(meta1)) => {
737 let meta = if meta1.mm_txnid > meta0.mm_txnid {
738 meta1
739 } else {
740 meta0
741 };
742 if meta.mm_magic != 0xBE_EF_C0_DE {
743 return Err(MigrateError::InvalidMagicNum);
744 }
745 if meta.mm_version != 1 && meta.mm_version != 999 {
746 return Err(MigrateError::InvalidDataVersion);
747 }
748 Ok(meta)
749 }
750 _ => Err(MigrateError::UnexpectedPageVariant),
751 }
752 }
753 }
754
755 #[cfg(test)]
756 mod tests {
757 use super::*;
758
759 use std::{env, fs, mem::size_of};
760
761 use lmdb::{Environment, Error as LmdbError};
762 use tempfile::{tempdir, tempfile};
763
764 fn compare_files(ref_file: &mut File, new_file: &mut File) -> MigrateResult<()> {
765 ref_file.seek(SeekFrom::Start(0))?;
766 new_file.seek(SeekFrom::Start(0))?;
767
768 let ref_buf = &mut [0; 1024];
769 let new_buf = &mut [0; 1024];
770
771 loop {
772 match ref_file.read(ref_buf) {
773 Err(err) => panic!("{}", err),
774 Ok(ref_len) => match new_file.read(new_buf) {
775 Err(err) => panic!("{}", err),
776 Ok(new_len) => {
777 assert_eq!(ref_len, new_len);
778 if ref_len == 0 {
779 break;
780 };
781 assert_eq!(ref_buf[0..ref_len], new_buf[0..new_len]);
782 }
783 },
784 }
785 }
786
787 Ok(())
788 }
789
790 #[test]
791 fn test_dump_32() -> MigrateResult<()> {
792 let cwd = env::current_dir()?;
793 let cwd = cwd.to_str().ok_or(MigrateError::StringConversionError)?;
794 let test_env_path: PathBuf = [cwd, "tests", "envs", "ref_env_32"].iter().collect();
795
796 // Dump data from the test env to a new dump file.
797 let mut migrator = Migrator::new(&test_env_path)?;
798 let mut new_dump_file = tempfile()?;
799 migrator.dump(None, &new_dump_file)?;
800
801 // Open the reference dump file.
802 let ref_dump_file_path: PathBuf = [cwd, "tests", "envs", "ref_dump.txt"].iter().collect();
803 let mut ref_dump_file = File::open(ref_dump_file_path)?;
804
805 // Compare the new dump file to the reference dump file.
806 compare_files(&mut ref_dump_file, &mut new_dump_file)?;
807
808 Ok(())
809 }
810
811 #[test]
812 fn test_dump_32_subdb() -> MigrateResult<()> {
813 let cwd = env::current_dir()?;
814 let cwd = cwd.to_str().ok_or(MigrateError::StringConversionError)?;
815 let test_env_path: PathBuf = [cwd, "tests", "envs", "ref_env_32"].iter().collect();
816
817 // Dump data from the test env to a new dump file.
818 let mut migrator = Migrator::new(&test_env_path)?;
819 let mut new_dump_file = tempfile()?;
820 migrator.dump(Some("subdb"), &new_dump_file)?;
821
822 // Open the reference dump file.
823 let ref_dump_file_path: PathBuf = [cwd, "tests", "envs", "ref_dump_subdb.txt"]
824 .iter()
825 .collect();
826 let mut ref_dump_file = File::open(ref_dump_file_path)?;
827
828 // Compare the new dump file to the reference dump file.
829 compare_files(&mut ref_dump_file, &mut new_dump_file)?;
830
831 Ok(())
832 }
833
834 #[test]
835 fn test_dump_64() -> MigrateResult<()> {
836 let cwd = env::current_dir()?;
837 let cwd = cwd.to_str().ok_or(MigrateError::StringConversionError)?;
838 let test_env_path: PathBuf = [cwd, "tests", "envs", "ref_env_64"].iter().collect();
839
840 // Dump data from the test env to a new dump file.
841 let mut migrator = Migrator::new(&test_env_path)?;
842 let mut new_dump_file = tempfile()?;
843 migrator.dump(None, &new_dump_file)?;
844
845 // Open the reference dump file.
846 let ref_dump_file_path: PathBuf = [cwd, "tests", "envs", "ref_dump.txt"].iter().collect();
847 let mut ref_dump_file = File::open(ref_dump_file_path)?;
848
849 // Compare the new dump file to the reference dump file.
850 compare_files(&mut ref_dump_file, &mut new_dump_file)?;
851
852 Ok(())
853 }
854
855 #[test]
856 fn test_dump_64_subdb() -> MigrateResult<()> {
857 let cwd = env::current_dir()?;
858 let cwd = cwd.to_str().ok_or(MigrateError::StringConversionError)?;
859 let test_env_path: PathBuf = [cwd, "tests", "envs", "ref_env_64"].iter().collect();
860
861 // Dump data from the test env to a new dump file.
862 let mut migrator = Migrator::new(&test_env_path)?;
863 let mut new_dump_file = tempfile()?;
864 migrator.dump(Some("subdb"), &new_dump_file)?;
865
866 // Open the reference dump file.
867 let ref_dump_file_path: PathBuf = [cwd, "tests", "envs", "ref_dump_subdb.txt"]
868 .iter()
869 .collect();
870 let mut ref_dump_file = File::open(ref_dump_file_path)?;
871
872 // Compare the new dump file to the reference dump file.
873 compare_files(&mut ref_dump_file, &mut new_dump_file)?;
874
875 Ok(())
876 }
877
878 #[test]
879 fn test_migrate_64() -> MigrateResult<()> {
880 let cwd = env::current_dir()?;
881 let cwd = cwd.to_str().ok_or(MigrateError::StringConversionError)?;
882 let test_env_path: PathBuf = [cwd, "tests", "envs", "ref_env_64"].iter().collect();
883
884 // Migrate data from the old env to a new one.
885 let new_env = tempdir()?;
886 let mut migrator = Migrator::new(&test_env_path)?;
887 migrator.migrate(new_env.path())?;
888
889 // Dump data from the new env to a new dump file.
890 let mut migrator = Migrator::new(new_env.path())?;
891 let mut new_dump_file = tempfile()?;
892 migrator.dump(Some("subdb"), &new_dump_file)?;
893
894 // Open the reference dump file.
895 let ref_dump_file_path: PathBuf = [cwd, "tests", "envs", "ref_dump_subdb.txt"]
896 .iter()
897 .collect();
898 let mut ref_dump_file = File::open(ref_dump_file_path)?;
899
900 // Compare the new dump file to the reference dump file.
901 compare_files(&mut ref_dump_file, &mut new_dump_file)?;
902
903 Ok(())
904 }
905
906 #[test]
907 fn test_migrate_32() -> MigrateResult<()> {
908 let cwd = env::current_dir()?;
909 let cwd = cwd.to_str().ok_or(MigrateError::StringConversionError)?;
910 let test_env_path: PathBuf = [cwd, "tests", "envs", "ref_env_32"].iter().collect();
911
912 // Migrate data from the old env to a new one.
913 let new_env = tempdir()?;
914 let mut migrator = Migrator::new(&test_env_path)?;
915 migrator.migrate(new_env.path())?;
916
917 // Dump data from the new env to a new dump file.
918 let mut migrator = Migrator::new(new_env.path())?;
919 let mut new_dump_file = tempfile()?;
920 migrator.dump(Some("subdb"), &new_dump_file)?;
921
922 // Open the reference dump file.
923 let ref_dump_file_path: PathBuf = [cwd, "tests", "envs", "ref_dump_subdb.txt"]
924 .iter()
925 .collect();
926 let mut ref_dump_file = File::open(ref_dump_file_path)?;
927
928 // Compare the new dump file to the reference dump file.
929 compare_files(&mut ref_dump_file, &mut new_dump_file)?;
930
931 Ok(())
932 }
933
934 #[test]
935 fn test_migrate_and_replace() -> MigrateResult<()> {
936 let test_env_name = match size_of::<usize>() {
937 4 => "ref_env_64",
938 8 => "ref_env_32",
939 _ => panic!("only 32- and 64-bit depths are supported"),
940 };
941
942 let cwd = env::current_dir()?;
943 let cwd = cwd.to_str().ok_or(MigrateError::StringConversionError)?;
944 let test_env_path: PathBuf = [cwd, "tests", "envs", test_env_name].iter().collect();
945
946 let old_env = tempdir()?;
947 fs::copy(
948 test_env_path.join("data.mdb"),
949 old_env.path().join("data.mdb"),
950 )?;
951 fs::copy(
952 test_env_path.join("lock.mdb"),
953 old_env.path().join("lock.mdb"),
954 )?;
955
956 // Confirm that it isn't possible to open the old environment with LMDB.
957 assert_eq!(
958 match Environment::new().open(old_env.path()) {
959 Err(err) => err,
960 _ => panic!("opening the environment should have failed"),
961 },
962 LmdbError::Invalid
963 );
964
965 // Migrate data from the old env to a new one.
966 let new_env = tempdir()?;
967 let mut migrator = Migrator::new(old_env.path())?;
968 migrator.migrate(new_env.path())?;
969
970 // Dump data from the new env to a new dump file.
971 let mut migrator = Migrator::new(new_env.path())?;
972 let mut new_dump_file = tempfile()?;
973 migrator.dump(Some("subdb"), &new_dump_file)?;
974
975 // Open the reference dump file.
976 let ref_dump_file_path: PathBuf = [cwd, "tests", "envs", "ref_dump_subdb.txt"]
977 .iter()
978 .collect();
979 let mut ref_dump_file = File::open(ref_dump_file_path)?;
980
981 // Compare the new dump file to the reference dump file.
982 compare_files(&mut ref_dump_file, &mut new_dump_file)?;
983
984 // Overwrite the old env's files with the new env's files and confirm that it's now
985 // possible to open the old env with LMDB.
986 fs::copy(
987 new_env.path().join("data.mdb"),
988 old_env.path().join("data.mdb"),
989 )?;
990 fs::copy(
991 new_env.path().join("lock.mdb"),
992 old_env.path().join("lock.mdb"),
993 )?;
994 assert!(Environment::new().open(old_env.path()).is_ok());
995
996 Ok(())
997 }
998 }