Learning-Design-and-Coding-From-LevelDB (keep updating)

LevelDB is a fast key-value storage library written at Google by Jeff Dean that provides an ordered mapping from string keys to string values. We could learn design and coding from the source code.

概述

include/leveldb & util

Status

  • include/leveldb/status.h
  • util/status.cc

Status是对每次操作结果的封装, 它只有一个成员变量char* state_来表示状态信息,它包含
三个字段[length, code, message], length表示message的长度,code是返回码,message是状态信息:

  // OK status has a NULL state_.  Otherwise, state_ is a new[] array
  // of the following form:
  //    state_[0..3] == length of message
  //    state_[4]    == code
  //    state_[5..]  == message
  const char* state_;

  enum Code {
    kOk = 0,
    kNotFound = 1,
    kCorruption = 2,
    kNotSupported = 3,
    kInvalidArgument = 4,
    kIOError = 5
  };

  Code code() const {
    return (state_ == NULL) ? kOk : static_cast<Code>(state_[4]);
  }

  const char* Status::CopyState(const char* state) {
    uint32_t size;
    memcpy(&size, state, sizeof(size));
    char* result = new char[size + 5];
    memcpy(result, state, size + 5);
    return result;
  }

这个类对字符串的操作非常精妙,比如上述代码通过memcpy获取message长度信息.

Slice

  • include/leveldb/slice.h

封装数据和其长度,便于直接通过指针操作, 并提供向std::String的转换.

class Slice {
...
private:
  const char* data_;
  size_t size_;
 ...
}

Cache

  • include/leveldb/cache.h
  • utils/cache.cc

overview

Cache一个接口类,提供了有淘汰机制KV的接口,客户代码可以自己定义具体的实现,也可以使用默认的LRUCache,
从下面代码中的注释中可以看出设计思路。

// A Cache is an interface that maps keys to values.  It has internal
// synchronization and may be safely accessed concurrently from
// multiple threads.  It may automatically evict entries to make room
// for new entries.  Values have a specified charge against the cache
// capacity.  For example, a cache where the values are variable
// length strings, may use the length of the string as the charge for
// the string.
//
// A builtin cache implementation with a least-recently-used eviction
// policy is provided.  Clients may use their own implementations if
// they want something more sophisticated (like scan-resistance, a
// custom eviction policy, variable cache sizing, etc.)

// Create a new cache with a fixed size capacity.  This implementation
// of Cache uses a least-recently-used eviction policy.
extern Cache* NewLRUCache(size_t capacity);

class Cache {
 public:
  // Opaque handle to an entry stored in the cache.
  struct Handle { };
  virtual Handle* Insert(const Slice& key, void* value, size_t charge,
                         void (*deleter)(const Slice& key, void* value)) = 0;
  virtual Handle* Lookup(const Slice& key) = 0;
                ... ...

虽然其接口参数有明确,但是数据类型并没有明确而是留给具体实现代码,所以返回类型是

Handle*
struct Handle {};

这就是一个典型的Opaque data type的应用,wikipedia: opaque pointer, wikipedia: opaque data type, stackoverflow: What is an opaque value?

你会发现在cache.h中有一段extern声明,

extern Cache* NewLRUCache(size_t capacity);

在cache.cc中有它的一种实现,

Cache* NewLRUCache(size_t capacity) {
  return new ShardedLRUCache(capacity);
}

通过extern声明(#include “cache.h”), 在链接的时候(链接cache.o)既可以选择cache.cc的默认实现即ShardedLRUCache, 也可以链接自己的实现。

ShardedLRUCache

cache.cc中提供了一个默认的cache实现即ShardedLRUCache, 其组成是LRUCache并基于key进行shard.
LRUCache依赖cache.c中的opaque数据抽象的具体实现LRUHandle和自己实现的一个哈希表HashHandle.
总而言之ShardedLRUCache就是二级hashtable, 其节点就是多个LRUCache.

ShardedLRUCache在bucket分配与key的shard时用一些非常有意思的位操作,代码如下

static const int kNumShardBits = 4;
static const int kNumShards = 1 << kNumShardBits;

LRUCache shard_[kNumShards];

static uint32_t Shard(uint32_t hash) {
  return hash >> (32 - kNumShardBits);
}

kNumShards = 2 ^ kNumShardBits 这个左移代替指数计算好理解,但是shard操作hash >> (32 - kNumShardBits)
这个值得思考,一般会直接余除,但是这样效果会一样吗或者说会均匀分布在kNumShards个bucket中吗?
假设我们考虑4个bit的uint4_t(虽然并没有这样的类型),当kNumShardBits = 1时,bucket数量也就是kNumShards为2,
那么 4 - kNumShardBits = 3,每次Shard的时候右移动3个bit,这时会发现只有bit 3的那个bit右移没有消失(在bit 0),也就是说bit 3的那个bit决定了Shard的value(0 / 1),正好均匀分布在2个bucket上了.
同理对于32bit的uint32_t整型数,其bit分布如下

31 … (32 - kNumShardBits), (32 - kNumShardBits - 1) … 0

如果右移32 - kNumShardBits,只有第一部分kNumShardBits个高位的bit有效,那么正好有2 ^ kNumShardBits 种
可能的值,均匀分布在index为0 - (2 ^ kNumShardBits - 1)的bucket上.
一个简单的Shard对效率都这么苛刻(位操作避免除法),由此可见作者对性能的要求.

LRUCache & LRUHandle & HandleTable

LRUCache由两个循环链表和一个HashTable组成(List+Hash的经典实现),一个链表是连接正在被使用的Node,一个链表连接
不再被使用的Node,HashTable就是使用链表解决Hash碰撞,所以每个Node(即LURHandle包含三个pointer和一个ref),作者
使用了经典的链表操作dummy node和二级指针Linus。Hash值的生成实现请见
Hash & Coding哪一章。

Hash & Coding

util/hash.cc util/hash.h
util/coding.cc util/coding.h
hash.cc提供了一个默认的类似murmurhash的hash值计算的实现,coding.cc中提供了32/64整型数和Slice/String的转换.

env & env_posix

util/env.cc include/leveldb/env.h
util/env_posix.cc

env

env中的接口类Env(虚基类)提供了文件操作的抽象,比如目录操作,日志,文件顺序/随机读取,在Option中可以配置Env使用的实现, leveldb提供了默认的posix标准的实现(具体见下一节).
SequentialFile/RandomAccessFile封装了文件顺序/随机Read和Skip,WritableFile封装了文件的Append/Close/Flush/Sync
操作,Loger则封装了类似变长参数的logv接口(类似vprintf).

env_posix

env_posix是leveldb对Env接口类提供的默认implementation.
Limiter类通过基于RAII的Scope互斥锁和原子操作提供线程安全的计数操作,避免资源过度消耗,比如fd, mmap file数量.
PosixSequentialFile是SequentialFile的子类实现了其Read和Seek接口, 本质就是对fread和seek的wrapper.
PosixRandomAccessFile是RandomAccessFile的子类, 实际是pread() based random-access, 同时包含了Limiter, 不知道为什么Random Accesss为什么需要Limiter.
PosixMmapReadableFile是MmapReadableFile的子类, 实际是mmap() based random-access.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值