跳至主要内容

LevelDB Source Reading (2): Read Write

LevelDB Source Reading (2): Read Write

Last blog introduces the structure of leveldb, this blog will introduce how leveldb handle reading/writing and some related question.

Reading

Reading Procedure:
  1. check memtable (skiplist)
  2. check immutable memtable
  3. iterate sorted table in different level[0…] to find possible file
  4. using table index ([key => offset]) to find the suitable block via binary search
  5. binary search in restart array to find the last restart point with a key < target
  6. linear search possible entries between two restarting point to check

Step 1 & 2:

// dp_impl.cc

 // First look in the memtable, then in the immutable memtable (if any).
 LookupKey lkey(key, snapshot);
 if (mem->Get(lkey, value, &s)) {
   // Done
 } else if (imm != NULL && imm->Get(lkey, value, &s)) {
   // Done

Step 3:

// version_set.cc: Version::Get

// We can search level-by-level since entries never hop across
// levels.  Therefore we are guaranteed that if we find data
// in an smaller level, later levels are irrelevant.


// Get the list of files to search in this level
// in level 0, iterate all table index
if (level == 0) {
 // Level-0 files may overlap each other.  Find all files that
 // overlap user_key and process them in order from newest to oldest.
 tmp.reserve(num_files);
 for (uint32_t i = 0; i < num_files; i++) {
   FileMetaData* f = files[i];
   if (ucmp->Compare(user_key, f->smallest.user_key()) >= 0 &&
       ucmp->Compare(user_key, f->largest.user_key()) <= 0) {
     tmp.push_back(f);
   }
 }
//...
// in level >= 1
// Binary search to find earliest index whose largest key >= ikey.
// i.e. largest >= ikey > smallest
uint32_t index = FindFile(vset_->icmp_, files_[level], ikey);

Step 4 & 5 & 6 in brief:

// try to find table by number using the mapping of [file_number => TableAndFile]
s = vset_->table_cache_->Get(options, f->number, f->file_size, ikey, &saver, SaveValue);

// table_cached.cc
Status TableCache::Get(...) {
	Status s = FindTable(file_number, file_size, &handle);
	// read from the abstraction of sorted table file
	Table* t = reinterpret_cast<TableAndFile*>(cache_->Value(handle))->table;  
    s = t->InternalGet(options, k, arg, saver);

Step 5 & 6 in detail

// block.cc
virtual void Seek(const Slice& target) {
    // Binary search in restart array to find the last restart point
    // with a key < target
    uint32_t left = 0;
    uint32_t right = num_restarts_ - 1;
    while (left < right) {
      uint32_t mid = (left + right + 1) / 2;
      uint32_t region_offset = GetRestartPoint(mid);
      uint32_t shared, non_shared, value_length;
      const char* key_ptr = DecodeEntry(data_ + region_offset,
                                        data_ + restarts_,
                                        &shared, &non_shared, &value_length);
      if (key_ptr == NULL || (shared != 0)) {
        CorruptionError();
        return;
      }
      Slice mid_key(key_ptr, non_shared);
      if (Compare(mid_key, target) < 0) {
        // Key at "mid" is smaller than "target".  Therefore all
        // blocks before "mid" are uninteresting.
        left = mid;
      } else {
        // Key at "mid" is >= "target".  Therefore all blocks at or
        // after "mid" are uninteresting.
        right = mid - 1;
      }
    }

    // Linear search (within restart block) for first key >= target
    SeekToRestartPoint(left);
    while (true) {
      if (!ParseNextKey()) {
        return;
      }
      if (Compare(key_, target) >= 0) {
        return;
      }
    }
  }

Write

Write Procedure

Adding to log file & memtable (both with sequence number) --> background compaction --> sorted table

Using queue to arrange multi-thread write request
writers_.push_back(&w);
while (!w.done && &w != writers_.front()) {
  w.cv.Wait();
}
Build batch before write
WriteBatch* updates = BuildBatchGroup(&last_writer);
Persist first, then add to memtable (SkipList)
// db_impl.cc

status = log_->AddRecord(WriteBatchInternal::Contents(updates));
bool sync_error = false;
if (status.ok() && options.sync) {
  status = logfile_->Sync();
  if (!status.ok()) {
    sync_error = true;
  }
}
if (status.ok()) {
  status = WriteBatchInternal::InsertInto(updates, mem_);
}

Ref

Written with StackEdit.

评论

此博客中的热门博文

Spring Boot: Customize Environment

Spring Boot: Customize Environment Environment variable is a very commonly used feature in daily programming: used in init script used in startup configuration used by logging etc In Spring Boot, all environment variables are a part of properties in Spring context and managed by Environment abstraction. Because Spring Boot can handle the parse of configuration files, when we want to implement a project which uses yml file as a separate config file, we choose the Spring Boot. The following is the problems we met when we implementing the parse of yml file and it is recorded for future reader. Bind to Class Property values can be injected directly into your beans using the @Value annotation, accessed via Spring’s Environment abstraction or bound to structured objects via @ConfigurationProperties. As the document says, there exists three ways to access properties in *.properties or *.yml : @Value : access single value Environment : can access multi

Elasticsearch: Join and SubQuery

Elasticsearch: Join and SubQuery Tony was bothered by the recent change of search engine requirement: they want the functionality of SQL-like join in Elasticsearch! “They are crazy! How can they think like that. Didn’t they understand that Elasticsearch is kind-of NoSQL 1 in which every index should be independent and self-contained? In this way, every index can work independently and scale as they like without considering other indexes, so the performance can boost. Following this design principle, Elasticsearch has little related supports.” Tony thought, after listening their requirements. Leader notice tony’s unwillingness and said, “Maybe it is hard to do, but the requirement is reasonable. We need to search person by his friends, didn’t we? What’s more, the harder to implement, the more you can learn from it, right?” Tony thought leader’s word does make sense so he set out to do the related implementations Application-Side Join “The first implementation

Learn Spring Expression Language

When reading the source code of some Spring based projects, we can see some code like following: @Value( "${env}" ) private int value ; and like following: @Autowired public void configure (MovieFinder movieFinder, @ Value ("#{ systemProperties[ 'user.region' ] } ") String defaultLocale) { this.movieFinder = movieFinder; this.defaultLocale = defaultLocale; } In this way, we can inject values from different sources very conveniently, and this is the features of Spring EL. What is Spring EL? How to use this handy feature to assist our developments? Today, we are going to learn some basics of Spring EL. Features The full name of Spring EL is Spring Expression Language, which exists in form of Java string and evaluated by Spring. It supports many syntax, from simple property access to complex safe navigation – method invocation when object is not null. And the following is the feature list from Spring EL document :