Supervised user whitelists: Cleanup
[chromium-blink-merge.git] / content / browser / indexed_db / leveldb / leveldb_database.cc
blob1d816a849c7dea0d6a1e529e261acd38650e572f
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"
7 #include <cerrno>
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;
33 namespace content {
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.
43 #if defined(OS_WIN)
44 static const bool kSyncWrites = true;
45 #else
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;
49 #endif
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(
74 std::string* start,
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.
89 db_.reset();
90 comparator_adapter_.reset();
91 env_.reset();
94 static leveldb::Status OpenDB(
95 leveldb::Comparator* comparator,
96 leveldb::Env* env,
97 const base::FilePath& path,
98 leveldb::DB** db,
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;
112 options.env = env;
114 // ChromiumEnv assumes UTF8, converts back to FilePath before using.
115 leveldb::Status s = leveldb::DB::Open(options, path.AsUTF8Unsafe(), db);
117 return s;
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);
127 namespace {
128 class LockImpl : public LevelDBLock {
129 public:
130 explicit LockImpl(leveldb::Env* env, leveldb::FileLock* lock)
131 : env_(env), lock_(lock) {}
132 ~LockImpl() override { env_->UnlockFile(lock_); }
134 private:
135 leveldb::Env* env_;
136 leveldb::FileLock* lock_;
138 DISALLOW_COPY_AND_ASSIGN(LockImpl);
140 } // namespace
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);
148 if (!status.ok())
149 return scoped_ptr<LevelDBLock>();
150 DCHECK(lock);
151 return scoped_ptr<LevelDBLock>(new LockImpl(env, lock));
154 static int CheckFreeSpace(const char* const type,
155 const base::FilePath& file_name) {
156 std::string 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",
164 2 /*boundary*/,
165 2 /*boundary*/ + 1,
166 base::HistogramBase::kUmaTargetedHistogramFlag)->Add(1 /*sample*/);
167 return -1;
169 int clamped_disk_space_k_bytes = free_disk_space_in_k_bytes > INT_MAX
170 ? 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,
176 histogram_max,
177 11 /*buckets*/,
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)
190 return;
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) {
203 DCHECK_LT(error, 0);
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);
219 DCHECK_GE(error, 0);
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,
226 kNumPatterns,
227 kNumPatterns + 1,
228 base::HistogramBase::kUmaTargetedHistogramFlag)->Add(error);
231 static void HistogramLevelDBError(const std::string& histogram_name,
232 const leveldb::Status& s) {
233 if (s.ok()) {
234 NOTREACHED();
235 return;
237 enum {
238 LEVEL_DB_NOT_FOUND,
239 LEVEL_DB_CORRUPTION,
240 LEVEL_DB_IO_ERROR,
241 LEVEL_DB_OTHER,
242 LEVEL_DB_MAX_ERROR
244 int leveldb_error = LEVEL_DB_OTHER;
245 if (s.IsNotFound())
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,
253 LEVEL_DB_MAX_ERROR,
254 LEVEL_DB_MAX_ERROR + 1,
255 base::HistogramBase::kUmaTargetedHistogramFlag)
256 ->Add(leveldb_error);
257 if (s.IsIOError())
258 ParseAndHistogramIOErrorDetails(histogram_name, s);
259 else
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));
272 leveldb::DB* db;
273 scoped_ptr<const leveldb::FilterPolicy> filter_policy;
274 const leveldb::Status s = OpenDB(comparator_adapter.get(),
275 leveldb::IDBEnv(),
276 file_name,
277 &db,
278 &filter_policy);
280 if (!s.ok()) {
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
284 // leveldb database.
285 if (is_disk_full)
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();
290 return s;
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();
304 return s;
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()));
313 leveldb::DB* db;
314 scoped_ptr<const leveldb::FilterPolicy> filter_policy;
315 const leveldb::Status s = OpenDB(comparator_adapter.get(),
316 in_memory_env.get(),
317 base::FilePath(),
318 &db,
319 &filter_policy);
321 if (!s.ok()) {
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));
345 if (!s.ok())
346 LOG(ERROR) << "LevelDB put failed: " << s.ToString();
347 else
348 UMA_HISTOGRAM_TIMES("WebCore.IndexedDB.LevelDB.PutTime",
349 base::TimeTicks::Now() - begin_time);
350 return s;
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));
358 if (!s.IsNotFound())
359 LOG(ERROR) << "LevelDB remove failed: " << s.ToString();
360 return s;
363 leveldb::Status LevelDBDatabase::Get(const StringPiece& key,
364 std::string* value,
365 bool* found,
366 const LevelDBSnapshot* snapshot) {
367 *found = false;
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);
374 if (s.ok()) {
375 *found = true;
376 return s;
378 if (s.IsNotFound())
379 return leveldb::Status::OK();
380 HistogramLevelDBError("WebCore.IndexedDB.LevelDBReadErrors", s);
381 LOG(ERROR) << "LevelDB get failed: " << s.ToString();
382 return s;
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());
392 if (!s.ok()) {
393 HistogramLevelDBError("WebCore.IndexedDB.LevelDBWriteErrors", s);
394 LOG(ERROR) << "LevelDB write failed: " << s.ToString();
395 } else {
396 UMA_HISTOGRAM_TIMES("WebCore.IndexedDB.LevelDB.WriteTime",
397 base::TimeTicks::Now() - begin_time);
399 return s;
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 {
415 return comparator_;
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