Coverage Report

Created: 2026-10-16 06:44

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