Coverage Report

Created: 2026-09-14 06:40

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
572
      : 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
493
  Output* current_output() { return &outputs[outputs.size() - 1]; }
63
64
  explicit CompactionState(Compaction* c)
65
8
      : compaction(c),
66
8
        smallest_snapshot(0),
67
8
        outfile(nullptr),
68
8
        builder(nullptr),
69
8
        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
432
static void ClipToRange(T* ptr, V minvalue, V maxvalue) {
91
432
  if (static_cast<V>(*ptr) > maxvalue) *ptr = maxvalue;
92
432
  if (static_cast<V>(*ptr) < minvalue) *ptr = minvalue;
93
432
}
db_impl.cc:void leveldb::ClipToRange<int, int>(int*, int, int)
Line
Count
Source
90
108
static void ClipToRange(T* ptr, V minvalue, V maxvalue) {
91
108
  if (static_cast<V>(*ptr) > maxvalue) *ptr = maxvalue;
92
108
  if (static_cast<V>(*ptr) < minvalue) *ptr = minvalue;
93
108
}
db_impl.cc:void leveldb::ClipToRange<unsigned long, int>(unsigned long*, int, int)
Line
Count
Source
90
324
static void ClipToRange(T* ptr, V minvalue, V maxvalue) {
91
324
  if (static_cast<V>(*ptr) > maxvalue) *ptr = maxvalue;
92
324
  if (static_cast<V>(*ptr) < minvalue) *ptr = minvalue;
93
324
}
94
Options SanitizeOptions(const std::string& dbname,
95
                        const InternalKeyComparator* icmp,
96
                        const InternalFilterPolicy* ipolicy,
97
108
                        const Options& src) {
98
108
  Options result = src;
99
108
  result.comparator = icmp;
100
108
  result.filter_policy = (src.filter_policy != nullptr) ? ipolicy : nullptr;
101
108
  ClipToRange(&result.max_open_files, 64 + kNumNonTableCacheFiles, 50000);
102
108
  ClipToRange(&result.write_buffer_size, 64 << 10, 1 << 30);
103
108
  ClipToRange(&result.max_file_size, 1 << 20, 1 << 30);
104
108
  ClipToRange(&result.block_size, 1 << 10, 4 << 20);
105
108
  if (result.info_log == nullptr) {
106
    // Open a log file in the same directory as the db
107
108
    src.env->CreateDir(dbname);  // In case it does not exist
108
108
    src.env->RenameFile(InfoLogFileName(dbname), OldInfoLogFileName(dbname));
109
108
    Status s = src.env->NewLogger(InfoLogFileName(dbname), &result.info_log);
110
108
    if (!s.ok()) {
111
      // No place suitable for logging
112
0
      result.info_log = nullptr;
113
0
    }
114
108
  }
115
108
  if (result.block_cache == nullptr) {
116
108
    result.block_cache = NewLRUCache(8 << 20);
117
108
  }
118
108
  return result;
119
108
}
120
121
108
static int TableCacheSize(const Options& sanitized_options) {
122
  // Reserve ten files or so for other uses and give the rest to TableCache.
123
108
  return sanitized_options.max_open_files - kNumNonTableCacheFiles;
124
108
}
125
126
DBImpl::DBImpl(const Options& raw_options, const std::string& dbname)
127
108
    : env_(raw_options.env),
128
108
      internal_comparator_(raw_options.comparator),
129
108
      internal_filter_policy_(raw_options.filter_policy),
130
108
      options_(SanitizeOptions(dbname, &internal_comparator_,
131
108
                               &internal_filter_policy_, raw_options)),
132
108
      owns_info_log_(options_.info_log != raw_options.info_log),
133
108
      owns_cache_(options_.block_cache != raw_options.block_cache),
134
108
      dbname_(dbname),
135
108
      table_cache_(new TableCache(dbname_, options_, TableCacheSize(options_))),
136
108
      db_lock_(nullptr),
137
108
      shutting_down_(false),
138
108
      background_work_finished_signal_(&mutex_),
139
108
      mem_(nullptr),
140
108
      imm_(nullptr),
141
108
      has_imm_(false),
142
108
      logfile_(nullptr),
143
108
      logfile_number_(0),
144
108
      log_(nullptr),
145
108
      seed_(0),
146
108
      tmp_batch_(new WriteBatch),
147
108
      background_compaction_scheduled_(false),
148
108
      manual_compaction_(nullptr),
149
108
      versions_(new VersionSet(dbname_, &options_, table_cache_,
150
108
                               &internal_comparator_)) {}
151
152
108
DBImpl::~DBImpl() {
153
  // Wait for background work to finish.
154
108
  mutex_.Lock();
155
108
  shutting_down_.store(true, std::memory_order_release);
156
110
  while (background_compaction_scheduled_) {
157
2
    background_work_finished_signal_.Wait();
158
2
  }
159
108
  mutex_.Unlock();
160
161
108
  if (db_lock_ != nullptr) {
162
108
    env_->UnlockFile(db_lock_);
163
108
  }
164
165
108
  delete versions_;
166
108
  if (mem_ != nullptr) mem_->Unref();
167
108
  if (imm_ != nullptr) imm_->Unref();
168
108
  delete tmp_batch_;
169
108
  delete log_;
170
108
  delete logfile_;
171
108
  delete table_cache_;
172
173
108
  if (owns_info_log_) {
174
108
    delete options_.info_log;
175
108
  }
176
108
  if (owns_cache_) {
177
108
    delete options_.block_cache;
178
108
  }
179
108
}
180
181
49
Status DBImpl::NewDB() {
182
49
  VersionEdit new_db;
183
49
  new_db.SetComparatorName(user_comparator()->Name());
184
49
  new_db.SetLogNumber(0);
185
49
  new_db.SetNextFile(2);
186
49
  new_db.SetLastSequence(0);
187
188
49
  const std::string manifest = DescriptorFileName(dbname_, 1);
189
49
  WritableFile* file;
190
49
  Status s = env_->NewWritableFile(manifest, &file);
191
49
  if (!s.ok()) {
192
0
    return s;
193
0
  }
194
49
  {
195
49
    log::Writer log(file);
196
49
    std::string record;
197
49
    new_db.EncodeTo(&record);
198
49
    s = log.AddRecord(record);
199
49
    if (s.ok()) {
200
49
      s = file->Sync();
201
49
    }
202
49
    if (s.ok()) {
203
49
      s = file->Close();
204
49
    }
205
49
  }
206
49
  delete file;
207
49
  if (s.ok()) {
208
    // Make "CURRENT" file that points to the new manifest file.
209
49
    s = SetCurrentFile(env_, dbname_, 1);
210
49
  } else {
211
0
    env_->RemoveFile(manifest);
212
0
  }
213
49
  return s;
214
49
}
215
216
146
void DBImpl::MaybeIgnoreError(Status* s) const {
217
146
  if (s->ok() || options_.paranoid_checks) {
218
    // No change needed
219
146
  } else {
220
0
    Log(options_.info_log, "Ignoring error %s", s->ToString().c_str());
221
0
    *s = Status::OK();
222
0
  }
223
146
}
224
225
136
void DBImpl::RemoveObsoleteFiles() {
226
136
  mutex_.AssertHeld();
227
228
136
  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
136
  std::set<uint64_t> live = pending_outputs_;
236
136
  versions_->AddLiveFiles(&live);
237
238
136
  std::vector<std::string> filenames;
239
136
  env_->GetChildren(dbname_, &filenames);  // Ignoring errors on purpose
240
136
  uint64_t number;
241
136
  FileType type;
242
136
  std::vector<std::string> files_to_delete;
243
1.42k
  for (std::string& filename : filenames) {
244
1.42k
    if (ParseFileName(filename, &number, &type)) {
245
1.15k
      bool keep = true;
246
1.15k
      switch (type) {
247
216
        case kLogFile:
248
216
          keep = ((number >= versions_->LogNumber()) ||
249
80
                  (number == versions_->PrevLogNumber()));
250
216
          break;
251
244
        case kDescriptorFile:
252
          // Keep my manifest file, and any newer incarnations'
253
          // (in case there is a race that allows other incarnations)
254
244
          keep = (number >= versions_->ManifestFileNumber());
255
244
          break;
256
204
        case kTableFile:
257
204
          keep = (live.find(number) != live.end());
258
204
          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
136
        case kCurrentFile:
265
272
        case kDBLockFile:
266
490
        case kInfoLogFile:
267
490
          keep = true;
268
490
          break;
269
1.15k
      }
270
271
1.15k
      if (!keep) {
272
216
        files_to_delete.push_back(std::move(filename));
273
216
        if (type == kTableFile) {
274
28
          table_cache_->Evict(number);
275
28
        }
276
216
        Log(options_.info_log, "Delete type=%d #%lld\n", static_cast<int>(type),
277
216
            static_cast<unsigned long long>(number));
278
216
      }
279
1.15k
    }
280
1.42k
  }
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
136
  mutex_.Unlock();
286
216
  for (const std::string& filename : files_to_delete) {
287
216
    env_->RemoveFile(dbname_ + "/" + filename);
288
216
  }
289
136
  mutex_.Lock();
290
136
}
291
292
108
Status DBImpl::Recover(VersionEdit* edit, bool* save_manifest) {
293
108
  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
108
  env_->CreateDir(dbname_);
299
108
  assert(db_lock_ == nullptr);
300
108
  Status s = env_->LockFile(LockFileName(dbname_), &db_lock_);
301
108
  if (!s.ok()) {
302
0
    return s;
303
0
  }
304
305
108
  if (!env_->FileExists(CurrentFileName(dbname_))) {
306
49
    if (options_.create_if_missing) {
307
49
      Log(options_.info_log, "Creating DB %s since it was missing.",
308
49
          dbname_.c_str());
309
49
      s = NewDB();
310
49
      if (!s.ok()) {
311
0
        return s;
312
0
      }
313
49
    } else {
314
0
      return Status::InvalidArgument(
315
0
          dbname_, "does not exist (create_if_missing is false)");
316
0
    }
317
59
  } else {
318
59
    if (options_.error_if_exists) {
319
0
      return Status::InvalidArgument(dbname_,
320
0
                                     "exists (error_if_exists is true)");
321
0
    }
322
59
  }
323
324
108
  s = versions_->Recover(save_manifest);
325
108
  if (!s.ok()) {
326
0
    return s;
327
0
  }
328
108
  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
108
  const uint64_t min_log = versions_->LogNumber();
338
108
  const uint64_t prev_log = versions_->PrevLogNumber();
339
108
  std::vector<std::string> filenames;
340
108
  s = env_->GetChildren(dbname_, &filenames);
341
108
  if (!s.ok()) {
342
0
    return s;
343
0
  }
344
108
  std::set<uint64_t> expected;
345
108
  versions_->AddLiveFiles(&expected);
346
108
  uint64_t number;
347
108
  FileType type;
348
108
  std::vector<uint64_t> logs;
349
959
  for (size_t i = 0; i < filenames.size(); i++) {
350
851
    if (ParseFileName(filenames[i], &number, &type)) {
351
635
      expected.erase(number);
352
635
      if (type == kLogFile && ((number >= min_log) || (number == prev_log)))
353
60
        logs.push_back(number);
354
635
    }
355
851
  }
356
108
  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
108
  std::sort(logs.begin(), logs.end());
365
168
  for (size_t i = 0; i < logs.size(); i++) {
366
60
    s = RecoverLogFile(logs[i], (i == logs.size() - 1), save_manifest, edit,
367
60
                       &max_sequence);
368
60
    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
60
    versions_->MarkFileNumberUsed(logs[i]);
376
60
  }
377
378
108
  if (versions_->LastSequence() < max_sequence) {
379
36
    versions_->SetLastSequence(max_sequence);
380
36
  }
381
382
108
  return Status::OK();
383
108
}
384
385
Status DBImpl::RecoverLogFile(uint64_t log_number, bool last_log,
386
                              bool* save_manifest, VersionEdit* edit,
387
60
                              SequenceNumber* max_sequence) {
388
60
  struct LogReporter : public log::Reader::Reporter {
389
60
    Env* env;
390
60
    Logger* info_log;
391
60
    const char* fname;
392
60
    Status* status;  // null if options_.paranoid_checks==false
393
60
    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
60
  };
400
401
60
  mutex_.AssertHeld();
402
403
  // Open the log file
404
60
  std::string fname = LogFileName(dbname_, log_number);
405
60
  SequentialFile* file;
406
60
  Status status = env_->NewSequentialFile(fname, &file);
407
60
  if (!status.ok()) {
408
0
    MaybeIgnoreError(&status);
409
0
    return status;
410
0
  }
411
412
  // Create the log reader.
413
60
  LogReporter reporter;
414
60
  reporter.env = env_;
415
60
  reporter.info_log = options_.info_log;
416
60
  reporter.fname = fname.c_str();
417
60
  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
60
  log::Reader reader(file, &reporter, true /*checksum*/, 0 /*initial_offset*/);
423
60
  Log(options_.info_log, "Recovering log #%llu",
424
60
      (unsigned long long)log_number);
425
426
  // Read all the records and add to a memtable
427
60
  std::string scratch;
428
60
  Slice record;
429
60
  WriteBatch batch;
430
60
  int compactions = 0;
431
60
  MemTable* mem = nullptr;
432
206
  while (reader.ReadRecord(&record, &scratch) && status.ok()) {
433
146
    if (record.size() < 12) {
434
0
      reporter.Corruption(record.size(),
435
0
                          Status::Corruption("log record too small"));
436
0
      continue;
437
0
    }
438
146
    WriteBatchInternal::SetContents(&batch, record);
439
440
146
    if (mem == nullptr) {
441
36
      mem = new MemTable(internal_comparator_);
442
36
      mem->Ref();
443
36
    }
444
146
    status = WriteBatchInternal::InsertInto(&batch, mem);
445
146
    MaybeIgnoreError(&status);
446
146
    if (!status.ok()) {
447
0
      break;
448
0
    }
449
146
    const SequenceNumber last_seq = WriteBatchInternal::Sequence(&batch) +
450
146
                                    WriteBatchInternal::Count(&batch) - 1;
451
146
    if (last_seq > *max_sequence) {
452
146
      *max_sequence = last_seq;
453
146
    }
454
455
146
    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
146
  }
468
469
60
  delete file;
470
471
  // See if we should keep reusing the last log file.
472
60
  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
60
  if (mem != nullptr) {
494
    // mem did not get reused; compact it.
495
36
    if (status.ok()) {
496
36
      *save_manifest = true;
497
36
      status = WriteLevel0Table(mem, edit, nullptr);
498
36
    }
499
36
    mem->Unref();
500
36
  }
501
502
60
  return status;
503
60
}
504
505
Status DBImpl::WriteLevel0Table(MemTable* mem, VersionEdit* edit,
506
56
                                Version* base) {
507
56
  mutex_.AssertHeld();
508
56
  const uint64_t start_micros = env_->NowMicros();
509
56
  FileMetaData meta;
510
56
  meta.number = versions_->NewFileNumber();
511
56
  pending_outputs_.insert(meta.number);
512
56
  Iterator* iter = mem->NewIterator();
513
56
  Log(options_.info_log, "Level-0 table #%llu: started",
514
56
      (unsigned long long)meta.number);
515
516
56
  Status s;
517
56
  {
518
56
    mutex_.Unlock();
519
56
    s = BuildTable(dbname_, env_, options_, table_cache_, iter, &meta);
520
56
    mutex_.Lock();
521
56
  }
522
523
56
  Log(options_.info_log, "Level-0 table #%llu: %lld bytes %s",
524
56
      (unsigned long long)meta.number, (unsigned long long)meta.file_size,
525
56
      s.ToString().c_str());
526
56
  delete iter;
527
56
  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
56
  int level = 0;
532
56
  if (s.ok() && meta.file_size > 0) {
533
44
    const Slice min_user_key = meta.smallest.user_key();
534
44
    const Slice max_user_key = meta.largest.user_key();
535
44
    if (base != nullptr) {
536
8
      level = base->PickLevelForMemTableOutput(min_user_key, max_user_key);
537
8
    }
538
44
    edit->AddFile(level, meta.number, meta.file_size, meta.smallest,
539
44
                  meta.largest);
540
44
  }
541
542
56
  CompactionStats stats;
543
56
  stats.micros = env_->NowMicros() - start_micros;
544
56
  stats.bytes_written = meta.file_size;
545
56
  stats_[level].Add(stats);
546
56
  return s;
547
56
}
548
549
20
void DBImpl::CompactMemTable() {
550
20
  mutex_.AssertHeld();
551
20
  assert(imm_ != nullptr);
552
553
  // Save the contents of the memtable as a new Table
554
20
  VersionEdit edit;
555
20
  Version* base = versions_->current();
556
20
  base->Ref();
557
20
  Status s = WriteLevel0Table(imm_, &edit, base);
558
20
  base->Unref();
559
560
20
  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
20
  if (s.ok()) {
566
20
    edit.SetPrevLogNumber(0);
567
20
    edit.SetLogNumber(logfile_number_);  // Earlier logs no longer needed
568
20
    s = versions_->LogAndApply(&edit, &mutex_);
569
20
  }
570
571
20
  if (s.ok()) {
572
    // Commit to the new state
573
20
    imm_->Unref();
574
20
    imm_ = nullptr;
575
20
    has_imm_.store(false, std::memory_order_release);
576
20
    RemoveObsoleteFiles();
577
20
  } else {
578
0
    RecordBackgroundError(s);
579
0
  }
580
20
}
581
582
20
void DBImpl::CompactRange(const Slice* begin, const Slice* end) {
583
20
  int max_level_with_files = 1;
584
20
  {
585
20
    MutexLock l(&mutex_);
586
20
    Version* base = versions_->current();
587
140
    for (int level = 1; level < config::kNumLevels; level++) {
588
120
      if (base->OverlapInLevel(level, begin, end)) {
589
3
        max_level_with_files = level;
590
3
      }
591
120
    }
592
20
  }
593
20
  TEST_CompactMemTable();  // TODO(sanjay): Skip if memtable does not overlap
594
40
  for (int level = 0; level < max_level_with_files; level++) {
595
20
    TEST_CompactRange(level, begin, end);
596
20
  }
597
20
}
598
599
void DBImpl::TEST_CompactRange(int level, const Slice* begin,
600
20
                               const Slice* end) {
601
20
  assert(level >= 0);
602
20
  assert(level + 1 < config::kNumLevels);
603
604
20
  InternalKey begin_storage, end_storage;
605
606
20
  ManualCompaction manual;
607
20
  manual.level = level;
608
20
  manual.done = false;
609
20
  if (begin == nullptr) {
610
0
    manual.begin = nullptr;
611
20
  } else {
612
20
    begin_storage = InternalKey(*begin, kMaxSequenceNumber, kValueTypeForSeek);
613
20
    manual.begin = &begin_storage;
614
20
  }
615
20
  if (end == nullptr) {
616
0
    manual.end = nullptr;
617
20
  } else {
618
20
    end_storage = InternalKey(*end, 0, static_cast<ValueType>(0));
619
20
    manual.end = &end_storage;
620
20
  }
621
622
20
  MutexLock l(&mutex_);
623
68
  while (!manual.done && !shutting_down_.load(std::memory_order_acquire) &&
624
48
         bg_error_.ok()) {
625
48
    if (manual_compaction_ == nullptr) {  // Idle
626
24
      manual_compaction_ = &manual;
627
24
      MaybeScheduleCompaction();
628
24
    } else {  // Running either my compaction or another compaction.
629
24
      background_work_finished_signal_.Wait();
630
24
    }
631
48
  }
632
  // Finish current background compaction in the case where
633
  // `background_work_finished_signal_` was signalled due to an error.
634
20
  while (background_compaction_scheduled_) {
635
0
    background_work_finished_signal_.Wait();
636
0
  }
637
20
  if (manual_compaction_ == &manual) {
638
    // Cancel my manual compaction since we aborted early for some reason.
639
0
    manual_compaction_ = nullptr;
640
0
  }
641
20
}
642
643
20
Status DBImpl::TEST_CompactMemTable() {
644
  // nullptr batch means just wait for earlier writes to be done
645
20
  Status s = Write(WriteOptions(), nullptr);
646
20
  if (s.ok()) {
647
    // Wait until the compaction completes
648
20
    MutexLock l(&mutex_);
649
40
    while (imm_ != nullptr && bg_error_.ok() &&
650
20
           !shutting_down_.load(std::memory_order_acquire)) {
651
20
      background_work_finished_signal_.Wait();
652
20
    }
653
20
    if (imm_ != nullptr) {
654
0
      s = bg_error_;
655
0
    }
656
20
  }
657
20
  return s;
658
20
}
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
202
void DBImpl::MaybeScheduleCompaction() {
669
202
  mutex_.AssertHeld();
670
202
  if (background_compaction_scheduled_) {
671
    // Already scheduled
672
197
  } else if (shutting_down_.load(std::memory_order_acquire)) {
673
    // DB is being deleted; no more background compactions
674
195
  } else if (!bg_error_.ok()) {
675
    // Already got an error; no more changes
676
195
  } else if (imm_ == nullptr && manual_compaction_ == nullptr &&
677
152
             !versions_->NeedsCompaction()) {
678
    // No work to be done
679
145
  } else {
680
50
    background_compaction_scheduled_ = true;
681
50
    env_->Schedule(&DBImpl::BGWork, this);
682
50
  }
683
202
}
684
685
50
void DBImpl::BGWork(void* db) {
686
50
  reinterpret_cast<DBImpl*>(db)->BackgroundCall();
687
50
}
688
689
50
void DBImpl::BackgroundCall() {
690
50
  MutexLock l(&mutex_);
691
50
  assert(background_compaction_scheduled_);
692
50
  if (shutting_down_.load(std::memory_order_acquire)) {
693
    // No more background work when shutting down.
694
49
  } else if (!bg_error_.ok()) {
695
    // No more background work after a background error.
696
49
  } else {
697
49
    BackgroundCompaction();
698
49
  }
699
700
50
  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
50
  MaybeScheduleCompaction();
705
50
  background_work_finished_signal_.SignalAll();
706
50
}
707
708
49
void DBImpl::BackgroundCompaction() {
709
49
  mutex_.AssertHeld();
710
711
49
  if (imm_ != nullptr) {
712
20
    CompactMemTable();
713
20
    return;
714
20
  }
715
716
29
  Compaction* c;
717
29
  bool is_manual = (manual_compaction_ != nullptr);
718
29
  InternalKey manual_end;
719
29
  if (is_manual) {
720
24
    ManualCompaction* m = manual_compaction_;
721
24
    c = versions_->CompactRange(m->level, m->begin, m->end);
722
24
    m->done = (c == nullptr);
723
24
    if (c != nullptr) {
724
4
      manual_end = c->input(0, c->num_input_files(0) - 1)->largest;
725
4
    }
726
24
    Log(options_.info_log,
727
24
        "Manual compaction at level-%d from %s .. %s; will stop at %s\n",
728
24
        m->level, (m->begin ? m->begin->DebugString().c_str() : "(begin)"),
729
24
        (m->end ? m->end->DebugString().c_str() : "(end)"),
730
24
        (m->done ? "(end)" : manual_end.DebugString().c_str()));
731
24
  } else {
732
5
    c = versions_->PickCompaction();
733
5
  }
734
735
29
  Status status;
736
29
  if (c == nullptr) {
737
    // Nothing to do
738
20
  } 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
8
  } else {
755
8
    CompactionState* compact = new CompactionState(c);
756
8
    status = DoCompactionWork(compact);
757
8
    if (!status.ok()) {
758
0
      RecordBackgroundError(status);
759
0
    }
760
8
    CleanupCompaction(compact);
761
8
    c->ReleaseInputs();
762
8
    RemoveObsoleteFiles();
763
8
  }
764
29
  delete c;
765
766
29
  if (status.ok()) {
767
    // Done
768
29
  } 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
29
  if (is_manual) {
775
24
    ManualCompaction* m = manual_compaction_;
776
24
    if (!status.ok()) {
777
0
      m->done = true;
778
0
    }
779
24
    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
4
      m->tmp_storage = manual_end;
783
4
      m->begin = &m->tmp_storage;
784
4
    }
785
24
    manual_compaction_ = nullptr;
786
24
  }
787
29
}
788
789
8
void DBImpl::CleanupCompaction(CompactionState* compact) {
790
8
  mutex_.AssertHeld();
791
8
  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
8
  } else {
796
8
    assert(compact->outfile == nullptr);
797
8
  }
798
8
  delete compact->outfile;
799
16
  for (size_t i = 0; i < compact->outputs.size(); i++) {
800
8
    const CompactionState::Output& out = compact->outputs[i];
801
8
    pending_outputs_.erase(out.number);
802
8
  }
803
8
  delete compact;
804
8
}
805
806
8
Status DBImpl::OpenCompactionOutputFile(CompactionState* compact) {
807
8
  assert(compact != nullptr);
808
8
  assert(compact->builder == nullptr);
809
8
  uint64_t file_number;
810
8
  {
811
8
    mutex_.Lock();
812
8
    file_number = versions_->NewFileNumber();
813
8
    pending_outputs_.insert(file_number);
814
8
    CompactionState::Output out;
815
8
    out.number = file_number;
816
8
    out.smallest.Clear();
817
8
    out.largest.Clear();
818
8
    compact->outputs.push_back(out);
819
8
    mutex_.Unlock();
820
8
  }
821
822
  // Make the output file
823
8
  std::string fname = TableFileName(dbname_, file_number);
824
8
  Status s = env_->NewWritableFile(fname, &compact->outfile);
825
8
  if (s.ok()) {
826
8
    compact->builder = new TableBuilder(options_, compact->outfile);
827
8
  }
828
8
  return s;
829
8
}
830
831
Status DBImpl::FinishCompactionOutputFile(CompactionState* compact,
832
8
                                          Iterator* input) {
833
8
  assert(compact != nullptr);
834
8
  assert(compact->outfile != nullptr);
835
8
  assert(compact->builder != nullptr);
836
837
8
  const uint64_t output_number = compact->current_output()->number;
838
8
  assert(output_number != 0);
839
840
  // Check for iterator errors
841
8
  Status s = input->status();
842
8
  const uint64_t current_entries = compact->builder->NumEntries();
843
8
  if (s.ok()) {
844
8
    s = compact->builder->Finish();
845
8
  } else {
846
0
    compact->builder->Abandon();
847
0
  }
848
8
  const uint64_t current_bytes = compact->builder->FileSize();
849
8
  compact->current_output()->file_size = current_bytes;
850
8
  compact->total_bytes += current_bytes;
851
8
  delete compact->builder;
852
8
  compact->builder = nullptr;
853
854
  // Finish and check for file errors
855
8
  if (s.ok()) {
856
8
    s = compact->outfile->Sync();
857
8
  }
858
8
  if (s.ok()) {
859
8
    s = compact->outfile->Close();
860
8
  }
861
8
  delete compact->outfile;
862
8
  compact->outfile = nullptr;
863
864
8
  if (s.ok() && current_entries > 0) {
865
    // Verify that the table is usable
866
8
    Iterator* iter =
867
8
        table_cache_->NewIterator(ReadOptions(), output_number, current_bytes);
868
8
    s = iter->status();
869
8
    delete iter;
870
8
    if (s.ok()) {
871
8
      Log(options_.info_log, "Generated table #%llu@%d: %lld keys, %lld bytes",
872
8
          (unsigned long long)output_number, compact->compaction->level(),
873
8
          (unsigned long long)current_entries,
874
8
          (unsigned long long)current_bytes);
875
8
    }
876
8
  }
877
8
  return s;
878
8
}
879
880
8
Status DBImpl::InstallCompactionResults(CompactionState* compact) {
881
8
  mutex_.AssertHeld();
882
8
  Log(options_.info_log, "Compacted %d@%d + %d@%d files => %lld bytes",
883
8
      compact->compaction->num_input_files(0), compact->compaction->level(),
884
8
      compact->compaction->num_input_files(1), compact->compaction->level() + 1,
885
8
      static_cast<long long>(compact->total_bytes));
886
887
  // Add compaction outputs
888
8
  compact->compaction->AddInputDeletions(compact->compaction->edit());
889
8
  const int level = compact->compaction->level();
890
16
  for (size_t i = 0; i < compact->outputs.size(); i++) {
891
8
    const CompactionState::Output& out = compact->outputs[i];
892
8
    compact->compaction->edit()->AddFile(level + 1, out.number, out.file_size,
893
8
                                         out.smallest, out.largest);
894
8
  }
895
8
  return versions_->LogAndApply(compact->compaction->edit(), &mutex_);
896
8
}
897
898
8
Status DBImpl::DoCompactionWork(CompactionState* compact) {
899
8
  const uint64_t start_micros = env_->NowMicros();
900
8
  int64_t imm_micros = 0;  // Micros spent doing imm_ compactions
901
902
8
  Log(options_.info_log, "Compacting %d@%d + %d@%d files",
903
8
      compact->compaction->num_input_files(0), compact->compaction->level(),
904
8
      compact->compaction->num_input_files(1),
905
8
      compact->compaction->level() + 1);
906
907
8
  assert(versions_->NumLevelFiles(compact->compaction->level()) > 0);
908
8
  assert(compact->builder == nullptr);
909
8
  assert(compact->outfile == nullptr);
910
8
  if (snapshots_.empty()) {
911
8
    compact->smallest_snapshot = versions_->LastSequence();
912
8
  } else {
913
0
    compact->smallest_snapshot = snapshots_.oldest()->sequence_number();
914
0
  }
915
916
8
  Iterator* input = versions_->MakeInputIterator(compact->compaction);
917
918
  // Release mutex while we're actually doing the compaction work
919
8
  mutex_.Unlock();
920
921
8
  input->SeekToFirst();
922
8
  Status status;
923
8
  ParsedInternalKey ikey;
924
8
  std::string current_user_key;
925
8
  bool has_current_user_key = false;
926
8
  SequenceNumber last_sequence_for_key = kMaxSequenceNumber;
927
485
  while (input->Valid() && !shutting_down_.load(std::memory_order_acquire)) {
928
    // Prioritize immutable compaction work
929
477
    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
477
    Slice key = input->key();
942
477
    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
477
    bool drop = false;
952
477
    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
477
    } else {
958
477
      if (!has_current_user_key ||
959
469
          user_comparator()->Compare(ikey.user_key, Slice(current_user_key)) !=
960
477
              0) {
961
        // First occurrence of this user key
962
477
        current_user_key.assign(ikey.user_key.data(), ikey.user_key.size());
963
477
        has_current_user_key = true;
964
477
        last_sequence_for_key = kMaxSequenceNumber;
965
477
      }
966
967
477
      if (last_sequence_for_key <= compact->smallest_snapshot) {
968
        // Hidden by an newer entry for same user key
969
0
        drop = true;  // (A)
970
477
      } else if (ikey.type == kTypeDeletion &&
971
8
                 ikey.sequence <= compact->smallest_snapshot &&
972
8
                 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
8
        drop = true;
981
8
      }
982
983
477
      last_sequence_for_key = ikey.sequence;
984
477
    }
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
477
    if (!drop) {
996
      // Open output file if necessary
997
469
      if (compact->builder == nullptr) {
998
8
        status = OpenCompactionOutputFile(compact);
999
8
        if (!status.ok()) {
1000
0
          break;
1001
0
        }
1002
8
      }
1003
469
      if (compact->builder->NumEntries() == 0) {
1004
8
        compact->current_output()->smallest.DecodeFrom(key);
1005
8
      }
1006
469
      compact->current_output()->largest.DecodeFrom(key);
1007
469
      compact->builder->Add(key, input->value());
1008
1009
      // Close output file if it is big enough
1010
469
      if (compact->builder->FileSize() >=
1011
469
          compact->compaction->MaxOutputFileSize()) {
1012
0
        status = FinishCompactionOutputFile(compact, input);
1013
0
        if (!status.ok()) {
1014
0
          break;
1015
0
        }
1016
0
      }
1017
469
    }
1018
1019
477
    input->Next();
1020
477
  }
1021
1022
8
  if (status.ok() && shutting_down_.load(std::memory_order_acquire)) {
1023
0
    status = Status::IOError("Deleting DB during compaction");
1024
0
  }
1025
8
  if (status.ok() && compact->builder != nullptr) {
1026
8
    status = FinishCompactionOutputFile(compact, input);
1027
8
  }
1028
8
  if (status.ok()) {
1029
8
    status = input->status();
1030
8
  }
1031
8
  delete input;
1032
8
  input = nullptr;
1033
1034
8
  CompactionStats stats;
1035
8
  stats.micros = env_->NowMicros() - start_micros - imm_micros;
1036
24
  for (int which = 0; which < 2; which++) {
1037
44
    for (int i = 0; i < compact->compaction->num_input_files(which); i++) {
1038
28
      stats.bytes_read += compact->compaction->input(which, i)->file_size;
1039
28
    }
1040
16
  }
1041
16
  for (size_t i = 0; i < compact->outputs.size(); i++) {
1042
8
    stats.bytes_written += compact->outputs[i].file_size;
1043
8
  }
1044
1045
8
  mutex_.Lock();
1046
8
  stats_[compact->compaction->level() + 1].Add(stats);
1047
1048
8
  if (status.ok()) {
1049
8
    status = InstallCompactionResults(compact);
1050
8
  }
1051
8
  if (!status.ok()) {
1052
0
    RecordBackgroundError(status);
1053
0
  }
1054
8
  VersionSet::LevelSummaryStorage tmp;
1055
8
  Log(options_.info_log, "compacted to: %s", versions_->LevelSummary(&tmp));
1056
8
  return status;
1057
8
}
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
40
      : mu(mutex), version(version), mem(mem), imm(imm) {}
1069
};
1070
1071
40
static void CleanupIteratorState(void* arg1, void* arg2) {
1072
40
  IterState* state = reinterpret_cast<IterState*>(arg1);
1073
40
  state->mu->Lock();
1074
40
  state->mem->Unref();
1075
40
  if (state->imm != nullptr) state->imm->Unref();
1076
40
  state->version->Unref();
1077
40
  state->mu->Unlock();
1078
40
  delete state;
1079
40
}
1080
1081
}  // anonymous namespace
1082
1083
Iterator* DBImpl::NewInternalIterator(const ReadOptions& options,
1084
                                      SequenceNumber* latest_snapshot,
1085
40
                                      uint32_t* seed) {
1086
40
  mutex_.Lock();
1087
40
  *latest_snapshot = versions_->LastSequence();
1088
1089
  // Collect together all needed child iterators
1090
40
  std::vector<Iterator*> list;
1091
40
  list.push_back(mem_->NewIterator());
1092
40
  mem_->Ref();
1093
40
  if (imm_ != nullptr) {
1094
0
    list.push_back(imm_->NewIterator());
1095
0
    imm_->Ref();
1096
0
  }
1097
40
  versions_->current()->AddIterators(options, &list);
1098
40
  Iterator* internal_iter =
1099
40
      NewMergingIterator(&internal_comparator_, &list[0], list.size());
1100
40
  versions_->current()->Ref();
1101
1102
40
  IterState* cleanup = new IterState(&mutex_, mem_, imm_, versions_->current());
1103
40
  internal_iter->RegisterCleanup(CleanupIteratorState, cleanup, nullptr);
1104
1105
40
  *seed = ++seed_;
1106
40
  mutex_.Unlock();
1107
40
  return internal_iter;
1108
40
}
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
24
                   std::string* value) {
1123
24
  Status s;
1124
24
  MutexLock l(&mutex_);
1125
24
  SequenceNumber snapshot;
1126
24
  if (options.snapshot != nullptr) {
1127
0
    snapshot =
1128
0
        static_cast<const SnapshotImpl*>(options.snapshot)->sequence_number();
1129
24
  } else {
1130
24
    snapshot = versions_->LastSequence();
1131
24
  }
1132
1133
24
  MemTable* mem = mem_;
1134
24
  MemTable* imm = imm_;
1135
24
  Version* current = versions_->current();
1136
24
  mem->Ref();
1137
24
  if (imm != nullptr) imm->Ref();
1138
24
  current->Ref();
1139
1140
24
  bool have_stat_update = false;
1141
24
  Version::GetStats stats;
1142
1143
  // Unlock while reading from files and memtables
1144
24
  {
1145
24
    mutex_.Unlock();
1146
    // First look in the memtable, then in the immutable memtable (if any).
1147
24
    LookupKey lkey(key, snapshot);
1148
24
    if (mem->Get(lkey, value, &s)) {
1149
      // Done
1150
23
    } else if (imm != nullptr && imm->Get(lkey, value, &s)) {
1151
      // Done
1152
23
    } else {
1153
23
      s = current->Get(options, lkey, value, &stats);
1154
23
      have_stat_update = true;
1155
23
    }
1156
24
    mutex_.Lock();
1157
24
  }
1158
1159
24
  if (have_stat_update && current->UpdateStats(stats)) {
1160
0
    MaybeScheduleCompaction();
1161
0
  }
1162
24
  mem->Unref();
1163
24
  if (imm != nullptr) imm->Unref();
1164
24
  current->Unref();
1165
24
  return s;
1166
24
}
1167
1168
40
Iterator* DBImpl::NewIterator(const ReadOptions& options) {
1169
40
  SequenceNumber latest_snapshot;
1170
40
  uint32_t seed;
1171
40
  Iterator* iter = NewInternalIterator(options, &latest_snapshot, &seed);
1172
40
  return NewDBIterator(this, user_comparator(), iter,
1173
40
                       (options.snapshot != nullptr
1174
40
                            ? static_cast<const SnapshotImpl*>(options.snapshot)
1175
28
                                  ->sequence_number()
1176
40
                            : latest_snapshot),
1177
40
                       seed);
1178
40
}
1179
1180
10
void DBImpl::RecordReadSample(Slice key) {
1181
10
  MutexLock l(&mutex_);
1182
10
  if (versions_->current()->RecordReadSample(key)) {
1183
0
    MaybeScheduleCompaction();
1184
0
  }
1185
10
}
1186
1187
28
const Snapshot* DBImpl::GetSnapshot() {
1188
28
  MutexLock l(&mutex_);
1189
28
  return snapshots_.New(versions_->LastSequence());
1190
28
}
1191
1192
28
void DBImpl::ReleaseSnapshot(const Snapshot* snapshot) {
1193
28
  MutexLock l(&mutex_);
1194
28
  snapshots_.Delete(static_cast<const SnapshotImpl*>(snapshot));
1195
28
}
1196
1197
// Convenience methods
1198
534
Status DBImpl::Put(const WriteOptions& o, const Slice& key, const Slice& val) {
1199
534
  return DB::Put(o, key, val);
1200
534
}
1201
1202
18
Status DBImpl::Delete(const WriteOptions& options, const Slice& key) {
1203
18
  return DB::Delete(options, key);
1204
18
}
1205
1206
572
Status DBImpl::Write(const WriteOptions& options, WriteBatch* updates) {
1207
572
  Writer w(&mutex_);
1208
572
  w.batch = updates;
1209
572
  w.sync = options.sync;
1210
572
  w.done = false;
1211
1212
572
  MutexLock l(&mutex_);
1213
572
  writers_.push_back(&w);
1214
572
  while (!w.done && &w != writers_.front()) {
1215
0
    w.cv.Wait();
1216
0
  }
1217
572
  if (w.done) {
1218
0
    return w.status;
1219
0
  }
1220
1221
  // May temporarily unlock and wait.
1222
572
  Status status = MakeRoomForWrite(updates == nullptr);
1223
572
  uint64_t last_sequence = versions_->LastSequence();
1224
572
  Writer* last_writer = &w;
1225
572
  if (status.ok() && updates != nullptr) {  // nullptr batch is for compactions
1226
552
    WriteBatch* write_batch = BuildBatchGroup(&last_writer);
1227
552
    WriteBatchInternal::SetSequence(write_batch, last_sequence + 1);
1228
552
    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
552
    {
1235
552
      mutex_.Unlock();
1236
552
      status = log_->AddRecord(WriteBatchInternal::Contents(write_batch));
1237
552
      bool sync_error = false;
1238
552
      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
552
      if (status.ok()) {
1245
552
        status = WriteBatchInternal::InsertInto(write_batch, mem_);
1246
552
      }
1247
552
      mutex_.Lock();
1248
552
      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
552
    }
1255
552
    if (write_batch == tmp_batch_) tmp_batch_->Clear();
1256
1257
552
    versions_->SetLastSequence(last_sequence);
1258
552
  }
1259
1260
572
  while (true) {
1261
572
    Writer* ready = writers_.front();
1262
572
    writers_.pop_front();
1263
572
    if (ready != &w) {
1264
0
      ready->status = status;
1265
0
      ready->done = true;
1266
0
      ready->cv.Signal();
1267
0
    }
1268
572
    if (ready == last_writer) break;
1269
572
  }
1270
1271
  // Notify new head of write queue
1272
572
  if (!writers_.empty()) {
1273
0
    writers_.front()->cv.Signal();
1274
0
  }
1275
1276
572
  return status;
1277
572
}
1278
1279
// REQUIRES: Writer list must be non-empty
1280
// REQUIRES: First writer must have a non-null batch
1281
552
WriteBatch* DBImpl::BuildBatchGroup(Writer** last_writer) {
1282
552
  mutex_.AssertHeld();
1283
552
  assert(!writers_.empty());
1284
552
  Writer* first = writers_.front();
1285
552
  WriteBatch* result = first->batch;
1286
552
  assert(result != nullptr);
1287
1288
552
  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
552
  size_t max_size = 1 << 20;
1294
552
  if (size <= (128 << 10)) {
1295
503
    max_size = size + (128 << 10);
1296
503
  }
1297
1298
552
  *last_writer = first;
1299
552
  std::deque<Writer*>::iterator iter = writers_.begin();
1300
552
  ++iter;  // Advance past "first"
1301
552
  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
552
  return result;
1327
552
}
1328
1329
// REQUIRES: mutex_ is held
1330
// REQUIRES: this thread is currently at the front of the writer queue
1331
572
Status DBImpl::MakeRoomForWrite(bool force) {
1332
572
  mutex_.AssertHeld();
1333
572
  assert(!writers_.empty());
1334
572
  bool allow_delay = !force;
1335
572
  Status s;
1336
592
  while (true) {
1337
592
    if (!bg_error_.ok()) {
1338
      // Yield previous error
1339
0
      s = bg_error_;
1340
0
      break;
1341
592
    } else if (allow_delay && versions_->NumLevelFiles(0) >=
1342
552
                                  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
592
    } else if (!force &&
1354
572
               (mem_->ApproximateMemoryUsage() <= options_.write_buffer_size)) {
1355
      // There is room in current memtable
1356
572
      break;
1357
572
    } 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
20
    } 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
20
    } else {
1367
      // Attempt to switch to a new memtable and trigger compaction of old
1368
20
      assert(versions_->PrevLogNumber() == 0);
1369
20
      uint64_t new_log_number = versions_->NewFileNumber();
1370
20
      WritableFile* lfile = nullptr;
1371
20
      s = env_->NewWritableFile(LogFileName(dbname_, new_log_number), &lfile);
1372
20
      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
20
      delete log_;
1379
1380
20
      s = logfile_->Close();
1381
20
      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
20
      delete logfile_;
1392
1393
20
      logfile_ = lfile;
1394
20
      logfile_number_ = new_log_number;
1395
20
      log_ = new log::Writer(lfile);
1396
20
      imm_ = mem_;
1397
20
      has_imm_.store(true, std::memory_order_release);
1398
20
      mem_ = new MemTable(internal_comparator_);
1399
20
      mem_->Ref();
1400
20
      force = false;  // Do not force another compaction if have room
1401
20
      MaybeScheduleCompaction();
1402
20
    }
1403
592
  }
1404
572
  return s;
1405
572
}
1406
1407
16
bool DBImpl::GetProperty(const Slice& property, std::string* value) {
1408
16
  value->clear();
1409
1410
16
  MutexLock l(&mutex_);
1411
16
  Slice in = property;
1412
16
  Slice prefix("leveldb.");
1413
16
  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
534
Status DB::Put(const WriteOptions& opt, const Slice& key, const Slice& value) {
1490
534
  WriteBatch batch;
1491
534
  batch.Put(key, value);
1492
534
  return Write(opt, &batch);
1493
534
}
1494
1495
18
Status DB::Delete(const WriteOptions& opt, const Slice& key) {
1496
18
  WriteBatch batch;
1497
18
  batch.Delete(key);
1498
18
  return Write(opt, &batch);
1499
18
}
1500
1501
108
DB::~DB() = default;
1502
1503
108
Status DB::Open(const Options& options, const std::string& dbname, DB** dbptr) {
1504
108
  *dbptr = nullptr;
1505
1506
108
  DBImpl* impl = new DBImpl(options, dbname);
1507
108
  impl->mutex_.Lock();
1508
108
  VersionEdit edit;
1509
  // Recover handles create_if_missing, error_if_exists
1510
108
  bool save_manifest = false;
1511
108
  Status s = impl->Recover(&edit, &save_manifest);
1512
108
  if (s.ok() && impl->mem_ == nullptr) {
1513
    // Create new log and a corresponding memtable.
1514
108
    uint64_t new_log_number = impl->versions_->NewFileNumber();
1515
108
    WritableFile* lfile;
1516
108
    s = options.env->NewWritableFile(LogFileName(dbname, new_log_number),
1517
108
                                     &lfile);
1518
108
    if (s.ok()) {
1519
108
      edit.SetLogNumber(new_log_number);
1520
108
      impl->logfile_ = lfile;
1521
108
      impl->logfile_number_ = new_log_number;
1522
108
      impl->log_ = new log::Writer(lfile);
1523
108
      impl->mem_ = new MemTable(impl->internal_comparator_);
1524
108
      impl->mem_->Ref();
1525
108
    }
1526
108
  }
1527
108
  if (s.ok() && save_manifest) {
1528
108
    edit.SetPrevLogNumber(0);  // No older logs needed after recovery.
1529
108
    edit.SetLogNumber(impl->logfile_number_);
1530
108
    s = impl->versions_->LogAndApply(&edit, &impl->mutex_);
1531
108
  }
1532
108
  if (s.ok()) {
1533
108
    impl->RemoveObsoleteFiles();
1534
108
    impl->MaybeScheduleCompaction();
1535
108
  }
1536
108
  impl->mutex_.Unlock();
1537
108
  if (s.ok()) {
1538
108
    assert(impl->mem_ != nullptr);
1539
108
    *dbptr = impl;
1540
108
  } else {
1541
0
    delete impl;
1542
0
  }
1543
108
  return s;
1544
108
}
1545
1546
136
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