Supervised user import: Listen for profile creation/deletion
[chromium-blink-merge.git] / content / browser / indexed_db / indexed_db_factory_impl.cc
blobf818f3f6181f7adff689abe7ec8308c47d497cfd
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/indexed_db_factory_impl.h"
7 #include <utility>
8 #include <vector>
10 #include "base/logging.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/time/time.h"
13 #include "content/browser/indexed_db/indexed_db_backing_store.h"
14 #include "content/browser/indexed_db/indexed_db_context_impl.h"
15 #include "content/browser/indexed_db/indexed_db_database_error.h"
16 #include "content/browser/indexed_db/indexed_db_tracing.h"
17 #include "content/browser/indexed_db/indexed_db_transaction_coordinator.h"
18 #include "storage/common/database/database_identifier.h"
19 #include "third_party/WebKit/public/platform/WebIDBDatabaseException.h"
20 #include "third_party/leveldatabase/env_chromium.h"
22 using base::ASCIIToUTF16;
24 namespace content {
26 const int64 kBackingStoreGracePeriodMs = 2000;
28 IndexedDBFactoryImpl::IndexedDBFactoryImpl(IndexedDBContextImpl* context)
29 : context_(context) {
32 IndexedDBFactoryImpl::~IndexedDBFactoryImpl() {
35 void IndexedDBFactoryImpl::RemoveDatabaseFromMaps(
36 const IndexedDBDatabase::Identifier& identifier) {
37 IndexedDBDatabaseMap::iterator it = database_map_.find(identifier);
38 DCHECK(it != database_map_.end());
39 IndexedDBDatabase* database = it->second;
40 database_map_.erase(it);
42 std::pair<OriginDBMap::iterator, OriginDBMap::iterator> range =
43 origin_dbs_.equal_range(database->identifier().first);
44 DCHECK(range.first != range.second);
45 for (OriginDBMap::iterator it2 = range.first; it2 != range.second; ++it2) {
46 if (it2->second == database) {
47 origin_dbs_.erase(it2);
48 break;
53 void IndexedDBFactoryImpl::ReleaseDatabase(
54 const IndexedDBDatabase::Identifier& identifier,
55 bool forced_close) {
56 DCHECK(!database_map_.find(identifier)->second->backing_store());
58 RemoveDatabaseFromMaps(identifier);
60 // No grace period on a forced-close, as the initiator is
61 // assuming the backing store will be released once all
62 // connections are closed.
63 ReleaseBackingStore(identifier.first, forced_close);
66 void IndexedDBFactoryImpl::ReleaseBackingStore(const GURL& origin_url,
67 bool immediate) {
68 if (immediate) {
69 IndexedDBBackingStoreMap::iterator it =
70 backing_stores_with_active_blobs_.find(origin_url);
71 if (it != backing_stores_with_active_blobs_.end()) {
72 it->second->active_blob_registry()->ForceShutdown();
73 backing_stores_with_active_blobs_.erase(it);
77 // Only close if this is the last reference.
78 if (!HasLastBackingStoreReference(origin_url))
79 return;
81 // If this factory does hold the last reference to the backing store, it can
82 // be closed - but unless requested to close it immediately, keep it around
83 // for a short period so that a re-open is fast.
84 if (immediate) {
85 CloseBackingStore(origin_url);
86 return;
89 // Start a timer to close the backing store, unless something else opens it
90 // in the mean time.
91 DCHECK(!backing_store_map_[origin_url]->close_timer()->IsRunning());
92 backing_store_map_[origin_url]->close_timer()->Start(
93 FROM_HERE,
94 base::TimeDelta::FromMilliseconds(kBackingStoreGracePeriodMs),
95 base::Bind(
96 &IndexedDBFactoryImpl::MaybeCloseBackingStore, this, origin_url));
99 void IndexedDBFactoryImpl::MaybeCloseBackingStore(const GURL& origin_url) {
100 // Another reference may have opened since the maybe-close was posted, so it
101 // is necessary to check again.
102 if (HasLastBackingStoreReference(origin_url))
103 CloseBackingStore(origin_url);
106 void IndexedDBFactoryImpl::CloseBackingStore(const GURL& origin_url) {
107 IndexedDBBackingStoreMap::iterator it = backing_store_map_.find(origin_url);
108 DCHECK(it != backing_store_map_.end());
109 // Stop the timer (if it's running) - this may happen if the timer was started
110 // and then a forced close occurs.
111 it->second->close_timer()->Stop();
112 backing_store_map_.erase(it);
115 bool IndexedDBFactoryImpl::HasLastBackingStoreReference(
116 const GURL& origin_url) const {
117 IndexedDBBackingStore* ptr;
119 // Scope so that the implicit scoped_refptr<> is freed.
120 IndexedDBBackingStoreMap::const_iterator it =
121 backing_store_map_.find(origin_url);
122 DCHECK(it != backing_store_map_.end());
123 ptr = it->second.get();
125 return ptr->HasOneRef();
128 void IndexedDBFactoryImpl::ForceClose(const GURL& origin_url) {
129 OriginDBs range = GetOpenDatabasesForOrigin(origin_url);
131 while (range.first != range.second) {
132 IndexedDBDatabase* db = range.first->second;
133 ++range.first;
134 db->ForceClose();
137 if (backing_store_map_.find(origin_url) != backing_store_map_.end())
138 ReleaseBackingStore(origin_url, true /* immediate */);
141 void IndexedDBFactoryImpl::ContextDestroyed() {
142 // Timers on backing stores hold a reference to this factory. When the
143 // context (which nominally owns this factory) is destroyed during thread
144 // termination the timers must be stopped so that this factory and the
145 // stores can be disposed of.
146 for (const auto& it : backing_store_map_)
147 it.second->close_timer()->Stop();
148 backing_store_map_.clear();
149 backing_stores_with_active_blobs_.clear();
150 context_ = NULL;
153 void IndexedDBFactoryImpl::ReportOutstandingBlobs(const GURL& origin_url,
154 bool blobs_outstanding) {
155 if (!context_)
156 return;
157 if (blobs_outstanding) {
158 DCHECK(!backing_stores_with_active_blobs_.count(origin_url));
159 IndexedDBBackingStoreMap::iterator it = backing_store_map_.find(origin_url);
160 if (it != backing_store_map_.end())
161 backing_stores_with_active_blobs_.insert(*it);
162 else
163 DCHECK(false);
164 } else {
165 IndexedDBBackingStoreMap::iterator it =
166 backing_stores_with_active_blobs_.find(origin_url);
167 if (it != backing_stores_with_active_blobs_.end()) {
168 backing_stores_with_active_blobs_.erase(it);
169 ReleaseBackingStore(origin_url, false /* immediate */);
174 void IndexedDBFactoryImpl::GetDatabaseNames(
175 scoped_refptr<IndexedDBCallbacks> callbacks,
176 const GURL& origin_url,
177 const base::FilePath& data_directory,
178 net::URLRequestContext* request_context) {
179 IDB_TRACE("IndexedDBFactoryImpl::GetDatabaseNames");
180 // TODO(dgrogan): Plumb data_loss back to script eventually?
181 blink::WebIDBDataLoss data_loss;
182 std::string data_loss_message;
183 bool disk_full;
184 leveldb::Status s;
185 // TODO(cmumford): Handle this error
186 scoped_refptr<IndexedDBBackingStore> backing_store =
187 OpenBackingStore(origin_url,
188 data_directory,
189 request_context,
190 &data_loss,
191 &data_loss_message,
192 &disk_full,
193 &s);
194 if (!backing_store.get()) {
195 callbacks->OnError(
196 IndexedDBDatabaseError(blink::WebIDBDatabaseExceptionUnknownError,
197 "Internal error opening backing store for "
198 "indexedDB.webkitGetDatabaseNames."));
199 return;
202 std::vector<base::string16> names = backing_store->GetDatabaseNames(&s);
203 if (!s.ok()) {
204 DLOG(ERROR) << "Internal error getting database names";
205 IndexedDBDatabaseError error(blink::WebIDBDatabaseExceptionUnknownError,
206 "Internal error opening backing store for "
207 "indexedDB.webkitGetDatabaseNames.");
208 callbacks->OnError(error);
209 backing_store = NULL;
210 if (s.IsCorruption())
211 HandleBackingStoreCorruption(origin_url, error);
212 return;
214 callbacks->OnSuccess(names);
215 backing_store = NULL;
216 ReleaseBackingStore(origin_url, false /* immediate */);
219 void IndexedDBFactoryImpl::DeleteDatabase(
220 const base::string16& name,
221 net::URLRequestContext* request_context,
222 scoped_refptr<IndexedDBCallbacks> callbacks,
223 const GURL& origin_url,
224 const base::FilePath& data_directory) {
225 IDB_TRACE("IndexedDBFactoryImpl::DeleteDatabase");
226 IndexedDBDatabase::Identifier unique_identifier(origin_url, name);
227 IndexedDBDatabaseMap::iterator it = database_map_.find(unique_identifier);
228 if (it != database_map_.end()) {
229 // If there are any connections to the database, directly delete the
230 // database.
231 it->second->DeleteDatabase(callbacks);
232 return;
235 // TODO(dgrogan): Plumb data_loss back to script eventually?
236 blink::WebIDBDataLoss data_loss;
237 std::string data_loss_message;
238 bool disk_full = false;
239 leveldb::Status s;
240 scoped_refptr<IndexedDBBackingStore> backing_store =
241 OpenBackingStore(origin_url,
242 data_directory,
243 request_context,
244 &data_loss,
245 &data_loss_message,
246 &disk_full,
247 &s);
248 if (!backing_store.get()) {
249 IndexedDBDatabaseError error(blink::WebIDBDatabaseExceptionUnknownError,
250 ASCIIToUTF16(
251 "Internal error opening backing store "
252 "for indexedDB.deleteDatabase."));
253 callbacks->OnError(error);
254 if (s.IsCorruption()) {
255 HandleBackingStoreCorruption(origin_url, error);
257 return;
260 scoped_refptr<IndexedDBDatabase> database = IndexedDBDatabase::Create(
261 name, backing_store.get(), this, unique_identifier, &s);
262 if (!database.get()) {
263 IndexedDBDatabaseError error(
264 blink::WebIDBDatabaseExceptionUnknownError,
265 ASCIIToUTF16(
266 "Internal error creating database backend for "
267 "indexedDB.deleteDatabase."));
268 callbacks->OnError(error);
269 if (s.IsCorruption()) {
270 backing_store = NULL;
271 HandleBackingStoreCorruption(origin_url, error);
273 return;
276 database_map_[unique_identifier] = database.get();
277 origin_dbs_.insert(std::make_pair(origin_url, database.get()));
278 database->DeleteDatabase(callbacks);
279 RemoveDatabaseFromMaps(unique_identifier);
280 database = NULL;
281 backing_store = NULL;
282 ReleaseBackingStore(origin_url, false /* immediate */);
285 void IndexedDBFactoryImpl::DatabaseDeleted(
286 const IndexedDBDatabase::Identifier& identifier) {
287 // NULL after ContextDestroyed() called, and in some unit tests.
288 if (!context_)
289 return;
290 context_->DatabaseDeleted(identifier.first);
293 void IndexedDBFactoryImpl::HandleBackingStoreFailure(const GURL& origin_url) {
294 // NULL after ContextDestroyed() called, and in some unit tests.
295 if (!context_)
296 return;
297 context_->ForceClose(origin_url,
298 IndexedDBContextImpl::FORCE_CLOSE_BACKING_STORE_FAILURE);
301 void IndexedDBFactoryImpl::HandleBackingStoreCorruption(
302 const GURL& origin_url,
303 const IndexedDBDatabaseError& error) {
304 // Make a copy of origin_url as this is likely a reference to a member of a
305 // backing store which this function will be deleting.
306 GURL saved_origin_url(origin_url);
307 DCHECK(context_);
308 base::FilePath path_base = context_->data_path();
309 IndexedDBBackingStore::RecordCorruptionInfo(
310 path_base, saved_origin_url, base::UTF16ToUTF8(error.message()));
311 HandleBackingStoreFailure(saved_origin_url);
312 // Note: DestroyBackingStore only deletes LevelDB files, leaving all others,
313 // so our corruption info file will remain.
314 leveldb::Status s =
315 IndexedDBBackingStore::DestroyBackingStore(path_base, saved_origin_url);
316 if (!s.ok())
317 DLOG(ERROR) << "Unable to delete backing store: " << s.ToString();
320 bool IndexedDBFactoryImpl::IsDatabaseOpen(const GURL& origin_url,
321 const base::string16& name) const {
322 return !!database_map_.count(IndexedDBDatabase::Identifier(origin_url, name));
325 bool IndexedDBFactoryImpl::IsBackingStoreOpen(const GURL& origin_url) const {
326 return backing_store_map_.find(origin_url) != backing_store_map_.end();
329 bool IndexedDBFactoryImpl::IsBackingStorePendingClose(
330 const GURL& origin_url) const {
331 IndexedDBBackingStoreMap::const_iterator it =
332 backing_store_map_.find(origin_url);
333 if (it == backing_store_map_.end())
334 return false;
335 return it->second->close_timer()->IsRunning();
338 scoped_refptr<IndexedDBBackingStore>
339 IndexedDBFactoryImpl::OpenBackingStoreHelper(
340 const GURL& origin_url,
341 const base::FilePath& data_directory,
342 net::URLRequestContext* request_context,
343 blink::WebIDBDataLoss* data_loss,
344 std::string* data_loss_message,
345 bool* disk_full,
346 bool first_time,
347 leveldb::Status* status) {
348 return IndexedDBBackingStore::Open(this,
349 origin_url,
350 data_directory,
351 request_context,
352 data_loss,
353 data_loss_message,
354 disk_full,
355 context_->TaskRunner(),
356 first_time,
357 status);
360 scoped_refptr<IndexedDBBackingStore> IndexedDBFactoryImpl::OpenBackingStore(
361 const GURL& origin_url,
362 const base::FilePath& data_directory,
363 net::URLRequestContext* request_context,
364 blink::WebIDBDataLoss* data_loss,
365 std::string* data_loss_message,
366 bool* disk_full,
367 leveldb::Status* status) {
368 const bool open_in_memory = data_directory.empty();
370 IndexedDBBackingStoreMap::iterator it2 = backing_store_map_.find(origin_url);
371 if (it2 != backing_store_map_.end()) {
372 it2->second->close_timer()->Stop();
373 return it2->second;
376 scoped_refptr<IndexedDBBackingStore> backing_store;
377 bool first_time = false;
378 if (open_in_memory) {
379 backing_store = IndexedDBBackingStore::OpenInMemory(
380 origin_url, context_->TaskRunner(), status);
381 } else {
382 first_time = !backends_opened_since_boot_.count(origin_url);
384 backing_store = OpenBackingStoreHelper(origin_url,
385 data_directory,
386 request_context,
387 data_loss,
388 data_loss_message,
389 disk_full,
390 first_time,
391 status);
394 if (backing_store.get()) {
395 if (first_time)
396 backends_opened_since_boot_.insert(origin_url);
397 backing_store_map_[origin_url] = backing_store;
398 // If an in-memory database, bind lifetime to this factory instance.
399 if (open_in_memory)
400 session_only_backing_stores_.insert(backing_store);
402 // All backing stores associated with this factory should be of the same
403 // type.
404 DCHECK_NE(session_only_backing_stores_.empty(), open_in_memory);
406 return backing_store;
409 return 0;
412 void IndexedDBFactoryImpl::Open(const base::string16& name,
413 const IndexedDBPendingConnection& connection,
414 net::URLRequestContext* request_context,
415 const GURL& origin_url,
416 const base::FilePath& data_directory) {
417 IDB_TRACE("IndexedDBFactoryImpl::Open");
418 scoped_refptr<IndexedDBDatabase> database;
419 IndexedDBDatabase::Identifier unique_identifier(origin_url, name);
420 IndexedDBDatabaseMap::iterator it = database_map_.find(unique_identifier);
421 blink::WebIDBDataLoss data_loss =
422 blink::WebIDBDataLossNone;
423 std::string data_loss_message;
424 bool disk_full = false;
425 bool was_open = (it != database_map_.end());
426 if (!was_open) {
427 leveldb::Status s;
428 scoped_refptr<IndexedDBBackingStore> backing_store =
429 OpenBackingStore(origin_url,
430 data_directory,
431 request_context,
432 &data_loss,
433 &data_loss_message,
434 &disk_full,
435 &s);
436 if (!backing_store.get()) {
437 if (disk_full) {
438 connection.callbacks->OnError(
439 IndexedDBDatabaseError(blink::WebIDBDatabaseExceptionQuotaError,
440 ASCIIToUTF16(
441 "Encountered full disk while opening "
442 "backing store for indexedDB.open.")));
443 return;
445 IndexedDBDatabaseError error(blink::WebIDBDatabaseExceptionUnknownError,
446 ASCIIToUTF16(
447 "Internal error opening backing store"
448 " for indexedDB.open."));
449 connection.callbacks->OnError(error);
450 if (s.IsCorruption()) {
451 HandleBackingStoreCorruption(origin_url, error);
453 return;
456 database = IndexedDBDatabase::Create(
457 name, backing_store.get(), this, unique_identifier, &s);
458 if (!database.get()) {
459 DLOG(ERROR) << "Unable to create the database";
460 IndexedDBDatabaseError error(blink::WebIDBDatabaseExceptionUnknownError,
461 ASCIIToUTF16(
462 "Internal error creating "
463 "database backend for "
464 "indexedDB.open."));
465 connection.callbacks->OnError(error);
466 if (s.IsCorruption()) {
467 backing_store = NULL; // Closes the LevelDB so that it can be deleted
468 HandleBackingStoreCorruption(origin_url, error);
470 return;
472 } else {
473 database = it->second;
476 if (data_loss != blink::WebIDBDataLossNone)
477 connection.callbacks->OnDataLoss(data_loss, data_loss_message);
479 database->OpenConnection(connection);
481 if (!was_open && database->ConnectionCount() > 0) {
482 database_map_[unique_identifier] = database.get();
483 origin_dbs_.insert(std::make_pair(origin_url, database.get()));
487 std::pair<IndexedDBFactoryImpl::OriginDBMapIterator,
488 IndexedDBFactoryImpl::OriginDBMapIterator>
489 IndexedDBFactoryImpl::GetOpenDatabasesForOrigin(const GURL& origin_url) const {
490 return origin_dbs_.equal_range(origin_url);
493 size_t IndexedDBFactoryImpl::GetConnectionCount(const GURL& origin_url) const {
494 size_t count(0);
496 OriginDBs range = GetOpenDatabasesForOrigin(origin_url);
497 for (OriginDBMapIterator it = range.first; it != range.second; ++it)
498 count += it->second->ConnectionCount();
500 return count;
503 } // namespace content