上一篇介绍了SkipList数据结构,但leveldb插入数据并不是直接操作SkipList,而是直接操作MemTable。可以理解为MemTable是对SkipList一层封装。
一、数据结构
class MemTable {
public:
// MemTables are reference counted. The initial reference count
// is zero and the caller must call Ref() at least once.
explicit MemTable(const InternalKeyComparator& comparator);
// Increase reference count.
void Ref() { ++refs_; }
// Drop reference count. Delete if no more references exist.
void Unref() {//引用计数器为0时表MemTable没有用了 要删除掉
--refs_;
assert(refs_ >= 0);
if (refs_ <= 0) {
delete this;
}
}
// Returns an estimate of the number of bytes of data in use by this
// data structure. It is safe to call when MemTable is being modified.
size_t ApproximateMemoryUsage();
// Return an iterator that yields the contents of the memtable.
//
// The caller must ensure that the underlying MemTable remains live
// while the returned iterator is live. The keys returned by this
// iterator are internal keys encoded by AppendInternalKey in the
// db/format.{h,cc} module.
Iterator* NewIterator();
// Add an entry into memtable that maps key to value at the
// specified sequence number and with the specified type.
// Typically value will be empty if type==kTypeDeletion.
void Add(SequenceNumber seq, ValueType type,
const Slice& key,
const Slice& value);
// If memtable contains a value for key, store it in *value and return true.
// If memtable contains a deletion for key, store a NotFound() error
// in *status and return true.
// Else, return false.
bool Get(const LookupKey& key, std::string* value, Status* s);
private:
~MemTable(); // Private since only Unref() should be used to delete it
struct KeyComparator {
const InternalKeyComparator comparator;
explicit KeyComparator(const InternalKeyComparator& c) : comparator(c) { }
int operator()(const char* a, const char* b) const;
};
friend class MemTableIterator;
friend class MemTableBackwardIterator;
typedef SkipList<const char*, KeyComparator> Table;
KeyComparator comparator_; // 比较器
int refs_;
Arena arena_;
Table table_; /* 跳表 Table类型重定义typedef */
// No copying allowed
MemTable(const MemTable&);
void operator=(const MemTable&);
};
通过上面数据结构定义可知:
1) 真正常用接口只有插入Put和查询Get
2) 封装了SkipList\比较器\迭代器
3) 通过引用计数器来控制器MemTable对象是否需要释放.以前的文章说明过,leveldb会现将输入插入到MemTable中,当MemTable使用内存达到一定门限后会转变成Immutable MemTable,然后将Immutable MemTable数据写到磁盘中.最后将Immutable MemTable内存释放掉,就是通过Ref进行控制的。
二、添加/删除
添加和删除操作对于MemTable来说都是Add操作,Add方法比较简单,具体函数实现如下:
void MemTable::Add(SequenceNumber s, ValueType type,
const Slice& key,
const Slice& value) {
size_t key_size = key.size();
size_t val_size = value.size();
size_t internal_key_size = key_size + 8;//这里的8是SequenceNumber右移8位 或 操作ValueType
const size_t encoded_len =
VarintLength(internal_key_size) + internal_key_size +
VarintLength(val_size) + val_size;
char* buf = arena_.Allocate(encoded_len);
//添加inernal_key长度及内容
char* p = EncodeVarint32(buf, internal_key_size);
memcpy(p, key.data(), key_size);
p += key_size;
EncodeFixed64(p, (s << 8) | type);//SequenceNumber最高8bit是预留给此处使用
p += 8;
//添加value长度及内容
p = EncodeVarint32(p, val_size);
memcpy(p, value.data(), val_size);
assert((p + val_size) - buf == encoded_len);
//插入到跳表中 比较规则 比较internalkey 可参考InternalKeyComparator::Compare
table_.Insert(buf);
}
说明:
1) 该方法构造一条Record,具体格式如下:
MemTable Record :=
internal_key:
value:
internal_key :=
internalkey-size: varint32
user-key : uint8[key_size]
SequenceNum|Type: fixed64
value :=
user-value_size: varint32
user-value: uint8[value_size]
2) 调用insert接口插入到SkipList中
三、查询
插入逻辑比较简单,接下来介绍查询操作,方法实现如下:
/**
* 查询接口
* @param key 查询key封装了InternalKey
* @param value 输出参数 用户输入value
* @param s 保存状态 当未找到key时 设置为NotFound
*/
bool MemTable::Get(const LookupKey& key, std::string* value, Status* s) {
Slice memkey = key.memtable_key();
Table::Iterator iter(&table_);
iter.Seek(memkey.data());// memkey.data返回的是InternalKey 查找 ./db/skiplist.h
if (iter.Valid()) {
// entry format is:
// klength varint32
// userkey char[klength]
// tag uint64
// vlength varint32
// value char[vlength]
// Check that it belongs to same user key. We do not check the
// sequence number since the Seek() call above should have skipped
// all entries with overly large sequence numbers.
// 由于查询过程中比较的key是按照InternalKey进行比较的, 这里按照user-key再次进行比较
const char* entry = iter.key();
uint32_t key_length;
const char* key_ptr = GetVarint32Ptr(entry, entry+5, &key_length);
if (comparator_.comparator.user_comparator()->Compare(
Slice(key_ptr, key_length - 8),
key.user_key()) == 0) {// 比较用户输入的key是否相等 比较函数util/comparator.cc
// Correct user key
const uint64_t tag = DecodeFixed64(key_ptr + key_length - 8);
switch (static_cast<ValueType>(tag & 0xff)) {
case kTypeValue: {
Slice v = GetLengthPrefixedSlice(key_ptr + key_length);
value->assign(v.data(), v.size());
return true;
}
case kTypeDeletion:
*s = Status::NotFound(Slice());
return true;
}
}
}
return false;
}
说明:
1) 为了处理方便,leveldb在查询的时候引入一个新的对象LookupKey,其内部构造就是InternalKey结构
2) 调用Seek按照InternalKey进行查找,如果没有找到则返回false,否则需要再次进行比较.对InternalKey进行解析,解析出user-key,再次按照user-key进行比较
3) 如果user-key比较相同则认为找到
四、比较器
在进行查找流程时,实际上遍历SkipList,然后在SkipList中进行比较,但是SkipList并没有提供比较器,比较器是由上层MemTable定义的,具体流程图如下:
比较器实现比较简单并且有很多注释,这里将相关代码罗列一下:
template<typename Key, class Comparator>
bool SkipList<Key,Comparator>::KeyIsAfterNode(const Key& key, Node* n) const {
// NULL n is considered infinite
// 这里先调用重载()运算符 MemTable::KeyComparator::operator()
return (n != NULL) && (compare_(n->key, key) < 0);
}
/**
* 重载()运算符
* @param aptr InternalKey格式
* @param bptr InternalKey格式
*/
int MemTable::KeyComparator::operator()(const char* aptr, const char* bptr)
const {
// Internal keys are encoded as length-prefixed strings.
Slice a = GetLengthPrefixedSlice(aptr);
Slice b = GetLengthPrefixedSlice(bptr); //返回值指向InternalKey对象中value部分
return comparator.Compare(a, b);// InternalKeyComparator::Compare db/dbformat.cc
}
int InternalKeyComparator::Compare(const Slice& akey, const Slice& bkey) const {
// Order by:
// increasing user key (according to user-supplied comparator)
// decreasing sequence number
// decreasing type (though sequence# should be enough to disambiguate)
// user key比较
int r = user_comparator_->Compare(ExtractUserKey(akey), ExtractUserKey(bkey));
if (r == 0) {//表示 user key 相同
//这里num应该是SequenceNumber|type type = 0 表示删除 type = 1表示查找或者插入
const uint64_t anum = DecodeFixed64(akey.data() + akey.size() - 8);
const uint64_t bnum = DecodeFixed64(bkey.data() + bkey.size() - 8);
if (anum > bnum) {
r = -1;
} else if (anum < bnum) {
r = +1;
}
}
return r;
}
特别说明:Compare在比较的时候先按照User-Key进行比较,如果User-Key相等则按照Sequence Number|Type比较。这就保证在写入ldb文件时候每一层文件key是有顺序的不重叠的(除level0外)。
五、总结
由于篇幅原因不能把MemTable所有内容都介绍出来,这里只把重点方法介绍了一下,其他方法需要自己阅读源码。