Coverage Report

Created: 2025-07-11 07:01

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