openethereum/util/src/journaldb.rs

391 lines
11 KiB
Rust
Raw Normal View History

2016-02-05 13:40:41 +01:00
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
2016-01-18 12:41:31 +01:00
//! Disk-backed HashDB implementation.
use common::*;
use rlp::*;
use hashdb::*;
2016-02-04 02:40:35 +01:00
use memorydb::*;
2016-02-05 01:49:06 +01:00
use rocksdb::{DB, Writable, WriteBatch, IteratorMode};
2016-01-31 17:01:36 +01:00
#[cfg(test)]
use std::env;
2016-01-18 12:41:31 +01:00
/// Implementation of the HashDB trait for a disk-backed database with a memory overlay
/// and latent-removal semantics.
///
/// Like OverlayDB, there is a memory overlay; `commit()` must be called in order to
/// write operations out to disk. Unlike OverlayDB, `remove()` operations do not take effect
/// immediately. Rather some age (based on a linear but arbitrary metric) must pass before
/// the removals actually take effect.
pub struct JournalDB {
2016-02-04 02:40:35 +01:00
overlay: MemoryDB,
2016-01-18 12:41:31 +01:00
backing: Arc<DB>,
2016-02-04 21:33:30 +01:00
counters: Arc<RwLock<HashMap<H256, i32>>>,
2016-01-18 12:41:31 +01:00
}
2016-02-04 21:33:30 +01:00
impl Clone for JournalDB {
fn clone(&self) -> JournalDB {
JournalDB {
overlay: MemoryDB::new(),
backing: self.backing.clone(),
counters: self.counters.clone(),
}
}
}
const LAST_ERA_KEY : [u8; 4] = [ b'l', b'a', b's', b't' ];
2016-02-05 01:49:06 +01:00
const VERSION_KEY : [u8; 4] = [ b'j', b'v', b'e', b'r' ];
const DB_VERSION: u32 = 1;
2016-02-04 21:33:30 +01:00
2016-01-18 12:41:31 +01:00
impl JournalDB {
/// Create a new instance given a `backing` database.
pub fn new(backing: DB) -> JournalDB {
let db = Arc::new(backing);
2016-02-04 21:33:30 +01:00
JournalDB::new_with_arc(db)
2016-01-18 12:41:31 +01:00
}
2016-01-21 23:33:52 +01:00
/// Create a new instance given a shared `backing` database.
pub fn new_with_arc(backing: Arc<DB>) -> JournalDB {
2016-02-05 01:49:06 +01:00
if backing.iterator(IteratorMode::Start).next().is_some() {
match backing.get(&VERSION_KEY).map(|d| d.map(|v| decode::<u32>(&v))) {
Ok(Some(DB_VERSION)) => {},
v => panic!("Incompatible DB version, expected {}, got {:?}", DB_VERSION, v)
}
} else {
backing.put(&VERSION_KEY, &encode(&DB_VERSION)).expect("Error writing version to database");
}
2016-02-04 21:33:30 +01:00
let counters = JournalDB::read_counters(&backing);
2016-01-21 23:33:52 +01:00
JournalDB {
2016-02-04 02:40:35 +01:00
overlay: MemoryDB::new(),
2016-01-21 23:33:52 +01:00
backing: backing,
2016-02-04 21:33:30 +01:00
counters: Arc::new(RwLock::new(counters)),
2016-01-21 23:33:52 +01:00
}
}
2016-01-18 12:41:31 +01:00
/// Create a new instance with an anonymous temporary database.
#[cfg(test)]
2016-01-18 12:41:31 +01:00
pub fn new_temp() -> JournalDB {
let mut dir = env::temp_dir();
dir.push(H32::random().hex());
Self::new(DB::open_default(dir.to_str().unwrap()).unwrap())
}
2016-02-05 01:49:06 +01:00
/// Check if this database has any commits
pub fn is_empty(&self) -> bool {
self.backing.get(&LAST_ERA_KEY).expect("Low level database error").is_none()
}
2016-01-18 12:41:31 +01:00
/// Commit all recent insert operations and historical removals from the old era
/// to the backing database.
2016-02-04 21:33:30 +01:00
#[allow(cyclomatic_complexity)]
2016-01-18 13:54:46 +01:00
pub fn commit(&mut self, now: u64, id: &H256, end: Option<(u64, H256)>) -> Result<u32, UtilError> {
2016-01-18 12:41:31 +01:00
// journal format:
// [era, 0] => [ id, [insert_0, ...], [remove_0, ...] ]
// [era, 1] => [ id, [insert_0, ...], [remove_0, ...] ]
// [era, n] => [ ... ]
2016-02-05 01:49:06 +01:00
// TODO: store reclaim_period.
2016-01-18 12:41:31 +01:00
// when we make a new commit, we journal the inserts and removes.
// for each end_era that we journaled that we are no passing by,
// we remove all of its removes assuming it is canonical and all
// of its inserts otherwise.
// record new commit's details.
2016-02-04 21:33:30 +01:00
let batch = WriteBatch::new();
let mut counters = self.counters.write().unwrap();
2016-01-18 12:41:31 +01:00
{
let mut index = 0usize;
let mut last;
while try!(self.backing.get({
let mut r = RlpStream::new_list(2);
r.append(&now);
r.append(&index);
2016-01-18 15:47:50 +01:00
last = r.drain();
2016-01-18 12:41:31 +01:00
&last
})).is_some() {
index += 1;
}
let mut r = RlpStream::new_list(3);
2016-02-04 02:40:35 +01:00
let inserts: Vec<H256> = self.overlay.keys().iter().filter(|&(_, &c)| c > 0).map(|(key, _)| key.clone()).collect();
2016-02-04 21:33:30 +01:00
for i in &inserts {
*counters.entry(i.clone()).or_insert(0) += 1;
}
2016-02-04 02:40:35 +01:00
let removes: Vec<H256> = self.overlay.keys().iter().filter(|&(_, &c)| c < 0).map(|(key, _)| key.clone()).collect();
2016-01-18 12:41:31 +01:00
r.append(id);
2016-02-04 02:40:35 +01:00
r.append(&inserts);
r.append(&removes);
2016-02-04 21:33:30 +01:00
try!(batch.put(&last, r.as_raw()));
2016-01-18 12:41:31 +01:00
}
// apply old commits' details
2016-01-18 13:30:01 +01:00
if let Some((end_era, canon_id)) = end {
let mut index = 0usize;
let mut last;
while let Some(rlp_data) = try!(self.backing.get({
let mut r = RlpStream::new_list(2);
r.append(&end_era);
r.append(&index);
2016-01-18 15:47:50 +01:00
last = r.drain();
2016-01-18 13:30:01 +01:00
&last
})) {
2016-02-05 02:08:17 +01:00
let to_add;
2016-01-18 13:30:01 +01:00
let rlp = Rlp::new(&rlp_data);
2016-02-04 21:33:30 +01:00
{
2016-02-05 02:08:17 +01:00
to_add = rlp.val_at(1);
2016-02-04 21:33:30 +01:00
for i in &to_add {
let delete_counter = {
if let Some(mut cnt) = counters.get_mut(i) {
*cnt -= 1;
*cnt == 0
}
else { false }
};
if delete_counter {
counters.remove(i);
}
}
}
2016-02-05 02:08:17 +01:00
let to_remove: Vec<H256> = if canon_id == rlp.val_at(0) {rlp.val_at(2)} else {to_add};
2016-01-19 13:47:30 +01:00
for i in &to_remove {
2016-02-04 21:33:30 +01:00
if !counters.contains_key(i) {
batch.delete(&i).expect("Low-level database error. Some issue with your hard disk?");
}
2016-01-18 13:30:01 +01:00
}
2016-02-04 21:33:30 +01:00
try!(batch.delete(&last));
2016-01-18 14:51:49 +01:00
trace!("JournalDB: delete journal for time #{}.{}, (canon was {}): {} entries", end_era, index, canon_id, to_remove.len());
2016-01-18 13:30:01 +01:00
index += 1;
2016-01-18 12:41:31 +01:00
}
2016-02-04 21:33:30 +01:00
try!(batch.put(&LAST_ERA_KEY, &encode(&end_era)));
2016-01-18 12:41:31 +01:00
}
2016-02-04 02:40:35 +01:00
let mut ret = 0u32;
let mut deletes = 0usize;
for i in self.overlay.drain().into_iter() {
let (key, (value, rc)) = i;
if rc > 0 {
assert!(rc == 1);
2016-02-04 21:33:30 +01:00
batch.put(&key.bytes(), &value).expect("Low-level database error. Some issue with your hard disk?");
2016-02-04 02:40:35 +01:00
ret += 1;
}
if rc < 0 {
assert!(rc == -1);
ret += 1;
deletes += 1;
}
}
2016-02-04 21:33:30 +01:00
try!(self.backing.write(batch));
2016-02-04 02:40:35 +01:00
trace!("JournalDB::commit() deleted {} nodes", deletes);
Ok(ret)
}
fn payload(&self, key: &H256) -> Option<Bytes> {
self.backing.get(&key.bytes()).expect("Low-level database error. Some issue with your hard disk?").map(|v| v.to_vec())
2016-01-18 12:41:31 +01:00
}
2016-02-04 21:33:30 +01:00
fn read_counters(db: &DB) -> HashMap<H256, i32> {
let mut res = HashMap::new();
if let Some(val) = db.get(&LAST_ERA_KEY).expect("Low-level database error.") {
let mut era = decode::<u64>(&val) + 1;
loop {
let mut index = 0usize;
while let Some(rlp_data) = db.get({
let mut r = RlpStream::new_list(2);
r.append(&era);
r.append(&index);
&r.drain()
}).expect("Low-level database error.") {
let rlp = Rlp::new(&rlp_data);
let to_add: Vec<H256> = rlp.val_at(1);
for h in to_add {
*res.entry(h).or_insert(0) += 1;
}
index += 1;
};
if index == 0 {
break;
}
era += 1;
}
}
2016-02-05 01:49:06 +01:00
trace!("Recovered {} counters", res.len());
2016-02-04 21:33:30 +01:00
res
}
2016-01-18 12:41:31 +01:00
}
impl HashDB for JournalDB {
2016-02-04 02:40:35 +01:00
fn keys(&self) -> HashMap<H256, i32> {
let mut ret: HashMap<H256, i32> = HashMap::new();
for (key, _) in self.backing.iterator(IteratorMode::Start) {
let h = H256::from_slice(key.deref());
ret.insert(h, 1);
}
for (key, refs) in self.overlay.keys().into_iter() {
let refs = *ret.get(&key).unwrap_or(&0) + refs;
ret.insert(key, refs);
}
ret
}
fn lookup(&self, key: &H256) -> Option<&[u8]> {
let k = self.overlay.raw(key);
match k {
Some(&(ref d, rc)) if rc > 0 => Some(d),
_ => {
if let Some(x) = self.payload(key) {
Some(&self.overlay.denote(key, x).0)
}
else {
None
}
}
}
}
fn exists(&self, key: &H256) -> bool {
self.lookup(key).is_some()
}
fn insert(&mut self, value: &[u8]) -> H256 {
2016-02-04 21:33:30 +01:00
self.overlay.insert(value)
2016-02-04 02:40:35 +01:00
}
fn emplace(&mut self, key: H256, value: Bytes) {
self.overlay.emplace(key, value);
}
fn kill(&mut self, key: &H256) {
2016-02-04 21:33:30 +01:00
self.overlay.kill(key);
}
2016-01-18 12:41:31 +01:00
}
2016-01-18 13:30:01 +01:00
#[cfg(test)]
mod tests {
use common::*;
use super::*;
use hashdb::*;
#[test]
fn long_history() {
// history is 3
let mut jdb = JournalDB::new_temp();
let h = jdb.insert(b"foo");
jdb.commit(0, &b"0".sha3(), None).unwrap();
assert!(jdb.exists(&h));
jdb.remove(&h);
jdb.commit(1, &b"1".sha3(), None).unwrap();
assert!(jdb.exists(&h));
jdb.commit(2, &b"2".sha3(), None).unwrap();
assert!(jdb.exists(&h));
2016-01-18 23:50:40 +01:00
jdb.commit(3, &b"3".sha3(), Some((0, b"0".sha3()))).unwrap();
2016-01-18 13:30:01 +01:00
assert!(jdb.exists(&h));
2016-01-18 23:50:40 +01:00
jdb.commit(4, &b"4".sha3(), Some((1, b"1".sha3()))).unwrap();
2016-01-18 13:30:01 +01:00
assert!(!jdb.exists(&h));
}
#[test]
fn complex() {
// history is 1
let mut jdb = JournalDB::new_temp();
let foo = jdb.insert(b"foo");
let bar = jdb.insert(b"bar");
jdb.commit(0, &b"0".sha3(), None).unwrap();
assert!(jdb.exists(&foo));
assert!(jdb.exists(&bar));
jdb.remove(&foo);
jdb.remove(&bar);
let baz = jdb.insert(b"baz");
2016-01-18 23:50:40 +01:00
jdb.commit(1, &b"1".sha3(), Some((0, b"0".sha3()))).unwrap();
2016-01-18 13:30:01 +01:00
assert!(jdb.exists(&foo));
assert!(jdb.exists(&bar));
assert!(jdb.exists(&baz));
let foo = jdb.insert(b"foo");
jdb.remove(&baz);
2016-01-18 23:50:40 +01:00
jdb.commit(2, &b"2".sha3(), Some((1, b"1".sha3()))).unwrap();
2016-01-18 13:30:01 +01:00
assert!(jdb.exists(&foo));
assert!(!jdb.exists(&bar));
assert!(jdb.exists(&baz));
jdb.remove(&foo);
2016-01-18 23:50:40 +01:00
jdb.commit(3, &b"3".sha3(), Some((2, b"2".sha3()))).unwrap();
2016-01-18 13:30:01 +01:00
assert!(jdb.exists(&foo));
assert!(!jdb.exists(&bar));
assert!(!jdb.exists(&baz));
2016-01-18 23:50:40 +01:00
jdb.commit(4, &b"4".sha3(), Some((3, b"3".sha3()))).unwrap();
2016-01-18 13:30:01 +01:00
assert!(!jdb.exists(&foo));
assert!(!jdb.exists(&bar));
assert!(!jdb.exists(&baz));
}
#[test]
fn fork() {
// history is 1
let mut jdb = JournalDB::new_temp();
let foo = jdb.insert(b"foo");
let bar = jdb.insert(b"bar");
jdb.commit(0, &b"0".sha3(), None).unwrap();
assert!(jdb.exists(&foo));
assert!(jdb.exists(&bar));
jdb.remove(&foo);
let baz = jdb.insert(b"baz");
2016-01-18 23:50:40 +01:00
jdb.commit(1, &b"1a".sha3(), Some((0, b"0".sha3()))).unwrap();
2016-01-18 13:30:01 +01:00
jdb.remove(&bar);
2016-01-18 23:50:40 +01:00
jdb.commit(1, &b"1b".sha3(), Some((0, b"0".sha3()))).unwrap();
2016-01-18 13:30:01 +01:00
assert!(jdb.exists(&foo));
assert!(jdb.exists(&bar));
assert!(jdb.exists(&baz));
2016-01-18 23:50:40 +01:00
jdb.commit(2, &b"2b".sha3(), Some((1, b"1b".sha3()))).unwrap();
2016-01-18 13:30:01 +01:00
assert!(jdb.exists(&foo));
assert!(!jdb.exists(&baz));
assert!(!jdb.exists(&bar));
}
2016-02-04 21:33:30 +01:00
#[test]
fn overwrite() {
// history is 1
let mut jdb = JournalDB::new_temp();
let foo = jdb.insert(b"foo");
jdb.commit(0, &b"0".sha3(), None).unwrap();
assert!(jdb.exists(&foo));
jdb.remove(&foo);
jdb.commit(1, &b"1".sha3(), Some((0, b"0".sha3()))).unwrap();
jdb.insert(b"foo");
assert!(jdb.exists(&foo));
jdb.commit(2, &b"2".sha3(), Some((1, b"1".sha3()))).unwrap();
assert!(jdb.exists(&foo));
jdb.commit(3, &b"2".sha3(), Some((0, b"2".sha3()))).unwrap();
assert!(jdb.exists(&foo));
}
2016-01-18 13:30:01 +01:00
}