1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
use crate::snapshot::RocksDBSnapshot;
use crate::transaction::RocksDBTransaction;
use crate::write_batch::RocksDBWriteBatch;
use crate::{internal_error, Result};
use ckb_app_config::DBConfig;
use ckb_db_schema::Col;
use ckb_logger::info;
use rocksdb::ops::{
CompactRangeCF, CreateCF, DropCF, GetColumnFamilys, GetPinned, GetPinnedCF, IterateCF, OpenCF,
Put, SetOptions, WriteOps,
};
use rocksdb::{
ffi, ColumnFamily, ColumnFamilyDescriptor, DBPinnableSlice, FullOptions, IteratorMode,
OptimisticTransactionDB, OptimisticTransactionOptions, Options, WriteBatch, WriteOptions,
};
use std::path::Path;
use std::sync::Arc;
#[derive(Clone)]
pub struct RocksDB {
pub(crate) inner: Arc<OptimisticTransactionDB>,
}
const DEFAULT_CACHE_SIZE: usize = 128 << 20;
impl RocksDB {
pub(crate) fn open_with_check(config: &DBConfig, columns: u32) -> Result<Self> {
let cf_names: Vec<_> = (0..columns).map(|c| c.to_string()).collect();
let (mut opts, cf_descriptors) = if let Some(ref file) = config.options_file {
let cache_size = match config.cache_size {
Some(0) => None,
Some(size) => Some(size),
None => Some(DEFAULT_CACHE_SIZE),
};
let mut full_opts =
FullOptions::load_from_file(file, cache_size, false).map_err(|err| {
internal_error(format!("failed to load the options file: {}", err))
})?;
let cf_names_str: Vec<&str> = cf_names.iter().map(|s| s.as_str()).collect();
full_opts
.complete_column_families(&cf_names_str, false)
.map_err(|err| {
internal_error(format!("failed to check all column families: {}", err))
})?;
let FullOptions {
db_opts,
cf_descriptors,
} = full_opts;
(db_opts, cf_descriptors)
} else {
let opts = Options::default();
let cf_descriptors: Vec<_> = cf_names
.iter()
.map(|ref c| ColumnFamilyDescriptor::new(*c, Options::default()))
.collect();
(opts, cf_descriptors)
};
opts.create_if_missing(true);
opts.create_missing_column_families(true);
let db = OptimisticTransactionDB::open_cf_descriptors(&opts, &config.path, cf_descriptors)
.map_err(|err| internal_error(format!("failed to open database: {}", err)))?;
if !config.options.is_empty() {
let rocksdb_options: Vec<(&str, &str)> = config
.options
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
db.set_options(&rocksdb_options)
.map_err(|_| internal_error("failed to set database option"))?;
}
Ok(RocksDB {
inner: Arc::new(db),
})
}
pub fn repair<P: AsRef<Path>>(path: P) -> Result<()> {
let repair_opts = Options::default();
OptimisticTransactionDB::repair(repair_opts, path)
.map_err(|err| internal_error(format!("failed to repair database: {}", err)))
}
pub fn open(config: &DBConfig, columns: u32) -> Self {
Self::open_with_check(config, columns).unwrap_or_else(|err| panic!("{}", err))
}
pub fn open_in<P: AsRef<Path>>(path: P, columns: u32) -> Self {
let config = DBConfig {
path: path.as_ref().to_path_buf(),
..Default::default()
};
Self::open_with_check(&config, columns).unwrap_or_else(|err| panic!("{}", err))
}
pub fn prepare_for_bulk_load_open<P: AsRef<Path>>(
path: P,
columns: u32,
) -> Result<Option<Self>> {
let mut opts = Options::default();
opts.create_missing_column_families(true);
opts.set_prepare_for_bulk_load();
let cfnames: Vec<_> = (0..columns).map(|c| c.to_string()).collect();
let cf_options: Vec<&str> = cfnames.iter().map(|n| n as &str).collect();
OptimisticTransactionDB::open_cf(&opts, path, &cf_options).map_or_else(
|err| {
let err_str = err.as_ref();
if err_str.starts_with("Invalid argument:")
&& err_str.ends_with("does not exist (create_if_missing is false)")
{
Ok(None)
} else if err_str.starts_with("Corruption:") {
info!(
"DB corrupted: {}.\n\
Try ckb db-repair command to repair DB.\n\
Note: Currently there is a limitation that un-flushed column families will be lost after repair.\
This would happen even if the DB is in healthy state.\n\
See https://github.com/facebook/rocksdb/wiki/RocksDB-Repairer for detail",
err_str
);
Err(internal_error(err_str))
} else {
Err(internal_error(format!(
"failed to open the database: {}",
err
)))
}
},
|db| {
Ok(Some(RocksDB {
inner: Arc::new(db),
}))
},
)
}
pub fn get_pinned(&self, col: Col, key: &[u8]) -> Result<Option<DBPinnableSlice>> {
let cf = cf_handle(&self.inner, col)?;
self.inner.get_pinned_cf(cf, &key).map_err(internal_error)
}
pub fn get_pinned_default(&self, key: &[u8]) -> Result<Option<DBPinnableSlice>> {
self.inner.get_pinned(&key).map_err(internal_error)
}
pub fn put_default<K, V>(&self, key: K, value: V) -> Result<()>
where
K: AsRef<[u8]>,
V: AsRef<[u8]>,
{
self.inner.put(key, value).map_err(internal_error)
}
pub fn full_traverse<F>(&self, col: Col, callback: &mut F) -> Result<()>
where
F: FnMut(&[u8], &[u8]) -> Result<()>,
{
let cf = cf_handle(&self.inner, col)?;
let iter = self
.inner
.full_iterator_cf(cf, IteratorMode::Start)
.map_err(internal_error)?;
for (key, val) in iter {
callback(&key, &val)?;
}
Ok(())
}
pub fn traverse<F>(
&self,
col: Col,
callback: &mut F,
mode: IteratorMode,
limit: usize,
) -> Result<(usize, Vec<u8>)>
where
F: FnMut(&[u8], &[u8]) -> Result<()>,
{
let mut count: usize = 0;
let mut next_key: Vec<u8> = vec![];
let cf = cf_handle(&self.inner, col)?;
let iter = self
.inner
.full_iterator_cf(cf, mode)
.map_err(internal_error)?;
for (key, val) in iter {
if count > limit {
next_key = key.to_vec();
break;
}
callback(&key, &val)?;
count += 1;
}
Ok((count, next_key))
}
pub fn transaction(&self) -> RocksDBTransaction {
let write_options = WriteOptions::default();
let mut transaction_options = OptimisticTransactionOptions::new();
transaction_options.set_snapshot(true);
RocksDBTransaction {
db: Arc::clone(&self.inner),
inner: self.inner.transaction(&write_options, &transaction_options),
}
}
pub fn new_write_batch(&self) -> RocksDBWriteBatch {
RocksDBWriteBatch {
db: Arc::clone(&self.inner),
inner: WriteBatch::default(),
}
}
pub fn write(&self, batch: &RocksDBWriteBatch) -> Result<()> {
self.inner.write(&batch.inner).map_err(internal_error)
}
pub fn write_sync(&self, batch: &RocksDBWriteBatch) -> Result<()> {
let mut wo = WriteOptions::new();
wo.set_sync(true);
self.inner
.write_opt(&batch.inner, &wo)
.map_err(internal_error)
}
pub fn compact_range(&self, col: Col, start: Option<&[u8]>, end: Option<&[u8]>) -> Result<()> {
let cf = cf_handle(&self.inner, col)?;
self.inner.compact_range_cf(&cf, start, end);
Ok(())
}
pub fn get_snapshot(&self) -> RocksDBSnapshot {
unsafe {
let snapshot = ffi::rocksdb_create_snapshot(self.inner.base_db_ptr());
RocksDBSnapshot::new(&self.inner, snapshot)
}
}
pub fn inner(&self) -> Arc<OptimisticTransactionDB> {
Arc::clone(&self.inner)
}
pub fn create_cf(&mut self, col: Col) -> Result<()> {
let inner = Arc::get_mut(&mut self.inner)
.ok_or_else(|| internal_error("create_cf get_mut failed"))?;
let opts = Options::default();
inner.create_cf(col, &opts).map_err(internal_error)
}
pub fn drop_cf(&mut self, col: Col) -> Result<()> {
let inner = Arc::get_mut(&mut self.inner)
.ok_or_else(|| internal_error("drop_cf get_mut failed"))?;
inner.drop_cf(col).map_err(internal_error)
}
}
#[inline]
pub(crate) fn cf_handle(db: &OptimisticTransactionDB, col: Col) -> Result<&ColumnFamily> {
db.cf_handle(col)
.ok_or_else(|| internal_error(format!("column {} not found", col)))
}