OLD | NEW |
---|---|
(Empty) | |
1 // Copyright (c) 2012 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. | |
4 | |
5 #include "base/prefs/leveldb_pref_store.h" | |
6 | |
7 #include "base/bind.h" | |
8 #include "base/callback.h" | |
9 #include "base/file_util.h" | |
10 #include "base/json/json_string_value_serializer.h" | |
11 #include "base/location.h" | |
12 #include "base/sequenced_task_runner.h" | |
13 #include "base/task_runner_util.h" | |
14 #include "base/threading/thread_restrictions.h" | |
15 #include "base/time/time.h" | |
16 #include "base/values.h" | |
17 #include "third_party/leveldatabase/env_chromium.h" | |
18 #include "third_party/leveldatabase/src/include/leveldb/db.h" | |
19 #include "third_party/leveldatabase/src/include/leveldb/write_batch.h" | |
20 | |
21 struct LevelDBPrefStore::ReadingResults { | |
22 ReadingResults() : db_owned(NULL), value_map_owned(NULL) { | |
Mattias Nissler (ping if slow)
2014/03/20 09:32:25
nit: no need for line break.
dgrogan
2014/04/12 00:32:45
Constructor removed.
| |
23 } | |
24 bool no_dir; | |
25 leveldb::DB* db_owned; | |
Mattias Nissler (ping if slow)
2014/03/20 09:32:25
Why aren't these scoped_ptrs if they are owned?
dgrogan
2014/04/12 00:32:45
Oops, meant to switch them before sending out. Don
| |
26 PrefValueMap* value_map_owned; | |
27 PersistentPrefStore::PrefReadError error; | |
28 }; | |
29 | |
30 // An instance of this class is created on the UI thread but is used | |
31 // exclusively on the FILE thread. | |
32 class LevelDBPrefStore::FileThreadSerializer { | |
33 public: | |
34 FileThreadSerializer(scoped_ptr<leveldb::DB> db) : db_(db.Pass()) {} | |
35 void WriteToDatabase( | |
36 scoped_ptr<std::map<std::string, std::string> > keys_to_set, | |
37 scoped_ptr<std::set<std::string> > keys_to_delete) { | |
38 DCHECK(keys_to_set->size() > 0 || keys_to_delete->size() > 0); | |
39 leveldb::WriteBatch batch; | |
40 for (std::map<std::string, std::string>::iterator iter = | |
41 keys_to_set->begin(); | |
42 iter != keys_to_set->end(); | |
43 iter++) { | |
44 batch.Put(iter->first, iter->second); | |
45 } | |
46 | |
47 for (std::set<std::string>::iterator iter = keys_to_delete->begin(); | |
48 iter != keys_to_delete->end(); | |
49 iter++) { | |
50 batch.Delete(*iter); | |
51 } | |
52 | |
53 leveldb::Status status = db_->Write(leveldb::WriteOptions(), &batch); | |
54 | |
55 // DCHECK is fine; the corresponding error is ignored in JsonPrefStore. | |
56 // There's also no API available to surface the error back up to the caller. | |
57 // TODO(dgrogan): UMA? | |
58 DCHECK(status.ok()) << status.ToString(); | |
59 } | |
60 | |
61 private: | |
62 scoped_ptr<leveldb::DB> db_; | |
63 DISALLOW_COPY_AND_ASSIGN(FileThreadSerializer); | |
64 }; | |
65 | |
66 /* static */ | |
67 void LevelDBPrefStore::OpenDB(const base::FilePath& path, | |
68 ReadingResults* reading_results) { | |
69 leveldb::Options options; | |
70 options.create_if_missing = true; | |
71 leveldb::Status status = leveldb::DB::Open( | |
72 options, path.AsUTF8Unsafe(), &reading_results->db_owned); | |
73 if (status.ok()) { | |
74 reading_results->error = PersistentPrefStore::PREF_READ_ERROR_NONE; | |
75 return; | |
76 } | |
77 if (leveldb_env::IsIOError(status)) { | |
78 reading_results->error = | |
79 PersistentPrefStore::PREF_READ_ERROR_LEVELDB_IO_ERROR; | |
80 return; | |
81 } | |
82 // If it's not an IO error, it's corruption that we can try to repair. | |
83 status = leveldb::RepairDB(path.AsUTF8Unsafe(), options); | |
Mattias Nissler (ping if slow)
2014/03/20 09:32:25
Is it OK to pass options.create_if_missing = true
dgrogan
2014/04/12 00:32:45
Yes, it's ignored by RepairDB.
| |
84 bool destroy_succeeded = false; | |
85 if (!status.ok()) { | |
86 // TODO(dgrogan): Should we move the old database aside instead of | |
87 // destroying it? | |
Mattias Nissler (ping if slow)
2014/03/20 09:32:25
Yes, please. That way, we will have a better chanc
dgrogan
2014/04/12 00:32:45
Done.
| |
88 status = leveldb::DestroyDB(path.AsUTF8Unsafe(), options); | |
Mattias Nissler (ping if slow)
2014/03/20 09:32:25
again, create_if_missing OK here?
dgrogan
2014/04/12 00:32:45
Yep.
| |
89 if (!status.ok()) { | |
90 reading_results->error = | |
91 PersistentPrefStore::PREF_READ_ERROR_LEVELDB_DESTROY_FAILED; | |
92 return; | |
93 } | |
94 destroy_succeeded = true; | |
95 } | |
96 // Either repair or destroy succeeded, now try to open again. | |
97 status = leveldb::DB::Open( | |
98 options, path.AsUTF8Unsafe(), &reading_results->db_owned); | |
99 if (!status.ok()) { | |
100 if (destroy_succeeded) | |
Mattias Nissler (ping if slow)
2014/03/20 09:32:25
nit: I suggest curly braces here; the line breaks
dgrogan
2014/04/12 00:32:45
Done.
| |
101 reading_results->error = | |
102 PersistentPrefStore::PREF_READ_ERROR_LEVELDB_DESTROYED_REOPEN_FAILED; | |
103 else | |
104 reading_results->error = | |
105 PersistentPrefStore::PREF_READ_ERROR_LEVELDB_REPAIRED_REOPEN_FAILED; | |
Mattias Nissler (ping if slow)
2014/03/20 09:32:25
Should we destroy and retry in this case?
dgrogan
2014/04/12 00:32:45
Done.
| |
106 return; | |
107 } | |
108 if (destroy_succeeded) | |
Mattias Nissler (ping if slow)
2014/03/20 09:32:25
nit: curly braces suggested
dgrogan
2014/04/12 00:32:45
Done.
| |
109 reading_results->error = | |
110 PersistentPrefStore::PREF_READ_ERROR_LEVELDB_DESTROYED_REOPEN_SUCCESS; | |
111 else | |
112 reading_results->error = | |
113 PersistentPrefStore::PREF_READ_ERROR_LEVELDB_REPAIRED_REOPEN_SUCCESS; | |
114 } | |
115 | |
116 /* static */ | |
117 scoped_ptr<LevelDBPrefStore::ReadingResults> LevelDBPrefStore::DoReading( | |
118 const base::FilePath& path) { | |
119 base::ThreadRestrictions::AssertIOAllowed(); | |
120 | |
121 scoped_ptr<ReadingResults> reading_results(new ReadingResults); | |
122 | |
123 reading_results->no_dir = !base::PathExists(path.DirName()); | |
124 OpenDB(path, reading_results.get()); | |
125 if (!reading_results->db_owned) | |
126 return reading_results.Pass(); | |
127 | |
128 scoped_ptr<PrefValueMap> value_map(new PrefValueMap); | |
129 scoped_ptr<leveldb::Iterator> it( | |
130 reading_results->db_owned->NewIterator(leveldb::ReadOptions())); | |
131 for (it->SeekToFirst(); it->Valid(); it->Next()) { | |
132 const std::string value_string = it->value().ToString(); | |
133 JSONStringValueSerializer deserializer(value_string); | |
134 std::string error_message; | |
135 int error_code; | |
136 base::Value* json_value = | |
137 deserializer.Deserialize(&error_code, &error_message); | |
138 if (json_value) { | |
139 value_map->SetValue(it->key().ToString(), json_value); | |
140 } else { | |
141 // TODO(dgrogan): UMA? | |
Mattias Nissler (ping if slow)
2014/03/20 09:32:25
Hm, good question. Another option would be to cras
dgrogan
2014/04/12 00:32:45
I'm confident LevelDB will catch all corruption in
| |
142 NOTREACHED() << error_message; | |
143 } | |
144 } | |
145 | |
146 if (!it->status().ok()) { | |
147 // TODO(dgrogan): UMA? | |
Mattias Nissler (ping if slow)
2014/03/20 09:32:25
I don't think that's necessary, the pref read erro
dgrogan
2014/04/12 00:32:45
That's right.
| |
148 reading_results->error = PersistentPrefStore::PREF_READ_ERROR_FILE_OTHER; | |
149 return reading_results.Pass(); | |
150 } | |
151 reading_results->value_map_owned = value_map.release(); | |
152 reading_results->error = PersistentPrefStore::PREF_READ_ERROR_NONE; | |
153 return reading_results.Pass(); | |
154 } | |
155 | |
156 LevelDBPrefStore::LevelDBPrefStore( | |
157 const base::FilePath& filename, | |
158 base::SequencedTaskRunner* sequenced_task_runner) | |
159 : path_(filename), | |
160 sequenced_task_runner_(sequenced_task_runner), | |
161 original_task_runner_(base::MessageLoopProxy::current()), | |
162 read_only_(false), | |
163 initialized_(false), | |
164 read_error_(PREF_READ_ERROR_OTHER), | |
165 weak_ptr_factory_(this) {} | |
166 | |
167 LevelDBPrefStore::~LevelDBPrefStore() { | |
168 CommitPendingWrite(); | |
169 sequenced_task_runner_->DeleteSoon(FROM_HERE, serializer_.release()); | |
170 } | |
171 | |
172 bool LevelDBPrefStore::GetValue(const std::string& key, | |
173 const base::Value** result) const { | |
174 DCHECK(initialized_); | |
175 const base::Value* tmp = NULL; | |
176 if (!prefs_.GetValue(key, &tmp)) { | |
177 return false; | |
178 } | |
179 | |
180 if (result) | |
181 *result = tmp; | |
182 return true; | |
183 } | |
184 | |
185 // Callers of GetMutableValue have to also call ReportValueChanged. | |
186 bool LevelDBPrefStore::GetMutableValue(const std::string& key, | |
187 base::Value** result) { | |
188 DCHECK(initialized_); | |
189 return prefs_.GetValue(key, result); | |
190 } | |
191 | |
192 void LevelDBPrefStore::AddObserver(PrefStore::Observer* observer) { | |
193 observers_.AddObserver(observer); | |
194 } | |
195 | |
196 void LevelDBPrefStore::RemoveObserver(PrefStore::Observer* observer) { | |
197 observers_.RemoveObserver(observer); | |
198 } | |
199 | |
200 bool LevelDBPrefStore::HasObservers() const { | |
201 return observers_.might_have_observers(); | |
202 } | |
203 | |
204 bool LevelDBPrefStore::IsInitializationComplete() const { return initialized_; } | |
205 | |
206 void LevelDBPrefStore::PersistFromUIThread() { | |
207 if (read_only_) | |
208 return; | |
209 DCHECK(serializer_); | |
210 | |
211 scoped_ptr<std::set<std::string>> keys_to_delete(new std::set<std::string>); | |
212 keys_to_delete->swap(keys_to_delete_); | |
213 | |
214 scoped_ptr<std::map<std::string, std::string> > keys_to_set( | |
215 new std::map<std::string, std::string>); | |
216 keys_to_set->swap(keys_to_set_); | |
217 | |
218 sequenced_task_runner_->PostTask( | |
219 FROM_HERE, | |
220 base::Bind(&LevelDBPrefStore::FileThreadSerializer::WriteToDatabase, | |
221 base::Unretained(serializer_.get()), | |
222 base::Passed(&keys_to_set), | |
223 base::Passed(&keys_to_delete))); | |
224 } | |
225 | |
226 void LevelDBPrefStore::ScheduleWrite() { | |
227 if (!timer_.IsRunning()) { | |
228 timer_.Start(FROM_HERE, | |
229 base::TimeDelta::FromSeconds(10), | |
230 this, | |
231 &LevelDBPrefStore::PersistFromUIThread); | |
232 } | |
233 } | |
234 | |
235 void LevelDBPrefStore::SetValue(const std::string& key, base::Value* value) { | |
236 SetValueInternal(key, value, true /*notify*/); | |
237 } | |
238 | |
239 void LevelDBPrefStore::SetValueSilently(const std::string& key, | |
240 base::Value* value) { | |
241 SetValueInternal(key, value, false /*notify*/); | |
242 } | |
243 | |
244 static std::string Serialize(base::Value* value) { | |
245 std::string value_string; | |
246 JSONStringValueSerializer serializer(&value_string); | |
247 bool serialized_ok = serializer.Serialize(*value); | |
248 DCHECK(serialized_ok); | |
249 return value_string; | |
250 } | |
251 | |
252 void LevelDBPrefStore::SetValueInternal(const std::string& key, | |
253 base::Value* value, | |
254 bool notify) { | |
255 DCHECK(initialized_); | |
256 DCHECK(value); | |
257 scoped_ptr<base::Value> new_value(value); | |
258 base::Value* old_value = NULL; | |
259 prefs_.GetValue(key, &old_value); | |
260 if (!old_value || !value->Equals(old_value)) { | |
261 std::string value_string = Serialize(value); | |
262 prefs_.SetValue(key, new_value.release()); | |
263 MarkForInsertion(key, value_string); | |
264 if (notify) | |
265 NotifyObservers(key); | |
266 } | |
267 } | |
268 | |
269 void LevelDBPrefStore::RemoveValue(const std::string& key) { | |
270 DCHECK(initialized_); | |
271 if (prefs_.RemoveValue(key)) { | |
272 MarkForDeletion(key); | |
273 NotifyObservers(key); | |
274 } | |
275 } | |
276 | |
277 bool LevelDBPrefStore::ReadOnly() const { return read_only_; } | |
278 | |
279 PersistentPrefStore::PrefReadError LevelDBPrefStore::GetReadError() const { | |
280 return read_error_; | |
281 } | |
282 | |
283 PersistentPrefStore::PrefReadError LevelDBPrefStore::ReadPrefs() { | |
284 DCHECK(!initialized_); | |
285 if (path_.empty()) { | |
286 scoped_ptr<LevelDBPrefStore::ReadingResults> reading_results( | |
287 new LevelDBPrefStore::ReadingResults); | |
288 reading_results->error = PREF_READ_ERROR_FILE_NOT_SPECIFIED; | |
289 OnStorageRead(reading_results.Pass()); | |
290 return PREF_READ_ERROR_FILE_NOT_SPECIFIED; | |
291 } | |
292 | |
293 scoped_ptr<LevelDBPrefStore::ReadingResults> reading_results = | |
294 DoReading(path_); | |
295 PersistentPrefStore::PrefReadError error = reading_results->error; | |
296 OnStorageRead(reading_results.Pass()); | |
297 return error; | |
298 } | |
299 | |
300 void LevelDBPrefStore::ReadPrefsAsync(ReadErrorDelegate* error_delegate) { | |
301 DCHECK_EQ(false, initialized_); | |
302 error_delegate_.reset(error_delegate); | |
303 if (path_.empty()) { | |
304 scoped_ptr<LevelDBPrefStore::ReadingResults> reading_results( | |
305 new LevelDBPrefStore::ReadingResults); | |
306 reading_results->error = PREF_READ_ERROR_FILE_NOT_SPECIFIED; | |
307 OnStorageRead(reading_results.Pass()); | |
308 } | |
309 PostTaskAndReplyWithResult(sequenced_task_runner_, | |
310 FROM_HERE, | |
311 base::Bind(&LevelDBPrefStore::DoReading, path_), | |
312 base::Bind(&LevelDBPrefStore::OnStorageRead, | |
313 weak_ptr_factory_.GetWeakPtr())); | |
314 } | |
315 | |
316 void LevelDBPrefStore::CommitPendingWrite() { | |
317 if (timer_.IsRunning()) { | |
318 timer_.Stop(); | |
319 PersistFromUIThread(); | |
320 } | |
321 } | |
322 | |
323 void LevelDBPrefStore::MarkForDeletion(const std::string& key) { | |
324 if (read_only_) | |
325 return; | |
326 keys_to_delete_.insert(key); | |
327 keys_to_set_.erase(key); | |
Mattias Nissler (ping if slow)
2014/03/20 09:32:25
Can you put a comment here explaining that the era
dgrogan
2014/04/12 00:32:45
Done.
| |
328 ScheduleWrite(); | |
329 } | |
330 | |
331 void LevelDBPrefStore::MarkForInsertion(const std::string& key, | |
332 const std::string& value) { | |
333 if (read_only_) | |
334 return; | |
335 keys_to_set_[key] = value; | |
336 keys_to_delete_.erase(key); | |
337 ScheduleWrite(); | |
338 } | |
339 | |
340 void LevelDBPrefStore::ReportValueChanged(const std::string& key) { | |
341 base::Value* new_value = NULL; | |
342 DCHECK(prefs_.GetValue(key, &new_value)); | |
343 std::string value_string = Serialize(new_value); | |
344 keys_to_set_[key] = value_string; | |
Mattias Nissler (ping if slow)
2014/03/20 09:32:25
This should be MarkForInsertion(key, value_string)
dgrogan
2014/04/12 00:32:45
Done.
| |
345 NotifyObservers(key); | |
346 } | |
347 | |
348 void LevelDBPrefStore::NotifyObservers(const std::string& key) { | |
349 FOR_EACH_OBSERVER(PrefStore::Observer, observers_, OnPrefValueChanged(key)); | |
350 } | |
351 | |
352 void LevelDBPrefStore::OnStorageRead( | |
353 scoped_ptr<LevelDBPrefStore::ReadingResults> reading_results) { | |
354 scoped_ptr<leveldb::DB> db(reading_results->db_owned); | |
355 scoped_ptr<PrefValueMap> value(reading_results->value_map_owned); | |
356 read_error_ = reading_results->error; | |
357 | |
358 if (reading_results->no_dir) { | |
359 FOR_EACH_OBSERVER( | |
360 PrefStore::Observer, observers_, OnInitializationCompleted(false)); | |
361 return; | |
362 } | |
363 | |
364 initialized_ = true; | |
365 | |
366 switch (read_error_) { | |
367 case PREF_READ_ERROR_FILE_OTHER: | |
368 case PREF_READ_ERROR_LEVELDB_IO_ERROR: | |
369 case PREF_READ_ERROR_FILE_NOT_SPECIFIED: | |
370 DCHECK(value.get() == NULL); | |
371 DCHECK(db.get() == NULL); | |
372 read_only_ = true; | |
373 break; | |
374 case PREF_READ_ERROR_NONE: | |
375 serializer_.reset(new FileThreadSerializer(db.Pass())); | |
376 prefs_.Swap(value.get()); | |
377 break; | |
378 default: | |
379 NOTREACHED() << "Unknown error: " << read_error_; | |
Mattias Nissler (ping if slow)
2014/03/20 09:32:25
You have introduced a bunch of new read errors, sh
dgrogan
2014/04/12 00:32:45
Yes, not sure how I missed this. Thanks.
| |
380 } | |
381 | |
382 // TODO(dgrogan): Call pref_filter_->FilterOnLoad | |
383 | |
384 if (error_delegate_.get() && read_error_ != PREF_READ_ERROR_NONE) | |
385 error_delegate_->OnError(read_error_); | |
386 | |
387 FOR_EACH_OBSERVER( | |
388 PrefStore::Observer, observers_, OnInitializationCompleted(true)); | |
389 } | |
OLD | NEW |