Debian Codegraph @

third_party/rust/rkv/src/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
11 //! A simple utility for migrating data from one RVK environment to another. Notably, this
12 //! tool can migrate data from an enviroment created with a different backend than the
13 //! current RKV consumer (e.g from Lmdb to SafeMode).
14 //!
15 //! The utility doesn't support migrating between 32-bit and 64-bit LMDB environments yet,
16 //! see `arch_migrator` if this is needed. However, this utility is ultimately intended to
17 //! handle all possible migrations.
18 //!
19 //! The destination environment should be empty of data, otherwise an error is returned.
20 //!
21 //! There are 3 versions of the migration methods:
22 //! * `migrate_<src>_to_<dst>`, where `<src>` and `<dst>` are the source and destination
23 //! environment types. You're responsive with opening both these environments, handling
24 //! all errors, and performing any cleanup if necessary.
25 //! * `open_and_migrate_<src>_to_<dst>`, which is similar the the above, but automatically
26 //! attempts to open the source environment and delete all of its supporting files if
27 //! there's no other environment open at that path. You're still responsible with
28 //! handling all errors.
29 //! * `easy_migrate_<src>_to_<dst>` which is similar to the above, but ignores the
30 //! migration and doesn't delete any files if the source environment is invalid
31 //! (corrupted), unavailable (path not accessible or incompatible with configuration),
32 //! or empty (database has no records).
33 //!
34 //! The tool currently has these limitations:
35 //!
36 //! 1. It doesn't support migration from environments created with
37 //! `EnvironmentFlags::NO_SUB_DIR`. To migrate such an environment, create a temporary
38 //! directory, copy the environment's data files in the temporary directory, then
39 //! migrate the temporary directory as the source environment.
40 //! 2. It doesn't support migration from databases created with DatabaseFlags::DUP_SORT`
41 //! (with or without `DatabaseFlags::DUP_FIXED`) nor with `DatabaseFlags::INTEGER_KEY`.
42 //! This effectively means that migration is limited to `SingleStore`s.
43 //! 3. It doesn't allow for existing data in the destination environment, which means that
44 //! it cannot overwrite nor append data.
45
46 use crate::{
47 backend::{LmdbEnvironment, SafeModeEnvironment},
48 error::MigrateError,
49 Rkv, StoreOptions,
50 };
51
52 pub use crate::backend::{LmdbArchMigrateError, LmdbArchMigrateResult, LmdbArchMigrator};
53
54 // FIXME: should parametrize this instead.
55
56 macro_rules! fn_migrator {
57 ($name:tt, $src_env:ty, $dst_env:ty) => {
58 /// Migrate all data in all of databases from the source environment to the destination
59 /// environment. This includes all key/value pairs in the main database that aren't
60 /// metadata about subdatabases and all key/value pairs in all subdatabases.
61 ///
62 /// Other backend-specific metadata such as map size or maximum databases left intact on
63 /// the given environments.
64 ///
65 /// The destination environment should be empty of data, otherwise an error is returned.
66 pub fn $name<S, D>(src_env: S, dst_env: D) -> Result<(), MigrateError>
67 where
68 S: std::ops::Deref<Target = Rkv<$src_env>>,
69 D: std::ops::Deref<Target = Rkv<$dst_env>>,
70 {
71 let src_dbs = src_env.get_dbs().unwrap();
72 if src_dbs.is_empty() {
73 return Err(MigrateError::SourceEmpty);
74 }
75 let dst_dbs = dst_env.get_dbs().unwrap();
76 if !dst_dbs.is_empty() {
77 return Err(MigrateError::DestinationNotEmpty);
78 }
79 for name in src_dbs {
80 let src_store = src_env.open_single(name.as_deref(), StoreOptions::default())?;
81 let dst_store = dst_env.open_single(name.as_deref(), StoreOptions::create())?;
82 let reader = src_env.read()?;
83 let mut writer = dst_env.write()?;
84 let mut iter = src_store.iter_start(&reader)?;
85 while let Some(Ok((key, value))) = iter.next() {
86 dst_store.put(&mut writer, key, &value).expect("wrote");
87 }
88 writer.commit()?;
89 }
90 Ok(())
91 }
92 };
93
94 (open $migrate:tt, $name:tt, $builder:tt, $src_env:ty, $dst_env:ty) => {
95 /// Same as the the `migrate_x_to_y` migration method above, but automatically attempts
96 /// to open the source environment. Finally, deletes all of its supporting files if
97 /// there's no other environment open at that path and the migration succeeded.
98 pub fn $name<F, D>(path: &std::path::Path, build: F, dst_env: D) -> Result<(), MigrateError>
99 where
100 F: FnOnce(crate::backend::$builder) -> crate::backend::$builder,
101 D: std::ops::Deref<Target = Rkv<$dst_env>>,
102 {
103 use crate::{backend::*, CloseOptions};
104
105 let mut manager = crate::Manager::<$src_env>::singleton().write()?;
106 let mut builder = Rkv::<$src_env>::environment_builder::<$builder>();
107 builder.set_max_dbs(crate::env::DEFAULT_MAX_DBS);
108 builder = build(builder);
109
110 let src_env =
111 manager.get_or_create_from_builder(path, builder, Rkv::from_builder::<$builder>)?;
112 Migrator::$migrate(src_env.read()?, dst_env)?;
113
114 drop(src_env);
115 manager.try_close(path, CloseOptions::delete_files_on_disk())?;
116
117 Ok(())
118 }
119 };
120
121 (easy $migrate:tt, $name:tt, $src_env:ty, $dst_env:ty) => {
122 /// Same as the `open_and_migrate_x_to_y` migration method above, but ignores the
123 /// migration and doesn't delete any files if the following conditions apply:
124 /// - Source environment is invalid/corrupted, unavailable, or empty.
125 /// - Destination environment is not empty.
126 /// Use this instead of the other migration methods if:
127 /// - You're not concerned by throwing away old data and starting fresh with a new store.
128 /// - You'll never want to overwrite data in the new store from the old store.
129 pub fn $name<D>(path: &std::path::Path, dst_env: D) -> Result<(), MigrateError>
130 where
131 D: std::ops::Deref<Target = Rkv<$dst_env>>,
132 {
133 match Migrator::$migrate(path, |builder| builder, dst_env) {
134 // Source environment is an invalid file or corrupted database.
135 Err(crate::MigrateError::StoreError(crate::StoreError::FileInvalid)) => Ok(()),
136 Err(crate::MigrateError::StoreError(crate::StoreError::DatabaseCorrupted)) => {
137 Ok(())
138 }
139 // Path not accessible.
140 Err(crate::MigrateError::StoreError(crate::StoreError::IoError(_))) => Ok(()),
141 // Path accessible but incompatible for configuration.
142 Err(crate::MigrateError::StoreError(
143 crate::StoreError::UnsuitableEnvironmentPath(_),
144 )) => Ok(()),
145 // Couldn't close source environment and delete files on disk (e.g. other stores still open).
146 Err(crate::MigrateError::CloseError(_)) => Ok(()),
147 // Nothing to migrate.
148 Err(crate::MigrateError::SourceEmpty) => Ok(()),
149 // Migrating would overwrite.
150 Err(crate::MigrateError::DestinationNotEmpty) => Ok(()),
151 result => result,
152 }?;
153
154 Ok(())
155 }
156 };
157 }
158
159 macro_rules! fns_migrator {
160 ($src:tt, $dst:tt) => {
161 paste::item! {
162 fns_migrator!([<migrate_ $src _to_ $dst>], $src, $dst);
163 fns_migrator!([<migrate_ $dst _to_ $src>], $dst, $src);
164 }
165 };
166 ($name:tt, $src:tt, $dst:tt) => {
167 paste::item! {
168 fn_migrator!($name, [<$src:camel Environment>], [<$dst:camel Environment>]);
169 fn_migrator!(open $name, [<open_and_ $name>], [<$src:camel>], [<$src:camel Environment>], [<$dst:camel Environment>]);
170 fn_migrator!(easy [<open_and_ $name>], [<easy_ $name>], [<$src:camel Environment>], [<$dst:camel Environment>]);
171 }
172 };
173 }
174
175 pub struct Migrator;
176
177 impl Migrator {
178 fns_migrator!(lmdb, safe_mode);
179 }