Coverage Report

Created: 2025-07-18 07:11

/src/leveldb/db/db_impl.cc
Line
Count
Source (jump to first uncovered line)
1
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
2
// Use of this source code is governed by a BSD-style license that can be
3
// found in the LICENSE file. See the AUTHORS file for names of contributors.
4
5
#include "db/db_impl.h"
6
7
#include <algorithm>
8
#include <atomic>
9
#include <cstdint>
10
#include <cstdio>
11
#include <set>
12
#include <string>
13
#include <vector>
14
15
#include "db/builder.h"
16
#include "db/db_iter.h"
17
#include "db/dbformat.h"
18
#include "db/filename.h"
19
#include "db/log_reader.h"
20
#include "db/log_writer.h"
21
#include "db/memtable.h"
22
#include "db/table_cache.h"
23
#include "db/version_set.h"
24
#include "db/write_batch_internal.h"
25
#include "leveldb/db.h"
26
#include "leveldb/env.h"
27
#include "leveldb/status.h"
28
#include "leveldb/table.h"
29
#include "leveldb/table_builder.h"
30
#include "port/port.h"
31
#include "table/block.h"
32
#include "table/merger.h"
33
#include "table/two_level_iterator.h"
34
#include "util/coding.h"
35
#include "util/logging.h"
36
#include "util/mutexlock.h"
37
38
namespace leveldb {
39
40
const int kNumNonTableCacheFiles = 10;
41
42
// Information kept for every waiting writer
43
struct DBImpl::Writer {
44
  explicit Writer(port::Mutex* mu)
45
2.10M
      : batch(nullptr), sync(false), done(false), cv(mu) {}
46
47
  Status status;
48
  WriteBatch* batch;
49
  bool sync;
50
  bool done;
51
  port::CondVar cv;
52
};
53
54
struct DBImpl::CompactionState {
55
  // Files produced by compaction
56
  struct Output {
57
    uint64_t number;
58
    uint64_t file_size;
59
    InternalKey smallest, largest;
60
  };
61
62
269k
  Output* current_output() { return &outputs[outputs.size() - 1]; }
63
64
  explicit CompactionState(Compaction* c)
65
27.3k
      : compaction(c),
66
27.3k
        smallest_snapshot(0),
67
27.3k
        outfile(nullptr),
68
27.3k
        builder(nullptr),
69
27.3k
        total_bytes(0) {}
70
71
  Compaction* const compaction;
72
73
  // Sequence numbers < smallest_snapshot are not significant since we
74
  // will never have to service a snapshot below smallest_snapshot.
75
  // Therefore if we have seen a sequence number S <= smallest_snapshot,
76
  // we can drop all entries for the same key with sequence numbers < S.
77
  SequenceNumber smallest_snapshot;
78
79
  std::vector<Output> outputs;
80
81
  // State kept for output being generated
82
  WritableFile* outfile;
83
  TableBuilder* builder;
84
85
  uint64_t total_bytes;
86
};
87
88
// Fix user-supplied options to be reasonable
89
template <class T, class V>
90
471k
static void ClipToRange(T* ptr, V minvalue, V maxvalue) {
91
471k
  if (static_cast<V>(*ptr) > maxvalue) *ptr = maxvalue;
92
471k
  if (static_cast<V>(*ptr) < minvalue) *ptr = minvalue;
93
471k
}
db_impl.cc:void leveldb::ClipToRange<int, int>(int*, int, int)
Line
Count
Source
90
117k
static void ClipToRange(T* ptr, V minvalue, V maxvalue) {
91
117k
  if (static_cast<V>(*ptr) > maxvalue) *ptr = maxvalue;
92
117k
  if (static_cast<V>(*ptr) < minvalue) *ptr = minvalue;
93
117k
}
db_impl.cc:void leveldb::ClipToRange<unsigned long, int>(unsigned long*, int, int)
Line
Count
Source
90
353k
static void ClipToRange(T* ptr, V minvalue, V maxvalue) {
91
353k
  if (static_cast<V>(*ptr) > maxvalue) *ptr = maxvalue;
92
353k
  if (static_cast<V>(*ptr) < minvalue) *ptr = minvalue;
93
353k
}
94
Options SanitizeOptions(const std::string& dbname,
95
                        const InternalKeyComparator* icmp,
96
                        const InternalFilterPolicy* ipolicy,
97
117k
                        const Options& src) {
98
117k
  Options result = src;
99
117k
  result.comparator = icmp;
100
117k
  result.filter_policy = (src.filter_policy != nullptr) ? ipolicy : nullptr;
101
117k
  ClipToRange(&result.max_open_files, 64 + kNumNonTableCacheFiles, 50000);
102
117k
  ClipToRange(&result.write_buffer_size, 64 << 10, 1 << 30);
103
117k
  ClipToRange(&result.max_file_size, 1 << 20, 1 << 30);
104
117k
  ClipToRange(&result.block_size, 1 << 10, 4 << 20);
105
117k
  if (result.info_log == nullptr) {
106
    // Open a log file in the same directory as the db
107
117k
    src.env->CreateDir(dbname);  // In case it does not exist
108
117k
    src.env->RenameFile(InfoLogFileName(dbname), OldInfoLogFileName(dbname));
109
117k
    Status s = src.env->NewLogger(InfoLogFileName(dbname), &result.info_log);
110
117k
    if (!s.ok()) {
111
      // No place suitable for logging
112
0
      result.info_log = nullptr;
113
0
    }
114
117k
  }
115
117k
  if (result.block_cache == nullptr) {
116
117k
    result.block_cache = NewLRUCache(8 << 20);
117
117k
  }
118
117k
  return result;
119
117k
}
120
121
117k
static int TableCacheSize(const Options& sanitized_options) {
122
  // Reserve ten files or so for other uses and give the rest to TableCache.
123
117k
  return sanitized_options.max_open_files - kNumNonTableCacheFiles;
124
117k
}
125
126
DBImpl::DBImpl(const Options& raw_options, const std::string& dbname)
127
117k
    : env_(raw_options.env),
128
117k
      internal_comparator_(raw_options.comparator),
129
117k
      internal_filter_policy_(raw_options.filter_policy),
130
117k
      options_(SanitizeOptions(dbname, &internal_comparator_,
131
117k
                               &internal_filter_policy_, raw_options)),
132
117k
      owns_info_log_(options_.info_log != raw_options.info_log),
133
117k
      owns_cache_(options_.block_cache != raw_options.block_cache),
134
117k
      dbname_(dbname),
135
117k
      table_cache_(new TableCache(dbname_, options_, TableCacheSize(options_))),
136
117k
      db_lock_(nullptr),
137
117k
      shutting_down_(false),
138
117k
      background_work_finished_signal_(&mutex_),
139
117k
      mem_(nullptr),
140
117k
      imm_(nullptr),
141
117k
      has_imm_(false),
142
117k
      logfile_(nullptr),
143
117k
      logfile_number_(0),
144
117k
      log_(nullptr),
145
117k
      seed_(0),
146
117k
      tmp_batch_(new WriteBatch),
147
117k
      background_compaction_scheduled_(false),
148
117k
      manual_compaction_(nullptr),
149
117k
      versions_(new VersionSet(dbname_, &options_, table_cache_,
150
117k
                               &internal_comparator_)) {}
151
152
117k
DBImpl::~DBImpl() {
153
  // Wait for background work to finish.
154
117k
  mutex_.Lock();
155
117k
  shutting_down_.store(true, std::memory_order_release);
156
151k
  while (background_compaction_scheduled_) {
157
33.4k
    background_work_finished_signal_.Wait();
158
33.4k
  }
159
117k
  mutex_.Unlock();
160
161
117k
  if (db_lock_ != nullptr) {
162
117k
    env_->UnlockFile(db_lock_);
163
117k
  }
164
165
117k
  delete versions_;
166
117k
  if (mem_ != nullptr) mem_->Unref();
167
117k
  if (imm_ != nullptr) imm_->Unref();
168
117k
  delete tmp_batch_;
169
117k
  delete log_;
170
117k
  delete logfile_;
171
117k
  delete table_cache_;
172
173
117k
  if (owns_info_log_) {
174
117k
    delete options_.info_log;
175
117k
  }
176
117k
  if (owns_cache_) {
177
117k
    delete options_.block_cache;
178
117k
  }
179
117k
}
180
181
5.38k
Status DBImpl::NewDB() {
182
5.38k
  VersionEdit new_db;
183
5.38k
  new_db.SetComparatorName(user_comparator()->Name());
184
5.38k
  new_db.SetLogNumber(0);
185
5.38k
  new_db.SetNextFile(2);
186
5.38k
  new_db.SetLastSequence(0);
187
188
5.38k
  const std::string manifest = DescriptorFileName(dbname_, 1);
189
5.38k
  WritableFile* file;
190
5.38k
  Status s = env_->NewWritableFile(manifest, &file);
191
5.38k
  if (!s.ok()) {
192
0
    return s;
193
0
  }
194
5.38k
  {
195
5.38k
    log::Writer log(file);
196
5.38k
    std::string record;
197
5.38k
    new_db.EncodeTo(&record);
198
5.38k
    s = log.AddRecord(record);
199
5.38k
    if (s.ok()) {
200
5.38k
      s = file->Sync();
201
5.38k
    }
202
5.38k
    if (s.ok()) {
203
5.38k
      s = file->Close();
204
5.38k
    }
205
5.38k
  }
206
5.38k
  delete file;
207
5.38k
  if (s.ok()) {
208
    // Make "CURRENT" file that points to the new manifest file.
209
5.38k
    s = SetCurrentFile(env_, dbname_, 1);
210
5.38k
  } else {
211
0
    env_->RemoveFile(manifest);
212
0
  }
213
5.38k
  return s;
214
5.38k
}
215
216
1.49M
void DBImpl::MaybeIgnoreError(Status* s) const {
217
1.49M
  if (s->ok() || options_.paranoid_checks) {
218
    // No change needed
219
1.49M
  } else {
220
0
    Log(options_.info_log, "Ignoring error %s", s->ToString().c_str());
221
0
    *s = Status::OK();
222
0
  }
223
1.49M
}
224
225
175k
void DBImpl::RemoveObsoleteFiles() {
226
175k
  mutex_.AssertHeld();
227
228
175k
  if (!bg_error_.ok()) {
229
    // After a background error, we don't know whether a new version may
230
    // or may not have been committed, so we cannot safely garbage collect.
231
7.45k
    return;
232
7.45k
  }
233
234
  // Make a set of all of the live files
235
167k
  std::set<uint64_t> live = pending_outputs_;
236
167k
  versions_->AddLiveFiles(&live);
237
238
167k
  std::vector<std::string> filenames;
239
167k
  env_->GetChildren(dbname_, &filenames);  // Ignoring errors on purpose
240
167k
  uint64_t number;
241
167k
  FileType type;
242
167k
  std::vector<std::string> files_to_delete;
243
2.79M
  for (std::string& filename : filenames) {
244
2.79M
    if (ParseFileName(filename, &number, &type)) {
245
2.45M
      bool keep = true;
246
2.45M
      switch (type) {
247
310k
        case kLogFile:
248
310k
          keep = ((number >= versions_->LogNumber()) ||
249
310k
                  (number == versions_->PrevLogNumber()));
250
310k
          break;
251
285k
        case kDescriptorFile:
252
          // Keep my manifest file, and any newer incarnations'
253
          // (in case there is a race that allows other incarnations)
254
285k
          keep = (number >= versions_->ManifestFileNumber());
255
285k
          break;
256
1.20M
        case kTableFile:
257
1.20M
          keep = (live.find(number) != live.end());
258
1.20M
          break;
259
0
        case kTempFile:
260
          // Any temp files that are currently being written to must
261
          // be recorded in pending_outputs_, which is inserted into "live"
262
0
          keep = (live.find(number) != live.end());
263
0
          break;
264
167k
        case kCurrentFile:
265
335k
        case kDBLockFile:
266
661k
        case kInfoLogFile:
267
661k
          keep = true;
268
661k
          break;
269
2.45M
      }
270
271
2.45M
      if (!keep) {
272
327k
        files_to_delete.push_back(std::move(filename));
273
327k
        if (type == kTableFile) {
274
67.4k
          table_cache_->Evict(number);
275
67.4k
        }
276
327k
        Log(options_.info_log, "Delete type=%d #%lld\n", static_cast<int>(type),
277
327k
            static_cast<unsigned long long>(number));
278
327k
      }
279
2.45M
    }
280
2.79M
  }
281
282
  // While deleting all files unblock other threads. All files being deleted
283
  // have unique names which will not collide with newly created files and
284
  // are therefore safe to delete while allowing other threads to proceed.
285
167k
  mutex_.Unlock();
286
327k
  for (const std::string& filename : files_to_delete) {
287
327k
    env_->RemoveFile(dbname_ + "/" + filename);
288
327k
  }
289
167k
  mutex_.Lock();
290
167k
}
291
292
117k
Status DBImpl::Recover(VersionEdit* edit, bool* save_manifest) {
293
117k
  mutex_.AssertHeld();
294
295
  // Ignore error from CreateDir since the creation of the DB is
296
  // committed only when the descriptor is created, and this directory
297
  // may already exist from a previous failed creation attempt.
298
117k
  env_->CreateDir(dbname_);
299
117k
  assert(db_lock_ == nullptr);
300
117k
  Status s = env_->LockFile(LockFileName(dbname_), &db_lock_);
301
117k
  if (!s.ok()) {
302
0
    return s;
303
0
  }
304
305
117k
  if (!env_->FileExists(CurrentFileName(dbname_))) {
306
5.38k
    if (options_.create_if_missing) {
307
5.38k
      Log(options_.info_log, "Creating DB %s since it was missing.",
308
5.38k
          dbname_.c_str());
309
5.38k
      s = NewDB();
310
5.38k
      if (!s.ok()) {
311
0
        return s;
312
0
      }
313
5.38k
    } else {
314
0
      return Status::InvalidArgument(
315
0
          dbname_, "does not exist (create_if_missing is false)");
316
0
    }
317
112k
  } else {
318
112k
    if (options_.error_if_exists) {
319
0
      return Status::InvalidArgument(dbname_,
320
0
                                     "exists (error_if_exists is true)");
321
0
    }
322
112k
  }
323
324
117k
  s = versions_->Recover(save_manifest);
325
117k
  if (!s.ok()) {
326
0
    return s;
327
0
  }
328
117k
  SequenceNumber max_sequence(0);
329
330
  // Recover from all newer log files than the ones named in the
331
  // descriptor (new log files may have been added by the previous
332
  // incarnation without registering them in the descriptor).
333
  //
334
  // Note that PrevLogNumber() is no longer used, but we pay
335
  // attention to it in case we are recovering a database
336
  // produced by an older version of leveldb.
337
117k
  const uint64_t min_log = versions_->LogNumber();
338
117k
  const uint64_t prev_log = versions_->PrevLogNumber();
339
117k
  std::vector<std::string> filenames;
340
117k
  s = env_->GetChildren(dbname_, &filenames);
341
117k
  if (!s.ok()) {
342
0
    return s;
343
0
  }
344
117k
  std::set<uint64_t> expected;
345
117k
  versions_->AddLiveFiles(&expected);
346
117k
  uint64_t number;
347
117k
  FileType type;
348
117k
  std::vector<uint64_t> logs;
349
1.87M
  for (size_t i = 0; i < filenames.size(); i++) {
350
1.75M
    if (ParseFileName(filenames[i], &number, &type)) {
351
1.51M
      expected.erase(number);
352
1.51M
      if (type == kLogFile && ((number >= min_log) || (number == prev_log)))
353
112k
        logs.push_back(number);
354
1.51M
    }
355
1.75M
  }
356
117k
  if (!expected.empty()) {
357
0
    char buf[50];
358
0
    std::snprintf(buf, sizeof(buf), "%d missing files; e.g.",
359
0
                  static_cast<int>(expected.size()));
360
0
    return Status::Corruption(buf, TableFileName(dbname_, *(expected.begin())));
361
0
  }
362
363
  // Recover in the order in which the logs were generated
364
117k
  std::sort(logs.begin(), logs.end());
365
230k
  for (size_t i = 0; i < logs.size(); i++) {
366
112k
    s = RecoverLogFile(logs[i], (i == logs.size() - 1), save_manifest, edit,
367
112k
                       &max_sequence);
368
112k
    if (!s.ok()) {
369
0
      return s;
370
0
    }
371
372
    // The previous incarnation may not have written any MANIFEST
373
    // records after allocating this log number.  So we manually
374
    // update the file number allocation counter in VersionSet.
375
112k
    versions_->MarkFileNumberUsed(logs[i]);
376
112k
  }
377
378
117k
  if (versions_->LastSequence() < max_sequence) {
379
36.4k
    versions_->SetLastSequence(max_sequence);
380
36.4k
  }
381
382
117k
  return Status::OK();
383
117k
}
384
385
Status DBImpl::RecoverLogFile(uint64_t log_number, bool last_log,
386
                              bool* save_manifest, VersionEdit* edit,
387
112k
                              SequenceNumber* max_sequence) {
388
112k
  struct LogReporter : public log::Reader::Reporter {
389
112k
    Env* env;
390
112k
    Logger* info_log;
391
112k
    const char* fname;
392
112k
    Status* status;  // null if options_.paranoid_checks==false
393
112k
    void Corruption(size_t bytes, const Status& s) override {
394
0
      Log(info_log, "%s%s: dropping %d bytes; %s",
395
0
          (this->status == nullptr ? "(ignoring error) " : ""), fname,
396
0
          static_cast<int>(bytes), s.ToString().c_str());
397
0
      if (this->status != nullptr && this->status->ok()) *this->status = s;
398
0
    }
399
112k
  };
400
401
112k
  mutex_.AssertHeld();
402
403
  // Open the log file
404
112k
  std::string fname = LogFileName(dbname_, log_number);
405
112k
  SequentialFile* file;
406
112k
  Status status = env_->NewSequentialFile(fname, &file);
407
112k
  if (!status.ok()) {
408
0
    MaybeIgnoreError(&status);
409
0
    return status;
410
0
  }
411
412
  // Create the log reader.
413
112k
  LogReporter reporter;
414
112k
  reporter.env = env_;
415
112k
  reporter.info_log = options_.info_log;
416
112k
  reporter.fname = fname.c_str();
417
112k
  reporter.status = (options_.paranoid_checks ? &status : nullptr);
418
  // We intentionally make log::Reader do checksumming even if
419
  // paranoid_checks==false so that corruptions cause entire commits
420
  // to be skipped instead of propagating bad information (like overly
421
  // large sequence numbers).
422
112k
  log::Reader reader(file, &reporter, true /*checksum*/, 0 /*initial_offset*/);
423
112k
  Log(options_.info_log, "Recovering log #%llu",
424
112k
      (unsigned long long)log_number);
425
426
  // Read all the records and add to a memtable
427
112k
  std::string scratch;
428
112k
  Slice record;
429
112k
  WriteBatch batch;
430
112k
  int compactions = 0;
431
112k
  MemTable* mem = nullptr;
432
1.60M
  while (reader.ReadRecord(&record, &scratch) && status.ok()) {
433
1.49M
    if (record.size() < 12) {
434
0
      reporter.Corruption(record.size(),
435
0
                          Status::Corruption("log record too small"));
436
0
      continue;
437
0
    }
438
1.49M
    WriteBatchInternal::SetContents(&batch, record);
439
440
1.49M
    if (mem == nullptr) {
441
43.1k
      mem = new MemTable(internal_comparator_);
442
43.1k
      mem->Ref();
443
43.1k
    }
444
1.49M
    status = WriteBatchInternal::InsertInto(&batch, mem);
445
1.49M
    MaybeIgnoreError(&status);
446
1.49M
    if (!status.ok()) {
447
0
      break;
448
0
    }
449
1.49M
    const SequenceNumber last_seq = WriteBatchInternal::Sequence(&batch) +
450
1.49M
                                    WriteBatchInternal::Count(&batch) - 1;
451
1.49M
    if (last_seq > *max_sequence) {
452
1.49M
      *max_sequence = last_seq;
453
1.49M
    }
454
455
1.49M
    if (mem->ApproximateMemoryUsage() > options_.write_buffer_size) {
456
0
      compactions++;
457
0
      *save_manifest = true;
458
0
      status = WriteLevel0Table(mem, edit, nullptr);
459
0
      mem->Unref();
460
0
      mem = nullptr;
461
0
      if (!status.ok()) {
462
        // Reflect errors immediately so that conditions like full
463
        // file-systems cause the DB::Open() to fail.
464
0
        break;
465
0
      }
466
0
    }
467
1.49M
  }
468
469
112k
  delete file;
470
471
  // See if we should keep reusing the last log file.
472
112k
  if (status.ok() && options_.reuse_logs && last_log && compactions == 0) {
473
0
    assert(logfile_ == nullptr);
474
0
    assert(log_ == nullptr);
475
0
    assert(mem_ == nullptr);
476
0
    uint64_t lfile_size;
477
0
    if (env_->GetFileSize(fname, &lfile_size).ok() &&
478
0
        env_->NewAppendableFile(fname, &logfile_).ok()) {
479
0
      Log(options_.info_log, "Reusing old log %s \n", fname.c_str());
480
0
      log_ = new log::Writer(logfile_, lfile_size);
481
0
      logfile_number_ = log_number;
482
0
      if (mem != nullptr) {
483
0
        mem_ = mem;
484
0
        mem = nullptr;
485
0
      } else {
486
        // mem can be nullptr if lognum exists but was empty.
487
0
        mem_ = new MemTable(internal_comparator_);
488
0
        mem_->Ref();
489
0
      }
490
0
    }
491
0
  }
492
493
112k
  if (mem != nullptr) {
494
    // mem did not get reused; compact it.
495
43.1k
    if (status.ok()) {
496
43.1k
      *save_manifest = true;
497
43.1k
      status = WriteLevel0Table(mem, edit, nullptr);
498
43.1k
    }
499
43.1k
    mem->Unref();
500
43.1k
  }
501
502
112k
  return status;
503
112k
}
504
505
Status DBImpl::WriteLevel0Table(MemTable* mem, VersionEdit* edit,
506
72.9k
                                Version* base) {
507
72.9k
  mutex_.AssertHeld();
508
72.9k
  const uint64_t start_micros = env_->NowMicros();
509
72.9k
  FileMetaData meta;
510
72.9k
  meta.number = versions_->NewFileNumber();
511
72.9k
  pending_outputs_.insert(meta.number);
512
72.9k
  Iterator* iter = mem->NewIterator();
513
72.9k
  Log(options_.info_log, "Level-0 table #%llu: started",
514
72.9k
      (unsigned long long)meta.number);
515
516
72.9k
  Status s;
517
72.9k
  {
518
72.9k
    mutex_.Unlock();
519
72.9k
    s = BuildTable(dbname_, env_, options_, table_cache_, iter, &meta);
520
72.9k
    mutex_.Lock();
521
72.9k
  }
522
523
72.9k
  Log(options_.info_log, "Level-0 table #%llu: %lld bytes %s",
524
72.9k
      (unsigned long long)meta.number, (unsigned long long)meta.file_size,
525
72.9k
      s.ToString().c_str());
526
72.9k
  delete iter;
527
72.9k
  pending_outputs_.erase(meta.number);
528
529
  // Note that if file_size is zero, the file has been deleted and
530
  // should not be added to the manifest.
531
72.9k
  int level = 0;
532
72.9k
  if (s.ok() && meta.file_size > 0) {
533
57.6k
    const Slice min_user_key = meta.smallest.user_key();
534
57.6k
    const Slice max_user_key = meta.largest.user_key();
535
57.6k
    if (base != nullptr) {
536
14.4k
      level = base->PickLevelForMemTableOutput(min_user_key, max_user_key);
537
14.4k
    }
538
57.6k
    edit->AddFile(level, meta.number, meta.file_size, meta.smallest,
539
57.6k
                  meta.largest);
540
57.6k
  }
541
542
72.9k
  CompactionStats stats;
543
72.9k
  stats.micros = env_->NowMicros() - start_micros;
544
72.9k
  stats.bytes_written = meta.file_size;
545
72.9k
  stats_[level].Add(stats);
546
72.9k
  return s;
547
72.9k
}
548
549
29.7k
void DBImpl::CompactMemTable() {
550
29.7k
  mutex_.AssertHeld();
551
29.7k
  assert(imm_ != nullptr);
552
553
  // Save the contents of the memtable as a new Table
554
29.7k
  VersionEdit edit;
555
29.7k
  Version* base = versions_->current();
556
29.7k
  base->Ref();
557
29.7k
  Status s = WriteLevel0Table(imm_, &edit, base);
558
29.7k
  base->Unref();
559
560
29.7k
  if (s.ok() && shutting_down_.load(std::memory_order_acquire)) {
561
0
    s = Status::IOError("Deleting DB during memtable compaction");
562
0
  }
563
564
  // Replace immutable memtable with the generated Table
565
29.7k
  if (s.ok()) {
566
29.7k
    edit.SetPrevLogNumber(0);
567
29.7k
    edit.SetLogNumber(logfile_number_);  // Earlier logs no longer needed
568
29.7k
    s = versions_->LogAndApply(&edit, &mutex_);
569
29.7k
  }
570
571
29.7k
  if (s.ok()) {
572
    // Commit to the new state
573
29.7k
    imm_->Unref();
574
29.7k
    imm_ = nullptr;
575
29.7k
    has_imm_.store(false, std::memory_order_release);
576
29.7k
    RemoveObsoleteFiles();
577
29.7k
  } else {
578
0
    RecordBackgroundError(s);
579
0
  }
580
29.7k
}
581
582
29.7k
void DBImpl::CompactRange(const Slice* begin, const Slice* end) {
583
29.7k
  int max_level_with_files = 1;
584
29.7k
  {
585
29.7k
    MutexLock l(&mutex_);
586
29.7k
    Version* base = versions_->current();
587
208k
    for (int level = 1; level < config::kNumLevels; level++) {
588
178k
      if (base->OverlapInLevel(level, begin, end)) {
589
17.6k
        max_level_with_files = level;
590
17.6k
      }
591
178k
    }
592
29.7k
  }
593
29.7k
  TEST_CompactMemTable();  // TODO(sanjay): Skip if memtable does not overlap
594
70.4k
  for (int level = 0; level < max_level_with_files; level++) {
595
40.7k
    TEST_CompactRange(level, begin, end);
596
40.7k
  }
597
29.7k
}
598
599
void DBImpl::TEST_CompactRange(int level, const Slice* begin,
600
40.7k
                               const Slice* end) {
601
40.7k
  assert(level >= 0);
602
40.7k
  assert(level + 1 < config::kNumLevels);
603
604
40.7k
  InternalKey begin_storage, end_storage;
605
606
40.7k
  ManualCompaction manual;
607
40.7k
  manual.level = level;
608
40.7k
  manual.done = false;
609
40.7k
  if (begin == nullptr) {
610
0
    manual.begin = nullptr;
611
40.7k
  } else {
612
40.7k
    begin_storage = InternalKey(*begin, kMaxSequenceNumber, kValueTypeForSeek);
613
40.7k
    manual.begin = &begin_storage;
614
40.7k
  }
615
40.7k
  if (end == nullptr) {
616
0
    manual.end = nullptr;
617
40.7k
  } else {
618
40.7k
    end_storage = InternalKey(*end, 0, static_cast<ValueType>(0));
619
40.7k
    manual.end = &end_storage;
620
40.7k
  }
621
622
40.7k
  MutexLock l(&mutex_);
623
151k
  while (!manual.done && !shutting_down_.load(std::memory_order_acquire) &&
624
151k
         bg_error_.ok()) {
625
110k
    if (manual_compaction_ == nullptr) {  // Idle
626
54.9k
      manual_compaction_ = &manual;
627
54.9k
      MaybeScheduleCompaction();
628
55.5k
    } else {  // Running either my compaction or another compaction.
629
55.5k
      background_work_finished_signal_.Wait();
630
55.5k
    }
631
110k
  }
632
  // Finish current background compaction in the case where
633
  // `background_work_finished_signal_` was signalled due to an error.
634
40.8k
  while (background_compaction_scheduled_) {
635
150
    background_work_finished_signal_.Wait();
636
150
  }
637
40.7k
  if (manual_compaction_ == &manual) {
638
    // Cancel my manual compaction since we aborted early for some reason.
639
0
    manual_compaction_ = nullptr;
640
0
  }
641
40.7k
}
642
643
29.7k
Status DBImpl::TEST_CompactMemTable() {
644
  // nullptr batch means just wait for earlier writes to be done
645
29.7k
  Status s = Write(WriteOptions(), nullptr);
646
29.7k
  if (s.ok()) {
647
    // Wait until the compaction completes
648
29.7k
    MutexLock l(&mutex_);
649
59.6k
    while (imm_ != nullptr && bg_error_.ok()) {
650
29.9k
      background_work_finished_signal_.Wait();
651
29.9k
    }
652
29.7k
    if (imm_ != nullptr) {
653
0
      s = bg_error_;
654
0
    }
655
29.7k
  }
656
29.7k
  return s;
657
29.7k
}
658
659
14.9k
void DBImpl::RecordBackgroundError(const Status& s) {
660
14.9k
  mutex_.AssertHeld();
661
14.9k
  if (bg_error_.ok()) {
662
7.45k
    bg_error_ = s;
663
7.45k
    background_work_finished_signal_.SignalAll();
664
7.45k
  }
665
14.9k
}
666
667
323k
void DBImpl::MaybeScheduleCompaction() {
668
323k
  mutex_.AssertHeld();
669
323k
  if (background_compaction_scheduled_) {
670
    // Already scheduled
671
320k
  } else if (shutting_down_.load(std::memory_order_acquire)) {
672
    // DB is being deleted; no more background compactions
673
286k
  } else if (!bg_error_.ok()) {
674
    // Already got an error; no more changes
675
286k
  } else if (imm_ == nullptr && manual_compaction_ == nullptr &&
676
286k
             !versions_->NeedsCompaction()) {
677
    // No work to be done
678
166k
  } else {
679
120k
    background_compaction_scheduled_ = true;
680
120k
    env_->Schedule(&DBImpl::BGWork, this);
681
120k
  }
682
323k
}
683
684
120k
void DBImpl::BGWork(void* db) {
685
120k
  reinterpret_cast<DBImpl*>(db)->BackgroundCall();
686
120k
}
687
688
120k
void DBImpl::BackgroundCall() {
689
120k
  MutexLock l(&mutex_);
690
120k
  assert(background_compaction_scheduled_);
691
120k
  if (shutting_down_.load(std::memory_order_acquire)) {
692
    // No more background work when shutting down.
693
105k
  } else if (!bg_error_.ok()) {
694
    // No more background work after a background error.
695
105k
  } else {
696
105k
    BackgroundCompaction();
697
105k
  }
698
699
120k
  background_compaction_scheduled_ = false;
700
701
  // Previous compaction may have produced too many files in a level,
702
  // so reschedule another compaction if needed.
703
120k
  MaybeScheduleCompaction();
704
120k
  background_work_finished_signal_.SignalAll();
705
120k
}
706
707
105k
void DBImpl::BackgroundCompaction() {
708
105k
  mutex_.AssertHeld();
709
710
105k
  if (imm_ != nullptr) {
711
29.6k
    CompactMemTable();
712
29.6k
    return;
713
29.6k
  }
714
715
76.0k
  Compaction* c;
716
76.0k
  bool is_manual = (manual_compaction_ != nullptr);
717
76.0k
  InternalKey manual_end;
718
76.0k
  if (is_manual) {
719
54.9k
    ManualCompaction* m = manual_compaction_;
720
54.9k
    c = versions_->CompactRange(m->level, m->begin, m->end);
721
54.9k
    m->done = (c == nullptr);
722
54.9k
    if (c != nullptr) {
723
14.2k
      manual_end = c->input(0, c->num_input_files(0) - 1)->largest;
724
14.2k
    }
725
54.9k
    Log(options_.info_log,
726
54.9k
        "Manual compaction at level-%d from %s .. %s; will stop at %s\n",
727
54.9k
        m->level, (m->begin ? m->begin->DebugString().c_str() : "(begin)"),
728
54.9k
        (m->end ? m->end->DebugString().c_str() : "(end)"),
729
54.9k
        (m->done ? "(end)" : manual_end.DebugString().c_str()));
730
54.9k
  } else {
731
21.1k
    c = versions_->PickCompaction();
732
21.1k
  }
733
734
76.0k
  Status status;
735
76.0k
  if (c == nullptr) {
736
    // Nothing to do
737
40.7k
  } else if (!is_manual && c->IsTrivialMove()) {
738
    // Move file to next level
739
8.00k
    assert(c->num_input_files(0) == 1);
740
8.00k
    FileMetaData* f = c->input(0, 0);
741
8.00k
    c->edit()->RemoveFile(c->level(), f->number);
742
8.00k
    c->edit()->AddFile(c->level() + 1, f->number, f->file_size, f->smallest,
743
8.00k
                       f->largest);
744
8.00k
    status = versions_->LogAndApply(c->edit(), &mutex_);
745
8.00k
    if (!status.ok()) {
746
0
      RecordBackgroundError(status);
747
0
    }
748
8.00k
    VersionSet::LevelSummaryStorage tmp;
749
8.00k
    Log(options_.info_log, "Moved #%lld to level-%d %lld bytes %s: %s\n",
750
8.00k
        static_cast<unsigned long long>(f->number), c->level() + 1,
751
8.00k
        static_cast<unsigned long long>(f->file_size),
752
8.00k
        status.ToString().c_str(), versions_->LevelSummary(&tmp));
753
27.3k
  } else {
754
27.3k
    CompactionState* compact = new CompactionState(c);
755
27.3k
    status = DoCompactionWork(compact);
756
27.3k
    if (!status.ok()) {
757
7.45k
      RecordBackgroundError(status);
758
7.45k
    }
759
27.3k
    CleanupCompaction(compact);
760
27.3k
    c->ReleaseInputs();
761
27.3k
    RemoveObsoleteFiles();
762
27.3k
  }
763
76.0k
  delete c;
764
765
76.0k
  if (status.ok()) {
766
    // Done
767
68.6k
  } else if (shutting_down_.load(std::memory_order_acquire)) {
768
    // Ignore compaction errors found during shutting down
769
7.45k
  } else {
770
0
    Log(options_.info_log, "Compaction error: %s", status.ToString().c_str());
771
0
  }
772
773
76.0k
  if (is_manual) {
774
54.9k
    ManualCompaction* m = manual_compaction_;
775
54.9k
    if (!status.ok()) {
776
0
      m->done = true;
777
0
    }
778
54.9k
    if (!m->done) {
779
      // We only compacted part of the requested range.  Update *m
780
      // to the range that is left to be compacted.
781
14.2k
      m->tmp_storage = manual_end;
782
14.2k
      m->begin = &m->tmp_storage;
783
14.2k
    }
784
54.9k
    manual_compaction_ = nullptr;
785
54.9k
  }
786
76.0k
}
787
788
27.3k
void DBImpl::CleanupCompaction(CompactionState* compact) {
789
27.3k
  mutex_.AssertHeld();
790
27.3k
  if (compact->builder != nullptr) {
791
    // May happen if we get a shutdown call in the middle of compaction
792
6.92k
    compact->builder->Abandon();
793
6.92k
    delete compact->builder;
794
20.4k
  } else {
795
20.4k
    assert(compact->outfile == nullptr);
796
20.4k
  }
797
27.3k
  delete compact->outfile;
798
49.8k
  for (size_t i = 0; i < compact->outputs.size(); i++) {
799
22.4k
    const CompactionState::Output& out = compact->outputs[i];
800
22.4k
    pending_outputs_.erase(out.number);
801
22.4k
  }
802
27.3k
  delete compact;
803
27.3k
}
804
805
22.4k
Status DBImpl::OpenCompactionOutputFile(CompactionState* compact) {
806
22.4k
  assert(compact != nullptr);
807
22.4k
  assert(compact->builder == nullptr);
808
22.4k
  uint64_t file_number;
809
22.4k
  {
810
22.4k
    mutex_.Lock();
811
22.4k
    file_number = versions_->NewFileNumber();
812
22.4k
    pending_outputs_.insert(file_number);
813
22.4k
    CompactionState::Output out;
814
22.4k
    out.number = file_number;
815
22.4k
    out.smallest.Clear();
816
22.4k
    out.largest.Clear();
817
22.4k
    compact->outputs.push_back(out);
818
22.4k
    mutex_.Unlock();
819
22.4k
  }
820
821
  // Make the output file
822
22.4k
  std::string fname = TableFileName(dbname_, file_number);
823
22.4k
  Status s = env_->NewWritableFile(fname, &compact->outfile);
824
22.4k
  if (s.ok()) {
825
22.4k
    compact->builder = new TableBuilder(options_, compact->outfile);
826
22.4k
  }
827
22.4k
  return s;
828
22.4k
}
829
830
Status DBImpl::FinishCompactionOutputFile(CompactionState* compact,
831
15.5k
                                          Iterator* input) {
832
15.5k
  assert(compact != nullptr);
833
15.5k
  assert(compact->outfile != nullptr);
834
15.5k
  assert(compact->builder != nullptr);
835
836
15.5k
  const uint64_t output_number = compact->current_output()->number;
837
15.5k
  assert(output_number != 0);
838
839
  // Check for iterator errors
840
15.5k
  Status s = input->status();
841
15.5k
  const uint64_t current_entries = compact->builder->NumEntries();
842
15.5k
  if (s.ok()) {
843
15.5k
    s = compact->builder->Finish();
844
15.5k
  } else {
845
0
    compact->builder->Abandon();
846
0
  }
847
15.5k
  const uint64_t current_bytes = compact->builder->FileSize();
848
15.5k
  compact->current_output()->file_size = current_bytes;
849
15.5k
  compact->total_bytes += current_bytes;
850
15.5k
  delete compact->builder;
851
15.5k
  compact->builder = nullptr;
852
853
  // Finish and check for file errors
854
15.5k
  if (s.ok()) {
855
15.5k
    s = compact->outfile->Sync();
856
15.5k
  }
857
15.5k
  if (s.ok()) {
858
15.5k
    s = compact->outfile->Close();
859
15.5k
  }
860
15.5k
  delete compact->outfile;
861
15.5k
  compact->outfile = nullptr;
862
863
15.5k
  if (s.ok() && current_entries > 0) {
864
    // Verify that the table is usable
865
15.5k
    Iterator* iter =
866
15.5k
        table_cache_->NewIterator(ReadOptions(), output_number, current_bytes);
867
15.5k
    s = iter->status();
868
15.5k
    delete iter;
869
15.5k
    if (s.ok()) {
870
15.5k
      Log(options_.info_log, "Generated table #%llu@%d: %lld keys, %lld bytes",
871
15.5k
          (unsigned long long)output_number, compact->compaction->level(),
872
15.5k
          (unsigned long long)current_entries,
873
15.5k
          (unsigned long long)current_bytes);
874
15.5k
    }
875
15.5k
  }
876
15.5k
  return s;
877
15.5k
}
878
879
19.8k
Status DBImpl::InstallCompactionResults(CompactionState* compact) {
880
19.8k
  mutex_.AssertHeld();
881
19.8k
  Log(options_.info_log, "Compacted %d@%d + %d@%d files => %lld bytes",
882
19.8k
      compact->compaction->num_input_files(0), compact->compaction->level(),
883
19.8k
      compact->compaction->num_input_files(1), compact->compaction->level() + 1,
884
19.8k
      static_cast<long long>(compact->total_bytes));
885
886
  // Add compaction outputs
887
19.8k
  compact->compaction->AddInputDeletions(compact->compaction->edit());
888
19.8k
  const int level = compact->compaction->level();
889
35.4k
  for (size_t i = 0; i < compact->outputs.size(); i++) {
890
15.5k
    const CompactionState::Output& out = compact->outputs[i];
891
15.5k
    compact->compaction->edit()->AddFile(level + 1, out.number, out.file_size,
892
15.5k
                                         out.smallest, out.largest);
893
15.5k
  }
894
19.8k
  return versions_->LogAndApply(compact->compaction->edit(), &mutex_);
895
19.8k
}
896
897
27.3k
Status DBImpl::DoCompactionWork(CompactionState* compact) {
898
27.3k
  const uint64_t start_micros = env_->NowMicros();
899
27.3k
  int64_t imm_micros = 0;  // Micros spent doing imm_ compactions
900
901
27.3k
  Log(options_.info_log, "Compacting %d@%d + %d@%d files",
902
27.3k
      compact->compaction->num_input_files(0), compact->compaction->level(),
903
27.3k
      compact->compaction->num_input_files(1),
904
27.3k
      compact->compaction->level() + 1);
905
906
27.3k
  assert(versions_->NumLevelFiles(compact->compaction->level()) > 0);
907
27.3k
  assert(compact->builder == nullptr);
908
27.3k
  assert(compact->outfile == nullptr);
909
27.3k
  if (snapshots_.empty()) {
910
27.3k
    compact->smallest_snapshot = versions_->LastSequence();
911
27.3k
  } else {
912
34
    compact->smallest_snapshot = snapshots_.oldest()->sequence_number();
913
34
  }
914
915
27.3k
  Iterator* input = versions_->MakeInputIterator(compact->compaction);
916
917
  // Release mutex while we're actually doing the compaction work
918
27.3k
  mutex_.Unlock();
919
920
27.3k
  input->SeekToFirst();
921
27.3k
  Status status;
922
27.3k
  ParsedInternalKey ikey;
923
27.3k
  std::string current_user_key;
924
27.3k
  bool has_current_user_key = false;
925
27.3k
  SequenceNumber last_sequence_for_key = kMaxSequenceNumber;
926
1.30M
  while (input->Valid() && !shutting_down_.load(std::memory_order_acquire)) {
927
    // Prioritize immutable compaction work
928
1.27M
    if (has_imm_.load(std::memory_order_relaxed)) {
929
84
      const uint64_t imm_start = env_->NowMicros();
930
84
      mutex_.Lock();
931
84
      if (imm_ != nullptr) {
932
84
        CompactMemTable();
933
        // Wake up MakeRoomForWrite() if necessary.
934
84
        background_work_finished_signal_.SignalAll();
935
84
      }
936
84
      mutex_.Unlock();
937
84
      imm_micros += (env_->NowMicros() - imm_start);
938
84
    }
939
940
1.27M
    Slice key = input->key();
941
1.27M
    if (compact->compaction->ShouldStopBefore(key) &&
942
1.27M
        compact->builder != nullptr) {
943
0
      status = FinishCompactionOutputFile(compact, input);
944
0
      if (!status.ok()) {
945
0
        break;
946
0
      }
947
0
    }
948
949
    // Handle key/value, add to state, etc.
950
1.27M
    bool drop = false;
951
1.27M
    if (!ParseInternalKey(key, &ikey)) {
952
      // Do not hide error keys
953
0
      current_user_key.clear();
954
0
      has_current_user_key = false;
955
0
      last_sequence_for_key = kMaxSequenceNumber;
956
1.27M
    } else {
957
1.27M
      if (!has_current_user_key ||
958
1.27M
          user_comparator()->Compare(ikey.user_key, Slice(current_user_key)) !=
959
1.25M
              0) {
960
        // First occurrence of this user key
961
242k
        current_user_key.assign(ikey.user_key.data(), ikey.user_key.size());
962
242k
        has_current_user_key = true;
963
242k
        last_sequence_for_key = kMaxSequenceNumber;
964
242k
      }
965
966
1.27M
      if (last_sequence_for_key <= compact->smallest_snapshot) {
967
        // Hidden by an newer entry for same user key
968
1.03M
        drop = true;  // (A)
969
1.03M
      } else if (ikey.type == kTypeDeletion &&
970
242k
                 ikey.sequence <= compact->smallest_snapshot &&
971
242k
                 compact->compaction->IsBaseLevelForKey(ikey.user_key)) {
972
        // For this user key:
973
        // (1) there is no data in higher levels
974
        // (2) data in lower levels will have larger sequence numbers
975
        // (3) data in layers that are being compacted here and have
976
        //     smaller sequence numbers will be dropped in the next
977
        //     few iterations of this loop (by rule (A) above).
978
        // Therefore this deletion marker is obsolete and can be dropped.
979
26.9k
        drop = true;
980
26.9k
      }
981
982
1.27M
      last_sequence_for_key = ikey.sequence;
983
1.27M
    }
984
#if 0
985
    Log(options_.info_log,
986
        "  Compact: %s, seq %d, type: %d %d, drop: %d, is_base: %d, "
987
        "%d smallest_snapshot: %d",
988
        ikey.user_key.ToString().c_str(),
989
        (int)ikey.sequence, ikey.type, kTypeValue, drop,
990
        compact->compaction->IsBaseLevelForKey(ikey.user_key),
991
        (int)last_sequence_for_key, (int)compact->smallest_snapshot);
992
#endif
993
994
1.27M
    if (!drop) {
995
      // Open output file if necessary
996
215k
      if (compact->builder == nullptr) {
997
22.4k
        status = OpenCompactionOutputFile(compact);
998
22.4k
        if (!status.ok()) {
999
0
          break;
1000
0
        }
1001
22.4k
      }
1002
215k
      if (compact->builder->NumEntries() == 0) {
1003
22.4k
        compact->current_output()->smallest.DecodeFrom(key);
1004
22.4k
      }
1005
215k
      compact->current_output()->largest.DecodeFrom(key);
1006
215k
      compact->builder->Add(key, input->value());
1007
1008
      // Close output file if it is big enough
1009
215k
      if (compact->builder->FileSize() >=
1010
215k
          compact->compaction->MaxOutputFileSize()) {
1011
0
        status = FinishCompactionOutputFile(compact, input);
1012
0
        if (!status.ok()) {
1013
0
          break;
1014
0
        }
1015
0
      }
1016
215k
    }
1017
1018
1.27M
    input->Next();
1019
1.27M
  }
1020
1021
27.3k
  if (status.ok() && shutting_down_.load(std::memory_order_acquire)) {
1022
7.45k
    status = Status::IOError("Deleting DB during compaction");
1023
7.45k
  }
1024
27.3k
  if (status.ok() && compact->builder != nullptr) {
1025
15.5k
    status = FinishCompactionOutputFile(compact, input);
1026
15.5k
  }
1027
27.3k
  if (status.ok()) {
1028
19.8k
    status = input->status();
1029
19.8k
  }
1030
27.3k
  delete input;
1031
27.3k
  input = nullptr;
1032
1033
27.3k
  CompactionStats stats;
1034
27.3k
  stats.micros = env_->NowMicros() - start_micros - imm_micros;
1035
82.0k
  for (int which = 0; which < 2; which++) {
1036
161k
    for (int i = 0; i < compact->compaction->num_input_files(which); i++) {
1037
107k
      stats.bytes_read += compact->compaction->input(which, i)->file_size;
1038
107k
    }
1039
54.6k
  }
1040
49.8k
  for (size_t i = 0; i < compact->outputs.size(); i++) {
1041
22.4k
    stats.bytes_written += compact->outputs[i].file_size;
1042
22.4k
  }
1043
1044
27.3k
  mutex_.Lock();
1045
27.3k
  stats_[compact->compaction->level() + 1].Add(stats);
1046
1047
27.3k
  if (status.ok()) {
1048
19.8k
    status = InstallCompactionResults(compact);
1049
19.8k
  }
1050
27.3k
  if (!status.ok()) {
1051
7.45k
    RecordBackgroundError(status);
1052
7.45k
  }
1053
27.3k
  VersionSet::LevelSummaryStorage tmp;
1054
27.3k
  Log(options_.info_log, "compacted to: %s", versions_->LevelSummary(&tmp));
1055
27.3k
  return status;
1056
27.3k
}
1057
1058
namespace {
1059
1060
struct IterState {
1061
  port::Mutex* const mu;
1062
  Version* const version GUARDED_BY(mu);
1063
  MemTable* const mem GUARDED_BY(mu);
1064
  MemTable* const imm GUARDED_BY(mu);
1065
1066
  IterState(port::Mutex* mutex, MemTable* mem, MemTable* imm, Version* version)
1067
148k
      : mu(mutex), version(version), mem(mem), imm(imm) {}
1068
};
1069
1070
148k
static void CleanupIteratorState(void* arg1, void* arg2) {
1071
148k
  IterState* state = reinterpret_cast<IterState*>(arg1);
1072
148k
  state->mu->Lock();
1073
148k
  state->mem->Unref();
1074
148k
  if (state->imm != nullptr) state->imm->Unref();
1075
148k
  state->version->Unref();
1076
148k
  state->mu->Unlock();
1077
148k
  delete state;
1078
148k
}
1079
1080
}  // anonymous namespace
1081
1082
Iterator* DBImpl::NewInternalIterator(const ReadOptions& options,
1083
                                      SequenceNumber* latest_snapshot,
1084
148k
                                      uint32_t* seed) {
1085
148k
  mutex_.Lock();
1086
148k
  *latest_snapshot = versions_->LastSequence();
1087
1088
  // Collect together all needed child iterators
1089
148k
  std::vector<Iterator*> list;
1090
148k
  list.push_back(mem_->NewIterator());
1091
148k
  mem_->Ref();
1092
148k
  if (imm_ != nullptr) {
1093
0
    list.push_back(imm_->NewIterator());
1094
0
    imm_->Ref();
1095
0
  }
1096
148k
  versions_->current()->AddIterators(options, &list);
1097
148k
  Iterator* internal_iter =
1098
148k
      NewMergingIterator(&internal_comparator_, &list[0], list.size());
1099
148k
  versions_->current()->Ref();
1100
1101
148k
  IterState* cleanup = new IterState(&mutex_, mem_, imm_, versions_->current());
1102
148k
  internal_iter->RegisterCleanup(CleanupIteratorState, cleanup, nullptr);
1103
1104
148k
  *seed = ++seed_;
1105
148k
  mutex_.Unlock();
1106
148k
  return internal_iter;
1107
148k
}
1108
1109
0
Iterator* DBImpl::TEST_NewInternalIterator() {
1110
0
  SequenceNumber ignored;
1111
0
  uint32_t ignored_seed;
1112
0
  return NewInternalIterator(ReadOptions(), &ignored, &ignored_seed);
1113
0
}
1114
1115
0
int64_t DBImpl::TEST_MaxNextLevelOverlappingBytes() {
1116
0
  MutexLock l(&mutex_);
1117
0
  return versions_->MaxNextLevelOverlappingBytes();
1118
0
}
1119
1120
Status DBImpl::Get(const ReadOptions& options, const Slice& key,
1121
46.5k
                   std::string* value) {
1122
46.5k
  Status s;
1123
46.5k
  MutexLock l(&mutex_);
1124
46.5k
  SequenceNumber snapshot;
1125
46.5k
  if (options.snapshot != nullptr) {
1126
0
    snapshot =
1127
0
        static_cast<const SnapshotImpl*>(options.snapshot)->sequence_number();
1128
46.5k
  } else {
1129
46.5k
    snapshot = versions_->LastSequence();
1130
46.5k
  }
1131
1132
46.5k
  MemTable* mem = mem_;
1133
46.5k
  MemTable* imm = imm_;
1134
46.5k
  Version* current = versions_->current();
1135
46.5k
  mem->Ref();
1136
46.5k
  if (imm != nullptr) imm->Ref();
1137
46.5k
  current->Ref();
1138
1139
46.5k
  bool have_stat_update = false;
1140
46.5k
  Version::GetStats stats;
1141
1142
  // Unlock while reading from files and memtables
1143
46.5k
  {
1144
46.5k
    mutex_.Unlock();
1145
    // First look in the memtable, then in the immutable memtable (if any).
1146
46.5k
    LookupKey lkey(key, snapshot);
1147
46.5k
    if (mem->Get(lkey, value, &s)) {
1148
      // Done
1149
39.8k
    } else if (imm != nullptr && imm->Get(lkey, value, &s)) {
1150
      // Done
1151
39.8k
    } else {
1152
39.8k
      s = current->Get(options, lkey, value, &stats);
1153
39.8k
      have_stat_update = true;
1154
39.8k
    }
1155
46.5k
    mutex_.Lock();
1156
46.5k
  }
1157
1158
46.5k
  if (have_stat_update && current->UpdateStats(stats)) {
1159
43
    MaybeScheduleCompaction();
1160
43
  }
1161
46.5k
  mem->Unref();
1162
46.5k
  if (imm != nullptr) imm->Unref();
1163
46.5k
  current->Unref();
1164
46.5k
  return s;
1165
46.5k
}
1166
1167
148k
Iterator* DBImpl::NewIterator(const ReadOptions& options) {
1168
148k
  SequenceNumber latest_snapshot;
1169
148k
  uint32_t seed;
1170
148k
  Iterator* iter = NewInternalIterator(options, &latest_snapshot, &seed);
1171
148k
  return NewDBIterator(this, user_comparator(), iter,
1172
148k
                       (options.snapshot != nullptr
1173
148k
                            ? static_cast<const SnapshotImpl*>(options.snapshot)
1174
83.7k
                                  ->sequence_number()
1175
148k
                            : latest_snapshot),
1176
148k
                       seed);
1177
148k
}
1178
1179
6.43k
void DBImpl::RecordReadSample(Slice key) {
1180
6.43k
  MutexLock l(&mutex_);
1181
6.43k
  if (versions_->current()->RecordReadSample(key)) {
1182
2
    MaybeScheduleCompaction();
1183
2
  }
1184
6.43k
}
1185
1186
83.7k
const Snapshot* DBImpl::GetSnapshot() {
1187
83.7k
  MutexLock l(&mutex_);
1188
83.7k
  return snapshots_.New(versions_->LastSequence());
1189
83.7k
}
1190
1191
83.7k
void DBImpl::ReleaseSnapshot(const Snapshot* snapshot) {
1192
83.7k
  MutexLock l(&mutex_);
1193
83.7k
  snapshots_.Delete(static_cast<const SnapshotImpl*>(snapshot));
1194
83.7k
}
1195
1196
// Convenience methods
1197
45.6k
Status DBImpl::Put(const WriteOptions& o, const Slice& key, const Slice& val) {
1198
45.6k
  return DB::Put(o, key, val);
1199
45.6k
}
1200
1201
2.03M
Status DBImpl::Delete(const WriteOptions& options, const Slice& key) {
1202
2.03M
  return DB::Delete(options, key);
1203
2.03M
}
1204
1205
2.10M
Status DBImpl::Write(const WriteOptions& options, WriteBatch* updates) {
1206
2.10M
  Writer w(&mutex_);
1207
2.10M
  w.batch = updates;
1208
2.10M
  w.sync = options.sync;
1209
2.10M
  w.done = false;
1210
1211
2.10M
  MutexLock l(&mutex_);
1212
2.10M
  writers_.push_back(&w);
1213
2.10M
  while (!w.done && &w != writers_.front()) {
1214
0
    w.cv.Wait();
1215
0
  }
1216
2.10M
  if (w.done) {
1217
0
    return w.status;
1218
0
  }
1219
1220
  // May temporarily unlock and wait.
1221
2.10M
  Status status = MakeRoomForWrite(updates == nullptr);
1222
2.10M
  uint64_t last_sequence = versions_->LastSequence();
1223
2.10M
  Writer* last_writer = &w;
1224
2.10M
  if (status.ok() && updates != nullptr) {  // nullptr batch is for compactions
1225
2.07M
    WriteBatch* write_batch = BuildBatchGroup(&last_writer);
1226
2.07M
    WriteBatchInternal::SetSequence(write_batch, last_sequence + 1);
1227
2.07M
    last_sequence += WriteBatchInternal::Count(write_batch);
1228
1229
    // Add to log and apply to memtable.  We can release the lock
1230
    // during this phase since &w is currently responsible for logging
1231
    // and protects against concurrent loggers and concurrent writes
1232
    // into mem_.
1233
2.07M
    {
1234
2.07M
      mutex_.Unlock();
1235
2.07M
      status = log_->AddRecord(WriteBatchInternal::Contents(write_batch));
1236
2.07M
      bool sync_error = false;
1237
2.07M
      if (status.ok() && options.sync) {
1238
0
        status = logfile_->Sync();
1239
0
        if (!status.ok()) {
1240
0
          sync_error = true;
1241
0
        }
1242
0
      }
1243
2.07M
      if (status.ok()) {
1244
2.07M
        status = WriteBatchInternal::InsertInto(write_batch, mem_);
1245
2.07M
      }
1246
2.07M
      mutex_.Lock();
1247
2.07M
      if (sync_error) {
1248
        // The state of the log file is indeterminate: the log record we
1249
        // just added may or may not show up when the DB is re-opened.
1250
        // So we force the DB into a mode where all future writes fail.
1251
0
        RecordBackgroundError(status);
1252
0
      }
1253
2.07M
    }
1254
2.07M
    if (write_batch == tmp_batch_) tmp_batch_->Clear();
1255
1256
2.07M
    versions_->SetLastSequence(last_sequence);
1257
2.07M
  }
1258
1259
2.10M
  while (true) {
1260
2.10M
    Writer* ready = writers_.front();
1261
2.10M
    writers_.pop_front();
1262
2.10M
    if (ready != &w) {
1263
0
      ready->status = status;
1264
0
      ready->done = true;
1265
0
      ready->cv.Signal();
1266
0
    }
1267
2.10M
    if (ready == last_writer) break;
1268
2.10M
  }
1269
1270
  // Notify new head of write queue
1271
2.10M
  if (!writers_.empty()) {
1272
0
    writers_.front()->cv.Signal();
1273
0
  }
1274
1275
2.10M
  return status;
1276
2.10M
}
1277
1278
// REQUIRES: Writer list must be non-empty
1279
// REQUIRES: First writer must have a non-null batch
1280
2.07M
WriteBatch* DBImpl::BuildBatchGroup(Writer** last_writer) {
1281
2.07M
  mutex_.AssertHeld();
1282
2.07M
  assert(!writers_.empty());
1283
2.07M
  Writer* first = writers_.front();
1284
2.07M
  WriteBatch* result = first->batch;
1285
2.07M
  assert(result != nullptr);
1286
1287
2.07M
  size_t size = WriteBatchInternal::ByteSize(first->batch);
1288
1289
  // Allow the group to grow up to a maximum size, but if the
1290
  // original write is small, limit the growth so we do not slow
1291
  // down the small write too much.
1292
2.07M
  size_t max_size = 1 << 20;
1293
2.07M
  if (size <= (128 << 10)) {
1294
2.07M
    max_size = size + (128 << 10);
1295
2.07M
  }
1296
1297
2.07M
  *last_writer = first;
1298
2.07M
  std::deque<Writer*>::iterator iter = writers_.begin();
1299
2.07M
  ++iter;  // Advance past "first"
1300
2.07M
  for (; iter != writers_.end(); ++iter) {
1301
0
    Writer* w = *iter;
1302
0
    if (w->sync && !first->sync) {
1303
      // Do not include a sync write into a batch handled by a non-sync write.
1304
0
      break;
1305
0
    }
1306
1307
0
    if (w->batch != nullptr) {
1308
0
      size += WriteBatchInternal::ByteSize(w->batch);
1309
0
      if (size > max_size) {
1310
        // Do not make batch too big
1311
0
        break;
1312
0
      }
1313
1314
      // Append to *result
1315
0
      if (result == first->batch) {
1316
        // Switch to temporary batch instead of disturbing caller's batch
1317
0
        result = tmp_batch_;
1318
0
        assert(WriteBatchInternal::Count(result) == 0);
1319
0
        WriteBatchInternal::Append(result, first->batch);
1320
0
      }
1321
0
      WriteBatchInternal::Append(result, w->batch);
1322
0
    }
1323
0
    *last_writer = w;
1324
0
  }
1325
2.07M
  return result;
1326
2.07M
}
1327
1328
// REQUIRES: mutex_ is held
1329
// REQUIRES: this thread is currently at the front of the writer queue
1330
2.10M
Status DBImpl::MakeRoomForWrite(bool force) {
1331
2.10M
  mutex_.AssertHeld();
1332
2.10M
  assert(!writers_.empty());
1333
2.10M
  bool allow_delay = !force;
1334
2.10M
  Status s;
1335
2.14M
  while (true) {
1336
2.14M
    if (!bg_error_.ok()) {
1337
      // Yield previous error
1338
0
      s = bg_error_;
1339
0
      break;
1340
2.14M
    } else if (allow_delay && versions_->NumLevelFiles(0) >=
1341
2.07M
                                  config::kL0_SlowdownWritesTrigger) {
1342
      // We are getting close to hitting a hard limit on the number of
1343
      // L0 files.  Rather than delaying a single write by several
1344
      // seconds when we hit the hard limit, start delaying each
1345
      // individual write by 1ms to reduce latency variance.  Also,
1346
      // this delay hands over some CPU to the compaction thread in
1347
      // case it is sharing the same core as the writer.
1348
4.04k
      mutex_.Unlock();
1349
4.04k
      env_->SleepForMicroseconds(1000);
1350
4.04k
      allow_delay = false;  // Do not delay a single write more than once
1351
4.04k
      mutex_.Lock();
1352
2.13M
    } else if (!force &&
1353
2.13M
               (mem_->ApproximateMemoryUsage() <= options_.write_buffer_size)) {
1354
      // There is room in current memtable
1355
2.10M
      break;
1356
2.10M
    } else if (imm_ != nullptr) {
1357
      // We have filled up the current memtable, but the previous
1358
      // one is still being compacted, so we wait.
1359
0
      Log(options_.info_log, "Current memtable full; waiting...\n");
1360
0
      background_work_finished_signal_.Wait();
1361
29.7k
    } else if (versions_->NumLevelFiles(0) >= config::kL0_StopWritesTrigger) {
1362
      // There are too many level-0 files.
1363
3
      Log(options_.info_log, "Too many L0 files; waiting...\n");
1364
3
      background_work_finished_signal_.Wait();
1365
29.7k
    } else {
1366
      // Attempt to switch to a new memtable and trigger compaction of old
1367
29.7k
      assert(versions_->PrevLogNumber() == 0);
1368
29.7k
      uint64_t new_log_number = versions_->NewFileNumber();
1369
29.7k
      WritableFile* lfile = nullptr;
1370
29.7k
      s = env_->NewWritableFile(LogFileName(dbname_, new_log_number), &lfile);
1371
29.7k
      if (!s.ok()) {
1372
        // Avoid chewing through file number space in a tight loop.
1373
0
        versions_->ReuseFileNumber(new_log_number);
1374
0
        break;
1375
0
      }
1376
1377
29.7k
      delete log_;
1378
1379
29.7k
      s = logfile_->Close();
1380
29.7k
      if (!s.ok()) {
1381
        // We may have lost some data written to the previous log file.
1382
        // Switch to the new log file anyway, but record as a background
1383
        // error so we do not attempt any more writes.
1384
        //
1385
        // We could perhaps attempt to save the memtable corresponding
1386
        // to log file and suppress the error if that works, but that
1387
        // would add more complexity in a critical code path.
1388
0
        RecordBackgroundError(s);
1389
0
      }
1390
29.7k
      delete logfile_;
1391
1392
29.7k
      logfile_ = lfile;
1393
29.7k
      logfile_number_ = new_log_number;
1394
29.7k
      log_ = new log::Writer(lfile);
1395
29.7k
      imm_ = mem_;
1396
29.7k
      has_imm_.store(true, std::memory_order_release);
1397
29.7k
      mem_ = new MemTable(internal_comparator_);
1398
29.7k
      mem_->Ref();
1399
29.7k
      force = false;  // Do not force another compaction if have room
1400
29.7k
      MaybeScheduleCompaction();
1401
29.7k
    }
1402
2.14M
  }
1403
2.10M
  return s;
1404
2.10M
}
1405
1406
10.9k
bool DBImpl::GetProperty(const Slice& property, std::string* value) {
1407
10.9k
  value->clear();
1408
1409
10.9k
  MutexLock l(&mutex_);
1410
10.9k
  Slice in = property;
1411
10.9k
  Slice prefix("leveldb.");
1412
10.9k
  if (!in.starts_with(prefix)) return false;
1413
1.88k
  in.remove_prefix(prefix.size());
1414
1415
1.88k
  if (in.starts_with("num-files-at-level")) {
1416
615
    in.remove_prefix(strlen("num-files-at-level"));
1417
615
    uint64_t level;
1418
615
    bool ok = ConsumeDecimalNumber(&in, &level) && in.empty();
1419
615
    if (!ok || level >= config::kNumLevels) {
1420
522
      return false;
1421
522
    } else {
1422
93
      char buf[100];
1423
93
      std::snprintf(buf, sizeof(buf), "%d",
1424
93
                    versions_->NumLevelFiles(static_cast<int>(level)));
1425
93
      *value = buf;
1426
93
      return true;
1427
93
    }
1428
1.26k
  } else if (in == "stats") {
1429
0
    char buf[200];
1430
0
    std::snprintf(buf, sizeof(buf),
1431
0
                  "                               Compactions\n"
1432
0
                  "Level  Files Size(MB) Time(sec) Read(MB) Write(MB)\n"
1433
0
                  "--------------------------------------------------\n");
1434
0
    value->append(buf);
1435
0
    for (int level = 0; level < config::kNumLevels; level++) {
1436
0
      int files = versions_->NumLevelFiles(level);
1437
0
      if (stats_[level].micros > 0 || files > 0) {
1438
0
        std::snprintf(buf, sizeof(buf), "%3d %8d %8.0f %9.0f %8.0f %9.0f\n",
1439
0
                      level, files, versions_->NumLevelBytes(level) / 1048576.0,
1440
0
                      stats_[level].micros / 1e6,
1441
0
                      stats_[level].bytes_read / 1048576.0,
1442
0
                      stats_[level].bytes_written / 1048576.0);
1443
0
        value->append(buf);
1444
0
      }
1445
0
    }
1446
0
    return true;
1447
1.26k
  } else if (in == "sstables") {
1448
298
    *value = versions_->current()->DebugString();
1449
298
    return true;
1450
971
  } else if (in == "approximate-memory-usage") {
1451
19
    size_t total_usage = options_.block_cache->TotalCharge();
1452
19
    if (mem_) {
1453
19
      total_usage += mem_->ApproximateMemoryUsage();
1454
19
    }
1455
19
    if (imm_) {
1456
0
      total_usage += imm_->ApproximateMemoryUsage();
1457
0
    }
1458
19
    char buf[50];
1459
19
    std::snprintf(buf, sizeof(buf), "%llu",
1460
19
                  static_cast<unsigned long long>(total_usage));
1461
19
    value->append(buf);
1462
19
    return true;
1463
19
  }
1464
1465
952
  return false;
1466
1.88k
}
1467
1468
0
void DBImpl::GetApproximateSizes(const Range* range, int n, uint64_t* sizes) {
1469
  // TODO(opt): better implementation
1470
0
  MutexLock l(&mutex_);
1471
0
  Version* v = versions_->current();
1472
0
  v->Ref();
1473
1474
0
  for (int i = 0; i < n; i++) {
1475
    // Convert user_key into a corresponding internal key.
1476
0
    InternalKey k1(range[i].start, kMaxSequenceNumber, kValueTypeForSeek);
1477
0
    InternalKey k2(range[i].limit, kMaxSequenceNumber, kValueTypeForSeek);
1478
0
    uint64_t start = versions_->ApproximateOffsetOf(v, k1);
1479
0
    uint64_t limit = versions_->ApproximateOffsetOf(v, k2);
1480
0
    sizes[i] = (limit >= start ? limit - start : 0);
1481
0
  }
1482
1483
0
  v->Unref();
1484
0
}
1485
1486
// Default implementations of convenience methods that subclasses of DB
1487
// can call if they wish
1488
45.6k
Status DB::Put(const WriteOptions& opt, const Slice& key, const Slice& value) {
1489
45.6k
  WriteBatch batch;
1490
45.6k
  batch.Put(key, value);
1491
45.6k
  return Write(opt, &batch);
1492
45.6k
}
1493
1494
2.03M
Status DB::Delete(const WriteOptions& opt, const Slice& key) {
1495
2.03M
  WriteBatch batch;
1496
2.03M
  batch.Delete(key);
1497
2.03M
  return Write(opt, &batch);
1498
2.03M
}
1499
1500
117k
DB::~DB() = default;
1501
1502
117k
Status DB::Open(const Options& options, const std::string& dbname, DB** dbptr) {
1503
117k
  *dbptr = nullptr;
1504
1505
117k
  DBImpl* impl = new DBImpl(options, dbname);
1506
117k
  impl->mutex_.Lock();
1507
117k
  VersionEdit edit;
1508
  // Recover handles create_if_missing, error_if_exists
1509
117k
  bool save_manifest = false;
1510
117k
  Status s = impl->Recover(&edit, &save_manifest);
1511
117k
  if (s.ok() && impl->mem_ == nullptr) {
1512
    // Create new log and a corresponding memtable.
1513
117k
    uint64_t new_log_number = impl->versions_->NewFileNumber();
1514
117k
    WritableFile* lfile;
1515
117k
    s = options.env->NewWritableFile(LogFileName(dbname, new_log_number),
1516
117k
                                     &lfile);
1517
117k
    if (s.ok()) {
1518
117k
      edit.SetLogNumber(new_log_number);
1519
117k
      impl->logfile_ = lfile;
1520
117k
      impl->logfile_number_ = new_log_number;
1521
117k
      impl->log_ = new log::Writer(lfile);
1522
117k
      impl->mem_ = new MemTable(impl->internal_comparator_);
1523
117k
      impl->mem_->Ref();
1524
117k
    }
1525
117k
  }
1526
117k
  if (s.ok() && save_manifest) {
1527
117k
    edit.SetPrevLogNumber(0);  // No older logs needed after recovery.
1528
117k
    edit.SetLogNumber(impl->logfile_number_);
1529
117k
    s = impl->versions_->LogAndApply(&edit, &impl->mutex_);
1530
117k
  }
1531
117k
  if (s.ok()) {
1532
117k
    impl->RemoveObsoleteFiles();
1533
117k
    impl->MaybeScheduleCompaction();
1534
117k
  }
1535
117k
  impl->mutex_.Unlock();
1536
117k
  if (s.ok()) {
1537
117k
    assert(impl->mem_ != nullptr);
1538
117k
    *dbptr = impl;
1539
117k
  } else {
1540
0
    delete impl;
1541
0
  }
1542
117k
  return s;
1543
117k
}
1544
1545
201k
Snapshot::~Snapshot() = default;
1546
1547
0
Status DestroyDB(const std::string& dbname, const Options& options) {
1548
0
  Env* env = options.env;
1549
0
  std::vector<std::string> filenames;
1550
0
  Status result = env->GetChildren(dbname, &filenames);
1551
0
  if (!result.ok()) {
1552
    // Ignore error in case directory does not exist
1553
0
    return Status::OK();
1554
0
  }
1555
1556
0
  FileLock* lock;
1557
0
  const std::string lockname = LockFileName(dbname);
1558
0
  result = env->LockFile(lockname, &lock);
1559
0
  if (result.ok()) {
1560
0
    uint64_t number;
1561
0
    FileType type;
1562
0
    for (size_t i = 0; i < filenames.size(); i++) {
1563
0
      if (ParseFileName(filenames[i], &number, &type) &&
1564
0
          type != kDBLockFile) {  // Lock file will be deleted at end
1565
0
        Status del = env->RemoveFile(dbname + "/" + filenames[i]);
1566
0
        if (result.ok() && !del.ok()) {
1567
0
          result = del;
1568
0
        }
1569
0
      }
1570
0
    }
1571
0
    env->UnlockFile(lock);  // Ignore error since state is already gone
1572
0
    env->RemoveFile(lockname);
1573
0
    env->RemoveDir(dbname);  // Ignore error in case dir contains other files
1574
0
  }
1575
0
  return result;
1576
0
}
1577
1578
}  // namespace leveldb