db_impl.h 24.1 KB
Newer Older
1 2 3 4 5
//  Copyright (c) 2013, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//
J
jorlow@chromium.org 已提交
6 7 8
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
9
#pragma once
H
Haobo Xu 已提交
10
#include <atomic>
11
#include <deque>
J
jorlow@chromium.org 已提交
12
#include <set>
13
#include <vector>
J
jorlow@chromium.org 已提交
14 15 16
#include "db/dbformat.h"
#include "db/log_writer.h"
#include "db/snapshot.h"
17
#include "db/version_edit.h"
18 19 20 21
#include "rocksdb/db.h"
#include "rocksdb/env.h"
#include "rocksdb/memtablerep.h"
#include "rocksdb/transaction_log.h"
J
jorlow@chromium.org 已提交
22
#include "port/port.h"
23
#include "util/stats_logger.h"
24
#include "memtablelist.h"
25
#include "util/autovector.h"
26

27
namespace rocksdb {
J
jorlow@chromium.org 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40

class MemTable;
class TableCache;
class Version;
class VersionEdit;
class VersionSet;

class DBImpl : public DB {
 public:
  DBImpl(const Options& options, const std::string& dbname);
  virtual ~DBImpl();

  // Implementations of the DB interface
41 42 43 44 45 46 47 48 49 50 51 52 53
  using DB::Put;
  virtual Status Put(const WriteOptions& options,
                     const ColumnFamilyHandle& column_family, const Slice& key,
                     const Slice& value);
  using DB::Merge;
  virtual Status Merge(const WriteOptions& options,
                       const ColumnFamilyHandle& column_family,
                       const Slice& key, const Slice& value);
  using DB::Delete;
  virtual Status Delete(const WriteOptions& options,
                        const ColumnFamilyHandle& column_family,
                        const Slice& key);
  using DB::Write;
J
jorlow@chromium.org 已提交
54
  virtual Status Write(const WriteOptions& options, WriteBatch* updates);
55
  using DB::Get;
J
jorlow@chromium.org 已提交
56
  virtual Status Get(const ReadOptions& options,
57
                     const ColumnFamilyHandle& column_family, const Slice& key,
J
jorlow@chromium.org 已提交
58
                     std::string* value);
59 60 61 62 63
  using DB::MultiGet;
  virtual std::vector<Status> MultiGet(
      const ReadOptions& options,
      const std::vector<ColumnFamilyHandle>& column_family,
      const std::vector<Slice>& keys, std::vector<std::string>* values);
64

65
  virtual Status CreateColumnFamily(const ColumnFamilyOptions& options,
66
                                    const std::string& column_family,
67 68 69
                                    ColumnFamilyHandle* handle);
  virtual Status DropColumnFamily(const ColumnFamilyHandle& column_family);

70 71 72 73
  // Returns false if key doesn't exist in the database and true if it may.
  // If value_found is not passed in as null, then return the value if found in
  // memory. On return, if value was found, then value_found will be set to true
  // , otherwise false.
74
  using DB::KeyMayExist;
75
  virtual bool KeyMayExist(const ReadOptions& options,
76 77
                           const ColumnFamilyHandle& column_family,
                           const Slice& key, std::string* value,
78
                           bool* value_found = nullptr);
79 80 81 82 83 84 85
  using DB::NewIterator;
  virtual Iterator* NewIterator(const ReadOptions& options,
                                const ColumnFamilyHandle& column_family);
  virtual Status NewIterators(
      const ReadOptions& options,
      const std::vector<ColumnFamilyHandle>& column_family,
      std::vector<Iterator*>* iterators);
J
jorlow@chromium.org 已提交
86 87
  virtual const Snapshot* GetSnapshot();
  virtual void ReleaseSnapshot(const Snapshot* snapshot);
88 89 90 91 92 93 94 95 96
  using DB::GetProperty;
  virtual bool GetProperty(const ColumnFamilyHandle& column_family,
                           const Slice& property, std::string* value);
  using DB::GetApproximateSizes;
  virtual void GetApproximateSizes(const ColumnFamilyHandle& column_family,
                                   const Range* range, int n, uint64_t* sizes);
  using DB::CompactRange;
  virtual void CompactRange(const ColumnFamilyHandle& column_family,
                            const Slice* begin, const Slice* end,
97
                            bool reduce_level = false, int target_level = -1);
98 99 100 101 102 103 104

  using DB::NumberLevels;
  virtual int NumberLevels(const ColumnFamilyHandle& column_family);
  using DB::MaxMemCompactionLevel;
  virtual int MaxMemCompactionLevel(const ColumnFamilyHandle& column_family);
  using DB::Level0StopWriteTrigger;
  virtual int Level0StopWriteTrigger(const ColumnFamilyHandle& column_family);
I
Igor Canadi 已提交
105
  virtual const std::string& GetName() const;
106
  virtual Env* GetEnv() const;
107 108 109 110 111 112
  using DB::GetOptions;
  virtual const Options& GetOptions(const ColumnFamilyHandle& column_family)
      const;
  using DB::Flush;
  virtual Status Flush(const FlushOptions& options,
                       const ColumnFamilyHandle& column_family);
113
  virtual Status DisableFileDeletions();
114
  virtual Status EnableFileDeletions(bool force);
I
Igor Canadi 已提交
115
  // All the returned filenames start with "/"
116
  virtual Status GetLiveFiles(std::vector<std::string>&,
117 118
                              uint64_t* manifest_file_size,
                              bool flush_memtable = true);
119
  virtual Status GetSortedWalFiles(VectorLogPtr& files);
120
  virtual SequenceNumber GetLatestSequenceNumber() const;
121
  virtual Status GetUpdatesSince(SequenceNumber seq_number,
122
                                 unique_ptr<TransactionLogIterator>* iter);
123 124
  virtual Status DeleteFile(std::string name);

125
  virtual void GetLiveFilesMetaData(std::vector<LiveFileMetaData>* metadata);
126

127 128
  virtual Status GetDbIdentity(std::string& identity);

129 130 131 132 133
  void RunManualCompaction(int input_level,
                           int output_level,
                           const Slice* begin,
                           const Slice* end);

J
jorlow@chromium.org 已提交
134 135
  // Extra methods (for testing) that are not in the public DB interface

136
  // Compact any files in the named level that overlap [*begin, *end]
137 138 139
  void TEST_CompactRange(int level,
                         const Slice* begin,
                         const Slice* end);
J
jorlow@chromium.org 已提交
140

141 142
  // Force current memtable contents to be flushed.
  Status TEST_FlushMemTable();
J
jorlow@chromium.org 已提交
143

144
  // Wait for memtable compaction
145
  Status TEST_WaitForFlushMemTable();
146 147 148 149

  // Wait for any compaction
  Status TEST_WaitForCompact();

J
jorlow@chromium.org 已提交
150 151 152 153 154
  // Return an internal iterator over the current state of the database.
  // The keys of this iterator are internal keys (see format.h).
  // The returned iterator should be deleted when no longer needed.
  Iterator* TEST_NewInternalIterator();

155 156
  // Return the maximum overlapping data (in bytes) at next level for any
  // file at a level >= 1.
J
jorlow@chromium.org 已提交
157
  int64_t TEST_MaxNextLevelOverlappingBytes();
158

159 160 161
  // Simulate a db crash, no elegant closing of database.
  void TEST_Destroy_DBImpl();

A
Abhishek Kona 已提交
162 163
  // Return the current manifest file no.
  uint64_t TEST_Current_Manifest_FileNo();
164 165 166 167

  // Trigger's a background call for testing.
  void TEST_PurgeObsoleteteWAL();

168
  // get total level0 file size. Only for testing.
169
  uint64_t TEST_GetLevel0TotalSize();
170

171 172 173 174 175
  void TEST_SetDefaultTimeToCheck(uint64_t default_interval_to_delete_obsolete_WAL)
  {
    default_interval_to_delete_obsolete_WAL_ = default_interval_to_delete_obsolete_WAL;
  }

I
Igor Canadi 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
  // holds references to memtable, all immutable memtables and version
  struct SuperVersion {
    MemTable* mem;
    MemTableList imm;
    Version* current;
    std::atomic<uint32_t> refs;
    // We need to_delete because during Cleanup(), imm.UnrefAll() returns
    // all memtables that we need to free through this vector. We then
    // delete all those memtables outside of mutex, during destruction
    std::vector<MemTable*> to_delete;

    // should be called outside the mutex
    explicit SuperVersion(const int num_memtables = 0);
    ~SuperVersion();
    SuperVersion* Ref();
    // Returns true if this was the last reference and caller should
    // call Clenaup() and delete the object
    bool Unref();

    // call these two methods with db mutex held
    // Cleanup unrefs mem, imm and current. Also, it stores all memtables
    // that needs to be deleted in to_delete vector. Unrefing those
    // objects needs to be done in the mutex
    void Cleanup();
    void Init(MemTable* new_mem, const MemTableList& new_imm,
              Version* new_current);
  };
I
Igor Canadi 已提交
203

I
Igor Canadi 已提交
204
  // needed for CleanupIteratorState
I
Igor Canadi 已提交
205 206
  struct DeletionState {
    inline bool HaveSomethingToDelete() const {
I
Igor Canadi 已提交
207
      return  all_files.size() ||
I
Igor Canadi 已提交
208 209 210
        sst_delete_files.size() ||
        log_delete_files.size();
    }
211

I
Igor Canadi 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225
    // a list of all files that we'll consider deleting
    // (every once in a while this is filled up with all files
    // in the DB directory)
    std::vector<std::string> all_files;

    // the list of all live sst files that cannot be deleted
    std::vector<uint64_t> sst_live;

    // a list of sst files that we need to delete
    std::vector<FileMetaData*> sst_delete_files;

    // a list of log files that we need to delete
    std::vector<uint64_t> log_delete_files;

226 227 228
    // a list of memtables to be free
    std::vector<MemTable *> memtables_to_free;

I
Igor Canadi 已提交
229 230 231 232
    SuperVersion* superversion_to_free; // if nullptr nothing to free

    SuperVersion* new_superversion; // if nullptr no new superversion

I
Igor Canadi 已提交
233 234 235 236
    // the current manifest_file_number, log_number and prev_log_number
    // that corresponds to the set of files in 'live'.
    uint64_t manifest_file_number, log_number, prev_log_number;

I
Igor Canadi 已提交
237 238
    explicit DeletionState(const int num_memtables = 0,
                           bool create_superversion = false) {
I
Igor Canadi 已提交
239 240 241
      manifest_file_number = 0;
      log_number = 0;
      prev_log_number = 0;
242
      memtables_to_free.reserve(num_memtables);
I
Igor Canadi 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
      superversion_to_free = nullptr;
      new_superversion =
          create_superversion ? new SuperVersion(num_memtables) : nullptr;
    }

    ~DeletionState() {
      // free pending memtables
      for (auto m : memtables_to_free) {
        delete m;
      }
      // free superversion. if nullptr, this will be noop
      delete superversion_to_free;
      // if new_superversion was not used, it will be non-nullptr and needs
      // to be freed here
      delete new_superversion;
I
Igor Canadi 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    }
  };

  // Returns the list of live files in 'live' and the list
  // of all files in the filesystem in 'all_files'.
  // If force == false and the last call was less than
  // options_.delete_obsolete_files_period_micros microseconds ago,
  // it will not fill up the deletion_state
  void FindObsoleteFiles(DeletionState& deletion_state,
                         bool force,
                         bool no_full_scan = false);

  // Diffs the files listed in filenames and those that do not
  // belong to live files are posibly removed. Also, removes all the
  // files in sst_delete_files and log_delete_files.
  // It is not necessary to hold the mutex when invoking this method.
  void PurgeObsoleteFiles(DeletionState& deletion_state);

276
 protected:
H
heyongqiang 已提交
277 278
  Env* const env_;
  const std::string dbname_;
279
  unique_ptr<VersionSet> versions_;
H
heyongqiang 已提交
280 281 282 283 284 285
  const InternalKeyComparator internal_comparator_;
  const Options options_;  // options_.comparator == &internal_comparator_

  const Comparator* user_comparator() const {
    return internal_comparator_.user_comparator();
  }
286

287 288
  MemTable* GetMemTable() {
    return mem_;
A
Abhishek Kona 已提交
289
  }
H
heyongqiang 已提交
290

291 292 293
  Iterator* NewInternalIterator(const ReadOptions&,
                                SequenceNumber* latest_snapshot);

J
jorlow@chromium.org 已提交
294 295
 private:
  friend class DB;
296 297
  struct CompactionState;
  struct Writer;
J
jorlow@chromium.org 已提交
298 299 300 301 302 303

  Status NewDB();

  // Recover the descriptor from persistent storage.  May do a significant
  // amount of work to recover recently logged updates.  Any changes to
  // be made to the descriptor are added to *edit.
304 305
  Status Recover(const std::vector<ColumnFamilyDescriptor>& column_families,
                 bool read_only = false, bool error_if_log_file_exist = false);
J
jorlow@chromium.org 已提交
306 307 308

  void MaybeIgnoreError(Status* s) const;

309 310
  const Status CreateArchivalDirectory();

J
jorlow@chromium.org 已提交
311 312 313
  // Delete any unneeded files and stale in-memory entries.
  void DeleteObsoleteFiles();

314
  // Flush the in-memory write buffer to storage.  Switches to a new
J
jorlow@chromium.org 已提交
315
  // log-file/memtable and writes a new descriptor iff successful.
I
Igor Canadi 已提交
316 317
  Status FlushMemTableToOutputFile(bool* madeProgress,
                                   DeletionState& deletion_state);
J
jorlow@chromium.org 已提交
318

I
Igor Canadi 已提交
319 320
  Status RecoverLogFile(uint64_t log_number, SequenceNumber* max_sequence,
                        bool read_only);
J
jorlow@chromium.org 已提交
321

322 323 324 325 326 327
  // The following two methods are used to flush a memtable to
  // storage. The first one is used atdatabase RecoveryTime (when the
  // database is opened) and is heavyweight because it holds the mutex
  // for the entire period. The second method WriteLevel0Table supports
  // concurrent flush memtables to storage.
  Status WriteLevel0TableForRecovery(MemTable* mem, VersionEdit* edit);
328
  Status WriteLevel0Table(std::vector<MemTable*> &mems, VersionEdit* edit,
329
                                uint64_t* filenumber);
J
jorlow@chromium.org 已提交
330

M
Mark Callaghan 已提交
331
  uint64_t SlowdownAmount(int n, double bottom, double top);
I
Igor Canadi 已提交
332 333 334 335 336
  // MakeRoomForWrite will return superversion_to_free through an arugment,
  // which the caller needs to delete. We do it because caller can delete
  // the superversion outside of mutex
  Status MakeRoomForWrite(bool force /* compact even if there is room? */,
                          SuperVersion** superversion_to_free);
337 338
  void BuildBatchGroup(Writer** last_writer,
                       autovector<WriteBatch*>* write_batch_group);
J
jorlow@chromium.org 已提交
339

H
heyongqiang 已提交
340 341 342
  // Force current memtable contents to be flushed.
  Status FlushMemTable(const FlushOptions& options);

343 344
  // Wait for memtable flushed
  Status WaitForFlushMemTable();
H
heyongqiang 已提交
345

346
  void MaybeScheduleLogDBDeployStats();
347 348
  static void BGLogDBDeployStats(void* db);
  void LogDBDeployStats();
349

350
  void MaybeScheduleFlushOrCompaction();
351 352 353 354
  static void BGWorkCompaction(void* db);
  static void BGWorkFlush(void* db);
  void BackgroundCallCompaction();
  void BackgroundCallFlush();
355
  Status BackgroundCompaction(bool* madeProgress,DeletionState& deletion_state);
I
Igor Canadi 已提交
356
  Status BackgroundFlush(bool* madeProgress, DeletionState& deletion_state);
357
  void CleanupCompaction(CompactionState* compact, Status status);
I
Igor Canadi 已提交
358 359
  Status DoCompactionWork(CompactionState* compact,
                          DeletionState& deletion_state);
J
jorlow@chromium.org 已提交
360 361 362 363

  Status OpenCompactionOutputFile(CompactionState* compact);
  Status FinishCompactionOutputFile(CompactionState* compact, Iterator* input);
  Status InstallCompactionResults(CompactionState* compact);
364 365
  void AllocateCompactionOutputFileNumbers(CompactionState* compact);
  void ReleaseCompactionUnusedFileNumbers(CompactionState* compact);
A
Abhishek Kona 已提交
366

367
  void PurgeObsoleteWALFiles();
368

369 370 371
  Status AppendSortedWalsOfType(const std::string& path,
                                VectorLogPtr& log_files,
                                WalFileType type);
372

373 374 375 376 377
  // Requires: all_logs should be sorted with earliest log file first
  // Retains all log files in all_logs which contain updates with seq no.
  // Greater Than or Equal to the requested SequenceNumber.
  Status RetainProbableWalFiles(VectorLogPtr& all_logs,
                                const SequenceNumber target);
378
  //  return true if
379 380
  bool CheckWalFileExistsAndEmpty(const WalFileType type,
                                  const uint64_t number);
381

382 383
  Status ReadFirstRecord(const WalFileType type, const uint64_t number,
                         WriteBatch* const result);
384 385

  Status ReadFirstLine(const std::string& fname, WriteBatch* const batch);
386

387 388
  void PrintStatistics();

389
  // dump rocksdb.stats to LOG
390 391
  void MaybeDumpStats();

392 393 394 395
  // Return the minimum empty level that could hold the total data in the
  // input level. Return the input level, if such level could not be found.
  int FindMinimumEmptyLevelFitting(int level);

396 397 398 399
  // Move the files in the input level to the target level.
  // If target_level < 0, automatically calculate the minimum level that could
  // hold the data set.
  void ReFitLevel(int level, int target_level = -1);
400

J
jorlow@chromium.org 已提交
401
  // Constant after construction
S
Sanjay Ghemawat 已提交
402
  const InternalFilterPolicy internal_filter_policy_;
J
jorlow@chromium.org 已提交
403 404 405
  bool owns_info_log_;

  // table_cache_ provides its own synchronization
406
  unique_ptr<TableCache> table_cache_;
J
jorlow@chromium.org 已提交
407

408
  // Lock over the persistent DB state.  Non-nullptr iff successfully acquired.
J
jorlow@chromium.org 已提交
409 410 411 412 413
  FileLock* db_lock_;

  // State below is protected by mutex_
  port::Mutex mutex_;
  port::AtomicPointer shutting_down_;
H
hans@chromium.org 已提交
414
  port::CondVar bg_cv_;          // Signalled when background work finishes
I
Igor Canadi 已提交
415
  MemTableRepFactory* mem_rep_factory_;
J
jorlow@chromium.org 已提交
416
  MemTable* mem_;
417
  MemTableList imm_;             // Memtable that are not changing
418
  uint64_t logfile_number_;
419
  unique_ptr<log::Writer> log_;
420

I
Igor Canadi 已提交
421 422
  SuperVersion* super_version_;

423 424
  std::string host_name_;

425 426
  // Queue of writers.
  std::deque<Writer*> writers_;
427
  WriteBatch tmp_batch_;
428

J
jorlow@chromium.org 已提交
429 430 431 432 433 434
  SnapshotList snapshots_;

  // Set of table files to protect from deletion because they are
  // part of ongoing compactions.
  std::set<uint64_t> pending_outputs_;

435
  // count how many background compactions are running or have been scheduled
436
  int bg_compaction_scheduled_;
J
jorlow@chromium.org 已提交
437

438 439 440 441 442
  // If non-zero, MaybeScheduleFlushOrCompaction() will only schedule manual
  // compactions (if manual_compaction_ is not null). This mechanism enables
  // manual compactions to wait until all other compactions are finished.
  int bg_manual_only_;

443 444 445
  // number of background memtable flush jobs, submitted to the HIGH pool
  int bg_flush_scheduled_;

446 447 448
  // Has a background stats log thread scheduled?
  bool bg_logstats_scheduled_;

H
hans@chromium.org 已提交
449 450
  // Information for a manual compaction
  struct ManualCompaction {
451 452
    int input_level;
    int output_level;
G
Gabor Cselle 已提交
453
    bool done;
454
    bool in_progress;           // compaction request being processed?
455 456
    const InternalKey* begin;   // nullptr means beginning of key range
    const InternalKey* end;     // nullptr means end of key range
G
Gabor Cselle 已提交
457
    InternalKey tmp_storage;    // Used to keep track of compaction progress
H
hans@chromium.org 已提交
458 459
  };
  ManualCompaction* manual_compaction_;
J
jorlow@chromium.org 已提交
460 461 462 463

  // Have we encountered a background error in paranoid mode?
  Status bg_error_;

464
  std::unique_ptr<StatsLogger> logger_;
465

466
  int64_t volatile last_log_ts;
467

468
  // shall we disable deletion of obsolete files
469 470 471 472 473 474
  // if 0 the deletion is enabled.
  // if non-zero, files will not be getting deleted
  // This enables two different threads to call
  // EnableFileDeletions() and DisableFileDeletions()
  // without any synchronization
  int disable_delete_obsolete_files_;
475

476 477 478
  // last time when DeleteObsoleteFiles was invoked
  uint64_t delete_obsolete_files_last_run_;

479 480 481
  // last time when PurgeObsoleteWALFiles ran.
  uint64_t purge_wal_files_last_run_;

482
  // last time stats were dumped to LOG
H
Haobo Xu 已提交
483
  std::atomic<uint64_t> last_stats_dump_time_microsec_;
484

485 486 487 488
  // obsolete files will be deleted every this seconds if ttl deletion is
  // enabled and archive size_limit is disabled.
  uint64_t default_interval_to_delete_obsolete_WAL_;

M
Mark Callaghan 已提交
489 490 491 492
  // These count the number of microseconds for which MakeRoomForWrite stalls.
  uint64_t stall_level0_slowdown_;
  uint64_t stall_memtable_compaction_;
  uint64_t stall_level0_num_files_;
493
  std::vector<uint64_t> stall_leveln_slowdown_;
J
Jim Paton 已提交
494 495 496 497
  uint64_t stall_level0_slowdown_count_;
  uint64_t stall_memtable_compaction_count_;
  uint64_t stall_level0_num_files_count_;
  std::vector<uint64_t> stall_leveln_slowdown_count_;
M
Mark Callaghan 已提交
498 499 500 501

  // Time at which this instance was started.
  const uint64_t started_at_;

502 503
  bool flush_on_destroy_; // Used when disableWAL is true.

504 505 506
  // Per level compaction stats.  stats_[level] stores the stats for
  // compactions that produced data for the specified "level".
  struct CompactionStats {
A
Abhishek Kona 已提交
507
    uint64_t micros;
M
Mark Callaghan 已提交
508 509 510 511 512 513 514 515

    // Bytes read from level N during compaction between levels N and N+1
    int64_t bytes_readn;

    // Bytes read from level N+1 during compaction between levels N and N+1
    int64_t bytes_readnp1;

    // Total bytes written during compaction between levels N and N+1
516 517
    int64_t bytes_written;

M
Mark Callaghan 已提交
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
    // Files read from level N during compaction between levels N and N+1
    int     files_in_leveln;

    // Files read from level N+1 during compaction between levels N and N+1
    int     files_in_levelnp1;

    // Files written during compaction between levels N and N+1
    int     files_out_levelnp1;

    // Number of compactions done
    int     count;

    CompactionStats() : micros(0), bytes_readn(0), bytes_readnp1(0),
                        bytes_written(0), files_in_leveln(0),
                        files_in_levelnp1(0), files_out_levelnp1(0),
                        count(0) { }
534 535 536

    void Add(const CompactionStats& c) {
      this->micros += c.micros;
M
Mark Callaghan 已提交
537 538
      this->bytes_readn += c.bytes_readn;
      this->bytes_readnp1 += c.bytes_readnp1;
539
      this->bytes_written += c.bytes_written;
M
Mark Callaghan 已提交
540 541 542 543
      this->files_in_leveln += c.files_in_leveln;
      this->files_in_levelnp1 += c.files_in_levelnp1;
      this->files_out_levelnp1 += c.files_out_levelnp1;
      this->count += 1;
544 545
    }
  };
M
Mark Callaghan 已提交
546

547
  std::vector<CompactionStats> stats_;
548

549 550
  // Used to compute per-interval statistics
  struct StatsSnapshot {
551 552 553 554 555 556 557 558 559 560
    uint64_t compaction_bytes_read_;     // Bytes read by compaction
    uint64_t compaction_bytes_written_;  // Bytes written by compaction
    uint64_t ingest_bytes_;              // Bytes written by user
    uint64_t wal_bytes_;                 // Bytes written to WAL
    uint64_t wal_synced_;                // Number of times WAL is synced
    uint64_t write_with_wal_;            // Number of writes that request WAL
    // These count the number of writes processed by the calling thread or
    // another thread.
    uint64_t write_other_;
    uint64_t write_self_;
561 562
    double   seconds_up_;

563 564 565 566
    StatsSnapshot() : compaction_bytes_read_(0), compaction_bytes_written_(0),
                      ingest_bytes_(0), wal_bytes_(0), wal_synced_(0),
                      write_with_wal_(0), write_other_(0), write_self_(0),
                      seconds_up_(0) {}
567 568
  };

569
  // Counters from the previous time per-interval stats were computed
570 571
  StatsSnapshot last_stats_;

H
heyongqiang 已提交
572
  static const int KEEP_LOG_FILE_NUM = 1000;
H
heyongqiang 已提交
573
  std::string db_absolute_path_;
H
heyongqiang 已提交
574

575 576 577
  // count of the number of contiguous delaying writes
  int delayed_writes_;

578
  // The options to access storage files
H
Haobo Xu 已提交
579
  const EnvOptions storage_options_;
580

581 582 583 584 585 586
  // A value of true temporarily disables scheduling of background work
  bool bg_work_gate_closed_;

  // Guard against multiple concurrent refitting
  bool refitting_level_;

J
jorlow@chromium.org 已提交
587 588 589 590
  // No copying allowed
  DBImpl(const DBImpl&);
  void operator=(const DBImpl&);

591 592
  // dump the delayed_writes_ to the log file and reset counter.
  void DelayLoggingAndReset();
593

594 595 596 597 598 599
  // Return the earliest snapshot where seqno is visible.
  // Store the snapshot right before that, if any, in prev_snapshot
  inline SequenceNumber findEarliestVisibleSnapshot(
    SequenceNumber in,
    std::vector<SequenceNumber>& snapshots,
    SequenceNumber* prev_snapshot);
600

I
Igor Canadi 已提交
601 602 603 604 605 606 607 608 609 610 611 612
  // will return a pointer to SuperVersion* if previous SuperVersion
  // if its reference count is zero and needs deletion or nullptr if not
  // As argument takes a pointer to allocated SuperVersion
  // Foreground threads call this function directly (they don't carry
  // deletion state and have to handle their own creation and deletion
  // of SuperVersion)
  SuperVersion* InstallSuperVersion(SuperVersion* new_superversion);
  // Background threads call this function, which is just a wrapper around
  // the InstallSuperVersion() function above. Background threads carry
  // deletion_state which can have new_superversion already allocated.
  void InstallSuperVersion(DeletionState& deletion_state);

613 614
  // Function that Get and KeyMayExist call with no_io true or false
  // Note: 'value_found' from KeyMayExist propagates here
615 616 617
  Status GetImpl(const ReadOptions& options,
                 const Slice& key,
                 std::string* value,
618
                 bool* value_found = nullptr);
J
jorlow@chromium.org 已提交
619 620 621 622 623 624
};

// Sanitize db options.  The caller should delete result.info_log if
// it is not equal to src.info_log.
extern Options SanitizeOptions(const std::string& db,
                               const InternalKeyComparator* icmp,
S
Sanjay Ghemawat 已提交
625
                               const InternalFilterPolicy* ipolicy,
J
jorlow@chromium.org 已提交
626 627
                               const Options& src);

S
Siying Dong 已提交
628 629 630 631 632 633 634 635 636

// Determine compression type, based on user options, level of the output
// file and whether compression is disabled.
// If enable_compression is false, then compression is always disabled no
// matter what the values of the other two parameters are.
// Otherwise, the compression type is determined based on options and level.
CompressionType GetCompressionType(const Options& options, int level,
                                   const bool enable_compression);

637 638 639
// Determine compression type for L0 file written by memtable flush.
CompressionType GetCompressionFlush(const Options& options);

640
}  // namespace rocksdb