db_impl.h 16.2 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 18 19 20
#include "rocksdb/db.h"
#include "rocksdb/env.h"
#include "rocksdb/memtablerep.h"
#include "rocksdb/transaction_log.h"
J
jorlow@chromium.org 已提交
21
#include "port/port.h"
22
#include "util/stats_logger.h"
23
#include "memtablelist.h"
24

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

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
  virtual Status Put(const WriteOptions&, const Slice& key, const Slice& value);
40 41
  virtual Status Merge(const WriteOptions&, const Slice& key,
                       const Slice& value);
J
jorlow@chromium.org 已提交
42 43 44 45 46
  virtual Status Delete(const WriteOptions&, const Slice& key);
  virtual Status Write(const WriteOptions& options, WriteBatch* updates);
  virtual Status Get(const ReadOptions& options,
                     const Slice& key,
                     std::string* value);
47 48 49
  virtual std::vector<Status> MultiGet(const ReadOptions& options,
                                       const std::vector<Slice>& keys,
                                       std::vector<std::string>* values);
50

51 52 53 54 55 56 57 58
  // 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.
  virtual bool KeyMayExist(const ReadOptions& options,
                           const Slice& key,
                           std::string* value,
                           bool* value_found = nullptr);
J
jorlow@chromium.org 已提交
59 60 61
  virtual Iterator* NewIterator(const ReadOptions&);
  virtual const Snapshot* GetSnapshot();
  virtual void ReleaseSnapshot(const Snapshot* snapshot);
62
  virtual bool GetProperty(const Slice& property, std::string* value);
J
jorlow@chromium.org 已提交
63
  virtual void GetApproximateSizes(const Range* range, int n, uint64_t* sizes);
64
  virtual void CompactRange(const Slice* begin, const Slice* end,
65
                            bool reduce_level = false, int target_level = -1);
66 67 68
  virtual int NumberLevels();
  virtual int MaxMemCompactionLevel();
  virtual int Level0StopWriteTrigger();
H
heyongqiang 已提交
69
  virtual Status Flush(const FlushOptions& options);
70 71
  virtual Status DisableFileDeletions();
  virtual Status EnableFileDeletions();
72
  virtual Status GetLiveFiles(std::vector<std::string>&,
73 74
                              uint64_t* manifest_file_size,
                              bool flush_memtable = true);
75
  virtual Status GetSortedWalFiles(VectorLogPtr& files);
76
  virtual SequenceNumber GetLatestSequenceNumber() const;
77
  virtual Status GetUpdatesSince(SequenceNumber seq_number,
78
                                 unique_ptr<TransactionLogIterator>* iter);
79 80 81 82
  virtual Status DeleteFile(std::string name);

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

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

86
  // Compact any files in the named level that overlap [*begin, *end]
G
Gabor Cselle 已提交
87
  void TEST_CompactRange(int level, const Slice* begin, const Slice* end);
J
jorlow@chromium.org 已提交
88

89 90
  // Force current memtable contents to be flushed.
  Status TEST_FlushMemTable();
J
jorlow@chromium.org 已提交
91

92
  // Wait for memtable compaction
93
  Status TEST_WaitForFlushMemTable();
94 95 96 97

  // Wait for any compaction
  Status TEST_WaitForCompact();

J
jorlow@chromium.org 已提交
98 99 100 101 102
  // 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();

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

107 108 109
  // Simulate a db crash, no elegant closing of database.
  void TEST_Destroy_DBImpl();

A
Abhishek Kona 已提交
110 111
  // Return the current manifest file no.
  uint64_t TEST_Current_Manifest_FileNo();
112 113 114 115

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

116 117 118
  // get total level0 file size. Only for testing.
  uint64_t TEST_GetLevel0TotalSize() { return versions_->NumLevelBytes(0);}

119
 protected:
H
heyongqiang 已提交
120 121
  Env* const env_;
  const std::string dbname_;
122
  unique_ptr<VersionSet> versions_;
H
heyongqiang 已提交
123 124 125 126 127 128
  const InternalKeyComparator internal_comparator_;
  const Options options_;  // options_.comparator == &internal_comparator_

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

130 131
  MemTable* GetMemTable() {
    return mem_;
A
Abhishek Kona 已提交
132
  }
H
heyongqiang 已提交
133

134 135 136
  Iterator* NewInternalIterator(const ReadOptions&,
                                SequenceNumber* latest_snapshot);

J
jorlow@chromium.org 已提交
137 138
 private:
  friend class DB;
139 140
  struct CompactionState;
  struct Writer;
D
Dhruba Borthakur 已提交
141
  struct DeletionState;
J
jorlow@chromium.org 已提交
142 143 144 145 146 147

  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.
148
  Status Recover(VersionEdit* edit, MemTable* external_table = nullptr,
H
heyongqiang 已提交
149
      bool error_if_log_file_exist = false);
J
jorlow@chromium.org 已提交
150 151 152

  void MaybeIgnoreError(Status* s) const;

153 154
  const Status CreateArchivalDirectory();

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

158
  // Flush the in-memory write buffer to storage.  Switches to a new
J
jorlow@chromium.org 已提交
159
  // log-file/memtable and writes a new descriptor iff successful.
160
  Status FlushMemTableToOutputFile(bool* madeProgress = nullptr);
J
jorlow@chromium.org 已提交
161 162 163

  Status RecoverLogFile(uint64_t log_number,
                        VersionEdit* edit,
164 165
                        SequenceNumber* max_sequence,
                        MemTable* external_table);
J
jorlow@chromium.org 已提交
166

167 168 169 170 171 172
  // 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);
173
  Status WriteLevel0Table(std::vector<MemTable*> &mems, VersionEdit* edit,
174
                                uint64_t* filenumber);
J
jorlow@chromium.org 已提交
175

J
Jim Paton 已提交
176
  uint64_t SlowdownAmount(int n, int top, int bottom);
177
  Status MakeRoomForWrite(bool force /* compact even if there is room? */);
178
  WriteBatch* BuildBatchGroup(Writer** last_writer);
J
jorlow@chromium.org 已提交
179

H
heyongqiang 已提交
180 181 182
  // Force current memtable contents to be flushed.
  Status FlushMemTable(const FlushOptions& options);

183 184
  // Wait for memtable flushed
  Status WaitForFlushMemTable();
H
heyongqiang 已提交
185

186
  void MaybeScheduleLogDBDeployStats();
187 188
  static void BGLogDBDeployStats(void* db);
  void LogDBDeployStats();
189

190
  void MaybeScheduleFlushOrCompaction();
191 192 193 194
  static void BGWorkCompaction(void* db);
  static void BGWorkFlush(void* db);
  void BackgroundCallCompaction();
  void BackgroundCallFlush();
195
  Status BackgroundCompaction(bool* madeProgress,DeletionState& deletion_state);
196
  Status BackgroundFlush(bool* madeProgress);
197
  void CleanupCompaction(CompactionState* compact, Status status);
J
jorlow@chromium.org 已提交
198 199 200 201 202
  Status DoCompactionWork(CompactionState* compact);

  Status OpenCompactionOutputFile(CompactionState* compact);
  Status FinishCompactionOutputFile(CompactionState* compact, Iterator* input);
  Status InstallCompactionResults(CompactionState* compact);
203 204
  void AllocateCompactionOutputFileNumbers(CompactionState* compact);
  void ReleaseCompactionUnusedFileNumbers(CompactionState* compact);
A
Abhishek Kona 已提交
205

J
jorlow@chromium.org 已提交
206

D
Dhruba Borthakur 已提交
207 208 209 210 211 212 213 214 215 216 217 218
  // Returns the list of live files in 'live' and the list
  // of all files in the filesystem in 'allfiles'.
  void FindObsoleteFiles(DeletionState& deletion_state);

  // Diffs the files listed in filenames and those that do not
  // belong to live files are posibly removed. If the removed file
  // is a sst file, then it returns the file number in files_to_evict.
  void PurgeObsoleteFiles(DeletionState& deletion_state);

  // Removes the file listed in files_to_evict from the table_cache
  void EvictObsoleteFiles(DeletionState& deletion_state);

219 220
  Status DeleteLogFile(uint64_t number);

221
  void PurgeObsoleteWALFiles();
222

223 224 225
  Status AppendSortedWalsOfType(const std::string& path,
                                VectorLogPtr& log_files,
                                WalFileType type);
226

227 228 229 230 231
  // 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);
232
  //  return true if
233 234
  bool CheckWalFileExistsAndEmpty(const WalFileType type,
                                  const uint64_t number);
235

236 237
  Status ReadFirstRecord(const WalFileType type, const uint64_t number,
                         WriteBatch* const result);
238 239

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

241 242
  void PrintStatistics();

243
  // dump rocksdb.stats to LOG
244 245
  void MaybeDumpStats();

246 247 248 249
  // 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);

250 251 252 253
  // 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);
254

J
jorlow@chromium.org 已提交
255
  // Constant after construction
S
Sanjay Ghemawat 已提交
256
  const InternalFilterPolicy internal_filter_policy_;
J
jorlow@chromium.org 已提交
257 258 259
  bool owns_info_log_;

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

262
  // Lock over the persistent DB state.  Non-nullptr iff successfully acquired.
J
jorlow@chromium.org 已提交
263 264 265 266 267
  FileLock* db_lock_;

  // State below is protected by mutex_
  port::Mutex mutex_;
  port::AtomicPointer shutting_down_;
H
hans@chromium.org 已提交
268
  port::CondVar bg_cv_;          // Signalled when background work finishes
J
Jim Paton 已提交
269
  std::shared_ptr<MemTableRepFactory> mem_rep_factory_;
J
jorlow@chromium.org 已提交
270
  MemTable* mem_;
271
  MemTableList imm_;             // Memtable that are not changing
272
  uint64_t logfile_number_;
273
  unique_ptr<log::Writer> log_;
274

275 276
  std::string host_name_;

277 278
  // Queue of writers.
  std::deque<Writer*> writers_;
279
  WriteBatch tmp_batch_;
280

J
jorlow@chromium.org 已提交
281 282 283 284 285 286
  SnapshotList snapshots_;

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

287 288
  // count how many background compaction been scheduled or is running?
  int bg_compaction_scheduled_;
J
jorlow@chromium.org 已提交
289

290 291 292
  // number of background memtable flush jobs, submitted to the HIGH pool
  int bg_flush_scheduled_;

293 294 295
  // Has a background stats log thread scheduled?
  bool bg_logstats_scheduled_;

H
hans@chromium.org 已提交
296 297 298
  // Information for a manual compaction
  struct ManualCompaction {
    int level;
G
Gabor Cselle 已提交
299
    bool done;
300
    bool in_progress;           // compaction request being processed?
301 302
    const InternalKey* begin;   // nullptr means beginning of key range
    const InternalKey* end;     // nullptr means end of key range
G
Gabor Cselle 已提交
303
    InternalKey tmp_storage;    // Used to keep track of compaction progress
H
hans@chromium.org 已提交
304 305
  };
  ManualCompaction* manual_compaction_;
J
jorlow@chromium.org 已提交
306 307 308 309

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

310
  std::unique_ptr<StatsLogger> logger_;
311

312
  int64_t volatile last_log_ts;
313

314 315 316
  // shall we disable deletion of obsolete files
  bool disable_delete_obsolete_files_;

317 318 319
  // last time when DeleteObsoleteFiles was invoked
  uint64_t delete_obsolete_files_last_run_;

320 321 322
  // last time when PurgeObsoleteWALFiles ran.
  uint64_t purge_wal_files_last_run_;

323
  // last time stats were dumped to LOG
H
Haobo Xu 已提交
324
  std::atomic<uint64_t> last_stats_dump_time_microsec_;
325

M
Mark Callaghan 已提交
326 327 328 329
  // 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_;
330
  std::vector<uint64_t> stall_leveln_slowdown_;
J
Jim Paton 已提交
331 332 333 334
  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 已提交
335 336 337 338

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

339 340
  bool flush_on_destroy_; // Used when disableWAL is true.

341 342 343
  // Per level compaction stats.  stats_[level] stores the stats for
  // compactions that produced data for the specified "level".
  struct CompactionStats {
A
Abhishek Kona 已提交
344
    uint64_t micros;
M
Mark Callaghan 已提交
345 346 347 348 349 350 351 352

    // 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
353 354
    int64_t bytes_written;

M
Mark Callaghan 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    // 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) { }
371 372 373

    void Add(const CompactionStats& c) {
      this->micros += c.micros;
M
Mark Callaghan 已提交
374 375
      this->bytes_readn += c.bytes_readn;
      this->bytes_readnp1 += c.bytes_readnp1;
376
      this->bytes_written += c.bytes_written;
M
Mark Callaghan 已提交
377 378 379 380
      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;
381 382
    }
  };
M
Mark Callaghan 已提交
383

384
  std::vector<CompactionStats> stats_;
385

386 387 388 389 390 391 392 393 394 395 396 397 398
  // Used to compute per-interval statistics
  struct StatsSnapshot {
    uint64_t bytes_read_;
    uint64_t bytes_written_;
    uint64_t bytes_new_;
    double   seconds_up_;

    StatsSnapshot() : bytes_read_(0), bytes_written_(0),
                      bytes_new_(0), seconds_up_(0) {}
  };

  StatsSnapshot last_stats_;

H
heyongqiang 已提交
399
  static const int KEEP_LOG_FILE_NUM = 1000;
H
heyongqiang 已提交
400
  std::string db_absolute_path_;
H
heyongqiang 已提交
401

402 403 404
  // count of the number of contiguous delaying writes
  int delayed_writes_;

405
  // The options to access storage files
H
Haobo Xu 已提交
406
  const EnvOptions storage_options_;
407

408 409 410 411 412 413
  // 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 已提交
414 415 416 417
  // No copying allowed
  DBImpl(const DBImpl&);
  void operator=(const DBImpl&);

418 419
  // dump the delayed_writes_ to the log file and reset counter.
  void DelayLoggingAndReset();
420

421 422 423 424 425 426
  // 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);
427

428 429
  // Function that Get and KeyMayExist call with no_io true or false
  // Note: 'value_found' from KeyMayExist propagates here
430 431 432
  Status GetImpl(const ReadOptions& options,
                 const Slice& key,
                 std::string* value,
433
                 bool* value_found = nullptr);
J
jorlow@chromium.org 已提交
434 435 436 437 438 439
};

// 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 已提交
440
                               const InternalFilterPolicy* ipolicy,
J
jorlow@chromium.org 已提交
441 442
                               const Options& src);

S
Siying Dong 已提交
443 444 445 446 447 448 449 450 451

// 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);

452
}  // namespace rocksdb