提供基本的ttl测试用例
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1567 lines
46 KiB

Release 1.18 Changes are: * Update version number to 1.18 * Replace the basic fprintf call with a call to fwrite in order to work around the apparent compiler optimization/rewrite failure that we are seeing with the new toolchain/iOS SDKs provided with Xcode6 and iOS8. * Fix ALL the header guards. * Createed a README.md with the LevelDB project description. * A new CONTRIBUTING file. * Don't implicitly convert uint64_t to size_t or int. Either preserve it as uint64_t, or explicitly cast. This fixes MSVC warnings about possible value truncation when compiling this code in Chromium. * Added a DumpFile() library function that encapsulates the guts of the "leveldbutil dump" command. This will allow clients to dump data to their log files instead of stdout. It will also allow clients to supply their own environment. * leveldb: Remove unused function 'ConsumeChar'. * leveldbutil: Remove unused member variables from WriteBatchItemPrinter. * OpenBSD, NetBSD and DragonflyBSD have _LITTLE_ENDIAN, so define PLATFORM_IS_LITTLE_ENDIAN like on FreeBSD. This fixes: * issue #143 * issue #198 * issue #249 * Switch from <cstdatomic> to <atomic>. The former never made it into the standard and doesn't exist in modern gcc versions at all. The later contains everything that leveldb was using from the former. This problem was noticed when porting to Portable Native Client where no memory barrier is defined. The fact that <cstdatomic> is missing normally goes unnoticed since memory barriers are defined for most architectures. * Make Hash() treat its input as unsigned. Before this change LevelDB files from platforms with different signedness of char were not compatible. This change fixes: issue #243 * Verify checksums of index/meta/filter blocks when paranoid_checks set. * Invoke all tools for iOS with xcrun. (This was causing problems with the new XCode 5.1.1 image on pulse.) * include <sys/stat.h> only once, and fix the following linter warning: "Found C system header after C++ system header" * When encountering a corrupted table file, return Status::Corruption instead of Status::InvalidArgument. * Support cygwin as build platform, patch is from https://code.google.com/p/leveldb/issues/detail?id=188 * Fix typo, merge patch from https://code.google.com/p/leveldb/issues/detail?id=159 * Fix typos and comments, and address the following two issues: * issue #166 * issue #241 * Add missing db synchronize after "fillseq" in the benchmark. * Removed unused variable in SeekRandom: value (issue #201)
10 years ago
9 years ago
Release 1.18 Changes are: * Update version number to 1.18 * Replace the basic fprintf call with a call to fwrite in order to work around the apparent compiler optimization/rewrite failure that we are seeing with the new toolchain/iOS SDKs provided with Xcode6 and iOS8. * Fix ALL the header guards. * Createed a README.md with the LevelDB project description. * A new CONTRIBUTING file. * Don't implicitly convert uint64_t to size_t or int. Either preserve it as uint64_t, or explicitly cast. This fixes MSVC warnings about possible value truncation when compiling this code in Chromium. * Added a DumpFile() library function that encapsulates the guts of the "leveldbutil dump" command. This will allow clients to dump data to their log files instead of stdout. It will also allow clients to supply their own environment. * leveldb: Remove unused function 'ConsumeChar'. * leveldbutil: Remove unused member variables from WriteBatchItemPrinter. * OpenBSD, NetBSD and DragonflyBSD have _LITTLE_ENDIAN, so define PLATFORM_IS_LITTLE_ENDIAN like on FreeBSD. This fixes: * issue #143 * issue #198 * issue #249 * Switch from <cstdatomic> to <atomic>. The former never made it into the standard and doesn't exist in modern gcc versions at all. The later contains everything that leveldb was using from the former. This problem was noticed when porting to Portable Native Client where no memory barrier is defined. The fact that <cstdatomic> is missing normally goes unnoticed since memory barriers are defined for most architectures. * Make Hash() treat its input as unsigned. Before this change LevelDB files from platforms with different signedness of char were not compatible. This change fixes: issue #243 * Verify checksums of index/meta/filter blocks when paranoid_checks set. * Invoke all tools for iOS with xcrun. (This was causing problems with the new XCode 5.1.1 image on pulse.) * include <sys/stat.h> only once, and fix the following linter warning: "Found C system header after C++ system header" * When encountering a corrupted table file, return Status::Corruption instead of Status::InvalidArgument. * Support cygwin as build platform, patch is from https://code.google.com/p/leveldb/issues/detail?id=188 * Fix typo, merge patch from https://code.google.com/p/leveldb/issues/detail?id=159 * Fix typos and comments, and address the following two issues: * issue #166 * issue #241 * Add missing db synchronize after "fillseq" in the benchmark. * Removed unused variable in SeekRandom: value (issue #201)
10 years ago
  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. #include "db/db_impl.h"
  5. #include <algorithm>
  6. #include <set>
  7. #include <string>
  8. #include <stdint.h>
  9. #include <stdio.h>
  10. #include <vector>
  11. #include "db/builder.h"
  12. #include "db/db_iter.h"
  13. #include "db/dbformat.h"
  14. #include "db/filename.h"
  15. #include "db/log_reader.h"
  16. #include "db/log_writer.h"
  17. #include "db/memtable.h"
  18. #include "db/table_cache.h"
  19. #include "db/version_set.h"
  20. #include "db/write_batch_internal.h"
  21. #include "leveldb/db.h"
  22. #include "leveldb/env.h"
  23. #include "leveldb/status.h"
  24. #include "leveldb/table.h"
  25. #include "leveldb/table_builder.h"
  26. #include "port/port.h"
  27. #include "table/block.h"
  28. #include "table/merger.h"
  29. #include "table/two_level_iterator.h"
  30. #include "util/coding.h"
  31. #include "util/logging.h"
  32. #include "util/mutexlock.h"
  33. namespace leveldb {
  34. const int kNumNonTableCacheFiles = 10;
  35. // Information kept for every waiting writer
  36. struct DBImpl::Writer {
  37. Status status;
  38. WriteBatch* batch;
  39. bool sync;
  40. bool done;
  41. port::CondVar cv;
  42. explicit Writer(port::Mutex* mu) : cv(mu) { }
  43. };
  44. struct DBImpl::CompactionState {
  45. Compaction* const compaction;
  46. // Sequence numbers < smallest_snapshot are not significant since we
  47. // will never have to service a snapshot below smallest_snapshot.
  48. // Therefore if we have seen a sequence number S <= smallest_snapshot,
  49. // we can drop all entries for the same key with sequence numbers < S.
  50. SequenceNumber smallest_snapshot;
  51. // Files produced by compaction
  52. struct Output {
  53. uint64_t number;
  54. uint64_t file_size;
  55. InternalKey smallest, largest;
  56. };
  57. std::vector<Output> outputs;
  58. // State kept for output being generated
  59. WritableFile* outfile;
  60. TableBuilder* builder;
  61. uint64_t total_bytes;
  62. Output* current_output() { return &outputs[outputs.size()-1]; }
  63. explicit CompactionState(Compaction* c)
  64. : compaction(c),
  65. outfile(NULL),
  66. builder(NULL),
  67. total_bytes(0) {
  68. }
  69. };
  70. // Fix user-supplied options to be reasonable
  71. template <class T,class V>
  72. static void ClipToRange(T* ptr, V minvalue, V maxvalue) {
  73. if (static_cast<V>(*ptr) > maxvalue) *ptr = maxvalue;
  74. if (static_cast<V>(*ptr) < minvalue) *ptr = minvalue;
  75. }
  76. Options SanitizeOptions(const std::string& dbname,
  77. const InternalKeyComparator* icmp,
  78. const InternalFilterPolicy* ipolicy,
  79. const Options& src) {
  80. Options result = src;
  81. result.comparator = icmp;
  82. result.filter_policy = (src.filter_policy != NULL) ? ipolicy : NULL;
  83. ClipToRange(&result.max_open_files, 64 + kNumNonTableCacheFiles, 50000);
  84. ClipToRange(&result.write_buffer_size, 64<<10, 1<<30);
  85. ClipToRange(&result.block_size, 1<<10, 4<<20);
  86. if (result.info_log == NULL) {
  87. // Open a log file in the same directory as the db
  88. src.env->CreateDir(dbname); // In case it does not exist
  89. src.env->RenameFile(InfoLogFileName(dbname), OldInfoLogFileName(dbname));
  90. Status s = src.env->NewLogger(InfoLogFileName(dbname), &result.info_log);
  91. if (!s.ok()) {
  92. // No place suitable for logging
  93. result.info_log = NULL;
  94. }
  95. }
  96. if (result.block_cache == NULL) {
  97. result.block_cache = NewLRUCache(8 << 20);
  98. }
  99. return result;
  100. }
  101. DBImpl::DBImpl(const Options& raw_options, const std::string& dbname)
  102. : env_(raw_options.env),
  103. internal_comparator_(raw_options.comparator),
  104. internal_filter_policy_(raw_options.filter_policy),
  105. options_(SanitizeOptions(dbname, &internal_comparator_,
  106. &internal_filter_policy_, raw_options)),
  107. owns_info_log_(options_.info_log != raw_options.info_log),
  108. owns_cache_(options_.block_cache != raw_options.block_cache),
  109. dbname_(dbname),
  110. db_lock_(NULL),
  111. shutting_down_(NULL),
  112. bg_cv_(&mutex_),
  113. mem_(NULL),
  114. imm_(NULL),
  115. logfile_(NULL),
  116. logfile_number_(0),
  117. log_(NULL),
  118. seed_(0),
  119. tmp_batch_(new WriteBatch),
  120. bg_compaction_scheduled_(false),
  121. manual_compaction_(NULL) {
  122. has_imm_.Release_Store(NULL);
  123. // Reserve ten files or so for other uses and give the rest to TableCache.
  124. const int table_cache_size = options_.max_open_files - kNumNonTableCacheFiles;
  125. table_cache_ = new TableCache(dbname_, &options_, table_cache_size);
  126. versions_ = new VersionSet(dbname_, &options_, table_cache_,
  127. &internal_comparator_);
  128. }
  129. DBImpl::~DBImpl() {
  130. // Wait for background work to finish
  131. mutex_.Lock();
  132. shutting_down_.Release_Store(this); // Any non-NULL value is ok
  133. while (bg_compaction_scheduled_) {
  134. bg_cv_.Wait();
  135. }
  136. mutex_.Unlock();
  137. if (db_lock_ != NULL) {
  138. env_->UnlockFile(db_lock_);
  139. }
  140. delete versions_;
  141. if (mem_ != NULL) mem_->Unref();
  142. if (imm_ != NULL) imm_->Unref();
  143. delete tmp_batch_;
  144. delete log_;
  145. delete logfile_;
  146. delete table_cache_;
  147. if (owns_info_log_) {
  148. delete options_.info_log;
  149. }
  150. if (owns_cache_) {
  151. delete options_.block_cache;
  152. }
  153. }
  154. Status DBImpl::NewDB() {
  155. VersionEdit new_db;
  156. new_db.SetComparatorName(user_comparator()->Name());
  157. new_db.SetLogNumber(0);
  158. new_db.SetNextFile(2);
  159. new_db.SetLastSequence(0);
  160. const std::string manifest = DescriptorFileName(dbname_, 1);
  161. WritableFile* file;
  162. Status s = env_->NewWritableFile(manifest, &file);
  163. if (!s.ok()) {
  164. return s;
  165. }
  166. {
  167. log::Writer log(file);
  168. std::string record;
  169. new_db.EncodeTo(&record);
  170. s = log.AddRecord(record);
  171. if (s.ok()) {
  172. s = file->Close();
  173. }
  174. }
  175. delete file;
  176. if (s.ok()) {
  177. // Make "CURRENT" file that points to the new manifest file.
  178. s = SetCurrentFile(env_, dbname_, 1);
  179. } else {
  180. env_->DeleteFile(manifest);
  181. }
  182. return s;
  183. }
  184. void DBImpl::MaybeIgnoreError(Status* s) const {
  185. if (s->ok() || options_.paranoid_checks) {
  186. // No change needed
  187. } else {
  188. Log(options_.info_log, "Ignoring error %s", s->ToString().c_str());
  189. *s = Status::OK();
  190. }
  191. }
  192. void DBImpl::DeleteObsoleteFiles() {
  193. if (!bg_error_.ok()) {
  194. // After a background error, we don't know whether a new version may
  195. // or may not have been committed, so we cannot safely garbage collect.
  196. return;
  197. }
  198. // Make a set of all of the live files
  199. std::set<uint64_t> live = pending_outputs_;
  200. versions_->AddLiveFiles(&live);
  201. std::vector<std::string> filenames;
  202. env_->GetChildren(dbname_, &filenames); // Ignoring errors on purpose
  203. uint64_t number;
  204. FileType type;
  205. for (size_t i = 0; i < filenames.size(); i++) {
  206. if (ParseFileName(filenames[i], &number, &type)) {
  207. bool keep = true;
  208. switch (type) {
  209. case kLogFile:
  210. keep = ((number >= versions_->LogNumber()) ||
  211. (number == versions_->PrevLogNumber()));
  212. break;
  213. case kDescriptorFile:
  214. // Keep my manifest file, and any newer incarnations'
  215. // (in case there is a race that allows other incarnations)
  216. keep = (number >= versions_->ManifestFileNumber());
  217. break;
  218. case kTableFile:
  219. keep = (live.find(number) != live.end());
  220. break;
  221. case kTempFile:
  222. // Any temp files that are currently being written to must
  223. // be recorded in pending_outputs_, which is inserted into "live"
  224. keep = (live.find(number) != live.end());
  225. break;
  226. case kCurrentFile:
  227. case kDBLockFile:
  228. case kInfoLogFile:
  229. keep = true;
  230. break;
  231. }
  232. if (!keep) {
  233. if (type == kTableFile) {
  234. table_cache_->Evict(number);
  235. }
  236. Log(options_.info_log, "Delete type=%d #%lld\n",
  237. int(type),
  238. static_cast<unsigned long long>(number));
  239. env_->DeleteFile(dbname_ + "/" + filenames[i]);
  240. }
  241. }
  242. }
  243. }
  244. Status DBImpl::Recover(VersionEdit* edit, bool *save_manifest) {
  245. mutex_.AssertHeld();
  246. // Ignore error from CreateDir since the creation of the DB is
  247. // committed only when the descriptor is created, and this directory
  248. // may already exist from a previous failed creation attempt.
  249. env_->CreateDir(dbname_);
  250. assert(db_lock_ == NULL);
  251. Status s = env_->LockFile(LockFileName(dbname_), &db_lock_);
  252. if (!s.ok()) {
  253. return s;
  254. }
  255. if (!env_->FileExists(CurrentFileName(dbname_))) {
  256. if (options_.create_if_missing) {
  257. s = NewDB();
  258. if (!s.ok()) {
  259. return s;
  260. }
  261. } else {
  262. return Status::InvalidArgument(
  263. dbname_, "does not exist (create_if_missing is false)");
  264. }
  265. } else {
  266. if (options_.error_if_exists) {
  267. return Status::InvalidArgument(
  268. dbname_, "exists (error_if_exists is true)");
  269. }
  270. }
  271. s = versions_->Recover(save_manifest);
  272. if (!s.ok()) {
  273. return s;
  274. }
  275. SequenceNumber max_sequence(0);
  276. // Recover from all newer log files than the ones named in the
  277. // descriptor (new log files may have been added by the previous
  278. // incarnation without registering them in the descriptor).
  279. //
  280. // Note that PrevLogNumber() is no longer used, but we pay
  281. // attention to it in case we are recovering a database
  282. // produced by an older version of leveldb.
  283. const uint64_t min_log = versions_->LogNumber();
  284. const uint64_t prev_log = versions_->PrevLogNumber();
  285. std::vector<std::string> filenames;
  286. s = env_->GetChildren(dbname_, &filenames);
  287. if (!s.ok()) {
  288. return s;
  289. }
  290. std::set<uint64_t> expected;
  291. versions_->AddLiveFiles(&expected);
  292. uint64_t number;
  293. FileType type;
  294. std::vector<uint64_t> logs;
  295. for (size_t i = 0; i < filenames.size(); i++) {
  296. if (ParseFileName(filenames[i], &number, &type)) {
  297. expected.erase(number);
  298. if (type == kLogFile && ((number >= min_log) || (number == prev_log)))
  299. logs.push_back(number);
  300. }
  301. }
  302. if (!expected.empty()) {
  303. char buf[50];
  304. snprintf(buf, sizeof(buf), "%d missing files; e.g.",
  305. static_cast<int>(expected.size()));
  306. return Status::Corruption(buf, TableFileName(dbname_, *(expected.begin())));
  307. }
  308. // Recover in the order in which the logs were generated
  309. std::sort(logs.begin(), logs.end());
  310. for (size_t i = 0; i < logs.size(); i++) {
  311. s = RecoverLogFile(logs[i], (i == logs.size() - 1), save_manifest, edit,
  312. &max_sequence);
  313. if (!s.ok()) {
  314. return s;
  315. }
  316. // The previous incarnation may not have written any MANIFEST
  317. // records after allocating this log number. So we manually
  318. // update the file number allocation counter in VersionSet.
  319. versions_->MarkFileNumberUsed(logs[i]);
  320. }
  321. if (versions_->LastSequence() < max_sequence) {
  322. versions_->SetLastSequence(max_sequence);
  323. }
  324. return Status::OK();
  325. }
  326. Status DBImpl::RecoverLogFile(uint64_t log_number, bool last_log,
  327. bool* save_manifest, VersionEdit* edit,
  328. SequenceNumber* max_sequence) {
  329. struct LogReporter : public log::Reader::Reporter {
  330. Env* env;
  331. Logger* info_log;
  332. const char* fname;
  333. Status* status; // NULL if options_.paranoid_checks==false
  334. virtual void Corruption(size_t bytes, const Status& s) {
  335. Log(info_log, "%s%s: dropping %d bytes; %s",
  336. (this->status == NULL ? "(ignoring error) " : ""),
  337. fname, static_cast<int>(bytes), s.ToString().c_str());
  338. if (this->status != NULL && this->status->ok()) *this->status = s;
  339. }
  340. };
  341. mutex_.AssertHeld();
  342. // Open the log file
  343. std::string fname = LogFileName(dbname_, log_number);
  344. SequentialFile* file;
  345. Status status = env_->NewSequentialFile(fname, &file);
  346. if (!status.ok()) {
  347. MaybeIgnoreError(&status);
  348. return status;
  349. }
  350. // Create the log reader.
  351. LogReporter reporter;
  352. reporter.env = env_;
  353. reporter.info_log = options_.info_log;
  354. reporter.fname = fname.c_str();
  355. reporter.status = (options_.paranoid_checks ? &status : NULL);
  356. // We intentionally make log::Reader do checksumming even if
  357. // paranoid_checks==false so that corruptions cause entire commits
  358. // to be skipped instead of propagating bad information (like overly
  359. // large sequence numbers).
  360. log::Reader reader(file, &reporter, true/*checksum*/,
  361. 0/*initial_offset*/);
  362. Log(options_.info_log, "Recovering log #%llu",
  363. (unsigned long long) log_number);
  364. // Read all the records and add to a memtable
  365. std::string scratch;
  366. Slice record;
  367. WriteBatch batch;
  368. int compactions = 0;
  369. MemTable* mem = NULL;
  370. while (reader.ReadRecord(&record, &scratch) &&
  371. status.ok()) {
  372. if (record.size() < 12) {
  373. reporter.Corruption(
  374. record.size(), Status::Corruption("log record too small"));
  375. continue;
  376. }
  377. WriteBatchInternal::SetContents(&batch, record);
  378. if (mem == NULL) {
  379. mem = new MemTable(internal_comparator_);
  380. mem->Ref();
  381. }
  382. status = WriteBatchInternal::InsertInto(&batch, mem);
  383. MaybeIgnoreError(&status);
  384. if (!status.ok()) {
  385. break;
  386. }
  387. const SequenceNumber last_seq =
  388. WriteBatchInternal::Sequence(&batch) +
  389. WriteBatchInternal::Count(&batch) - 1;
  390. if (last_seq > *max_sequence) {
  391. *max_sequence = last_seq;
  392. }
  393. if (mem->ApproximateMemoryUsage() > options_.write_buffer_size) {
  394. compactions++;
  395. *save_manifest = true;
  396. status = WriteLevel0Table(mem, edit, NULL);
  397. mem->Unref();
  398. mem = NULL;
  399. if (!status.ok()) {
  400. // Reflect errors immediately so that conditions like full
  401. // file-systems cause the DB::Open() to fail.
  402. break;
  403. }
  404. }
  405. }
  406. delete file;
  407. // See if we should keep reusing the last log file.
  408. if (status.ok() && options_.reuse_logs && last_log && compactions == 0) {
  409. assert(logfile_ == NULL);
  410. assert(log_ == NULL);
  411. assert(mem_ == NULL);
  412. uint64_t lfile_size;
  413. if (env_->GetFileSize(fname, &lfile_size).ok() &&
  414. env_->NewAppendableFile(fname, &logfile_).ok()) {
  415. Log(options_.info_log, "Reusing old log %s \n", fname.c_str());
  416. log_ = new log::Writer(logfile_, lfile_size);
  417. logfile_number_ = log_number;
  418. if (mem != NULL) {
  419. mem_ = mem;
  420. mem = NULL;
  421. } else {
  422. // mem can be NULL if lognum exists but was empty.
  423. mem_ = new MemTable(internal_comparator_);
  424. mem_->Ref();
  425. }
  426. }
  427. }
  428. if (mem != NULL) {
  429. // mem did not get reused; compact it.
  430. if (status.ok()) {
  431. *save_manifest = true;
  432. status = WriteLevel0Table(mem, edit, NULL);
  433. }
  434. mem->Unref();
  435. }
  436. return status;
  437. }
  438. Status DBImpl::WriteLevel0Table(MemTable* mem, VersionEdit* edit,
  439. Version* base) {
  440. mutex_.AssertHeld();
  441. const uint64_t start_micros = env_->NowMicros();
  442. FileMetaData meta;
  443. meta.number = versions_->NewFileNumber();
  444. pending_outputs_.insert(meta.number);
  445. Iterator* iter = mem->NewIterator();
  446. Log(options_.info_log, "Level-0 table #%llu: started",
  447. (unsigned long long) meta.number);
  448. Status s;
  449. {
  450. mutex_.Unlock();
  451. s = BuildTable(dbname_, env_, options_, table_cache_, iter, &meta);
  452. mutex_.Lock();
  453. }
  454. Log(options_.info_log, "Level-0 table #%llu: %lld bytes %s",
  455. (unsigned long long) meta.number,
  456. (unsigned long long) meta.file_size,
  457. s.ToString().c_str());
  458. delete iter;
  459. pending_outputs_.erase(meta.number);
  460. // Note that if file_size is zero, the file has been deleted and
  461. // should not be added to the manifest.
  462. int level = 0;
  463. if (s.ok() && meta.file_size > 0) {
  464. const Slice min_user_key = meta.smallest.user_key();
  465. const Slice max_user_key = meta.largest.user_key();
  466. if (base != NULL) {
  467. level = base->PickLevelForMemTableOutput(min_user_key, max_user_key);
  468. }
  469. edit->AddFile(level, meta.number, meta.file_size,
  470. meta.smallest, meta.largest);
  471. }
  472. CompactionStats stats;
  473. stats.micros = env_->NowMicros() - start_micros;
  474. stats.bytes_written = meta.file_size;
  475. stats_[level].Add(stats);
  476. return s;
  477. }
  478. void DBImpl::CompactMemTable() {
  479. mutex_.AssertHeld();
  480. assert(imm_ != NULL);
  481. // Save the contents of the memtable as a new Table
  482. VersionEdit edit;
  483. Version* base = versions_->current();
  484. base->Ref();
  485. Status s = WriteLevel0Table(imm_, &edit, base);
  486. base->Unref();
  487. if (s.ok() && shutting_down_.Acquire_Load()) {
  488. s = Status::IOError("Deleting DB during memtable compaction");
  489. }
  490. // Replace immutable memtable with the generated Table
  491. if (s.ok()) {
  492. edit.SetPrevLogNumber(0);
  493. edit.SetLogNumber(logfile_number_); // Earlier logs no longer needed
  494. s = versions_->LogAndApply(&edit, &mutex_);
  495. }
  496. if (s.ok()) {
  497. // Commit to the new state
  498. imm_->Unref();
  499. imm_ = NULL;
  500. has_imm_.Release_Store(NULL);
  501. DeleteObsoleteFiles();
  502. } else {
  503. RecordBackgroundError(s);
  504. }
  505. }
  506. void DBImpl::CompactRange(const Slice* begin, const Slice* end) {
  507. int max_level_with_files = 1;
  508. {
  509. MutexLock l(&mutex_);
  510. Version* base = versions_->current();
  511. for (int level = 1; level < config::kNumLevels; level++) {
  512. if (base->OverlapInLevel(level, begin, end)) {
  513. max_level_with_files = level;
  514. }
  515. }
  516. }
  517. TEST_CompactMemTable(); // TODO(sanjay): Skip if memtable does not overlap
  518. for (int level = 0; level < max_level_with_files; level++) {
  519. TEST_CompactRange(level, begin, end);
  520. }
  521. }
  522. void DBImpl::TEST_CompactRange(int level, const Slice* begin,const Slice* end) {
  523. assert(level >= 0);
  524. assert(level + 1 < config::kNumLevels);
  525. InternalKey begin_storage, end_storage;
  526. ManualCompaction manual;
  527. manual.level = level;
  528. manual.done = false;
  529. if (begin == NULL) {
  530. manual.begin = NULL;
  531. } else {
  532. begin_storage = InternalKey(*begin, kMaxSequenceNumber, kValueTypeForSeek);
  533. manual.begin = &begin_storage;
  534. }
  535. if (end == NULL) {
  536. manual.end = NULL;
  537. } else {
  538. end_storage = InternalKey(*end, 0, static_cast<ValueType>(0));
  539. manual.end = &end_storage;
  540. }
  541. MutexLock l(&mutex_);
  542. while (!manual.done && !shutting_down_.Acquire_Load() && bg_error_.ok()) {
  543. if (manual_compaction_ == NULL) { // Idle
  544. manual_compaction_ = &manual;
  545. MaybeScheduleCompaction();
  546. } else { // Running either my compaction or another compaction.
  547. bg_cv_.Wait();
  548. }
  549. }
  550. if (manual_compaction_ == &manual) {
  551. // Cancel my manual compaction since we aborted early for some reason.
  552. manual_compaction_ = NULL;
  553. }
  554. }
  555. Status DBImpl::TEST_CompactMemTable() {
  556. // NULL batch means just wait for earlier writes to be done
  557. Status s = Write(WriteOptions(), NULL);
  558. if (s.ok()) {
  559. // Wait until the compaction completes
  560. MutexLock l(&mutex_);
  561. while (imm_ != NULL && bg_error_.ok()) {
  562. bg_cv_.Wait();
  563. }
  564. if (imm_ != NULL) {
  565. s = bg_error_;
  566. }
  567. }
  568. return s;
  569. }
  570. void DBImpl::RecordBackgroundError(const Status& s) {
  571. mutex_.AssertHeld();
  572. if (bg_error_.ok()) {
  573. bg_error_ = s;
  574. bg_cv_.SignalAll();
  575. }
  576. }
  577. void DBImpl::MaybeScheduleCompaction() {
  578. mutex_.AssertHeld();
  579. if (bg_compaction_scheduled_) {
  580. // Already scheduled
  581. } else if (shutting_down_.Acquire_Load()) {
  582. // DB is being deleted; no more background compactions
  583. } else if (!bg_error_.ok()) {
  584. // Already got an error; no more changes
  585. } else if (imm_ == NULL &&
  586. manual_compaction_ == NULL &&
  587. !versions_->NeedsCompaction()) {
  588. // No work to be done
  589. } else {
  590. bg_compaction_scheduled_ = true;
  591. env_->Schedule(&DBImpl::BGWork, this);
  592. }
  593. }
  594. void DBImpl::BGWork(void* db) {
  595. reinterpret_cast<DBImpl*>(db)->BackgroundCall();
  596. }
  597. void DBImpl::BackgroundCall() {
  598. MutexLock l(&mutex_);
  599. assert(bg_compaction_scheduled_);
  600. if (shutting_down_.Acquire_Load()) {
  601. // No more background work when shutting down.
  602. } else if (!bg_error_.ok()) {
  603. // No more background work after a background error.
  604. } else {
  605. BackgroundCompaction();
  606. }
  607. bg_compaction_scheduled_ = false;
  608. // Previous compaction may have produced too many files in a level,
  609. // so reschedule another compaction if needed.
  610. MaybeScheduleCompaction();
  611. bg_cv_.SignalAll();
  612. }
  613. void DBImpl::BackgroundCompaction() {
  614. mutex_.AssertHeld();
  615. if (imm_ != NULL) {
  616. CompactMemTable();
  617. return;
  618. }
  619. Compaction* c;
  620. bool is_manual = (manual_compaction_ != NULL);
  621. InternalKey manual_end;
  622. if (is_manual) {
  623. ManualCompaction* m = manual_compaction_;
  624. c = versions_->CompactRange(m->level, m->begin, m->end);
  625. m->done = (c == NULL);
  626. if (c != NULL) {
  627. manual_end = c->input(0, c->num_input_files(0) - 1)->largest;
  628. }
  629. Log(options_.info_log,
  630. "Manual compaction at level-%d from %s .. %s; will stop at %s\n",
  631. m->level,
  632. (m->begin ? m->begin->DebugString().c_str() : "(begin)"),
  633. (m->end ? m->end->DebugString().c_str() : "(end)"),
  634. (m->done ? "(end)" : manual_end.DebugString().c_str()));
  635. } else {
  636. c = versions_->PickCompaction();
  637. }
  638. Status status;
  639. if (c == NULL) {
  640. // Nothing to do
  641. } else if (!is_manual && c->IsTrivialMove()) {
  642. // Move file to next level
  643. assert(c->num_input_files(0) == 1);
  644. FileMetaData* f = c->input(0, 0);
  645. c->edit()->DeleteFile(c->level(), f->number);
  646. c->edit()->AddFile(c->level() + 1, f->number, f->file_size,
  647. f->smallest, f->largest);
  648. status = versions_->LogAndApply(c->edit(), &mutex_);
  649. if (!status.ok()) {
  650. RecordBackgroundError(status);
  651. }
  652. VersionSet::LevelSummaryStorage tmp;
  653. Log(options_.info_log, "Moved #%lld to level-%d %lld bytes %s: %s\n",
  654. static_cast<unsigned long long>(f->number),
  655. c->level() + 1,
  656. static_cast<unsigned long long>(f->file_size),
  657. status.ToString().c_str(),
  658. versions_->LevelSummary(&tmp));
  659. } else {
  660. CompactionState* compact = new CompactionState(c);
  661. status = DoCompactionWork(compact);
  662. if (!status.ok()) {
  663. RecordBackgroundError(status);
  664. }
  665. CleanupCompaction(compact);
  666. c->ReleaseInputs();
  667. DeleteObsoleteFiles();
  668. }
  669. delete c;
  670. if (status.ok()) {
  671. // Done
  672. } else if (shutting_down_.Acquire_Load()) {
  673. // Ignore compaction errors found during shutting down
  674. } else {
  675. Log(options_.info_log,
  676. "Compaction error: %s", status.ToString().c_str());
  677. }
  678. if (is_manual) {
  679. ManualCompaction* m = manual_compaction_;
  680. if (!status.ok()) {
  681. m->done = true;
  682. }
  683. if (!m->done) {
  684. // We only compacted part of the requested range. Update *m
  685. // to the range that is left to be compacted.
  686. m->tmp_storage = manual_end;
  687. m->begin = &m->tmp_storage;
  688. }
  689. manual_compaction_ = NULL;
  690. }
  691. }
  692. void DBImpl::CleanupCompaction(CompactionState* compact) {
  693. mutex_.AssertHeld();
  694. if (compact->builder != NULL) {
  695. // May happen if we get a shutdown call in the middle of compaction
  696. compact->builder->Abandon();
  697. delete compact->builder;
  698. } else {
  699. assert(compact->outfile == NULL);
  700. }
  701. delete compact->outfile;
  702. for (size_t i = 0; i < compact->outputs.size(); i++) {
  703. const CompactionState::Output& out = compact->outputs[i];
  704. pending_outputs_.erase(out.number);
  705. }
  706. delete compact;
  707. }
  708. Status DBImpl::OpenCompactionOutputFile(CompactionState* compact) {
  709. assert(compact != NULL);
  710. assert(compact->builder == NULL);
  711. uint64_t file_number;
  712. {
  713. mutex_.Lock();
  714. file_number = versions_->NewFileNumber();
  715. pending_outputs_.insert(file_number);
  716. CompactionState::Output out;
  717. out.number = file_number;
  718. out.smallest.Clear();
  719. out.largest.Clear();
  720. compact->outputs.push_back(out);
  721. mutex_.Unlock();
  722. }
  723. // Make the output file
  724. std::string fname = TableFileName(dbname_, file_number);
  725. Status s = env_->NewWritableFile(fname, &compact->outfile);
  726. if (s.ok()) {
  727. compact->builder = new TableBuilder(options_, compact->outfile);
  728. }
  729. return s;
  730. }
  731. Status DBImpl::FinishCompactionOutputFile(CompactionState* compact,
  732. Iterator* input) {
  733. assert(compact != NULL);
  734. assert(compact->outfile != NULL);
  735. assert(compact->builder != NULL);
  736. const uint64_t output_number = compact->current_output()->number;
  737. assert(output_number != 0);
  738. // Check for iterator errors
  739. Status s = input->status();
  740. const uint64_t current_entries = compact->builder->NumEntries();
  741. if (s.ok()) {
  742. s = compact->builder->Finish();
  743. } else {
  744. compact->builder->Abandon();
  745. }
  746. const uint64_t current_bytes = compact->builder->FileSize();
  747. compact->current_output()->file_size = current_bytes;
  748. compact->total_bytes += current_bytes;
  749. delete compact->builder;
  750. compact->builder = NULL;
  751. // Finish and check for file errors
  752. if (s.ok()) {
  753. s = compact->outfile->Sync();
  754. }
  755. if (s.ok()) {
  756. s = compact->outfile->Close();
  757. }
  758. delete compact->outfile;
  759. compact->outfile = NULL;
  760. if (s.ok() && current_entries > 0) {
  761. // Verify that the table is usable
  762. Iterator* iter = table_cache_->NewIterator(ReadOptions(),
  763. output_number,
  764. current_bytes);
  765. s = iter->status();
  766. delete iter;
  767. if (s.ok()) {
  768. Log(options_.info_log,
  769. "Generated table #%llu@%d: %lld keys, %lld bytes",
  770. (unsigned long long) output_number,
  771. compact->compaction->level(),
  772. (unsigned long long) current_entries,
  773. (unsigned long long) current_bytes);
  774. }
  775. }
  776. return s;
  777. }
  778. Status DBImpl::InstallCompactionResults(CompactionState* compact) {
  779. mutex_.AssertHeld();
  780. Log(options_.info_log, "Compacted %d@%d + %d@%d files => %lld bytes",
  781. compact->compaction->num_input_files(0),
  782. compact->compaction->level(),
  783. compact->compaction->num_input_files(1),
  784. compact->compaction->level() + 1,
  785. static_cast<long long>(compact->total_bytes));
  786. // Add compaction outputs
  787. compact->compaction->AddInputDeletions(compact->compaction->edit());
  788. const int level = compact->compaction->level();
  789. for (size_t i = 0; i < compact->outputs.size(); i++) {
  790. const CompactionState::Output& out = compact->outputs[i];
  791. compact->compaction->edit()->AddFile(
  792. level + 1,
  793. out.number, out.file_size, out.smallest, out.largest);
  794. }
  795. return versions_->LogAndApply(compact->compaction->edit(), &mutex_);
  796. }
  797. Status DBImpl::DoCompactionWork(CompactionState* compact) {
  798. const uint64_t start_micros = env_->NowMicros();
  799. int64_t imm_micros = 0; // Micros spent doing imm_ compactions
  800. Log(options_.info_log, "Compacting %d@%d + %d@%d files",
  801. compact->compaction->num_input_files(0),
  802. compact->compaction->level(),
  803. compact->compaction->num_input_files(1),
  804. compact->compaction->level() + 1);
  805. assert(versions_->NumLevelFiles(compact->compaction->level()) > 0);
  806. assert(compact->builder == NULL);
  807. assert(compact->outfile == NULL);
  808. if (snapshots_.empty()) {
  809. compact->smallest_snapshot = versions_->LastSequence();
  810. } else {
  811. compact->smallest_snapshot = snapshots_.oldest()->number_;
  812. }
  813. // Release mutex while we're actually doing the compaction work
  814. mutex_.Unlock();
  815. Iterator* input = versions_->MakeInputIterator(compact->compaction);
  816. input->SeekToFirst();
  817. Status status;
  818. ParsedInternalKey ikey;
  819. std::string current_user_key;
  820. bool has_current_user_key = false;
  821. SequenceNumber last_sequence_for_key = kMaxSequenceNumber;
  822. for (; input->Valid() && !shutting_down_.Acquire_Load(); ) {
  823. // Prioritize immutable compaction work
  824. if (has_imm_.NoBarrier_Load() != NULL) {
  825. const uint64_t imm_start = env_->NowMicros();
  826. mutex_.Lock();
  827. if (imm_ != NULL) {
  828. CompactMemTable();
  829. bg_cv_.SignalAll(); // Wakeup MakeRoomForWrite() if necessary
  830. }
  831. mutex_.Unlock();
  832. imm_micros += (env_->NowMicros() - imm_start);
  833. }
  834. Slice key = input->key();
  835. if (compact->compaction->ShouldStopBefore(key) &&
  836. compact->builder != NULL) {
  837. status = FinishCompactionOutputFile(compact, input);
  838. if (!status.ok()) {
  839. break;
  840. }
  841. }
  842. // Handle key/value, add to state, etc.
  843. bool drop = false;
  844. if (!ParseInternalKey(key, &ikey)) {
  845. // Do not hide error keys
  846. current_user_key.clear();
  847. has_current_user_key = false;
  848. last_sequence_for_key = kMaxSequenceNumber;
  849. } else {
  850. if (!has_current_user_key ||
  851. user_comparator()->Compare(ikey.user_key,
  852. Slice(current_user_key)) != 0) {
  853. // First occurrence of this user key
  854. current_user_key.assign(ikey.user_key.data(), ikey.user_key.size());
  855. has_current_user_key = true;
  856. last_sequence_for_key = kMaxSequenceNumber;
  857. }
  858. if (last_sequence_for_key <= compact->smallest_snapshot) {
  859. // Hidden by an newer entry for same user key
  860. drop = true; // (A)
  861. } else if (ikey.type == kTypeDeletion &&
  862. ikey.sequence <= compact->smallest_snapshot &&
  863. compact->compaction->IsBaseLevelForKey(ikey.user_key)) {
  864. // For this user key:
  865. // (1) there is no data in higher levels
  866. // (2) data in lower levels will have larger sequence numbers
  867. // (3) data in layers that are being compacted here and have
  868. // smaller sequence numbers will be dropped in the next
  869. // few iterations of this loop (by rule (A) above).
  870. // Therefore this deletion marker is obsolete and can be dropped.
  871. drop = true;
  872. }
  873. last_sequence_for_key = ikey.sequence;
  874. }
  875. #if 0
  876. Log(options_.info_log,
  877. " Compact: %s, seq %d, type: %d %d, drop: %d, is_base: %d, "
  878. "%d smallest_snapshot: %d",
  879. ikey.user_key.ToString().c_str(),
  880. (int)ikey.sequence, ikey.type, kTypeValue, drop,
  881. compact->compaction->IsBaseLevelForKey(ikey.user_key),
  882. (int)last_sequence_for_key, (int)compact->smallest_snapshot);
  883. #endif
  884. if (!drop) {
  885. // Open output file if necessary
  886. if (compact->builder == NULL) {
  887. status = OpenCompactionOutputFile(compact);
  888. if (!status.ok()) {
  889. break;
  890. }
  891. }
  892. if (compact->builder->NumEntries() == 0) {
  893. compact->current_output()->smallest.DecodeFrom(key);
  894. }
  895. compact->current_output()->largest.DecodeFrom(key);
  896. compact->builder->Add(key, input->value());
  897. // Close output file if it is big enough
  898. if (compact->builder->FileSize() >=
  899. compact->compaction->MaxOutputFileSize()) {
  900. status = FinishCompactionOutputFile(compact, input);
  901. if (!status.ok()) {
  902. break;
  903. }
  904. }
  905. }
  906. input->Next();
  907. }
  908. if (status.ok() && shutting_down_.Acquire_Load()) {
  909. status = Status::IOError("Deleting DB during compaction");
  910. }
  911. if (status.ok() && compact->builder != NULL) {
  912. status = FinishCompactionOutputFile(compact, input);
  913. }
  914. if (status.ok()) {
  915. status = input->status();
  916. }
  917. delete input;
  918. input = NULL;
  919. CompactionStats stats;
  920. stats.micros = env_->NowMicros() - start_micros - imm_micros;
  921. for (int which = 0; which < 2; which++) {
  922. for (int i = 0; i < compact->compaction->num_input_files(which); i++) {
  923. stats.bytes_read += compact->compaction->input(which, i)->file_size;
  924. }
  925. }
  926. for (size_t i = 0; i < compact->outputs.size(); i++) {
  927. stats.bytes_written += compact->outputs[i].file_size;
  928. }
  929. mutex_.Lock();
  930. stats_[compact->compaction->level() + 1].Add(stats);
  931. if (status.ok()) {
  932. status = InstallCompactionResults(compact);
  933. }
  934. if (!status.ok()) {
  935. RecordBackgroundError(status);
  936. }
  937. VersionSet::LevelSummaryStorage tmp;
  938. Log(options_.info_log,
  939. "compacted to: %s", versions_->LevelSummary(&tmp));
  940. return status;
  941. }
  942. namespace {
  943. struct IterState {
  944. port::Mutex* mu;
  945. Version* version;
  946. MemTable* mem;
  947. MemTable* imm;
  948. };
  949. static void CleanupIteratorState(void* arg1, void* arg2) {
  950. IterState* state = reinterpret_cast<IterState*>(arg1);
  951. state->mu->Lock();
  952. state->mem->Unref();
  953. if (state->imm != NULL) state->imm->Unref();
  954. state->version->Unref();
  955. state->mu->Unlock();
  956. delete state;
  957. }
  958. } // namespace
  959. Iterator* DBImpl::NewInternalIterator(const ReadOptions& options,
  960. SequenceNumber* latest_snapshot,
  961. uint32_t* seed) {
  962. IterState* cleanup = new IterState;
  963. mutex_.Lock();
  964. *latest_snapshot = versions_->LastSequence();
  965. // Collect together all needed child iterators
  966. std::vector<Iterator*> list;
  967. list.push_back(mem_->NewIterator());
  968. mem_->Ref();
  969. if (imm_ != NULL) {
  970. list.push_back(imm_->NewIterator());
  971. imm_->Ref();
  972. }
  973. versions_->current()->AddIterators(options, &list);
  974. Iterator* internal_iter =
  975. NewMergingIterator(&internal_comparator_, &list[0], list.size());
  976. versions_->current()->Ref();
  977. cleanup->mu = &mutex_;
  978. cleanup->mem = mem_;
  979. cleanup->imm = imm_;
  980. cleanup->version = versions_->current();
  981. internal_iter->RegisterCleanup(CleanupIteratorState, cleanup, NULL);
  982. *seed = ++seed_;
  983. mutex_.Unlock();
  984. return internal_iter;
  985. }
  986. Iterator* DBImpl::TEST_NewInternalIterator() {
  987. SequenceNumber ignored;
  988. uint32_t ignored_seed;
  989. return NewInternalIterator(ReadOptions(), &ignored, &ignored_seed);
  990. }
  991. int64_t DBImpl::TEST_MaxNextLevelOverlappingBytes() {
  992. MutexLock l(&mutex_);
  993. return versions_->MaxNextLevelOverlappingBytes();
  994. }
  995. Status DBImpl::Get(const ReadOptions& options,
  996. const Slice& key,
  997. std::string* value) {
  998. Status s;
  999. MutexLock l(&mutex_);
  1000. SequenceNumber snapshot;
  1001. if (options.snapshot != NULL) {
  1002. snapshot = reinterpret_cast<const SnapshotImpl*>(options.snapshot)->number_;
  1003. } else {
  1004. snapshot = versions_->LastSequence();
  1005. }
  1006. MemTable* mem = mem_;
  1007. MemTable* imm = imm_;
  1008. Version* current = versions_->current();
  1009. mem->Ref();
  1010. if (imm != NULL) imm->Ref();
  1011. current->Ref();
  1012. bool have_stat_update = false;
  1013. Version::GetStats stats;
  1014. // Unlock while reading from files and memtables
  1015. {
  1016. mutex_.Unlock();
  1017. // First look in the memtable, then in the immutable memtable (if any).
  1018. LookupKey lkey(key, snapshot);
  1019. if (mem->Get(lkey, value, &s)) {
  1020. // Done
  1021. } else if (imm != NULL && imm->Get(lkey, value, &s)) {
  1022. // Done
  1023. } else {
  1024. s = current->Get(options, lkey, value, &stats);
  1025. have_stat_update = true;
  1026. }
  1027. mutex_.Lock();
  1028. }
  1029. if (have_stat_update && current->UpdateStats(stats)) {
  1030. MaybeScheduleCompaction();
  1031. }
  1032. mem->Unref();
  1033. if (imm != NULL) imm->Unref();
  1034. current->Unref();
  1035. return s;
  1036. }
  1037. Iterator* DBImpl::NewIterator(const ReadOptions& options) {
  1038. SequenceNumber latest_snapshot;
  1039. uint32_t seed;
  1040. Iterator* iter = NewInternalIterator(options, &latest_snapshot, &seed);
  1041. return NewDBIterator(
  1042. this, user_comparator(), iter,
  1043. (options.snapshot != NULL
  1044. ? reinterpret_cast<const SnapshotImpl*>(options.snapshot)->number_
  1045. : latest_snapshot),
  1046. seed);
  1047. }
  1048. void DBImpl::RecordReadSample(Slice key) {
  1049. MutexLock l(&mutex_);
  1050. if (versions_->current()->RecordReadSample(key)) {
  1051. MaybeScheduleCompaction();
  1052. }
  1053. }
  1054. const Snapshot* DBImpl::GetSnapshot() {
  1055. MutexLock l(&mutex_);
  1056. return snapshots_.New(versions_->LastSequence());
  1057. }
  1058. void DBImpl::ReleaseSnapshot(const Snapshot* s) {
  1059. MutexLock l(&mutex_);
  1060. snapshots_.Delete(reinterpret_cast<const SnapshotImpl*>(s));
  1061. }
  1062. // Convenience methods
  1063. Status DBImpl::Put(const WriteOptions& o, const Slice& key, const Slice& val) {
  1064. return DB::Put(o, key, val);
  1065. }
  1066. Status DBImpl::Delete(const WriteOptions& options, const Slice& key) {
  1067. return DB::Delete(options, key);
  1068. }
  1069. Status DBImpl::Write(const WriteOptions& options, WriteBatch* my_batch) {
  1070. Writer w(&mutex_);
  1071. w.batch = my_batch;
  1072. w.sync = options.sync;
  1073. w.done = false;
  1074. MutexLock l(&mutex_);
  1075. writers_.push_back(&w);
  1076. while (!w.done && &w != writers_.front()) {
  1077. w.cv.Wait();
  1078. }
  1079. if (w.done) {
  1080. return w.status;
  1081. }
  1082. // May temporarily unlock and wait.
  1083. Status status = MakeRoomForWrite(my_batch == NULL);
  1084. uint64_t last_sequence = versions_->LastSequence();
  1085. Writer* last_writer = &w;
  1086. if (status.ok() && my_batch != NULL) { // NULL batch is for compactions
  1087. WriteBatch* updates = BuildBatchGroup(&last_writer);
  1088. WriteBatchInternal::SetSequence(updates, last_sequence + 1);
  1089. last_sequence += WriteBatchInternal::Count(updates);
  1090. // Add to log and apply to memtable. We can release the lock
  1091. // during this phase since &w is currently responsible for logging
  1092. // and protects against concurrent loggers and concurrent writes
  1093. // into mem_.
  1094. {
  1095. mutex_.Unlock();
  1096. status = log_->AddRecord(WriteBatchInternal::Contents(updates));
  1097. bool sync_error = false;
  1098. if (status.ok() && options.sync) {
  1099. status = logfile_->Sync();
  1100. if (!status.ok()) {
  1101. sync_error = true;
  1102. }
  1103. }
  1104. if (status.ok()) {
  1105. status = WriteBatchInternal::InsertInto(updates, mem_);
  1106. }
  1107. mutex_.Lock();
  1108. if (sync_error) {
  1109. // The state of the log file is indeterminate: the log record we
  1110. // just added may or may not show up when the DB is re-opened.
  1111. // So we force the DB into a mode where all future writes fail.
  1112. RecordBackgroundError(status);
  1113. }
  1114. }
  1115. if (updates == tmp_batch_) tmp_batch_->Clear();
  1116. versions_->SetLastSequence(last_sequence);
  1117. }
  1118. while (true) {
  1119. Writer* ready = writers_.front();
  1120. writers_.pop_front();
  1121. if (ready != &w) {
  1122. ready->status = status;
  1123. ready->done = true;
  1124. ready->cv.Signal();
  1125. }
  1126. if (ready == last_writer) break;
  1127. }
  1128. // Notify new head of write queue
  1129. if (!writers_.empty()) {
  1130. writers_.front()->cv.Signal();
  1131. }
  1132. return status;
  1133. }
  1134. // REQUIRES: Writer list must be non-empty
  1135. // REQUIRES: First writer must have a non-NULL batch
  1136. WriteBatch* DBImpl::BuildBatchGroup(Writer** last_writer) {
  1137. assert(!writers_.empty());
  1138. Writer* first = writers_.front();
  1139. WriteBatch* result = first->batch;
  1140. assert(result != NULL);
  1141. size_t size = WriteBatchInternal::ByteSize(first->batch);
  1142. // Allow the group to grow up to a maximum size, but if the
  1143. // original write is small, limit the growth so we do not slow
  1144. // down the small write too much.
  1145. size_t max_size = 1 << 20;
  1146. if (size <= (128<<10)) {
  1147. max_size = size + (128<<10);
  1148. }
  1149. *last_writer = first;
  1150. std::deque<Writer*>::iterator iter = writers_.begin();
  1151. ++iter; // Advance past "first"
  1152. for (; iter != writers_.end(); ++iter) {
  1153. Writer* w = *iter;
  1154. if (w->sync && !first->sync) {
  1155. // Do not include a sync write into a batch handled by a non-sync write.
  1156. break;
  1157. }
  1158. if (w->batch != NULL) {
  1159. size += WriteBatchInternal::ByteSize(w->batch);
  1160. if (size > max_size) {
  1161. // Do not make batch too big
  1162. break;
  1163. }
  1164. // Append to *result
  1165. if (result == first->batch) {
  1166. // Switch to temporary batch instead of disturbing caller's batch
  1167. result = tmp_batch_;
  1168. assert(WriteBatchInternal::Count(result) == 0);
  1169. WriteBatchInternal::Append(result, first->batch);
  1170. }
  1171. WriteBatchInternal::Append(result, w->batch);
  1172. }
  1173. *last_writer = w;
  1174. }
  1175. return result;
  1176. }
  1177. // REQUIRES: mutex_ is held
  1178. // REQUIRES: this thread is currently at the front of the writer queue
  1179. Status DBImpl::MakeRoomForWrite(bool force) {
  1180. mutex_.AssertHeld();
  1181. assert(!writers_.empty());
  1182. bool allow_delay = !force;
  1183. Status s;
  1184. while (true) {
  1185. if (!bg_error_.ok()) {
  1186. // Yield previous error
  1187. s = bg_error_;
  1188. break;
  1189. } else if (
  1190. allow_delay &&
  1191. versions_->NumLevelFiles(0) >= config::kL0_SlowdownWritesTrigger) {
  1192. // We are getting close to hitting a hard limit on the number of
  1193. // L0 files. Rather than delaying a single write by several
  1194. // seconds when we hit the hard limit, start delaying each
  1195. // individual write by 1ms to reduce latency variance. Also,
  1196. // this delay hands over some CPU to the compaction thread in
  1197. // case it is sharing the same core as the writer.
  1198. mutex_.Unlock();
  1199. env_->SleepForMicroseconds(1000);
  1200. allow_delay = false; // Do not delay a single write more than once
  1201. mutex_.Lock();
  1202. } else if (!force &&
  1203. (mem_->ApproximateMemoryUsage() <= options_.write_buffer_size)) {
  1204. // There is room in current memtable
  1205. break;
  1206. } else if (imm_ != NULL) {
  1207. // We have filled up the current memtable, but the previous
  1208. // one is still being compacted, so we wait.
  1209. Log(options_.info_log, "Current memtable full; waiting...\n");
  1210. bg_cv_.Wait();
  1211. } else if (versions_->NumLevelFiles(0) >= config::kL0_StopWritesTrigger) {
  1212. // There are too many level-0 files.
  1213. Log(options_.info_log, "Too many L0 files; waiting...\n");
  1214. bg_cv_.Wait();
  1215. } else {
  1216. // Attempt to switch to a new memtable and trigger compaction of old
  1217. assert(versions_->PrevLogNumber() == 0);
  1218. uint64_t new_log_number = versions_->NewFileNumber();
  1219. WritableFile* lfile = NULL;
  1220. s = env_->NewWritableFile(LogFileName(dbname_, new_log_number), &lfile);
  1221. if (!s.ok()) {
  1222. // Avoid chewing through file number space in a tight loop.
  1223. versions_->ReuseFileNumber(new_log_number);
  1224. break;
  1225. }
  1226. delete log_;
  1227. delete logfile_;
  1228. logfile_ = lfile;
  1229. logfile_number_ = new_log_number;
  1230. log_ = new log::Writer(lfile);
  1231. imm_ = mem_;
  1232. has_imm_.Release_Store(imm_);
  1233. mem_ = new MemTable(internal_comparator_);
  1234. mem_->Ref();
  1235. force = false; // Do not force another compaction if have room
  1236. MaybeScheduleCompaction();
  1237. }
  1238. }
  1239. return s;
  1240. }
  1241. bool DBImpl::GetProperty(const Slice& property, std::string* value) {
  1242. value->clear();
  1243. MutexLock l(&mutex_);
  1244. Slice in = property;
  1245. Slice prefix("leveldb.");
  1246. if (!in.starts_with(prefix)) return false;
  1247. in.remove_prefix(prefix.size());
  1248. if (in.starts_with("num-files-at-level")) {
  1249. in.remove_prefix(strlen("num-files-at-level"));
  1250. uint64_t level;
  1251. bool ok = ConsumeDecimalNumber(&in, &level) && in.empty();
  1252. if (!ok || level >= config::kNumLevels) {
  1253. return false;
  1254. } else {
  1255. char buf[100];
  1256. snprintf(buf, sizeof(buf), "%d",
  1257. versions_->NumLevelFiles(static_cast<int>(level)));
  1258. *value = buf;
  1259. return true;
  1260. }
  1261. } else if (in == "stats") {
  1262. char buf[200];
  1263. snprintf(buf, sizeof(buf),
  1264. " Compactions\n"
  1265. "Level Files Size(MB) Time(sec) Read(MB) Write(MB)\n"
  1266. "--------------------------------------------------\n"
  1267. );
  1268. value->append(buf);
  1269. for (int level = 0; level < config::kNumLevels; level++) {
  1270. int files = versions_->NumLevelFiles(level);
  1271. if (stats_[level].micros > 0 || files > 0) {
  1272. snprintf(
  1273. buf, sizeof(buf),
  1274. "%3d %8d %8.0f %9.0f %8.0f %9.0f\n",
  1275. level,
  1276. files,
  1277. versions_->NumLevelBytes(level) / 1048576.0,
  1278. stats_[level].micros / 1e6,
  1279. stats_[level].bytes_read / 1048576.0,
  1280. stats_[level].bytes_written / 1048576.0);
  1281. value->append(buf);
  1282. }
  1283. }
  1284. return true;
  1285. } else if (in == "sstables") {
  1286. *value = versions_->current()->DebugString();
  1287. return true;
  1288. } else if (in == "approximate-memory-usage") {
  1289. size_t total_usage = options_.block_cache->TotalCharge();
  1290. if (mem_) {
  1291. total_usage += mem_->ApproximateMemoryUsage();
  1292. }
  1293. if (imm_) {
  1294. total_usage += imm_->ApproximateMemoryUsage();
  1295. }
  1296. char buf[50];
  1297. snprintf(buf, sizeof(buf), "%llu",
  1298. static_cast<unsigned long long>(total_usage));
  1299. value->append(buf);
  1300. return true;
  1301. }
  1302. return false;
  1303. }
  1304. void DBImpl::GetApproximateSizes(
  1305. const Range* range, int n,
  1306. uint64_t* sizes) {
  1307. // TODO(opt): better implementation
  1308. Version* v;
  1309. {
  1310. MutexLock l(&mutex_);
  1311. versions_->current()->Ref();
  1312. v = versions_->current();
  1313. }
  1314. for (int i = 0; i < n; i++) {
  1315. // Convert user_key into a corresponding internal key.
  1316. InternalKey k1(range[i].start, kMaxSequenceNumber, kValueTypeForSeek);
  1317. InternalKey k2(range[i].limit, kMaxSequenceNumber, kValueTypeForSeek);
  1318. uint64_t start = versions_->ApproximateOffsetOf(v, k1);
  1319. uint64_t limit = versions_->ApproximateOffsetOf(v, k2);
  1320. sizes[i] = (limit >= start ? limit - start : 0);
  1321. }
  1322. {
  1323. MutexLock l(&mutex_);
  1324. v->Unref();
  1325. }
  1326. }
  1327. // Default implementations of convenience methods that subclasses of DB
  1328. // can call if they wish
  1329. Status DB::Put(const WriteOptions& opt, const Slice& key, const Slice& value) {
  1330. WriteBatch batch;
  1331. batch.Put(key, value);
  1332. return Write(opt, &batch);
  1333. }
  1334. Status DB::Delete(const WriteOptions& opt, const Slice& key) {
  1335. WriteBatch batch;
  1336. batch.Delete(key);
  1337. return Write(opt, &batch);
  1338. }
  1339. DB::~DB() { }
  1340. Status DB::Open(const Options& options, const std::string& dbname,
  1341. DB** dbptr) {
  1342. *dbptr = NULL;
  1343. DBImpl* impl = new DBImpl(options, dbname);
  1344. impl->mutex_.Lock();
  1345. VersionEdit edit;
  1346. // Recover handles create_if_missing, error_if_exists
  1347. bool save_manifest = false;
  1348. Status s = impl->Recover(&edit, &save_manifest);
  1349. if (s.ok() && impl->mem_ == NULL) {
  1350. // Create new log and a corresponding memtable.
  1351. uint64_t new_log_number = impl->versions_->NewFileNumber();
  1352. WritableFile* lfile;
  1353. s = options.env->NewWritableFile(LogFileName(dbname, new_log_number),
  1354. &lfile);
  1355. if (s.ok()) {
  1356. edit.SetLogNumber(new_log_number);
  1357. impl->logfile_ = lfile;
  1358. impl->logfile_number_ = new_log_number;
  1359. impl->log_ = new log::Writer(lfile);
  1360. impl->mem_ = new MemTable(impl->internal_comparator_);
  1361. impl->mem_->Ref();
  1362. }
  1363. }
  1364. if (s.ok() && save_manifest) {
  1365. edit.SetPrevLogNumber(0); // No older logs needed after recovery.
  1366. edit.SetLogNumber(impl->logfile_number_);
  1367. s = impl->versions_->LogAndApply(&edit, &impl->mutex_);
  1368. }
  1369. if (s.ok()) {
  1370. impl->DeleteObsoleteFiles();
  1371. impl->MaybeScheduleCompaction();
  1372. }
  1373. impl->mutex_.Unlock();
  1374. if (s.ok()) {
  1375. assert(impl->mem_ != NULL);
  1376. *dbptr = impl;
  1377. } else {
  1378. delete impl;
  1379. }
  1380. return s;
  1381. }
  1382. Snapshot::~Snapshot() {
  1383. }
  1384. Status DestroyDB(const std::string& dbname, const Options& options) {
  1385. Env* env = options.env;
  1386. std::vector<std::string> filenames;
  1387. // Ignore error in case directory does not exist
  1388. env->GetChildren(dbname, &filenames);
  1389. if (filenames.empty()) {
  1390. return Status::OK();
  1391. }
  1392. FileLock* lock;
  1393. const std::string lockname = LockFileName(dbname);
  1394. Status result = env->LockFile(lockname, &lock);
  1395. if (result.ok()) {
  1396. uint64_t number;
  1397. FileType type;
  1398. for (size_t i = 0; i < filenames.size(); i++) {
  1399. if (ParseFileName(filenames[i], &number, &type) &&
  1400. type != kDBLockFile) { // Lock file will be deleted at end
  1401. Status del = env->DeleteFile(dbname + "/" + filenames[i]);
  1402. if (result.ok() && !del.ok()) {
  1403. result = del;
  1404. }
  1405. }
  1406. }
  1407. env->UnlockFile(lock); // Ignore error since state is already gone
  1408. env->DeleteFile(lockname);
  1409. env->DeleteDir(dbname); // Ignore error in case dir contains other files
  1410. }
  1411. return result;
  1412. }
  1413. } // namespace leveldb