memtable.cc 7.7 KB
Newer Older
J
jorlow@chromium.org 已提交
1 2 3 4 5
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include "db/memtable.h"
J
Jim Paton 已提交
6 7 8

#include <memory>

J
jorlow@chromium.org 已提交
9
#include "db/dbformat.h"
10 11 12
#include "leveldb/comparator.h"
#include "leveldb/env.h"
#include "leveldb/iterator.h"
13
#include "leveldb/merge_operator.h"
J
jorlow@chromium.org 已提交
14 15 16 17 18 19 20 21 22 23 24
#include "util/coding.h"

namespace leveldb {

static Slice GetLengthPrefixedSlice(const char* data) {
  uint32_t len;
  const char* p = data;
  p = GetVarint32Ptr(p, p + 5, &len);  // +5: we assume "p" is not corrupted
  return Slice(p, len);
}

J
Jim Paton 已提交
25 26
MemTable::MemTable(const InternalKeyComparator& cmp,
                   std::shared_ptr<MemTableRepFactory> table_factory,
X
Xing Jin 已提交
27 28
                   int numlevel,
                   const Options& options)
J
jorlow@chromium.org 已提交
29
    : comparator_(cmp),
30
      refs_(0),
X
Xing Jin 已提交
31 32
      arena_impl_(options.arena_block_size),
      table_(table_factory->CreateMemTableRep(comparator_, &arena_impl_)),
33 34
      flush_in_progress_(false),
      flush_completed_(false),
A
Abhishek Kona 已提交
35
      file_number_(0),
36
      edit_(numlevel),
37
      first_seqno_(0),
J
Jim Paton 已提交
38
      mem_logfile_number_(0) { }
J
jorlow@chromium.org 已提交
39 40

MemTable::~MemTable() {
41
  assert(refs_ == 0);
J
jorlow@chromium.org 已提交
42 43
}

J
Jim Paton 已提交
44
size_t MemTable::ApproximateMemoryUsage() {
X
Xing Jin 已提交
45
  return arena_impl_.ApproximateMemoryUsage();
J
Jim Paton 已提交
46
}
J
jorlow@chromium.org 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

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);
  return comparator.Compare(a, b);
}

// Encode a suitable internal key target for "target" and return it.
// Uses *scratch as scratch space, and the returned pointer will point
// into this scratch space.
static const char* EncodeKey(std::string* scratch, const Slice& target) {
  scratch->clear();
  PutVarint32(scratch, target.size());
  scratch->append(target.data(), target.size());
  return scratch->data();
}

class MemTableIterator: public Iterator {
 public:
J
Jim Paton 已提交
68 69 70 71 72 73 74 75 76 77 78 79
  explicit MemTableIterator(MemTableRep* table)
    : iter_(table->GetIterator()) { }

  virtual bool Valid() const { return iter_->Valid(); }
  virtual void Seek(const Slice& k) { iter_->Seek(EncodeKey(&tmp_, k)); }
  virtual void SeekToFirst() { iter_->SeekToFirst(); }
  virtual void SeekToLast() { iter_->SeekToLast(); }
  virtual void Next() { iter_->Next(); }
  virtual void Prev() { iter_->Prev(); }
  virtual Slice key() const {
    return GetLengthPrefixedSlice(iter_->key());
  }
J
jorlow@chromium.org 已提交
80
  virtual Slice value() const {
J
Jim Paton 已提交
81
    Slice key_slice = GetLengthPrefixedSlice(iter_->key());
J
jorlow@chromium.org 已提交
82 83 84 85 86 87
    return GetLengthPrefixedSlice(key_slice.data() + key_slice.size());
  }

  virtual Status status() const { return Status::OK(); }

 private:
J
Jim Paton 已提交
88
  std::shared_ptr<MemTableRep::Iterator> iter_;
J
jorlow@chromium.org 已提交
89 90 91 92 93 94 95 96
  std::string tmp_;       // For passing to EncodeKey

  // No copying allowed
  MemTableIterator(const MemTableIterator&);
  void operator=(const MemTableIterator&);
};

Iterator* MemTable::NewIterator() {
J
Jim Paton 已提交
97
  return new MemTableIterator(table_.get());
J
jorlow@chromium.org 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
}

void MemTable::Add(SequenceNumber s, ValueType type,
                   const Slice& key,
                   const Slice& value) {
  // Format of an entry is concatenation of:
  //  key_size     : varint32 of internal_key.size()
  //  key bytes    : char[internal_key.size()]
  //  value_size   : varint32 of value.size()
  //  value bytes  : char[value.size()]
  size_t key_size = key.size();
  size_t val_size = value.size();
  size_t internal_key_size = key_size + 8;
  const size_t encoded_len =
      VarintLength(internal_key_size) + internal_key_size +
      VarintLength(val_size) + val_size;
X
Xing Jin 已提交
114
  char* buf = arena_impl_.Allocate(encoded_len);
J
jorlow@chromium.org 已提交
115 116 117 118 119 120 121
  char* p = EncodeVarint32(buf, internal_key_size);
  memcpy(p, key.data(), key_size);
  p += key_size;
  EncodeFixed64(p, (s << 8) | type);
  p += 8;
  p = EncodeVarint32(p, val_size);
  memcpy(p, value.data(), val_size);
122
  assert((p + val_size) - buf == (unsigned)encoded_len);
J
Jim Paton 已提交
123
  table_->Insert(buf);
124 125 126 127 128 129

  // The first sequence number inserted into the memtable
  assert(first_seqno_ == 0 || s > first_seqno_);
  if (first_seqno_ == 0) {
    first_seqno_ = s;
  }
J
jorlow@chromium.org 已提交
130 131
}

132
bool MemTable::Get(const LookupKey& key, std::string* value, Status* s,
133
                   std::deque<std::string>* operands, const Options& options) {
134
  Slice memkey = key.memtable_key();
J
Jim Paton 已提交
135 136
  std::shared_ptr<MemTableRep::Iterator> iter(table_.get()->GetIterator());
  iter->Seek(memkey.data());
137

138 139
  // It is the caller's responsibility to allocate/delete operands list
  assert(operands != nullptr);
140

141
  bool merge_in_progress = s->IsMergeInProgress();
142 143
  auto merge_operator = options.merge_operator;
  auto logger = options.info_log;
144 145
  std::string merge_result;

J
Jim Paton 已提交
146
  for (; iter->Valid(); iter->Next()) {
147 148
    // entry format is:
    //    klength  varint32
149
    //    userkey  char[klength-8]
150 151 152 153 154 155
    //    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.
J
Jim Paton 已提交
156
    const char* entry = iter->key();
157 158 159 160 161 162 163 164 165 166
    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) {
      // 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);
167
          *s = Status::OK();
168
          if (merge_in_progress) {
169
            assert(merge_operator);
D
Deon Nicholas 已提交
170 171
            if (!merge_operator->FullMerge(key.user_key(), &v, *operands,
                                           value, logger.get())) {
M
Mayank Agarwal 已提交
172
              RecordTick(options.statistics, NUMBER_MERGE_FAILURES);
173 174
              *s = Status::Corruption("Error: Could not perform merge.");
            }
175 176 177
          } else {
            value->assign(v.data(), v.size());
          }
178 179
          return true;
        }
180 181
        case kTypeDeletion: {
          if (merge_in_progress) {
182 183
            assert(merge_operator);
            *s = Status::OK();
D
Deon Nicholas 已提交
184 185
            if (!merge_operator->FullMerge(key.user_key(), nullptr, *operands,
                                           value, logger.get())) {
M
Mayank Agarwal 已提交
186
              RecordTick(options.statistics, NUMBER_MERGE_FAILURES);
187 188
              *s = Status::Corruption("Error: Could not perform merge.");
            }
189 190 191
          } else {
            *s = Status::NotFound(Slice());
          }
192
          return true;
193
        }
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
        case kTypeMerge: {
          Slice v = GetLengthPrefixedSlice(key_ptr + key_length);
          merge_in_progress = true;
          operands->push_front(v.ToString());
          while(operands->size() >= 2) {
            // Attempt to associative merge. (Returns true if successful)
            if (merge_operator->PartialMerge(key.user_key(),
                                             Slice((*operands)[0]),
                                             Slice((*operands)[1]),
                                             &merge_result,
                                             logger.get())) {
              operands->pop_front();
              swap(operands->front(), merge_result);
            } else {
              // Stack them because user can't associative merge
              break;
            }
          }
          break;
        }
J
Jim Paton 已提交
214 215 216
        case kTypeLogData:
          assert(false);
          break;
217
      }
218 219 220
    } else {
      // exit loop if user key does not match
      break;
221 222
    }
  }
223

224 225
  // No change to value, since we have not yet found a Put/Delete

226 227 228
  if (merge_in_progress) {
    *s = Status::MergeInProgress("");
  }
229 230 231
  return false;
}

H
Hans Wennborg 已提交
232
}  // namespace leveldb