Coverage Report

Created: 2023-01-25 06:32

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