作者: 韩晨旭 10225101440 李畅 10225102463
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.

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