env_chromium.cc 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493
  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 "third_party/leveldatabase/env_chromium.h"
  5. #include <atomic>
  6. #include <iterator>
  7. #include <limits>
  8. #include <utility>
  9. #include "base/bind.h"
  10. #include "base/check_op.h"
  11. #include "base/files/file_error_or.h"
  12. #include "base/files/file_util.h"
  13. #include "base/format_macros.h"
  14. #include "base/metrics/histogram_functions.h"
  15. #include "base/no_destructor.h"
  16. #include "base/notreached.h"
  17. #include "base/process/process_metrics.h"
  18. #include "base/strings/string_number_conversions.h"
  19. #include "base/strings/string_util.h"
  20. #include "base/strings/stringprintf.h"
  21. #include "base/strings/utf_string_conversions.h"
  22. #include "base/system/sys_info.h"
  23. #include "base/task/task_traits.h"
  24. #include "base/task/thread_pool.h"
  25. #include "base/time/time.h"
  26. #include "base/time/time_override.h"
  27. #include "base/trace_event/memory_dump_manager.h"
  28. #include "base/trace_event/memory_dump_provider.h"
  29. #include "base/trace_event/process_memory_dump.h"
  30. #include "base/trace_event/trace_event.h"
  31. #include "build/build_config.h"
  32. #include "build/chromeos_buildflags.h"
  33. #include "components/services/storage/public/cpp/filesystem/filesystem_proxy.h"
  34. #include "third_party/leveldatabase/chromium_logger.h"
  35. #include "third_party/leveldatabase/leveldb_chrome.h"
  36. #include "third_party/leveldatabase/port/port_chromium.h"
  37. #include "third_party/leveldatabase/src/include/leveldb/options.h"
  38. #include "third_party/re2/src/re2/re2.h"
  39. using base::FilePath;
  40. using base::trace_event::MemoryAllocatorDump;
  41. using base::trace_event::MemoryDumpArgs;
  42. using base::trace_event::ProcessMemoryDump;
  43. using leveldb::FileLock;
  44. using leveldb::Slice;
  45. using leveldb::Status;
  46. namespace leveldb_env {
  47. namespace {
  48. template <typename ValueType>
  49. using FileErrorOr = base::FileErrorOr<ValueType>;
  50. // After this limit we don't bother doing file eviction for leveldb for speed,
  51. // memory usage, and simplicity.
  52. const constexpr size_t kFileLimitToDisableEviction = 10'000;
  53. // The maximum time for the |Retrier| to indicate that an operation should
  54. // be retried.
  55. constexpr auto kMaxRetryDuration = base::Milliseconds(1000);
  56. const FilePath::CharType table_extension[] = FILE_PATH_LITERAL(".ldb");
  57. static const FilePath::CharType kLevelDBTestDirectoryPrefix[] =
  58. FILE_PATH_LITERAL("leveldb-test-");
  59. // This name should not be changed or users involved in a crash might not be
  60. // able to recover data.
  61. static const char kDatabaseNameSuffixForRebuildDB[] = "__tmp_for_rebuild";
  62. class ChromiumFileLock : public FileLock {
  63. public:
  64. ChromiumFileLock(std::unique_ptr<storage::FilesystemProxy::FileLock> lock,
  65. const std::string& name)
  66. : lock(std::move(lock)), name(name) {}
  67. ChromiumFileLock(const ChromiumFileLock&) = delete;
  68. ChromiumFileLock& operator=(const ChromiumFileLock&) = delete;
  69. const std::unique_ptr<storage::FilesystemProxy::FileLock> lock;
  70. const std::string name;
  71. };
  72. class Retrier {
  73. public:
  74. Retrier()
  75. // TODO(crbug.com/1059965): figure out a better way to handle time for
  76. // tests.
  77. : start_(base::subtle::TimeTicksNowIgnoringOverride()),
  78. limit_(start_ + kMaxRetryDuration),
  79. last_(start_),
  80. time_to_sleep_(base::Milliseconds(10)) {}
  81. Retrier(const Retrier&) = delete;
  82. Retrier& operator=(const Retrier&) = delete;
  83. ~Retrier() = default;
  84. bool ShouldKeepTrying() {
  85. if (last_ < limit_) {
  86. base::PlatformThread::Sleep(time_to_sleep_);
  87. // TODO(crbug.com/1059965): figure out a better way to handle time for
  88. // tests.
  89. last_ = base::subtle::TimeTicksNowIgnoringOverride();
  90. return true;
  91. }
  92. return false;
  93. }
  94. private:
  95. const base::TimeTicks start_;
  96. base::TimeTicks limit_;
  97. base::TimeTicks last_;
  98. base::TimeDelta time_to_sleep_;
  99. };
  100. class ChromiumSequentialFile : public leveldb::SequentialFile {
  101. public:
  102. ChromiumSequentialFile(const std::string& fname, base::File f)
  103. : filename_(fname), file_(std::move(f)) {}
  104. ChromiumSequentialFile(const ChromiumSequentialFile&) = delete;
  105. ChromiumSequentialFile& operator=(const ChromiumSequentialFile&) = delete;
  106. ~ChromiumSequentialFile() override = default;
  107. // Note: This method is relatively hot during leveldb database
  108. // compaction. Please avoid making them slower.
  109. Status Read(size_t n, Slice* result, char* scratch) override {
  110. int bytes_read = file_.ReadAtCurrentPosNoBestEffort(scratch, n);
  111. if (bytes_read == -1) {
  112. base::File::Error error = base::File::GetLastFileError();
  113. return MakeIOError(filename_, base::File::ErrorToString(error),
  114. kSequentialFileRead, error);
  115. }
  116. *result = Slice(scratch, bytes_read);
  117. return Status::OK();
  118. }
  119. Status Skip(uint64_t n) override {
  120. if (file_.Seek(base::File::FROM_CURRENT, n) == -1) {
  121. base::File::Error error = base::File::GetLastFileError();
  122. return MakeIOError(filename_, base::File::ErrorToString(error),
  123. kSequentialFileSkip, error);
  124. } else {
  125. return Status::OK();
  126. }
  127. }
  128. private:
  129. std::string filename_;
  130. base::File file_;
  131. };
  132. void RemoveFile(const Slice& key, void* value) {
  133. delete static_cast<base::File*>(value);
  134. }
  135. Status ReadFromFileToScratch(uint64_t offset,
  136. size_t n,
  137. Slice* result,
  138. char* scratch,
  139. base::File* file,
  140. const base::FilePath& file_path) {
  141. int bytes_read = file->Read(offset, scratch, n);
  142. if (bytes_read < 0) {
  143. return MakeIOError(file_path.AsUTF8Unsafe(), "Could not perform read",
  144. kRandomAccessFileRead);
  145. }
  146. *result = Slice(scratch, (bytes_read < 0) ? 0 : bytes_read);
  147. return Status::OK();
  148. }
  149. // The cache mechanism uses leveldb's LRU cache, which is a threadsafe sharded
  150. // LRU cache. The keys use the pointer value of |this|, and the values are file
  151. // objects.
  152. // Each object will only use its own cache entry, so the |Erase| call in the
  153. // object destructor should synchronously delete the file from the cache. This
  154. // ensures that pointer location re-use won't re-use an entry in the cache as
  155. // the entry at |this| will always have been deleted.
  156. // Files are always cleaned up with |RemoveFile|, which will be called when the
  157. // ChromiumEvictableRandomAccessFile is deleted, the cache is deleted, or the
  158. // file is evicted.
  159. class ChromiumEvictableRandomAccessFile : public leveldb::RandomAccessFile {
  160. public:
  161. ChromiumEvictableRandomAccessFile(base::FilePath file_path,
  162. base::File file,
  163. storage::FilesystemProxy* filesystem,
  164. leveldb::Cache* file_cache)
  165. : filepath_(std::move(file_path)),
  166. filesystem_(filesystem),
  167. file_cache_(file_cache),
  168. cache_key_data_(this),
  169. cache_key_(
  170. leveldb::Slice(reinterpret_cast<const char*>(&cache_key_data_),
  171. sizeof(cache_key_data_))) {
  172. DCHECK(file_cache_);
  173. base::File* heap_file = new base::File(std::move(file));
  174. // A |charge| of '1' is used because the capacity is the file handle limit,
  175. // and each entry is one file.
  176. file_cache_->Release(file_cache_->Insert(cache_key_, heap_file,
  177. 1 /* charge */, &RemoveFile));
  178. }
  179. ChromiumEvictableRandomAccessFile(const ChromiumEvictableRandomAccessFile&) =
  180. delete;
  181. ChromiumEvictableRandomAccessFile& operator=(
  182. const ChromiumEvictableRandomAccessFile&) = delete;
  183. virtual ~ChromiumEvictableRandomAccessFile() {
  184. file_cache_->Erase(cache_key_);
  185. }
  186. // Note: This method is relatively hot during leveldb database
  187. // compaction. Please avoid making them slower.
  188. Status Read(uint64_t offset,
  189. size_t n,
  190. Slice* result,
  191. char* scratch) const override {
  192. leveldb::Cache::Handle* handle = file_cache_->Lookup(cache_key_);
  193. if (!handle) {
  194. int flags = base::File::FLAG_READ | base::File::FLAG_OPEN;
  195. FileErrorOr<base::File> result = filesystem_->OpenFile(filepath_, flags);
  196. if (result.is_error()) {
  197. return MakeIOError(filepath_.AsUTF8Unsafe(), "Could not perform read",
  198. kRandomAccessFileRead);
  199. }
  200. handle = file_cache_->Insert(cache_key_,
  201. new base::File(std::move(result.value())),
  202. sizeof(base::File), &RemoveFile);
  203. }
  204. base::File* file = static_cast<base::File*>(file_cache_->Value(handle));
  205. Status status =
  206. ReadFromFileToScratch(offset, n, result, scratch, file, filepath_);
  207. file_cache_->Release(handle);
  208. return status;
  209. }
  210. private:
  211. const base::FilePath filepath_;
  212. storage::FilesystemProxy* const filesystem_;
  213. mutable leveldb::Cache* file_cache_;
  214. const ChromiumEvictableRandomAccessFile* cache_key_data_;
  215. leveldb::Slice cache_key_;
  216. };
  217. class ChromiumRandomAccessFile : public leveldb::RandomAccessFile {
  218. public:
  219. ChromiumRandomAccessFile(base::FilePath file_path, base::File file)
  220. : filepath_(std::move(file_path)), file_(std::move(file)) {}
  221. ChromiumRandomAccessFile(const ChromiumRandomAccessFile&) = delete;
  222. ChromiumRandomAccessFile& operator=(const ChromiumRandomAccessFile&) = delete;
  223. virtual ~ChromiumRandomAccessFile() {}
  224. // Note: This method is relatively hot during leveldb database
  225. // compaction. Please avoid making them slower.
  226. Status Read(uint64_t offset,
  227. size_t n,
  228. Slice* result,
  229. char* scratch) const override {
  230. return ReadFromFileToScratch(offset, n, result, scratch, &file_, filepath_);
  231. }
  232. private:
  233. const base::FilePath filepath_;
  234. mutable base::File file_;
  235. };
  236. class ChromiumWritableFile : public leveldb::WritableFile {
  237. public:
  238. ChromiumWritableFile(const std::string& fname,
  239. base::File f,
  240. storage::FilesystemProxy* filesystem);
  241. ChromiumWritableFile(const ChromiumWritableFile&) = delete;
  242. ChromiumWritableFile& operator=(const ChromiumWritableFile&) = delete;
  243. ~ChromiumWritableFile() override = default;
  244. leveldb::Status Append(const leveldb::Slice& data) override;
  245. leveldb::Status Close() override;
  246. leveldb::Status Flush() override;
  247. leveldb::Status Sync() override;
  248. private:
  249. enum Type { kManifest, kTable, kOther };
  250. leveldb::Status SyncParent();
  251. std::string filename_;
  252. base::File file_;
  253. #if defined(OS_POSIX) || defined(OS_FUCHSIA)
  254. storage::FilesystemProxy* const filesystem_;
  255. #endif
  256. Type file_type_;
  257. std::string parent_dir_;
  258. };
  259. ChromiumWritableFile::ChromiumWritableFile(const std::string& fname,
  260. base::File f,
  261. storage::FilesystemProxy* filesystem)
  262. : filename_(fname),
  263. file_(std::move(f)),
  264. #if defined(OS_POSIX) || defined(OS_FUCHSIA)
  265. filesystem_(filesystem),
  266. #endif
  267. file_type_(kOther) {
  268. FilePath path = FilePath::FromUTF8Unsafe(fname);
  269. if (path.BaseName().AsUTF8Unsafe().find("MANIFEST") == 0)
  270. file_type_ = kManifest;
  271. else if (path.MatchesExtension(table_extension))
  272. file_type_ = kTable;
  273. parent_dir_ = FilePath::FromUTF8Unsafe(fname).DirName().AsUTF8Unsafe();
  274. }
  275. Status ChromiumWritableFile::SyncParent() {
  276. TRACE_EVENT0("leveldb", "SyncParent");
  277. #if defined(OS_POSIX) || defined(OS_FUCHSIA)
  278. FilePath path = FilePath::FromUTF8Unsafe(parent_dir_);
  279. FileErrorOr<base::File> result = filesystem_->OpenFile(
  280. path, base::File::FLAG_OPEN | base::File::FLAG_READ);
  281. if (result.is_error()) {
  282. return MakeIOError(parent_dir_, "Unable to open directory", kSyncParent,
  283. result.error());
  284. }
  285. if (!result->Flush()) {
  286. base::File::Error error = base::File::GetLastFileError();
  287. return MakeIOError(parent_dir_, base::File::ErrorToString(error),
  288. kSyncParent, error);
  289. }
  290. #endif
  291. return Status::OK();
  292. }
  293. Status ChromiumWritableFile::Append(const Slice& data) {
  294. DCHECK(file_.IsValid());
  295. int bytes_written = file_.WriteAtCurrentPos(data.data(), data.size());
  296. if (static_cast<size_t>(bytes_written) != data.size()) {
  297. base::File::Error error = base::File::GetLastFileError();
  298. return MakeIOError(filename_, base::File::ErrorToString(error),
  299. kWritableFileAppend, error);
  300. }
  301. return Status::OK();
  302. }
  303. Status ChromiumWritableFile::Close() {
  304. file_.Close();
  305. return Status::OK();
  306. }
  307. Status ChromiumWritableFile::Flush() {
  308. // base::File doesn't do buffered I/O (i.e. POSIX FILE streams) so nothing to
  309. // flush.
  310. return Status::OK();
  311. }
  312. Status ChromiumWritableFile::Sync() {
  313. TRACE_EVENT0("leveldb", "WritableFile::Sync");
  314. // leveldb's implicit contract for Sync() is that if this instance is for a
  315. // manifest file then the directory is also sync'ed, to ensure new files
  316. // referred to by the manifest are in the filesystem.
  317. //
  318. // This needs to happen before the manifest file is flushed to disk, to
  319. // avoid crashing in a state where the manifest refers to files that are not
  320. // yet on disk.
  321. //
  322. // See leveldb's env_posix.cc.
  323. if (file_type_ == kManifest) {
  324. Status status = SyncParent();
  325. if (!status.ok())
  326. return status;
  327. }
  328. if (!file_.Flush()) {
  329. base::File::Error error = base::File::GetLastFileError();
  330. return MakeIOError(filename_, base::File::ErrorToString(error),
  331. kWritableFileSync, error);
  332. }
  333. return Status::OK();
  334. }
  335. // Return the maximum number of read-only files to keep open.
  336. size_t GetLevelDBFileLimit(size_t max_file_descriptors) {
  337. // Allow use of 20% of available file descriptors for read-only files.
  338. return max_file_descriptors / 5;
  339. }
  340. std::string GetDumpNameForDB(const leveldb::DB* db) {
  341. return base::StringPrintf("leveldatabase/db_0x%" PRIXPTR,
  342. reinterpret_cast<uintptr_t>(db));
  343. }
  344. std::string GetDumpNameForCache(DBTracker::SharedReadCacheUse cache) {
  345. switch (cache) {
  346. case DBTracker::SharedReadCacheUse_Browser:
  347. return "leveldatabase/block_cache/browser";
  348. case DBTracker::SharedReadCacheUse_Web:
  349. return "leveldatabase/block_cache/web";
  350. case DBTracker::SharedReadCacheUse_Unified:
  351. return "leveldatabase/block_cache/unified";
  352. case DBTracker::SharedReadCacheUse_InMemory:
  353. return "leveldatabase/block_cache/in_memory";
  354. case DBTracker::SharedReadCacheUse_NumCacheUses:
  355. NOTREACHED();
  356. }
  357. NOTREACHED();
  358. return "";
  359. }
  360. MemoryAllocatorDump* CreateDumpMalloced(ProcessMemoryDump* pmd,
  361. const std::string& name,
  362. size_t size) {
  363. auto* dump = pmd->CreateAllocatorDump(name);
  364. dump->AddScalar(MemoryAllocatorDump::kNameSize,
  365. MemoryAllocatorDump::kUnitsBytes, size);
  366. static const char* system_allocator_name =
  367. base::trace_event::MemoryDumpManager::GetInstance()
  368. ->system_allocator_pool_name();
  369. if (system_allocator_name)
  370. pmd->AddSuballocation(dump->guid(), system_allocator_name);
  371. return dump;
  372. }
  373. void RecordCacheUsageInTracing(ProcessMemoryDump* pmd,
  374. DBTracker::SharedReadCacheUse cache) {
  375. std::string name = GetDumpNameForCache(cache);
  376. leveldb::Cache* cache_ptr = nullptr;
  377. switch (cache) {
  378. case DBTracker::SharedReadCacheUse_Browser:
  379. cache_ptr = leveldb_chrome::GetSharedBrowserBlockCache();
  380. break;
  381. case DBTracker::SharedReadCacheUse_Web:
  382. cache_ptr = leveldb_chrome::GetSharedWebBlockCache();
  383. break;
  384. case DBTracker::SharedReadCacheUse_Unified:
  385. cache_ptr = leveldb_chrome::GetSharedBrowserBlockCache();
  386. break;
  387. case DBTracker::SharedReadCacheUse_InMemory:
  388. cache_ptr = leveldb_chrome::GetSharedInMemoryBlockCache();
  389. break;
  390. case DBTracker::SharedReadCacheUse_NumCacheUses:
  391. NOTREACHED();
  392. }
  393. if (!cache_ptr)
  394. return;
  395. CreateDumpMalloced(pmd, name, cache_ptr->TotalCharge());
  396. }
  397. } // namespace
  398. Options::Options() {
  399. // Note: Ensure that these default values correspond to those in
  400. // components/services/leveldb/public/mojom/leveldb.mojom.
  401. // TODO(cmumford) Create struct-trait for leveldb.mojom.OpenOptions to force
  402. // users to pass in a leveldb_env::Options instance (and it's defaults).
  403. //
  404. // Currently log reuse is an experimental feature in leveldb. More info at:
  405. // https://github.com/google/leveldb/commit/251ebf5dc70129ad3
  406. #if BUILDFLAG(IS_CHROMEOS_ASH)
  407. // Reusing logs on Chrome OS resulted in an unacceptably high leveldb
  408. // corruption rate (at least for Indexed DB). More info at
  409. // https://crbug.com/460568
  410. reuse_logs = false;
  411. #else
  412. // Low end devices have limited RAM. Reusing logs will prevent the database
  413. // from being compacted on open and instead load the log file back into the
  414. // memory buffer which won't be written until it hits the maximum size
  415. // (leveldb::Options::write_buffer_size - 4MB by default). The downside here
  416. // is that databases opens take longer as the open is blocked on compaction.
  417. reuse_logs = !base::SysInfo::IsLowEndDevice();
  418. #endif
  419. // By default use a single shared block cache to conserve memory. The owner of
  420. // this object can create their own, or set to NULL to have leveldb create a
  421. // new db-specific block cache.
  422. block_cache = leveldb_chrome::GetSharedBrowserBlockCache();
  423. }
  424. const char* MethodIDToString(MethodID method) {
  425. switch (method) {
  426. case kSequentialFileRead:
  427. return "SequentialFileRead";
  428. case kSequentialFileSkip:
  429. return "SequentialFileSkip";
  430. case kRandomAccessFileRead:
  431. return "RandomAccessFileRead";
  432. case kWritableFileAppend:
  433. return "WritableFileAppend";
  434. case kWritableFileClose:
  435. return "WritableFileClose";
  436. case kWritableFileFlush:
  437. return "WritableFileFlush";
  438. case kWritableFileSync:
  439. return "WritableFileSync";
  440. case kNewSequentialFile:
  441. return "NewSequentialFile";
  442. case kNewRandomAccessFile:
  443. return "NewRandomAccessFile";
  444. case kNewWritableFile:
  445. return "NewWritableFile";
  446. case kNewAppendableFile:
  447. return "NewAppendableFile";
  448. case kCreateDir:
  449. return "CreateDir";
  450. case kGetFileSize:
  451. return "GetFileSize";
  452. case kRenameFile:
  453. return "RenameFile";
  454. case kLockFile:
  455. return "LockFile";
  456. case kUnlockFile:
  457. return "UnlockFile";
  458. case kGetTestDirectory:
  459. return "GetTestDirectory";
  460. case kNewLogger:
  461. return "NewLogger";
  462. case kSyncParent:
  463. return "SyncParent";
  464. case kGetChildren:
  465. return "GetChildren";
  466. case kRemoveFile:
  467. return "RemoveFile";
  468. case kRemoveDir:
  469. return "RemoveDir";
  470. case kObsoleteDeleteFile:
  471. case kObsoleteDeleteDir:
  472. case kNumEntries:
  473. NOTREACHED();
  474. return "Unknown";
  475. }
  476. NOTREACHED();
  477. return "Unknown";
  478. }
  479. Status MakeIOError(Slice filename,
  480. const std::string& message,
  481. MethodID method,
  482. base::File::Error error) {
  483. DCHECK_LT(error, 0);
  484. char buf[512];
  485. base::snprintf(buf, sizeof(buf), "%s (ChromeMethodBFE: %d::%s::%d)",
  486. message.c_str(), method, MethodIDToString(method), -error);
  487. // TOOD(crbug.com/760362): Map base::File::FILE_ERROR_NOT_FOUND to
  488. // Status::NotFound, after fixing LevelDB to handle
  489. // the NotFound correctly.
  490. return Status::IOError(filename, buf);
  491. }
  492. Status MakeIOError(Slice filename,
  493. const std::string& message,
  494. MethodID method) {
  495. char buf[512];
  496. base::snprintf(buf, sizeof(buf), "%s (ChromeMethodOnly: %d::%s)",
  497. message.c_str(), method, MethodIDToString(method));
  498. return Status::IOError(filename, buf);
  499. }
  500. ErrorParsingResult ParseMethodAndError(const leveldb::Status& status,
  501. MethodID* method_param,
  502. base::File::Error* error) {
  503. const std::string status_string = status.ToString();
  504. int method;
  505. if (RE2::PartialMatch(status_string.c_str(), "ChromeMethodOnly: (\\d+)",
  506. &method)) {
  507. *method_param = static_cast<MethodID>(method);
  508. return METHOD_ONLY;
  509. }
  510. int parsed_error;
  511. if (RE2::PartialMatch(status_string.c_str(),
  512. "ChromeMethodBFE: (\\d+)::.*::(\\d+)", &method,
  513. &parsed_error)) {
  514. *method_param = static_cast<MethodID>(method);
  515. *error = static_cast<base::File::Error>(-parsed_error);
  516. DCHECK_LT(*error, base::File::FILE_OK);
  517. DCHECK_GT(*error, base::File::FILE_ERROR_MAX);
  518. return METHOD_AND_BFE;
  519. }
  520. return NONE;
  521. }
  522. // Keep in sync with LevelDBCorruptionTypes in histograms.xml. Also, don't
  523. // change the order because indices into this array have been recorded in uma
  524. // histograms.
  525. const char* patterns[] = {
  526. "missing files",
  527. "log record too small",
  528. "corrupted internal key",
  529. "partial record",
  530. "missing start of fragmented record",
  531. "error in middle of record",
  532. "unknown record type",
  533. "truncated record at end",
  534. "bad record length",
  535. "VersionEdit",
  536. "FileReader invoked with unexpected value",
  537. "corrupted key",
  538. "CURRENT file does not end with newline",
  539. "no meta-nextfile entry",
  540. "no meta-lognumber entry",
  541. "no last-sequence-number entry",
  542. "malformed WriteBatch",
  543. "bad WriteBatch Put",
  544. "bad WriteBatch Delete",
  545. "unknown WriteBatch tag",
  546. "WriteBatch has wrong count",
  547. "bad entry in block",
  548. "bad block contents",
  549. "bad block handle",
  550. "truncated block read",
  551. "block checksum mismatch",
  552. "checksum mismatch",
  553. "corrupted compressed block contents",
  554. "bad block type",
  555. "bad magic number",
  556. "file is too short",
  557. };
  558. // Returns 1-based index into the above array or 0 if nothing matches.
  559. int GetCorruptionCode(const leveldb::Status& status) {
  560. DCHECK(!status.IsIOError());
  561. DCHECK(!status.ok());
  562. const int kOtherError = 0;
  563. int error = kOtherError;
  564. const std::string& str_error = status.ToString();
  565. const size_t kNumPatterns = std::size(patterns);
  566. for (size_t i = 0; i < kNumPatterns; ++i) {
  567. if (str_error.find(patterns[i]) != std::string::npos) {
  568. error = i + 1;
  569. break;
  570. }
  571. }
  572. return error;
  573. }
  574. int GetNumCorruptionCodes() {
  575. // + 1 for the "other" error that is returned when a corruption message
  576. // doesn't match any of the patterns.
  577. return std::size(patterns) + 1;
  578. }
  579. std::string GetCorruptionMessage(const leveldb::Status& status) {
  580. int code = GetCorruptionCode(status);
  581. if (code == 0)
  582. return "Unknown corruption";
  583. return patterns[code - 1];
  584. }
  585. bool IndicatesDiskFull(const leveldb::Status& status) {
  586. if (status.ok())
  587. return false;
  588. leveldb_env::MethodID method;
  589. base::File::Error error = base::File::FILE_OK;
  590. leveldb_env::ErrorParsingResult result =
  591. leveldb_env::ParseMethodAndError(status, &method, &error);
  592. return (result == leveldb_env::METHOD_AND_BFE &&
  593. static_cast<base::File::Error>(error) ==
  594. base::File::FILE_ERROR_NO_SPACE);
  595. }
  596. std::string DatabaseNameForRewriteDB(const std::string& original_name) {
  597. return original_name + kDatabaseNameSuffixForRebuildDB;
  598. }
  599. // Given the size of the disk, identified by |disk_size| in bytes, determine the
  600. // appropriate write_buffer_size. Ignoring snapshots, if the current set of
  601. // tables in a database contains a set of key/value pairs identified by {A}, and
  602. // a set of key/value pairs identified by {B} has been written and is in the log
  603. // file, then during compaction you will have {A} + {B} + {A, B} = 2A + 2B.
  604. // There is no way to know the size of A, so minimizing the size of B will
  605. // maximize the likelihood of a successful compaction.
  606. size_t WriteBufferSize(int64_t disk_size) {
  607. const leveldb_env::Options default_options;
  608. const int64_t kMinBufferSize = 1024 * 1024;
  609. const int64_t kMaxBufferSize = default_options.write_buffer_size;
  610. const int64_t kDiskMinBuffSize = 10 * 1024 * 1024;
  611. const int64_t kDiskMaxBuffSize = 40 * 1024 * 1024;
  612. if (disk_size == -1)
  613. return default_options.write_buffer_size;
  614. if (disk_size <= kDiskMinBuffSize)
  615. return kMinBufferSize;
  616. if (disk_size >= kDiskMaxBuffSize)
  617. return kMaxBufferSize;
  618. // A linear equation to intersect (kDiskMinBuffSize, kMinBufferSize) and
  619. // (kDiskMaxBuffSize, kMaxBufferSize).
  620. return static_cast<size_t>(
  621. kMinBufferSize +
  622. ((kMaxBufferSize - kMinBufferSize) * (disk_size - kDiskMinBuffSize)) /
  623. (kDiskMaxBuffSize - kDiskMinBuffSize));
  624. }
  625. ChromiumEnv::ChromiumEnv() : ChromiumEnv("LevelDBEnv") {}
  626. ChromiumEnv::ChromiumEnv(std::unique_ptr<storage::FilesystemProxy> filesystem)
  627. : ChromiumEnv("LevelDBEnv", std::move(filesystem)) {}
  628. ChromiumEnv::ChromiumEnv(const std::string& name)
  629. : ChromiumEnv(name,
  630. std::make_unique<storage::FilesystemProxy>(
  631. storage::FilesystemProxy::UNRESTRICTED,
  632. base::FilePath())) {}
  633. ChromiumEnv::ChromiumEnv(const std::string& name,
  634. std::unique_ptr<storage::FilesystemProxy> filesystem)
  635. : filesystem_(std::move(filesystem)), name_(name) {
  636. DCHECK(filesystem_);
  637. size_t max_open_files = base::GetMaxFds();
  638. if (max_open_files < kFileLimitToDisableEviction) {
  639. file_cache_.reset(
  640. leveldb::NewLRUCache(GetLevelDBFileLimit(max_open_files)));
  641. }
  642. }
  643. ChromiumEnv::~ChromiumEnv() {
  644. // In chromium, ChromiumEnv is leaked. It'd be nice to add NOTREACHED here to
  645. // ensure that behavior isn't accidentally changed, but there's an instance in
  646. // a unit test that is deleted.
  647. }
  648. bool ChromiumEnv::FileExists(const std::string& fname) {
  649. return filesystem_->PathExists(FilePath::FromUTF8Unsafe(fname));
  650. }
  651. const char* ChromiumEnv::FileErrorString(base::File::Error error) {
  652. switch (error) {
  653. case base::File::FILE_ERROR_FAILED:
  654. return "No further details.";
  655. case base::File::FILE_ERROR_IN_USE:
  656. return "File currently in use.";
  657. case base::File::FILE_ERROR_EXISTS:
  658. return "File already exists.";
  659. case base::File::FILE_ERROR_NOT_FOUND:
  660. return "File not found.";
  661. case base::File::FILE_ERROR_ACCESS_DENIED:
  662. return "Access denied.";
  663. case base::File::FILE_ERROR_TOO_MANY_OPENED:
  664. return "Too many files open.";
  665. case base::File::FILE_ERROR_NO_MEMORY:
  666. return "Out of memory.";
  667. case base::File::FILE_ERROR_NO_SPACE:
  668. return "No space left on drive.";
  669. case base::File::FILE_ERROR_NOT_A_DIRECTORY:
  670. return "Not a directory.";
  671. case base::File::FILE_ERROR_INVALID_OPERATION:
  672. return "Invalid operation.";
  673. case base::File::FILE_ERROR_SECURITY:
  674. return "Security error.";
  675. case base::File::FILE_ERROR_ABORT:
  676. return "File operation aborted.";
  677. case base::File::FILE_ERROR_NOT_A_FILE:
  678. return "The supplied path was not a file.";
  679. case base::File::FILE_ERROR_NOT_EMPTY:
  680. return "The file was not empty.";
  681. case base::File::FILE_ERROR_INVALID_URL:
  682. return "Invalid URL.";
  683. case base::File::FILE_ERROR_IO:
  684. return "OS or hardware error.";
  685. case base::File::FILE_OK:
  686. return "OK.";
  687. case base::File::FILE_ERROR_MAX:
  688. NOTREACHED();
  689. }
  690. NOTIMPLEMENTED();
  691. return "Unknown error.";
  692. }
  693. // Delete unused table backup files - a feature no longer supported.
  694. // TODO(cmumford): Delete this function once found backup files drop below some
  695. // very small (TBD) number.
  696. void ChromiumEnv::RemoveBackupFiles(const FilePath& dir) {
  697. base::HistogramBase* histogram = base::BooleanHistogram::FactoryGet(
  698. "LevelDBEnv.DeleteTableBackupFile",
  699. base::Histogram::kUmaTargetedHistogramFlag);
  700. FileErrorOr<std::vector<base::FilePath>> result =
  701. filesystem_->GetDirectoryEntries(
  702. dir, storage::FilesystemProxy::DirectoryEntryType::kFilesOnly);
  703. if (result.is_error())
  704. return;
  705. for (const auto& path : result.value()) {
  706. if (path.Extension() == FILE_PATH_LITERAL(".bak"))
  707. histogram->AddBoolean(filesystem_->DeleteFile(path));
  708. }
  709. }
  710. // Test must call this *before* opening any random-access files.
  711. void ChromiumEnv::SetReadOnlyFileLimitForTesting(int max_open_files) {
  712. DCHECK(!file_cache_ || file_cache_->TotalCharge() == 0);
  713. file_cache_.reset(leveldb::NewLRUCache(max_open_files));
  714. }
  715. Status ChromiumEnv::GetChildren(const std::string& dir,
  716. std::vector<std::string>* result) {
  717. FilePath dir_path = FilePath::FromUTF8Unsafe(dir);
  718. RemoveBackupFiles(dir_path);
  719. FileErrorOr<std::vector<FilePath>> entries_result =
  720. filesystem_->GetDirectoryEntries(
  721. dir_path,
  722. storage::FilesystemProxy::DirectoryEntryType::kFilesAndDirectories);
  723. if (entries_result.is_error()) {
  724. return MakeIOError(dir, "Could not open/read directory", kGetChildren,
  725. entries_result.error());
  726. }
  727. result->clear();
  728. for (const auto& entry : entries_result.value())
  729. result->push_back(entry.BaseName().AsUTF8Unsafe());
  730. return Status::OK();
  731. }
  732. Status ChromiumEnv::RemoveFile(const std::string& fname) {
  733. Status result;
  734. FilePath fname_filepath = FilePath::FromUTF8Unsafe(fname);
  735. if (!filesystem_->DeleteFile(fname_filepath)) {
  736. result = MakeIOError(fname, "Could not delete file.", kRemoveFile);
  737. }
  738. return result;
  739. }
  740. Status ChromiumEnv::CreateDir(const std::string& name) {
  741. Status result;
  742. base::File::Error error = base::File::FILE_OK;
  743. Retrier retrier;
  744. do {
  745. error = filesystem_->CreateDirectory(base::FilePath::FromUTF8Unsafe(name));
  746. if (error == base::File::FILE_OK)
  747. return result;
  748. } while (retrier.ShouldKeepTrying());
  749. return MakeIOError(name, "Could not create directory.", kCreateDir, error);
  750. }
  751. Status ChromiumEnv::RemoveDir(const std::string& name) {
  752. Status result;
  753. if (!filesystem_->DeleteFile(FilePath::FromUTF8Unsafe(name))) {
  754. result = MakeIOError(name, "Could not delete directory.", kRemoveDir);
  755. }
  756. return result;
  757. }
  758. Status ChromiumEnv::GetFileSize(const std::string& fname, uint64_t* size) {
  759. Status s;
  760. absl::optional<base::File::Info> info =
  761. filesystem_->GetFileInfo(base::FilePath::FromUTF8Unsafe(fname));
  762. if (!info) {
  763. *size = 0;
  764. s = MakeIOError(fname, "Could not determine file size.", kGetFileSize);
  765. } else {
  766. *size = static_cast<uint64_t>(info->size);
  767. }
  768. return s;
  769. }
  770. Status ChromiumEnv::RenameFile(const std::string& src, const std::string& dst) {
  771. Status result;
  772. FilePath src_file_path = FilePath::FromUTF8Unsafe(src);
  773. if (!filesystem_->PathExists(src_file_path))
  774. return result;
  775. FilePath destination = FilePath::FromUTF8Unsafe(dst);
  776. Retrier retrier;
  777. base::File::Error error = base::File::FILE_OK;
  778. do {
  779. error = filesystem_->RenameFile(src_file_path, destination);
  780. if (error == base::File::FILE_OK)
  781. return result;
  782. } while (retrier.ShouldKeepTrying());
  783. DCHECK(error != base::File::FILE_OK);
  784. char buf[100];
  785. base::snprintf(buf,
  786. sizeof(buf),
  787. "Could not rename file: %s",
  788. FileErrorString(error));
  789. return MakeIOError(src, buf, kRenameFile, error);
  790. }
  791. Status ChromiumEnv::LockFile(const std::string& fname, FileLock** lock) {
  792. *lock = nullptr;
  793. Status result;
  794. const base::FilePath path = base::FilePath::FromUTF8Unsafe(fname);
  795. Retrier retrier;
  796. FileErrorOr<std::unique_ptr<storage::FilesystemProxy::FileLock>> lock_result =
  797. base::File::Error::FILE_ERROR_FAILED;
  798. do {
  799. lock_result = filesystem_->LockFile(path);
  800. } while (lock_result.is_error() && retrier.ShouldKeepTrying());
  801. if (lock_result.is_error()) {
  802. return MakeIOError(fname, FileErrorString(lock_result.error()), kLockFile,
  803. lock_result.error());
  804. }
  805. *lock = new ChromiumFileLock(std::move(lock_result.value()), fname);
  806. return result;
  807. }
  808. Status ChromiumEnv::UnlockFile(FileLock* lock) {
  809. std::unique_ptr<ChromiumFileLock> my_lock(
  810. reinterpret_cast<ChromiumFileLock*>(lock));
  811. Status result = Status::OK();
  812. base::File::Error error_code = my_lock->lock->Release();
  813. if (error_code != base::File::FILE_OK) {
  814. result =
  815. MakeIOError(my_lock->name, "Could not unlock lock file.", kUnlockFile);
  816. }
  817. return result;
  818. }
  819. Status ChromiumEnv::GetTestDirectory(std::string* path) {
  820. mu_.Acquire();
  821. if (test_directory_.empty()) {
  822. if (!base::CreateNewTempDirectory(kLevelDBTestDirectoryPrefix,
  823. &test_directory_)) {
  824. mu_.Release();
  825. return MakeIOError(
  826. "Could not create temp directory.", "", kGetTestDirectory);
  827. }
  828. }
  829. *path = test_directory_.AsUTF8Unsafe();
  830. mu_.Release();
  831. return Status::OK();
  832. }
  833. Status ChromiumEnv::NewLogger(const std::string& fname,
  834. leveldb::Logger** result) {
  835. FilePath path = FilePath::FromUTF8Unsafe(fname);
  836. FileErrorOr<base::File> open_result = filesystem_->OpenFile(
  837. path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
  838. if (open_result.is_error()) {
  839. *result = nullptr;
  840. return MakeIOError(fname, "Unable to create log file", kNewLogger,
  841. open_result.error());
  842. } else {
  843. *result = new leveldb::ChromiumLogger(std::move(open_result.value()));
  844. return Status::OK();
  845. }
  846. }
  847. Status ChromiumEnv::NewSequentialFile(const std::string& fname,
  848. leveldb::SequentialFile** result) {
  849. FilePath path = FilePath::FromUTF8Unsafe(fname);
  850. FileErrorOr<base::File> open_result = filesystem_->OpenFile(
  851. path, base::File::FLAG_OPEN | base::File::FLAG_READ);
  852. if (open_result.is_error()) {
  853. *result = nullptr;
  854. return MakeIOError(fname, "Unable to create sequential file",
  855. kNewSequentialFile, open_result.error());
  856. } else {
  857. *result = new ChromiumSequentialFile(fname, std::move(open_result.value()));
  858. return Status::OK();
  859. }
  860. }
  861. Status ChromiumEnv::NewRandomAccessFile(const std::string& fname,
  862. leveldb::RandomAccessFile** result) {
  863. base::FilePath file_path = FilePath::FromUTF8Unsafe(fname);
  864. FileErrorOr<base::File> open_result = filesystem_->OpenFile(
  865. file_path, base::File::FLAG_READ | base::File::FLAG_OPEN);
  866. if (!open_result.is_error()) {
  867. base::File file = std::move(open_result.value());
  868. if (file_cache_) {
  869. *result = new ChromiumEvictableRandomAccessFile(
  870. std::move(file_path), std::move(file), filesystem_.get(),
  871. file_cache_.get());
  872. } else {
  873. *result =
  874. new ChromiumRandomAccessFile(std::move(file_path), std::move(file));
  875. }
  876. return Status::OK();
  877. }
  878. *result = nullptr;
  879. return MakeIOError(fname, FileErrorString(open_result.error()),
  880. kNewRandomAccessFile, open_result.error());
  881. }
  882. Status ChromiumEnv::NewWritableFile(const std::string& fname,
  883. leveldb::WritableFile** result) {
  884. FilePath path = FilePath::FromUTF8Unsafe(fname);
  885. FileErrorOr<base::File> open_result = filesystem_->OpenFile(
  886. path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
  887. if (open_result.is_error()) {
  888. *result = nullptr;
  889. return MakeIOError(fname, "Unable to create writable file",
  890. kNewWritableFile, open_result.error());
  891. }
  892. *result = new ChromiumWritableFile(fname, std::move(open_result.value()),
  893. filesystem_.get());
  894. return Status::OK();
  895. }
  896. Status ChromiumEnv::NewAppendableFile(const std::string& fname,
  897. leveldb::WritableFile** result) {
  898. FilePath path = FilePath::FromUTF8Unsafe(fname);
  899. FileErrorOr<base::File> open_result = filesystem_->OpenFile(
  900. path, base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_APPEND);
  901. if (open_result.is_error()) {
  902. *result = nullptr;
  903. return MakeIOError(fname, "Unable to create appendable file",
  904. kNewAppendableFile, open_result.error());
  905. }
  906. *result = new ChromiumWritableFile(fname, std::move(open_result.value()),
  907. filesystem_.get());
  908. return Status::OK();
  909. }
  910. uint64_t ChromiumEnv::NowMicros() {
  911. return base::TimeTicks::Now().ToInternalValue();
  912. }
  913. void ChromiumEnv::SleepForMicroseconds(int micros) {
  914. // Round up to the next millisecond.
  915. base::PlatformThread::Sleep(base::Microseconds(micros));
  916. }
  917. class Thread : public base::PlatformThread::Delegate {
  918. public:
  919. Thread(void (*function)(void* arg), void* arg)
  920. : function_(function), arg_(arg) {
  921. base::PlatformThreadHandle handle;
  922. bool success = base::PlatformThread::Create(0, this, &handle);
  923. DCHECK(success);
  924. }
  925. Thread(const Thread&) = delete;
  926. Thread& operator=(const Thread&) = delete;
  927. virtual ~Thread() {}
  928. void ThreadMain() override {
  929. (*function_)(arg_);
  930. delete this;
  931. }
  932. private:
  933. void (*function_)(void* arg);
  934. void* arg_;
  935. };
  936. void ChromiumEnv::Schedule(ScheduleFunc* function, void* arg) {
  937. // The BLOCK_SHUTDOWN is required to avoid shutdown hangs. The scheduled
  938. // tasks may be blocking foreground threads waiting for their completions.
  939. // see: https://crbug.com/1086185.
  940. base::ThreadPool::PostTask(FROM_HERE,
  941. {base::MayBlock(), base::WithBaseSyncPrimitives(),
  942. base::TaskShutdownBehavior::BLOCK_SHUTDOWN},
  943. base::BindOnce(function, arg));
  944. }
  945. void ChromiumEnv::StartThread(void (*function)(void* arg), void* arg) {
  946. new Thread(function, arg); // Will self-delete.
  947. }
  948. LevelDBStatusValue GetLevelDBStatusUMAValue(const leveldb::Status& s) {
  949. if (s.ok())
  950. return LEVELDB_STATUS_OK;
  951. if (s.IsNotFound())
  952. return LEVELDB_STATUS_NOT_FOUND;
  953. if (s.IsCorruption())
  954. return LEVELDB_STATUS_CORRUPTION;
  955. if (s.IsNotSupportedError())
  956. return LEVELDB_STATUS_NOT_SUPPORTED;
  957. if (s.IsIOError())
  958. return LEVELDB_STATUS_IO_ERROR;
  959. // TODO(cmumford): IsInvalidArgument() was just added to leveldb. Use this
  960. // function once that change goes to the public repository.
  961. return LEVELDB_STATUS_INVALID_ARGUMENT;
  962. }
  963. // Forwards all calls to the underlying leveldb::DB instance.
  964. // Adds / removes itself in the DBTracker it's created with.
  965. class DBTracker::TrackedDBImpl : public base::LinkNode<TrackedDBImpl>,
  966. public TrackedDB {
  967. public:
  968. TrackedDBImpl(DBTracker* tracker,
  969. const std::string name,
  970. leveldb::DB* db,
  971. const leveldb::Cache* block_cache,
  972. DatabaseErrorReportingCallback on_get_error,
  973. DatabaseErrorReportingCallback on_write_error)
  974. : tracker_(tracker),
  975. name_(name),
  976. db_(db),
  977. on_get_error_(std::move(on_get_error)),
  978. on_write_error_(std::move(on_write_error)) {
  979. if (leveldb_chrome::GetSharedWebBlockCache() ==
  980. leveldb_chrome::GetSharedBrowserBlockCache()) {
  981. shared_read_cache_use_ = SharedReadCacheUse_Unified;
  982. } else if (block_cache == leveldb_chrome::GetSharedBrowserBlockCache()) {
  983. shared_read_cache_use_ = SharedReadCacheUse_Browser;
  984. } else if (block_cache == leveldb_chrome::GetSharedWebBlockCache()) {
  985. shared_read_cache_use_ = SharedReadCacheUse_Web;
  986. } else if (block_cache == leveldb_chrome::GetSharedInMemoryBlockCache()) {
  987. shared_read_cache_use_ = SharedReadCacheUse_InMemory;
  988. } else {
  989. NOTREACHED();
  990. }
  991. tracker_->DatabaseOpened(this, shared_read_cache_use_);
  992. }
  993. TrackedDBImpl(const TrackedDBImpl&) = delete;
  994. TrackedDBImpl& operator=(const TrackedDBImpl&) = delete;
  995. ~TrackedDBImpl() override {
  996. tracker_->DatabaseDestroyed(this, shared_read_cache_use_);
  997. leveldb::port::ScopedAllowWait scoped_allow_wait;
  998. db_.reset();
  999. }
  1000. const std::string& name() const override { return name_; }
  1001. SharedReadCacheUse block_cache_type() const override {
  1002. return shared_read_cache_use_;
  1003. }
  1004. leveldb::Status Put(const leveldb::WriteOptions& options,
  1005. const leveldb::Slice& key,
  1006. const leveldb::Slice& value) override {
  1007. return db_->Put(options, key, value);
  1008. }
  1009. leveldb::Status Delete(const leveldb::WriteOptions& options,
  1010. const leveldb::Slice& key) override {
  1011. return db_->Delete(options, key);
  1012. }
  1013. leveldb::Status Write(const leveldb::WriteOptions& options,
  1014. leveldb::WriteBatch* updates) override {
  1015. leveldb::Status status = db_->Write(options, updates);
  1016. if (LIKELY(status.ok()))
  1017. return status;
  1018. if (on_write_error_)
  1019. on_write_error_.Run(status);
  1020. return status;
  1021. }
  1022. leveldb::Status Get(const leveldb::ReadOptions& options,
  1023. const leveldb::Slice& key,
  1024. std::string* value) override {
  1025. leveldb::Status status = db_->Get(options, key, value);
  1026. if (LIKELY(status.ok() || status.IsNotFound()))
  1027. return status;
  1028. if (on_get_error_)
  1029. on_get_error_.Run(status);
  1030. return status;
  1031. }
  1032. const leveldb::Snapshot* GetSnapshot() override { return db_->GetSnapshot(); }
  1033. void ReleaseSnapshot(const leveldb::Snapshot* snapshot) override {
  1034. return db_->ReleaseSnapshot(snapshot);
  1035. }
  1036. bool GetProperty(const leveldb::Slice& property,
  1037. std::string* value) override {
  1038. return db_->GetProperty(property, value);
  1039. }
  1040. void GetApproximateSizes(const leveldb::Range* range,
  1041. int n,
  1042. uint64_t* sizes) override {
  1043. return db_->GetApproximateSizes(range, n, sizes);
  1044. }
  1045. void CompactRange(const leveldb::Slice* begin,
  1046. const leveldb::Slice* end) override {
  1047. return db_->CompactRange(begin, end);
  1048. }
  1049. leveldb::Iterator* NewIterator(const leveldb::ReadOptions& options) override {
  1050. return db_->NewIterator(options);
  1051. }
  1052. private:
  1053. DBTracker* tracker_;
  1054. std::string name_;
  1055. std::unique_ptr<leveldb::DB> db_;
  1056. SharedReadCacheUse shared_read_cache_use_;
  1057. const DatabaseErrorReportingCallback on_get_error_;
  1058. const DatabaseErrorReportingCallback on_write_error_;
  1059. };
  1060. // Reports live databases and in-memory env's to memory-infra. For each live
  1061. // database the following information is reported:
  1062. // 1. Instance pointer (to disambiguate databases).
  1063. // 2. Memory taken by the database, with the shared cache being attributed
  1064. // equally to each database sharing 3. The name of the database (when not in
  1065. // BACKGROUND mode to avoid exposing
  1066. // PIIs in slow reports).
  1067. //
  1068. // Example report (as seen after clicking "leveldatabase" in "Overview" pane
  1069. // in Chrome tracing UI):
  1070. //
  1071. // Component effective_size size name
  1072. // ---------------------------------------------------------------------------
  1073. // leveldatabase 390 KiB 490 KiB
  1074. // db_0x7FE70F2040A0 100 KiB 100 KiB Users/.../Sync
  1075. // block_cache (browser) 40 KiB 40 KiB
  1076. // db_0x7FE70F530D80 150 KiB 150 KiB Users/.../Data Proxy
  1077. // block_cache (web) 30 KiB 30 KiB
  1078. // db_0x7FE70F530D80 140 KiB 140 KiB Users/.../Extensions
  1079. // block_cache (web) 30 KiB 30 KiB
  1080. // block_cache 0 KiB 100 KiB
  1081. // browser 0 KiB 40 KiB
  1082. // web 0 KiB 60 KiB
  1083. // memenv_0x7FE80F2040A0 4 KiB 4 KiB
  1084. // memenv_0x7FE80F3040A0 4 KiB 4 KiB
  1085. //
  1086. class DBTracker::MemoryDumpProvider
  1087. : public base::trace_event::MemoryDumpProvider {
  1088. public:
  1089. void DumpAllDatabases(ProcessMemoryDump* pmd);
  1090. bool OnMemoryDump(const MemoryDumpArgs& args,
  1091. ProcessMemoryDump* pmd) override {
  1092. DumpAllDatabases(pmd);
  1093. return true;
  1094. }
  1095. void DatabaseOpened(const TrackedDBImpl* database) {
  1096. database_use_count_[database->block_cache_type()]++;
  1097. }
  1098. void DatabaseDestroyed(const TrackedDBImpl* database) {
  1099. database_use_count_[database->block_cache_type()]--;
  1100. DCHECK_GE(database_use_count_[database->block_cache_type()], 0);
  1101. }
  1102. private:
  1103. void DumpVisitor(ProcessMemoryDump* pmd, TrackedDB* db);
  1104. int database_use_count_[SharedReadCacheUse_NumCacheUses] = {};
  1105. };
  1106. void DBTracker::MemoryDumpProvider::DumpAllDatabases(ProcessMemoryDump* pmd) {
  1107. if (pmd->GetAllocatorDump("leveldatabase"))
  1108. return;
  1109. pmd->CreateAllocatorDump("leveldatabase");
  1110. const auto* browser_cache = leveldb_chrome::GetSharedBrowserBlockCache();
  1111. const auto* web_cache = leveldb_chrome::GetSharedWebBlockCache();
  1112. if (browser_cache == web_cache) {
  1113. RecordCacheUsageInTracing(pmd, SharedReadCacheUse_Unified);
  1114. } else {
  1115. RecordCacheUsageInTracing(pmd, SharedReadCacheUse_Browser);
  1116. RecordCacheUsageInTracing(pmd, SharedReadCacheUse_Web);
  1117. }
  1118. RecordCacheUsageInTracing(pmd, SharedReadCacheUse_InMemory);
  1119. DBTracker::GetInstance()->VisitDatabases(
  1120. base::BindRepeating(&DBTracker::MemoryDumpProvider::DumpVisitor,
  1121. base::Unretained(this), base::Unretained(pmd)));
  1122. leveldb_chrome::DumpAllTrackedEnvs(pmd);
  1123. }
  1124. void DBTracker::MemoryDumpProvider::DumpVisitor(ProcessMemoryDump* pmd,
  1125. TrackedDB* db) {
  1126. std::string db_dump_name = GetDumpNameForDB(db);
  1127. auto* db_cache_dump = pmd->CreateAllocatorDump(db_dump_name + "/block_cache");
  1128. const std::string cache_dump_name =
  1129. GetDumpNameForCache(db->block_cache_type());
  1130. pmd->AddSuballocation(db_cache_dump->guid(), cache_dump_name);
  1131. size_t cache_usage =
  1132. pmd->GetAllocatorDump(cache_dump_name)->GetSizeInternal();
  1133. // The |database_use_count_| can be accessed by the visitor because the
  1134. // visitor is called holding the lock at DBTracker.
  1135. size_t cache_usage_pss =
  1136. cache_usage / database_use_count_[db->block_cache_type()];
  1137. db_cache_dump->AddScalar(MemoryAllocatorDump::kNameSize,
  1138. MemoryAllocatorDump::kUnitsBytes, cache_usage_pss);
  1139. auto* db_dump = pmd->CreateAllocatorDump(db_dump_name);
  1140. uint64_t total_usage = 0;
  1141. std::string usage_string;
  1142. bool success =
  1143. db->GetProperty("leveldb.approximate-memory-usage", &usage_string) &&
  1144. base::StringToUint64(usage_string, &total_usage);
  1145. DCHECK(success);
  1146. db_dump->AddScalar(MemoryAllocatorDump::kNameSize,
  1147. MemoryAllocatorDump::kUnitsBytes,
  1148. total_usage - cache_usage + cache_usage_pss);
  1149. if (pmd->dump_args().level_of_detail !=
  1150. base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND) {
  1151. db_dump->AddString("name", "", db->name());
  1152. }
  1153. }
  1154. DBTracker::DBTracker() : mdp_(new MemoryDumpProvider()) {
  1155. base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
  1156. mdp_.get(), "LevelDB", nullptr);
  1157. }
  1158. DBTracker::~DBTracker() {
  1159. NOTREACHED(); // DBTracker is a singleton
  1160. }
  1161. // static
  1162. DBTracker* DBTracker::GetInstance() {
  1163. static DBTracker* instance = new DBTracker();
  1164. return instance;
  1165. }
  1166. // static
  1167. MemoryAllocatorDump* DBTracker::GetOrCreateAllocatorDump(
  1168. ProcessMemoryDump* pmd,
  1169. leveldb::DB* tracked_db) {
  1170. DCHECK(GetInstance()->IsTrackedDB(tracked_db))
  1171. << std::hex << tracked_db << " is not tracked";
  1172. // Create dumps for all databases to make sure the shared cache is equally
  1173. // attributed to each database sharing it.
  1174. GetInstance()->mdp_->DumpAllDatabases(pmd);
  1175. return pmd->GetAllocatorDump(GetDumpNameForDB(tracked_db));
  1176. }
  1177. // static
  1178. MemoryAllocatorDump* DBTracker::GetOrCreateAllocatorDump(
  1179. ProcessMemoryDump* pmd,
  1180. leveldb::Env* tracked_memenv) {
  1181. GetInstance()->mdp_->DumpAllDatabases(pmd);
  1182. return leveldb_chrome::GetEnvAllocatorDump(pmd, tracked_memenv);
  1183. }
  1184. bool DBTracker::IsTrackedDB(const leveldb::DB* db) const {
  1185. base::AutoLock lock(databases_lock_);
  1186. for (auto* i = databases_.head(); i != databases_.end(); i = i->next()) {
  1187. if (i->value() == db)
  1188. return true;
  1189. }
  1190. return false;
  1191. }
  1192. leveldb::Status DBTracker::OpenDatabase(const leveldb_env::Options& options,
  1193. const std::string& name,
  1194. TrackedDB** dbptr) {
  1195. leveldb::DB* db = nullptr;
  1196. auto status = leveldb::DB::Open(options, name, &db);
  1197. // Enforce expectations: either we succeed, and get a valid object in |db|,
  1198. // or we fail, and |db| is still NULL.
  1199. CHECK((status.ok() && db) || (!status.ok() && !db));
  1200. if (status.ok()) {
  1201. // TrackedDBImpl ctor adds the instance to the tracker.
  1202. *dbptr = new TrackedDBImpl(GetInstance(), name, db, options.block_cache,
  1203. std::move(options.on_get_error),
  1204. std::move(options.on_write_error));
  1205. }
  1206. return status;
  1207. }
  1208. void DBTracker::VisitDatabases(const DatabaseVisitor& visitor) {
  1209. base::AutoLock lock(databases_lock_);
  1210. for (auto* i = databases_.head(); i != databases_.end(); i = i->next())
  1211. visitor.Run(i->value());
  1212. }
  1213. void DBTracker::DatabaseOpened(TrackedDBImpl* database,
  1214. SharedReadCacheUse cache_use) {
  1215. base::AutoLock lock(databases_lock_);
  1216. databases_.Append(database);
  1217. mdp_->DatabaseOpened(database);
  1218. }
  1219. void DBTracker::DatabaseDestroyed(TrackedDBImpl* database,
  1220. SharedReadCacheUse cache_use) {
  1221. base::AutoLock lock(databases_lock_);
  1222. mdp_->DatabaseDestroyed(database);
  1223. database->RemoveFromList();
  1224. }
  1225. leveldb::Status OpenDB(const leveldb_env::Options& options,
  1226. const std::string& name,
  1227. std::unique_ptr<leveldb::DB>* dbptr) {
  1228. // For UMA logging purposes we need the block cache to be created outside of
  1229. // leveldb so that the size can be logged and it can be pruned.
  1230. DCHECK(options.block_cache != nullptr);
  1231. DBTracker::TrackedDB* tracked_db = nullptr;
  1232. leveldb::Status s;
  1233. if (options.env && leveldb_chrome::IsMemEnv(options.env)) {
  1234. Options mem_options = options;
  1235. mem_options.block_cache = leveldb_chrome::GetSharedInMemoryBlockCache();
  1236. mem_options.write_buffer_size = 0; // minimum size.
  1237. s = DBTracker::GetInstance()->OpenDatabase(mem_options, name, &tracked_db);
  1238. } else {
  1239. std::string tmp_name = DatabaseNameForRewriteDB(name);
  1240. // If Chrome crashes during rewrite, there might be a temporary db but
  1241. // no actual db.
  1242. if (options.env->FileExists(tmp_name) &&
  1243. !options.env->FileExists(name + "/CURRENT")) {
  1244. s = leveldb::DestroyDB(name, options);
  1245. if (!s.ok())
  1246. return s;
  1247. s = options.env->RenameFile(tmp_name, name);
  1248. if (!s.ok())
  1249. return s;
  1250. }
  1251. s = DBTracker::GetInstance()->OpenDatabase(options, name, &tracked_db);
  1252. // It is possible that the database was partially deleted during a
  1253. // rewrite and can't be opened anymore.
  1254. if (!s.ok() && options.env->FileExists(tmp_name)) {
  1255. s = leveldb::DestroyDB(name, options);
  1256. if (!s.ok())
  1257. return s;
  1258. s = options.env->RenameFile(tmp_name, name);
  1259. if (!s.ok())
  1260. return s;
  1261. s = DBTracker::GetInstance()->OpenDatabase(options, name, &tracked_db);
  1262. }
  1263. // There might be a temporary database that needs to be cleaned up.
  1264. if (options.env->FileExists(tmp_name)) {
  1265. leveldb::DestroyDB(tmp_name, options);
  1266. }
  1267. }
  1268. if (s.ok())
  1269. dbptr->reset(tracked_db);
  1270. return s;
  1271. }
  1272. leveldb::Status RewriteDB(const leveldb_env::Options& options,
  1273. const std::string& name,
  1274. std::unique_ptr<leveldb::DB>* dbptr) {
  1275. DCHECK(options.create_if_missing);
  1276. if (leveldb_chrome::IsMemEnv(options.env))
  1277. return Status::OK();
  1278. TRACE_EVENT1("leveldb", "ChromiumEnv::RewriteDB", "name", name);
  1279. leveldb::Status s;
  1280. std::string tmp_name = DatabaseNameForRewriteDB(name);
  1281. if (options.env->FileExists(tmp_name)) {
  1282. s = leveldb::DestroyDB(tmp_name, options);
  1283. if (!s.ok())
  1284. return s;
  1285. }
  1286. // Copy all data from *dbptr to a temporary db.
  1287. std::unique_ptr<leveldb::DB> tmp_db;
  1288. s = leveldb_env::OpenDB(options, tmp_name, &tmp_db);
  1289. if (!s.ok())
  1290. return s;
  1291. std::unique_ptr<leveldb::Iterator> it(
  1292. (*dbptr)->NewIterator(leveldb::ReadOptions()));
  1293. for (it->SeekToFirst(); it->Valid(); it->Next()) {
  1294. s = tmp_db->Put(leveldb::WriteOptions(), it->key(), it->value());
  1295. if (!s.ok())
  1296. break;
  1297. }
  1298. it.reset();
  1299. tmp_db.reset();
  1300. if (!s.ok()) {
  1301. leveldb::DestroyDB(tmp_name, options);
  1302. return s;
  1303. }
  1304. // Replace the old database with tmp_db.
  1305. (*dbptr).reset();
  1306. s = leveldb::DestroyDB(name, options);
  1307. if (!s.ok())
  1308. return s;
  1309. s = options.env->RenameFile(tmp_name, name);
  1310. if (!s.ok())
  1311. return s;
  1312. return leveldb_env::OpenDB(options, name, dbptr);
  1313. }
  1314. base::StringPiece MakeStringPiece(const leveldb::Slice& s) {
  1315. return base::StringPiece(s.data(), s.size());
  1316. }
  1317. leveldb::Slice MakeSlice(const base::StringPiece& s) {
  1318. return leveldb::Slice(s.begin(), s.size());
  1319. }
  1320. leveldb::Slice MakeSlice(base::span<const uint8_t> s) {
  1321. return MakeSlice(
  1322. base::StringPiece(reinterpret_cast<const char*>(s.data()), s.size()));
  1323. }
  1324. } // namespace leveldb_env
  1325. namespace leveldb {
  1326. Env* Env::Default() {
  1327. static base::NoDestructor<leveldb_env::ChromiumEnv> default_env;
  1328. return default_env.get();
  1329. }
  1330. } // namespace leveldb