db_impl.cc 49 KB

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