1 // Copyright (c) 2013 The Chromium 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.
5 #include "content/browser/indexed_db/leveldb/leveldb_database.h"
9 #include "base/basictypes.h"
10 #include "base/files/file.h"
11 #include "base/logging.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/metrics/histogram.h"
14 #include "base/strings/string16.h"
15 #include "base/strings/string_piece.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/sys_info.h"
19 #include "content/browser/indexed_db/indexed_db_class_factory.h"
20 #include "content/browser/indexed_db/leveldb/leveldb_comparator.h"
21 #include "content/browser/indexed_db/leveldb/leveldb_iterator_impl.h"
22 #include "content/browser/indexed_db/leveldb/leveldb_write_batch.h"
23 #include "third_party/leveldatabase/env_chromium.h"
24 #include "third_party/leveldatabase/env_idb.h"
25 #include "third_party/leveldatabase/src/helpers/memenv/memenv.h"
26 #include "third_party/leveldatabase/src/include/leveldb/db.h"
27 #include "third_party/leveldatabase/src/include/leveldb/env.h"
28 #include "third_party/leveldatabase/src/include/leveldb/filter_policy.h"
29 #include "third_party/leveldatabase/src/include/leveldb/slice.h"
31 using base::StringPiece
;
35 // Forcing flushes to disk at the end of a transaction guarantees that the
36 // data hit disk, but drastically impacts throughput when the filesystem is
37 // busy with background compactions. Not syncing trades off reliability for
38 // performance. Note that background compactions which move data from the
39 // log to SSTs are always done with reliable writes.
41 // Sync writes are necessary on Windows for quota calculations; POSIX
42 // calculates file sizes correctly even when not synced to disk.
44 static const bool kSyncWrites
= true;
46 // TODO(dgrogan): Either remove the #if block or change this back to false.
47 // See http://crbug.com/338385.
48 static const bool kSyncWrites
= true;
51 static leveldb::Slice
MakeSlice(const StringPiece
& s
) {
52 return leveldb::Slice(s
.begin(), s
.size());
55 static StringPiece
MakeStringPiece(const leveldb::Slice
& s
) {
56 return StringPiece(s
.data(), s
.size());
59 LevelDBDatabase::ComparatorAdapter::ComparatorAdapter(
60 const LevelDBComparator
* comparator
)
61 : comparator_(comparator
) {}
63 int LevelDBDatabase::ComparatorAdapter::Compare(const leveldb::Slice
& a
,
64 const leveldb::Slice
& b
) const {
65 return comparator_
->Compare(MakeStringPiece(a
), MakeStringPiece(b
));
68 const char* LevelDBDatabase::ComparatorAdapter::Name() const {
69 return comparator_
->Name();
72 // TODO(jsbell): Support the methods below in the future.
73 void LevelDBDatabase::ComparatorAdapter::FindShortestSeparator(
75 const leveldb::Slice
& limit
) const {}
77 void LevelDBDatabase::ComparatorAdapter::FindShortSuccessor(
78 std::string
* key
) const {}
80 LevelDBSnapshot::LevelDBSnapshot(LevelDBDatabase
* db
)
81 : db_(db
->db_
.get()), snapshot_(db_
->GetSnapshot()) {}
83 LevelDBSnapshot::~LevelDBSnapshot() { db_
->ReleaseSnapshot(snapshot_
); }
85 LevelDBDatabase::LevelDBDatabase() {}
87 LevelDBDatabase::~LevelDBDatabase() {
88 // db_'s destructor uses comparator_adapter_; order of deletion is important.
90 comparator_adapter_
.reset();
94 static leveldb::Status
OpenDB(
95 leveldb::Comparator
* comparator
,
97 const base::FilePath
& path
,
99 scoped_ptr
<const leveldb::FilterPolicy
>* filter_policy
) {
100 filter_policy
->reset(leveldb::NewBloomFilterPolicy(10));
101 leveldb::Options options
;
102 options
.comparator
= comparator
;
103 options
.create_if_missing
= true;
104 options
.paranoid_checks
= true;
105 options
.filter_policy
= filter_policy
->get();
106 options
.reuse_logs
= leveldb_env::kDefaultLogReuseOptionValue
;
107 options
.compression
= leveldb::kSnappyCompression
;
109 // For info about the troubles we've run into with this parameter, see:
110 // https://code.google.com/p/chromium/issues/detail?id=227313#c11
111 options
.max_open_files
= 80;
114 // ChromiumEnv assumes UTF8, converts back to FilePath before using.
115 leveldb::Status s
= leveldb::DB::Open(options
, path
.AsUTF8Unsafe(), db
);
120 leveldb::Status
LevelDBDatabase::Destroy(const base::FilePath
& file_name
) {
121 leveldb::Options options
;
122 options
.env
= leveldb::IDBEnv();
123 // ChromiumEnv assumes UTF8, converts back to FilePath before using.
124 return leveldb::DestroyDB(file_name
.AsUTF8Unsafe(), options
);
128 class LockImpl
: public LevelDBLock
{
130 explicit LockImpl(leveldb::Env
* env
, leveldb::FileLock
* lock
)
131 : env_(env
), lock_(lock
) {}
132 ~LockImpl() override
{ env_
->UnlockFile(lock_
); }
136 leveldb::FileLock
* lock_
;
138 DISALLOW_COPY_AND_ASSIGN(LockImpl
);
142 scoped_ptr
<LevelDBLock
> LevelDBDatabase::LockForTesting(
143 const base::FilePath
& file_name
) {
144 leveldb::Env
* env
= leveldb::IDBEnv();
145 base::FilePath lock_path
= file_name
.AppendASCII("LOCK");
146 leveldb::FileLock
* lock
= NULL
;
147 leveldb::Status status
= env
->LockFile(lock_path
.AsUTF8Unsafe(), &lock
);
149 return scoped_ptr
<LevelDBLock
>();
151 return scoped_ptr
<LevelDBLock
>(new LockImpl(env
, lock
));
154 static int CheckFreeSpace(const char* const type
,
155 const base::FilePath
& file_name
) {
157 std::string("WebCore.IndexedDB.LevelDB.Open") + type
+ "FreeDiskSpace";
158 int64 free_disk_space_in_k_bytes
=
159 base::SysInfo::AmountOfFreeDiskSpace(file_name
) / 1024;
160 if (free_disk_space_in_k_bytes
< 0) {
161 base::Histogram::FactoryGet(
162 "WebCore.IndexedDB.LevelDB.FreeDiskSpaceFailure",
166 base::HistogramBase::kUmaTargetedHistogramFlag
)->Add(1 /*sample*/);
169 int clamped_disk_space_k_bytes
= free_disk_space_in_k_bytes
> INT_MAX
171 : free_disk_space_in_k_bytes
;
172 const uint64 histogram_max
= static_cast<uint64
>(1e9
);
173 static_assert(histogram_max
<= INT_MAX
, "histogram_max too big");
174 base::Histogram::FactoryGet(name
,
178 base::HistogramBase::kUmaTargetedHistogramFlag
)
179 ->Add(clamped_disk_space_k_bytes
);
180 return clamped_disk_space_k_bytes
;
183 static void ParseAndHistogramIOErrorDetails(const std::string
& histogram_name
,
184 const leveldb::Status
& s
) {
185 leveldb_env::MethodID method
;
186 base::File::Error error
= base::File::FILE_OK
;
187 leveldb_env::ErrorParsingResult result
=
188 leveldb_env::ParseMethodAndError(s
, &method
, &error
);
189 if (result
== leveldb_env::NONE
)
191 std::string
method_histogram_name(histogram_name
);
192 method_histogram_name
.append(".EnvMethod");
193 base::LinearHistogram::FactoryGet(
194 method_histogram_name
,
196 leveldb_env::kNumEntries
,
197 leveldb_env::kNumEntries
+ 1,
198 base::HistogramBase::kUmaTargetedHistogramFlag
)->Add(method
);
200 std::string
error_histogram_name(histogram_name
);
202 if (result
== leveldb_env::METHOD_AND_BFE
) {
204 error_histogram_name
.append(std::string(".BFE.") +
205 leveldb_env::MethodIDToString(method
));
206 base::LinearHistogram::FactoryGet(
207 error_histogram_name
,
209 -base::File::FILE_ERROR_MAX
,
210 -base::File::FILE_ERROR_MAX
+ 1,
211 base::HistogramBase::kUmaTargetedHistogramFlag
)->Add(-error
);
215 static void ParseAndHistogramCorruptionDetails(
216 const std::string
& histogram_name
,
217 const leveldb::Status
& status
) {
218 int error
= leveldb_env::GetCorruptionCode(status
);
220 std::string
corruption_histogram_name(histogram_name
);
221 corruption_histogram_name
.append(".Corruption");
222 const int kNumPatterns
= leveldb_env::GetNumCorruptionCodes();
223 base::LinearHistogram::FactoryGet(
224 corruption_histogram_name
,
228 base::HistogramBase::kUmaTargetedHistogramFlag
)->Add(error
);
231 static void HistogramLevelDBError(const std::string
& histogram_name
,
232 const leveldb::Status
& s
) {
244 int leveldb_error
= LEVEL_DB_OTHER
;
246 leveldb_error
= LEVEL_DB_NOT_FOUND
;
247 else if (s
.IsCorruption())
248 leveldb_error
= LEVEL_DB_CORRUPTION
;
249 else if (s
.IsIOError())
250 leveldb_error
= LEVEL_DB_IO_ERROR
;
251 base::Histogram::FactoryGet(histogram_name
,
254 LEVEL_DB_MAX_ERROR
+ 1,
255 base::HistogramBase::kUmaTargetedHistogramFlag
)
256 ->Add(leveldb_error
);
258 ParseAndHistogramIOErrorDetails(histogram_name
, s
);
260 ParseAndHistogramCorruptionDetails(histogram_name
, s
);
263 leveldb::Status
LevelDBDatabase::Open(const base::FilePath
& file_name
,
264 const LevelDBComparator
* comparator
,
265 scoped_ptr
<LevelDBDatabase
>* result
,
266 bool* is_disk_full
) {
267 base::TimeTicks begin_time
= base::TimeTicks::Now();
269 scoped_ptr
<ComparatorAdapter
> comparator_adapter(
270 new ComparatorAdapter(comparator
));
273 scoped_ptr
<const leveldb::FilterPolicy
> filter_policy
;
274 const leveldb::Status s
= OpenDB(comparator_adapter
.get(),
281 HistogramLevelDBError("WebCore.IndexedDB.LevelDBOpenErrors", s
);
282 int free_space_k_bytes
= CheckFreeSpace("Failure", file_name
);
283 // Disks with <100k of free space almost never succeed in opening a
286 *is_disk_full
= free_space_k_bytes
>= 0 && free_space_k_bytes
< 100;
288 LOG(ERROR
) << "Failed to open LevelDB database from "
289 << file_name
.AsUTF8Unsafe() << "," << s
.ToString();
293 UMA_HISTOGRAM_MEDIUM_TIMES("WebCore.IndexedDB.LevelDB.OpenTime",
294 base::TimeTicks::Now() - begin_time
);
296 CheckFreeSpace("Success", file_name
);
298 (*result
).reset(new LevelDBDatabase
);
299 (*result
)->db_
= make_scoped_ptr(db
);
300 (*result
)->comparator_adapter_
= comparator_adapter
.Pass();
301 (*result
)->comparator_
= comparator
;
302 (*result
)->filter_policy_
= filter_policy
.Pass();
307 scoped_ptr
<LevelDBDatabase
> LevelDBDatabase::OpenInMemory(
308 const LevelDBComparator
* comparator
) {
309 scoped_ptr
<ComparatorAdapter
> comparator_adapter(
310 new ComparatorAdapter(comparator
));
311 scoped_ptr
<leveldb::Env
> in_memory_env(leveldb::NewMemEnv(leveldb::IDBEnv()));
314 scoped_ptr
<const leveldb::FilterPolicy
> filter_policy
;
315 const leveldb::Status s
= OpenDB(comparator_adapter
.get(),
322 LOG(ERROR
) << "Failed to open in-memory LevelDB database: " << s
.ToString();
323 return scoped_ptr
<LevelDBDatabase
>();
326 scoped_ptr
<LevelDBDatabase
> result(new LevelDBDatabase
);
327 result
->env_
= in_memory_env
.Pass();
328 result
->db_
= make_scoped_ptr(db
);
329 result
->comparator_adapter_
= comparator_adapter
.Pass();
330 result
->comparator_
= comparator
;
331 result
->filter_policy_
= filter_policy
.Pass();
333 return result
.Pass();
336 leveldb::Status
LevelDBDatabase::Put(const StringPiece
& key
,
337 std::string
* value
) {
338 base::TimeTicks begin_time
= base::TimeTicks::Now();
340 leveldb::WriteOptions write_options
;
341 write_options
.sync
= kSyncWrites
;
343 const leveldb::Status s
=
344 db_
->Put(write_options
, MakeSlice(key
), MakeSlice(*value
));
346 LOG(ERROR
) << "LevelDB put failed: " << s
.ToString();
348 UMA_HISTOGRAM_TIMES("WebCore.IndexedDB.LevelDB.PutTime",
349 base::TimeTicks::Now() - begin_time
);
353 leveldb::Status
LevelDBDatabase::Remove(const StringPiece
& key
) {
354 leveldb::WriteOptions write_options
;
355 write_options
.sync
= kSyncWrites
;
357 const leveldb::Status s
= db_
->Delete(write_options
, MakeSlice(key
));
359 LOG(ERROR
) << "LevelDB remove failed: " << s
.ToString();
363 leveldb::Status
LevelDBDatabase::Get(const StringPiece
& key
,
366 const LevelDBSnapshot
* snapshot
) {
368 leveldb::ReadOptions read_options
;
369 read_options
.verify_checksums
= true; // TODO(jsbell): Disable this if the
370 // performance impact is too great.
371 read_options
.snapshot
= snapshot
? snapshot
->snapshot_
: 0;
373 const leveldb::Status s
= db_
->Get(read_options
, MakeSlice(key
), value
);
379 return leveldb::Status::OK();
380 HistogramLevelDBError("WebCore.IndexedDB.LevelDBReadErrors", s
);
381 LOG(ERROR
) << "LevelDB get failed: " << s
.ToString();
385 leveldb::Status
LevelDBDatabase::Write(const LevelDBWriteBatch
& write_batch
) {
386 base::TimeTicks begin_time
= base::TimeTicks::Now();
387 leveldb::WriteOptions write_options
;
388 write_options
.sync
= kSyncWrites
;
390 const leveldb::Status s
=
391 db_
->Write(write_options
, write_batch
.write_batch_
.get());
393 HistogramLevelDBError("WebCore.IndexedDB.LevelDBWriteErrors", s
);
394 LOG(ERROR
) << "LevelDB write failed: " << s
.ToString();
396 UMA_HISTOGRAM_TIMES("WebCore.IndexedDB.LevelDB.WriteTime",
397 base::TimeTicks::Now() - begin_time
);
402 scoped_ptr
<LevelDBIterator
> LevelDBDatabase::CreateIterator(
403 const LevelDBSnapshot
* snapshot
) {
404 leveldb::ReadOptions read_options
;
405 read_options
.verify_checksums
= true; // TODO(jsbell): Disable this if the
406 // performance impact is too great.
407 read_options
.snapshot
= snapshot
? snapshot
->snapshot_
: 0;
409 scoped_ptr
<leveldb::Iterator
> i(db_
->NewIterator(read_options
));
410 return scoped_ptr
<LevelDBIterator
>(
411 IndexedDBClassFactory::Get()->CreateIteratorImpl(i
.Pass()));
414 const LevelDBComparator
* LevelDBDatabase::Comparator() const {
418 void LevelDBDatabase::Compact(const base::StringPiece
& start
,
419 const base::StringPiece
& stop
) {
420 const leveldb::Slice start_slice
= MakeSlice(start
);
421 const leveldb::Slice stop_slice
= MakeSlice(stop
);
422 // NULL batch means just wait for earlier writes to be done
423 db_
->Write(leveldb::WriteOptions(), NULL
);
424 db_
->CompactRange(&start_slice
, &stop_slice
);
427 void LevelDBDatabase::CompactAll() { db_
->CompactRange(NULL
, NULL
); }
429 } // namespace content