ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / content / browser / indexed_db / leveldb / leveldb_database.cc
blobc78ec0d3698748fa031d25be2c22bba72f1c7f24
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 #if defined(OS_CHROMEOS)
107 // Disabled on CrOS until crbug.com/460568 is fixed.
108 options.reuse_logs = false;
109 #else
110 options.reuse_logs = true;
111 #endif
112 options.compression = leveldb::kSnappyCompression;
114 // For info about the troubles we've run into with this parameter, see:
115 // https://code.google.com/p/chromium/issues/detail?id=227313#c11
116 options.max_open_files = 80;
117 options.env = env;
119 // ChromiumEnv assumes UTF8, converts back to FilePath before using.
120 leveldb::Status s = leveldb::DB::Open(options, path.AsUTF8Unsafe(), db);
122 return s;
125 leveldb::Status LevelDBDatabase::Destroy(const base::FilePath& file_name) {
126 leveldb::Options options;
127 options.env = leveldb::IDBEnv();
128 // ChromiumEnv assumes UTF8, converts back to FilePath before using.
129 return leveldb::DestroyDB(file_name.AsUTF8Unsafe(), options);
132 namespace {
133 class LockImpl : public LevelDBLock {
134 public:
135 explicit LockImpl(leveldb::Env* env, leveldb::FileLock* lock)
136 : env_(env), lock_(lock) {}
137 ~LockImpl() override { env_->UnlockFile(lock_); }
139 private:
140 leveldb::Env* env_;
141 leveldb::FileLock* lock_;
143 DISALLOW_COPY_AND_ASSIGN(LockImpl);
145 } // namespace
147 scoped_ptr<LevelDBLock> LevelDBDatabase::LockForTesting(
148 const base::FilePath& file_name) {
149 leveldb::Env* env = leveldb::IDBEnv();
150 base::FilePath lock_path = file_name.AppendASCII("LOCK");
151 leveldb::FileLock* lock = NULL;
152 leveldb::Status status = env->LockFile(lock_path.AsUTF8Unsafe(), &lock);
153 if (!status.ok())
154 return scoped_ptr<LevelDBLock>();
155 DCHECK(lock);
156 return scoped_ptr<LevelDBLock>(new LockImpl(env, lock));
159 static int CheckFreeSpace(const char* const type,
160 const base::FilePath& file_name) {
161 std::string name =
162 std::string("WebCore.IndexedDB.LevelDB.Open") + type + "FreeDiskSpace";
163 int64 free_disk_space_in_k_bytes =
164 base::SysInfo::AmountOfFreeDiskSpace(file_name) / 1024;
165 if (free_disk_space_in_k_bytes < 0) {
166 base::Histogram::FactoryGet(
167 "WebCore.IndexedDB.LevelDB.FreeDiskSpaceFailure",
169 2 /*boundary*/,
170 2 /*boundary*/ + 1,
171 base::HistogramBase::kUmaTargetedHistogramFlag)->Add(1 /*sample*/);
172 return -1;
174 int clamped_disk_space_k_bytes = free_disk_space_in_k_bytes > INT_MAX
175 ? INT_MAX
176 : free_disk_space_in_k_bytes;
177 const uint64 histogram_max = static_cast<uint64>(1e9);
178 static_assert(histogram_max <= INT_MAX, "histogram_max too big");
179 base::Histogram::FactoryGet(name,
181 histogram_max,
182 11 /*buckets*/,
183 base::HistogramBase::kUmaTargetedHistogramFlag)
184 ->Add(clamped_disk_space_k_bytes);
185 return clamped_disk_space_k_bytes;
188 static void ParseAndHistogramIOErrorDetails(const std::string& histogram_name,
189 const leveldb::Status& s) {
190 leveldb_env::MethodID method;
191 base::File::Error error = base::File::FILE_OK;
192 leveldb_env::ErrorParsingResult result =
193 leveldb_env::ParseMethodAndError(s, &method, &error);
194 if (result == leveldb_env::NONE)
195 return;
196 std::string method_histogram_name(histogram_name);
197 method_histogram_name.append(".EnvMethod");
198 base::LinearHistogram::FactoryGet(
199 method_histogram_name,
201 leveldb_env::kNumEntries,
202 leveldb_env::kNumEntries + 1,
203 base::HistogramBase::kUmaTargetedHistogramFlag)->Add(method);
205 std::string error_histogram_name(histogram_name);
207 if (result == leveldb_env::METHOD_AND_PFE) {
208 DCHECK_LT(error, 0);
209 error_histogram_name.append(std::string(".PFE.") +
210 leveldb_env::MethodIDToString(method));
211 base::LinearHistogram::FactoryGet(
212 error_histogram_name,
214 -base::File::FILE_ERROR_MAX,
215 -base::File::FILE_ERROR_MAX + 1,
216 base::HistogramBase::kUmaTargetedHistogramFlag)->Add(-error);
220 static void ParseAndHistogramCorruptionDetails(
221 const std::string& histogram_name,
222 const leveldb::Status& status) {
223 int error = leveldb_env::GetCorruptionCode(status);
224 DCHECK_GE(error, 0);
225 std::string corruption_histogram_name(histogram_name);
226 corruption_histogram_name.append(".Corruption");
227 const int kNumPatterns = leveldb_env::GetNumCorruptionCodes();
228 base::LinearHistogram::FactoryGet(
229 corruption_histogram_name,
231 kNumPatterns,
232 kNumPatterns + 1,
233 base::HistogramBase::kUmaTargetedHistogramFlag)->Add(error);
236 static void HistogramLevelDBError(const std::string& histogram_name,
237 const leveldb::Status& s) {
238 if (s.ok()) {
239 NOTREACHED();
240 return;
242 enum {
243 LEVEL_DB_NOT_FOUND,
244 LEVEL_DB_CORRUPTION,
245 LEVEL_DB_IO_ERROR,
246 LEVEL_DB_OTHER,
247 LEVEL_DB_MAX_ERROR
249 int leveldb_error = LEVEL_DB_OTHER;
250 if (s.IsNotFound())
251 leveldb_error = LEVEL_DB_NOT_FOUND;
252 else if (s.IsCorruption())
253 leveldb_error = LEVEL_DB_CORRUPTION;
254 else if (s.IsIOError())
255 leveldb_error = LEVEL_DB_IO_ERROR;
256 base::Histogram::FactoryGet(histogram_name,
258 LEVEL_DB_MAX_ERROR,
259 LEVEL_DB_MAX_ERROR + 1,
260 base::HistogramBase::kUmaTargetedHistogramFlag)
261 ->Add(leveldb_error);
262 if (s.IsIOError())
263 ParseAndHistogramIOErrorDetails(histogram_name, s);
264 else
265 ParseAndHistogramCorruptionDetails(histogram_name, s);
268 leveldb::Status LevelDBDatabase::Open(const base::FilePath& file_name,
269 const LevelDBComparator* comparator,
270 scoped_ptr<LevelDBDatabase>* result,
271 bool* is_disk_full) {
272 base::TimeTicks begin_time = base::TimeTicks::Now();
274 scoped_ptr<ComparatorAdapter> comparator_adapter(
275 new ComparatorAdapter(comparator));
277 leveldb::DB* db;
278 scoped_ptr<const leveldb::FilterPolicy> filter_policy;
279 const leveldb::Status s = OpenDB(comparator_adapter.get(),
280 leveldb::IDBEnv(),
281 file_name,
282 &db,
283 &filter_policy);
285 if (!s.ok()) {
286 HistogramLevelDBError("WebCore.IndexedDB.LevelDBOpenErrors", s);
287 int free_space_k_bytes = CheckFreeSpace("Failure", file_name);
288 // Disks with <100k of free space almost never succeed in opening a
289 // leveldb database.
290 if (is_disk_full)
291 *is_disk_full = free_space_k_bytes >= 0 && free_space_k_bytes < 100;
293 LOG(ERROR) << "Failed to open LevelDB database from "
294 << file_name.AsUTF8Unsafe() << "," << s.ToString();
295 return s;
298 UMA_HISTOGRAM_MEDIUM_TIMES("WebCore.IndexedDB.LevelDB.OpenTime",
299 base::TimeTicks::Now() - begin_time);
301 CheckFreeSpace("Success", file_name);
303 (*result).reset(new LevelDBDatabase);
304 (*result)->db_ = make_scoped_ptr(db);
305 (*result)->comparator_adapter_ = comparator_adapter.Pass();
306 (*result)->comparator_ = comparator;
307 (*result)->filter_policy_ = filter_policy.Pass();
309 return s;
312 scoped_ptr<LevelDBDatabase> LevelDBDatabase::OpenInMemory(
313 const LevelDBComparator* comparator) {
314 scoped_ptr<ComparatorAdapter> comparator_adapter(
315 new ComparatorAdapter(comparator));
316 scoped_ptr<leveldb::Env> in_memory_env(leveldb::NewMemEnv(leveldb::IDBEnv()));
318 leveldb::DB* db;
319 scoped_ptr<const leveldb::FilterPolicy> filter_policy;
320 const leveldb::Status s = OpenDB(comparator_adapter.get(),
321 in_memory_env.get(),
322 base::FilePath(),
323 &db,
324 &filter_policy);
326 if (!s.ok()) {
327 LOG(ERROR) << "Failed to open in-memory LevelDB database: " << s.ToString();
328 return scoped_ptr<LevelDBDatabase>();
331 scoped_ptr<LevelDBDatabase> result(new LevelDBDatabase);
332 result->env_ = in_memory_env.Pass();
333 result->db_ = make_scoped_ptr(db);
334 result->comparator_adapter_ = comparator_adapter.Pass();
335 result->comparator_ = comparator;
336 result->filter_policy_ = filter_policy.Pass();
338 return result.Pass();
341 leveldb::Status LevelDBDatabase::Put(const StringPiece& key,
342 std::string* value) {
343 base::TimeTicks begin_time = base::TimeTicks::Now();
345 leveldb::WriteOptions write_options;
346 write_options.sync = kSyncWrites;
348 const leveldb::Status s =
349 db_->Put(write_options, MakeSlice(key), MakeSlice(*value));
350 if (!s.ok())
351 LOG(ERROR) << "LevelDB put failed: " << s.ToString();
352 else
353 UMA_HISTOGRAM_TIMES("WebCore.IndexedDB.LevelDB.PutTime",
354 base::TimeTicks::Now() - begin_time);
355 return s;
358 leveldb::Status LevelDBDatabase::Remove(const StringPiece& key) {
359 leveldb::WriteOptions write_options;
360 write_options.sync = kSyncWrites;
362 const leveldb::Status s = db_->Delete(write_options, MakeSlice(key));
363 if (!s.IsNotFound())
364 LOG(ERROR) << "LevelDB remove failed: " << s.ToString();
365 return s;
368 leveldb::Status LevelDBDatabase::Get(const StringPiece& key,
369 std::string* value,
370 bool* found,
371 const LevelDBSnapshot* snapshot) {
372 *found = false;
373 leveldb::ReadOptions read_options;
374 read_options.verify_checksums = true; // TODO(jsbell): Disable this if the
375 // performance impact is too great.
376 read_options.snapshot = snapshot ? snapshot->snapshot_ : 0;
378 const leveldb::Status s = db_->Get(read_options, MakeSlice(key), value);
379 if (s.ok()) {
380 *found = true;
381 return s;
383 if (s.IsNotFound())
384 return leveldb::Status::OK();
385 HistogramLevelDBError("WebCore.IndexedDB.LevelDBReadErrors", s);
386 LOG(ERROR) << "LevelDB get failed: " << s.ToString();
387 return s;
390 leveldb::Status LevelDBDatabase::Write(const LevelDBWriteBatch& write_batch) {
391 base::TimeTicks begin_time = base::TimeTicks::Now();
392 leveldb::WriteOptions write_options;
393 write_options.sync = kSyncWrites;
395 const leveldb::Status s =
396 db_->Write(write_options, write_batch.write_batch_.get());
397 if (!s.ok()) {
398 HistogramLevelDBError("WebCore.IndexedDB.LevelDBWriteErrors", s);
399 LOG(ERROR) << "LevelDB write failed: " << s.ToString();
400 } else {
401 UMA_HISTOGRAM_TIMES("WebCore.IndexedDB.LevelDB.WriteTime",
402 base::TimeTicks::Now() - begin_time);
404 return s;
407 scoped_ptr<LevelDBIterator> LevelDBDatabase::CreateIterator(
408 const LevelDBSnapshot* snapshot) {
409 leveldb::ReadOptions read_options;
410 read_options.verify_checksums = true; // TODO(jsbell): Disable this if the
411 // performance impact is too great.
412 read_options.snapshot = snapshot ? snapshot->snapshot_ : 0;
414 scoped_ptr<leveldb::Iterator> i(db_->NewIterator(read_options));
415 return scoped_ptr<LevelDBIterator>(
416 IndexedDBClassFactory::Get()->CreateIteratorImpl(i.Pass()));
419 const LevelDBComparator* LevelDBDatabase::Comparator() const {
420 return comparator_;
423 void LevelDBDatabase::Compact(const base::StringPiece& start,
424 const base::StringPiece& stop) {
425 const leveldb::Slice start_slice = MakeSlice(start);
426 const leveldb::Slice stop_slice = MakeSlice(stop);
427 // NULL batch means just wait for earlier writes to be done
428 db_->Write(leveldb::WriteOptions(), NULL);
429 db_->CompactRange(&start_slice, &stop_slice);
432 void LevelDBDatabase::CompactAll() { db_->CompactRange(NULL, NULL); }
434 } // namespace content