blob: 637ec70b81f1eafacccd5a691f17ec4db4481bc8 [file] [log] [blame]
[email protected]d3b05ea2012-01-24 22:57:051// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]277404c22010-04-22 13:09:452// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]03b9b4e2012-10-22 20:01:525#include "base/prefs/json_pref_store.h"
[email protected]277404c22010-04-22 13:09:456
7#include <algorithm>
danakj0c8d4aa2015-11-25 05:29:588#include <utility>
[email protected]277404c22010-04-22 13:09:459
[email protected]844a1002011-04-19 11:37:2110#include "base/bind.h"
11#include "base/callback.h"
[email protected]ac771fb362014-07-16 06:04:4412#include "base/files/file_path.h"
[email protected]e3177dd52014-08-13 20:22:1413#include "base/files/file_util.h"
[email protected]ffbec692012-02-26 20:26:4214#include "base/json/json_file_value_serializer.h"
15#include "base/json/json_string_value_serializer.h"
[email protected]844a1002011-04-19 11:37:2116#include "base/memory/ref_counted.h"
[email protected]ac771fb362014-07-16 06:04:4417#include "base/metrics/histogram.h"
[email protected]56cbcb3a2013-12-23 21:24:4618#include "base/prefs/pref_filter.h"
[email protected]fb441962013-05-08 05:35:2419#include "base/sequenced_task_runner.h"
raymesbfb910a2015-04-29 07:43:0920#include "base/strings/string_number_conversions.h"
[email protected]ac771fb362014-07-16 06:04:4421#include "base/strings/string_util.h"
[email protected]f2456592014-07-22 19:30:1722#include "base/task_runner_util.h"
[email protected]0de615a2012-11-08 04:40:5923#include "base/threading/sequenced_worker_pool.h"
raymesbfb910a2015-04-29 07:43:0924#include "base/time/default_clock.h"
[email protected]277404c22010-04-22 13:09:4525#include "base/values.h"
[email protected]277404c22010-04-22 13:09:4526
[email protected]f2456592014-07-22 19:30:1727// Result returned from internal read tasks.
28struct JsonPrefStore::ReadResult {
29 public:
30 ReadResult();
31 ~ReadResult();
32
33 scoped_ptr<base::Value> value;
34 PrefReadError error;
35 bool no_dir;
36
37 private:
38 DISALLOW_COPY_AND_ASSIGN(ReadResult);
39};
40
41JsonPrefStore::ReadResult::ReadResult()
42 : error(PersistentPrefStore::PREF_READ_ERROR_NONE), no_dir(false) {
43}
44
45JsonPrefStore::ReadResult::~ReadResult() {
46}
47
[email protected]277404c22010-04-22 13:09:4548namespace {
49
50// Some extensions we'll tack on to copies of the Preferences files.
[email protected]f2456592014-07-22 19:30:1751const base::FilePath::CharType kBadExtension[] = FILE_PATH_LITERAL("bad");
[email protected]277404c22010-04-22 13:09:4552
[email protected]f2456592014-07-22 19:30:1753PersistentPrefStore::PrefReadError HandleReadErrors(
[email protected]a43a667b2013-06-14 17:56:0854 const base::Value* value,
[email protected]023ad6ab2013-02-17 05:07:2355 const base::FilePath& path,
[email protected]844a1002011-04-19 11:37:2156 int error_code,
[email protected]f2456592014-07-22 19:30:1757 const std::string& error_msg) {
[email protected]844a1002011-04-19 11:37:2158 if (!value) {
[email protected]0de615a2012-11-08 04:40:5959 DVLOG(1) << "Error while loading JSON file: " << error_msg
60 << ", file: " << path.value();
[email protected]844a1002011-04-19 11:37:2161 switch (error_code) {
prashhir54a994502015-03-05 09:30:5762 case JSONFileValueDeserializer::JSON_ACCESS_DENIED:
[email protected]f2456592014-07-22 19:30:1763 return PersistentPrefStore::PREF_READ_ERROR_ACCESS_DENIED;
prashhir54a994502015-03-05 09:30:5764 case JSONFileValueDeserializer::JSON_CANNOT_READ_FILE:
[email protected]f2456592014-07-22 19:30:1765 return PersistentPrefStore::PREF_READ_ERROR_FILE_OTHER;
prashhir54a994502015-03-05 09:30:5766 case JSONFileValueDeserializer::JSON_FILE_LOCKED:
[email protected]f2456592014-07-22 19:30:1767 return PersistentPrefStore::PREF_READ_ERROR_FILE_LOCKED;
prashhir54a994502015-03-05 09:30:5768 case JSONFileValueDeserializer::JSON_NO_SUCH_FILE:
[email protected]f2456592014-07-22 19:30:1769 return PersistentPrefStore::PREF_READ_ERROR_NO_FILE;
[email protected]844a1002011-04-19 11:37:2170 default:
[email protected]844a1002011-04-19 11:37:2171 // JSON errors indicate file corruption of some sort.
72 // Since the file is corrupt, move it to the side and continue with
73 // empty preferences. This will result in them losing their settings.
74 // We keep the old file for possible support and debugging assistance
75 // as well as to detect if they're seeing these errors repeatedly.
76 // TODO(erikkay) Instead, use the last known good file.
[email protected]023ad6ab2013-02-17 05:07:2377 base::FilePath bad = path.ReplaceExtension(kBadExtension);
[email protected]844a1002011-04-19 11:37:2178
79 // If they've ever had a parse error before, put them in another bucket.
80 // TODO(erikkay) if we keep this error checking for very long, we may
81 // want to differentiate between recent and long ago errors.
[email protected]f2456592014-07-22 19:30:1782 bool bad_existed = base::PathExists(bad);
[email protected]5553d5b2013-07-01 23:07:3683 base::Move(path, bad);
[email protected]f2456592014-07-22 19:30:1784 return bad_existed ? PersistentPrefStore::PREF_READ_ERROR_JSON_REPEAT
85 : PersistentPrefStore::PREF_READ_ERROR_JSON_PARSE;
[email protected]844a1002011-04-19 11:37:2186 }
[email protected]844a1002011-04-19 11:37:2187 }
thestig1433edb2015-08-06 21:45:2788 if (!value->IsType(base::Value::TYPE_DICTIONARY))
89 return PersistentPrefStore::PREF_READ_ERROR_JSON_TYPE;
[email protected]f2456592014-07-22 19:30:1790 return PersistentPrefStore::PREF_READ_ERROR_NONE;
91}
92
gabf16b59a2015-01-31 19:09:0293// Records a sample for |size| in the Settings.JsonDataReadSizeKilobytes
94// histogram suffixed with the base name of the JSON file under |path|.
95void RecordJsonDataSizeHistogram(const base::FilePath& path, size_t size) {
96 std::string spaceless_basename;
97 base::ReplaceChars(path.BaseName().MaybeAsASCII(), " ", "_",
98 &spaceless_basename);
99
100 // The histogram below is an expansion of the UMA_HISTOGRAM_CUSTOM_COUNTS
101 // macro adapted to allow for a dynamically suffixed histogram name.
102 // Note: The factory creates and owns the histogram.
103 base::HistogramBase* histogram = base::Histogram::FactoryGet(
104 "Settings.JsonDataReadSizeKilobytes." + spaceless_basename, 1, 10000, 50,
105 base::HistogramBase::kUmaTargetedHistogramFlag);
106 histogram->Add(static_cast<int>(size) / 1024);
107}
108
[email protected]f2456592014-07-22 19:30:17109scoped_ptr<JsonPrefStore::ReadResult> ReadPrefsFromDisk(
110 const base::FilePath& path,
111 const base::FilePath& alternate_path) {
112 if (!base::PathExists(path) && !alternate_path.empty() &&
113 base::PathExists(alternate_path)) {
114 base::Move(alternate_path, path);
115 }
116
117 int error_code;
118 std::string error_msg;
119 scoped_ptr<JsonPrefStore::ReadResult> read_result(
120 new JsonPrefStore::ReadResult);
prashhir54a994502015-03-05 09:30:57121 JSONFileValueDeserializer deserializer(path);
olli.raulaba045252015-10-16 06:16:40122 read_result->value = deserializer.Deserialize(&error_code, &error_msg);
[email protected]f2456592014-07-22 19:30:17123 read_result->error =
124 HandleReadErrors(read_result->value.get(), path, error_code, error_msg);
125 read_result->no_dir = !base::PathExists(path.DirName());
gabf16b59a2015-01-31 19:09:02126
127 if (read_result->error == PersistentPrefStore::PREF_READ_ERROR_NONE)
prashhir54a994502015-03-05 09:30:57128 RecordJsonDataSizeHistogram(path, deserializer.get_last_read_size());
gabf16b59a2015-01-31 19:09:02129
danakj0c8d4aa2015-11-25 05:29:58130 return read_result;
[email protected]844a1002011-04-19 11:37:21131}
132
[email protected]277404c22010-04-22 13:09:45133} // namespace
134
[email protected]f2456592014-07-22 19:30:17135// static
[email protected]0de615a2012-11-08 04:40:59136scoped_refptr<base::SequencedTaskRunner> JsonPrefStore::GetTaskRunnerForFile(
[email protected]023ad6ab2013-02-17 05:07:23137 const base::FilePath& filename,
[email protected]0de615a2012-11-08 04:40:59138 base::SequencedWorkerPool* worker_pool) {
139 std::string token("json_pref_store-");
140 token.append(filename.AsUTF8Unsafe());
141 return worker_pool->GetSequencedTaskRunnerWithShutdownBehavior(
142 worker_pool->GetNamedSequenceToken(token),
143 base::SequencedWorkerPool::BLOCK_SHUTDOWN);
144}
145
dcheng077d1b22014-08-28 18:47:38146JsonPrefStore::JsonPrefStore(
thestig1433edb2015-08-06 21:45:27147 const base::FilePath& pref_filename,
dcheng077d1b22014-08-28 18:47:38148 const scoped_refptr<base::SequencedTaskRunner>& sequenced_task_runner,
149 scoped_ptr<PrefFilter> pref_filter)
thestig1433edb2015-08-06 21:45:27150 : JsonPrefStore(pref_filename,
raymes4b6e14e2015-05-12 00:10:30151 base::FilePath(),
152 sequenced_task_runner,
danakj0c8d4aa2015-11-25 05:29:58153 std::move(pref_filter)) {}
[email protected]277404c22010-04-22 13:09:45154
dcheng077d1b22014-08-28 18:47:38155JsonPrefStore::JsonPrefStore(
thestig1433edb2015-08-06 21:45:27156 const base::FilePath& pref_filename,
157 const base::FilePath& pref_alternate_filename,
dcheng077d1b22014-08-28 18:47:38158 const scoped_refptr<base::SequencedTaskRunner>& sequenced_task_runner,
159 scoped_ptr<PrefFilter> pref_filter)
thestig1433edb2015-08-06 21:45:27160 : path_(pref_filename),
161 alternate_path_(pref_alternate_filename),
[email protected]cfcf0e52014-06-20 18:29:47162 sequenced_task_runner_(sequenced_task_runner),
163 prefs_(new base::DictionaryValue()),
164 read_only_(false),
thestig1433edb2015-08-06 21:45:27165 writer_(pref_filename, sequenced_task_runner),
danakj0c8d4aa2015-11-25 05:29:58166 pref_filter_(std::move(pref_filter)),
[email protected]cfcf0e52014-06-20 18:29:47167 initialized_(false),
168 filtering_in_progress_(false),
raymes4b6e14e2015-05-12 00:10:30169 pending_lossy_write_(false),
raymesbfb910a2015-04-29 07:43:09170 read_error_(PREF_READ_ERROR_NONE),
171 write_count_histogram_(writer_.commit_interval(), path_) {
bratell970f39d2015-01-07 16:40:58172 DCHECK(!path_.empty());
[email protected]cfcf0e52014-06-20 18:29:47173}
174
[email protected]892f1d62012-11-08 18:24:34175bool JsonPrefStore::GetValue(const std::string& key,
[email protected]a43a667b2013-06-14 17:56:08176 const base::Value** result) const {
[email protected]f2456592014-07-22 19:30:17177 DCHECK(CalledOnValidThread());
178
thestig1433edb2015-08-06 21:45:27179 base::Value* tmp = nullptr;
[email protected]892f1d62012-11-08 18:24:34180 if (!prefs_->Get(key, &tmp))
181 return false;
182
183 if (result)
184 *result = tmp;
185 return true;
[email protected]f2d1f612010-12-09 15:10:17186}
187
188void JsonPrefStore::AddObserver(PrefStore::Observer* observer) {
[email protected]f2456592014-07-22 19:30:17189 DCHECK(CalledOnValidThread());
190
[email protected]f2d1f612010-12-09 15:10:17191 observers_.AddObserver(observer);
192}
193
194void JsonPrefStore::RemoveObserver(PrefStore::Observer* observer) {
[email protected]f2456592014-07-22 19:30:17195 DCHECK(CalledOnValidThread());
196
[email protected]f2d1f612010-12-09 15:10:17197 observers_.RemoveObserver(observer);
198}
199
[email protected]14e0ec62013-08-26 22:01:39200bool JsonPrefStore::HasObservers() const {
[email protected]f2456592014-07-22 19:30:17201 DCHECK(CalledOnValidThread());
202
[email protected]14e0ec62013-08-26 22:01:39203 return observers_.might_have_observers();
[email protected]d3b05ea2012-01-24 22:57:05204}
205
[email protected]845b43a82011-05-11 10:14:43206bool JsonPrefStore::IsInitializationComplete() const {
[email protected]f2456592014-07-22 19:30:17207 DCHECK(CalledOnValidThread());
208
[email protected]845b43a82011-05-11 10:14:43209 return initialized_;
210}
211
[email protected]892f1d62012-11-08 18:24:34212bool JsonPrefStore::GetMutableValue(const std::string& key,
[email protected]a43a667b2013-06-14 17:56:08213 base::Value** result) {
[email protected]f2456592014-07-22 19:30:17214 DCHECK(CalledOnValidThread());
215
[email protected]892f1d62012-11-08 18:24:34216 return prefs_->Get(key, result);
[email protected]68bf41a2011-03-25 16:38:31217}
218
raymes76de1af2015-05-06 03:22:21219void JsonPrefStore::SetValue(const std::string& key,
estade0bd407f2015-06-26 18:16:18220 scoped_ptr<base::Value> value,
raymes76de1af2015-05-06 03:22:21221 uint32 flags) {
[email protected]f2456592014-07-22 19:30:17222 DCHECK(CalledOnValidThread());
223
[email protected]9b5f56b42011-08-24 21:17:59224 DCHECK(value);
thestig1433edb2015-08-06 21:45:27225 base::Value* old_value = nullptr;
[email protected]9b5f56b42011-08-24 21:17:59226 prefs_->Get(key, &old_value);
227 if (!old_value || !value->Equals(old_value)) {
danakj0c8d4aa2015-11-25 05:29:58228 prefs_->Set(key, std::move(value));
raymes76de1af2015-05-06 03:22:21229 ReportValueChanged(key, flags);
[email protected]9b5f56b42011-08-24 21:17:59230 }
[email protected]f2d1f612010-12-09 15:10:17231}
232
[email protected]a43a667b2013-06-14 17:56:08233void JsonPrefStore::SetValueSilently(const std::string& key,
estade0bd407f2015-06-26 18:16:18234 scoped_ptr<base::Value> value,
raymes76de1af2015-05-06 03:22:21235 uint32 flags) {
[email protected]f2456592014-07-22 19:30:17236 DCHECK(CalledOnValidThread());
237
[email protected]9b5f56b42011-08-24 21:17:59238 DCHECK(value);
thestig1433edb2015-08-06 21:45:27239 base::Value* old_value = nullptr;
[email protected]9b5f56b42011-08-24 21:17:59240 prefs_->Get(key, &old_value);
[email protected]25308672011-10-10 17:22:50241 if (!old_value || !value->Equals(old_value)) {
danakj0c8d4aa2015-11-25 05:29:58242 prefs_->Set(key, std::move(value));
raymes4b6e14e2015-05-12 00:10:30243 ScheduleWrite(flags);
[email protected]25308672011-10-10 17:22:50244 }
[email protected]f2d1f612010-12-09 15:10:17245}
246
raymes76de1af2015-05-06 03:22:21247void JsonPrefStore::RemoveValue(const std::string& key, uint32 flags) {
[email protected]f2456592014-07-22 19:30:17248 DCHECK(CalledOnValidThread());
249
thestig1433edb2015-08-06 21:45:27250 if (prefs_->RemovePath(key, nullptr))
raymes76de1af2015-05-06 03:22:21251 ReportValueChanged(key, flags);
[email protected]f2d1f612010-12-09 15:10:17252}
253
raymes76de1af2015-05-06 03:22:21254void JsonPrefStore::RemoveValueSilently(const std::string& key, uint32 flags) {
[email protected]f2456592014-07-22 19:30:17255 DCHECK(CalledOnValidThread());
256
thestig1433edb2015-08-06 21:45:27257 prefs_->RemovePath(key, nullptr);
raymes4b6e14e2015-05-12 00:10:30258 ScheduleWrite(flags);
[email protected]e33c9512014-05-12 02:24:13259}
260
[email protected]ddb1e5a2010-12-13 20:10:45261bool JsonPrefStore::ReadOnly() const {
[email protected]f2456592014-07-22 19:30:17262 DCHECK(CalledOnValidThread());
263
[email protected]ddb1e5a2010-12-13 20:10:45264 return read_only_;
265}
266
[email protected]59c10712012-03-13 02:10:34267PersistentPrefStore::PrefReadError JsonPrefStore::GetReadError() const {
[email protected]f2456592014-07-22 19:30:17268 DCHECK(CalledOnValidThread());
269
[email protected]59c10712012-03-13 02:10:34270 return read_error_;
271}
272
[email protected]7b2720b2012-04-25 16:59:11273PersistentPrefStore::PrefReadError JsonPrefStore::ReadPrefs() {
[email protected]f2456592014-07-22 19:30:17274 DCHECK(CalledOnValidThread());
275
[email protected]f2456592014-07-22 19:30:17276 OnFileRead(ReadPrefsFromDisk(path_, alternate_path_));
277 return filtering_in_progress_ ? PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE
278 : read_error_;
[email protected]7b2720b2012-04-25 16:59:11279}
280
[email protected]e33c9512014-05-12 02:24:13281void JsonPrefStore::ReadPrefsAsync(ReadErrorDelegate* error_delegate) {
[email protected]f2456592014-07-22 19:30:17282 DCHECK(CalledOnValidThread());
283
[email protected]7b2720b2012-04-25 16:59:11284 initialized_ = false;
285 error_delegate_.reset(error_delegate);
[email protected]7b2720b2012-04-25 16:59:11286
[email protected]3b268bc2014-07-28 17:43:15287 // Weakly binds the read task so that it doesn't kick in during shutdown.
[email protected]f2456592014-07-22 19:30:17288 base::PostTaskAndReplyWithResult(
dchengd81e7d72014-08-27 00:23:23289 sequenced_task_runner_.get(),
[email protected]f2456592014-07-22 19:30:17290 FROM_HERE,
291 base::Bind(&ReadPrefsFromDisk, path_, alternate_path_),
[email protected]3b268bc2014-07-28 17:43:15292 base::Bind(&JsonPrefStore::OnFileRead, AsWeakPtr()));
[email protected]7b2720b2012-04-25 16:59:11293}
294
295void JsonPrefStore::CommitPendingWrite() {
[email protected]f2456592014-07-22 19:30:17296 DCHECK(CalledOnValidThread());
297
raymes4b6e14e2015-05-12 00:10:30298 // Schedule a write for any lossy writes that are outstanding to ensure that
299 // they get flushed when this function is called.
benwells26730592015-05-28 13:08:08300 SchedulePendingLossyWrites();
raymes4b6e14e2015-05-12 00:10:30301
[email protected]7b2720b2012-04-25 16:59:11302 if (writer_.HasPendingWrite() && !read_only_)
303 writer_.DoScheduledWrite();
304}
305
benwells26730592015-05-28 13:08:08306void JsonPrefStore::SchedulePendingLossyWrites() {
307 if (pending_lossy_write_)
308 writer_.ScheduleWrite(this);
309}
310
raymes76de1af2015-05-06 03:22:21311void JsonPrefStore::ReportValueChanged(const std::string& key, uint32 flags) {
[email protected]f2456592014-07-22 19:30:17312 DCHECK(CalledOnValidThread());
313
[email protected]a0ce7e72014-01-21 16:50:56314 if (pref_filter_)
315 pref_filter_->FilterUpdate(key);
[email protected]56cbcb3a2013-12-23 21:24:46316
[email protected]7b2720b2012-04-25 16:59:11317 FOR_EACH_OBSERVER(PrefStore::Observer, observers_, OnPrefValueChanged(key));
[email protected]56cbcb3a2013-12-23 21:24:46318
raymes4b6e14e2015-05-12 00:10:30319 ScheduleWrite(flags);
[email protected]7b2720b2012-04-25 16:59:11320}
321
[email protected]e33c9512014-05-12 02:24:13322void JsonPrefStore::RegisterOnNextSuccessfulWriteCallback(
323 const base::Closure& on_next_successful_write) {
[email protected]f2456592014-07-22 19:30:17324 DCHECK(CalledOnValidThread());
325
[email protected]e33c9512014-05-12 02:24:13326 writer_.RegisterOnNextSuccessfulWriteCallback(on_next_successful_write);
327}
328
[email protected]f2456592014-07-22 19:30:17329void JsonPrefStore::OnFileRead(scoped_ptr<ReadResult> read_result) {
330 DCHECK(CalledOnValidThread());
331
332 DCHECK(read_result);
333
[email protected]e33c9512014-05-12 02:24:13334 scoped_ptr<base::DictionaryValue> unfiltered_prefs(new base::DictionaryValue);
335
[email protected]f2456592014-07-22 19:30:17336 read_error_ = read_result->error;
[email protected]845b43a82011-05-11 10:14:43337
[email protected]f2456592014-07-22 19:30:17338 bool initialization_successful = !read_result->no_dir;
[email protected]e33c9512014-05-12 02:24:13339
340 if (initialization_successful) {
341 switch (read_error_) {
342 case PREF_READ_ERROR_ACCESS_DENIED:
343 case PREF_READ_ERROR_FILE_OTHER:
344 case PREF_READ_ERROR_FILE_LOCKED:
345 case PREF_READ_ERROR_JSON_TYPE:
346 case PREF_READ_ERROR_FILE_NOT_SPECIFIED:
347 read_only_ = true;
348 break;
349 case PREF_READ_ERROR_NONE:
[email protected]f2456592014-07-22 19:30:17350 DCHECK(read_result->value.get());
[email protected]e33c9512014-05-12 02:24:13351 unfiltered_prefs.reset(
[email protected]f2456592014-07-22 19:30:17352 static_cast<base::DictionaryValue*>(read_result->value.release()));
[email protected]e33c9512014-05-12 02:24:13353 break;
354 case PREF_READ_ERROR_NO_FILE:
355 // If the file just doesn't exist, maybe this is first run. In any case
356 // there's no harm in writing out default prefs in this case.
357 break;
358 case PREF_READ_ERROR_JSON_PARSE:
359 case PREF_READ_ERROR_JSON_REPEAT:
360 break;
361 case PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE:
362 // This is a special error code to be returned by ReadPrefs when it
363 // can't complete synchronously, it should never be returned by the read
364 // operation itself.
365 NOTREACHED();
366 break;
367 case PREF_READ_ERROR_MAX_ENUM:
368 NOTREACHED();
369 break;
370 }
[email protected]845b43a82011-05-11 10:14:43371 }
372
[email protected]e33c9512014-05-12 02:24:13373 if (pref_filter_) {
374 filtering_in_progress_ = true;
375 const PrefFilter::PostFilterOnLoadCallback post_filter_on_load_callback(
376 base::Bind(
[email protected]3b268bc2014-07-28 17:43:15377 &JsonPrefStore::FinalizeFileRead, AsWeakPtr(),
378 initialization_successful));
[email protected]e33c9512014-05-12 02:24:13379 pref_filter_->FilterOnLoad(post_filter_on_load_callback,
danakj0c8d4aa2015-11-25 05:29:58380 std::move(unfiltered_prefs));
[email protected]e33c9512014-05-12 02:24:13381 } else {
danakj0c8d4aa2015-11-25 05:29:58382 FinalizeFileRead(initialization_successful, std::move(unfiltered_prefs),
383 false);
[email protected]844a1002011-04-19 11:37:21384 }
[email protected]844a1002011-04-19 11:37:21385}
386
[email protected]7b2720b2012-04-25 16:59:11387JsonPrefStore::~JsonPrefStore() {
388 CommitPendingWrite();
[email protected]f89ee342011-03-07 09:28:27389}
390
[email protected]277404c22010-04-22 13:09:45391bool JsonPrefStore::SerializeData(std::string* output) {
[email protected]f2456592014-07-22 19:30:17392 DCHECK(CalledOnValidThread());
393
raymes4b6e14e2015-05-12 00:10:30394 pending_lossy_write_ = false;
395
raymesbfb910a2015-04-29 07:43:09396 write_count_histogram_.RecordWriteOccured();
397
[email protected]bc831ff12014-01-31 20:48:33398 if (pref_filter_)
[email protected]a0ce7e72014-01-21 16:50:56399 pref_filter_->FilterSerializeData(prefs_.get());
400
[email protected]277404c22010-04-22 13:09:45401 JSONStringValueSerializer serializer(output);
gab97c50ac2015-03-06 20:41:43402 // Not pretty-printing prefs shrinks pref file size by ~30%. To obtain
403 // readable prefs for debugging purposes, you can dump your prefs into any
404 // command-line or online JSON pretty printing tool.
405 serializer.set_pretty_print(false);
gabf16b59a2015-01-31 19:09:02406 return serializer.Serialize(*prefs_);
[email protected]277404c22010-04-22 13:09:45407}
[email protected]e33c9512014-05-12 02:24:13408
409void JsonPrefStore::FinalizeFileRead(bool initialization_successful,
410 scoped_ptr<base::DictionaryValue> prefs,
411 bool schedule_write) {
[email protected]f2456592014-07-22 19:30:17412 DCHECK(CalledOnValidThread());
413
[email protected]e33c9512014-05-12 02:24:13414 filtering_in_progress_ = false;
415
416 if (!initialization_successful) {
417 FOR_EACH_OBSERVER(PrefStore::Observer,
418 observers_,
419 OnInitializationCompleted(false));
420 return;
421 }
422
danakj0c8d4aa2015-11-25 05:29:58423 prefs_ = std::move(prefs);
[email protected]e33c9512014-05-12 02:24:13424
425 initialized_ = true;
426
raymes4b6e14e2015-05-12 00:10:30427 if (schedule_write)
428 ScheduleWrite(DEFAULT_PREF_WRITE_FLAGS);
[email protected]e33c9512014-05-12 02:24:13429
430 if (error_delegate_ && read_error_ != PREF_READ_ERROR_NONE)
431 error_delegate_->OnError(read_error_);
432
433 FOR_EACH_OBSERVER(PrefStore::Observer,
434 observers_,
435 OnInitializationCompleted(true));
436
437 return;
438}
raymesbfb910a2015-04-29 07:43:09439
raymes4b6e14e2015-05-12 00:10:30440void JsonPrefStore::ScheduleWrite(uint32 flags) {
441 if (read_only_)
442 return;
443
444 if (flags & LOSSY_PREF_WRITE_FLAG)
445 pending_lossy_write_ = true;
446 else
447 writer_.ScheduleWrite(this);
448}
449
raymesbfb910a2015-04-29 07:43:09450// NOTE: This value should NOT be changed without renaming the histogram
451// otherwise it will create incompatible buckets.
452const int32_t
453 JsonPrefStore::WriteCountHistogram::kHistogramWriteReportIntervalMins = 5;
454
455JsonPrefStore::WriteCountHistogram::WriteCountHistogram(
456 const base::TimeDelta& commit_interval,
457 const base::FilePath& path)
458 : WriteCountHistogram(commit_interval,
459 path,
460 scoped_ptr<base::Clock>(new base::DefaultClock)) {
461}
462
463JsonPrefStore::WriteCountHistogram::WriteCountHistogram(
464 const base::TimeDelta& commit_interval,
465 const base::FilePath& path,
466 scoped_ptr<base::Clock> clock)
467 : commit_interval_(commit_interval),
468 path_(path),
469 clock_(clock.release()),
470 report_interval_(
471 base::TimeDelta::FromMinutes(kHistogramWriteReportIntervalMins)),
472 last_report_time_(clock_->Now()),
473 writes_since_last_report_(0) {
474}
475
476JsonPrefStore::WriteCountHistogram::~WriteCountHistogram() {
477 ReportOutstandingWrites();
478}
479
480void JsonPrefStore::WriteCountHistogram::RecordWriteOccured() {
481 ReportOutstandingWrites();
482
483 ++writes_since_last_report_;
484}
485
486void JsonPrefStore::WriteCountHistogram::ReportOutstandingWrites() {
487 base::Time current_time = clock_->Now();
488 base::TimeDelta time_since_last_report = current_time - last_report_time_;
489
490 if (time_since_last_report <= report_interval_)
491 return;
492
493 // If the time since the last report exceeds the report interval, report all
494 // the writes since the last report. They must have all occurred in the same
495 // report interval.
496 base::HistogramBase* histogram = GetHistogram();
497 histogram->Add(writes_since_last_report_);
498
499 // There may be several report intervals that elapsed that don't have any
500 // writes in them. Report these too.
501 int64 total_num_intervals_elapsed =
502 (time_since_last_report / report_interval_);
503 for (int64 i = 0; i < total_num_intervals_elapsed - 1; ++i)
504 histogram->Add(0);
505
506 writes_since_last_report_ = 0;
507 last_report_time_ += total_num_intervals_elapsed * report_interval_;
508}
509
510base::HistogramBase* JsonPrefStore::WriteCountHistogram::GetHistogram() {
511 std::string spaceless_basename;
512 base::ReplaceChars(path_.BaseName().MaybeAsASCII(), " ", "_",
513 &spaceless_basename);
514 std::string histogram_name =
515 "Settings.JsonDataWriteCount." + spaceless_basename;
516
517 // The min value for a histogram is 1. The max value is the maximum number of
518 // writes that can occur in the window being recorded. The number of buckets
519 // used is the max value (plus the underflow/overflow buckets).
520 int32_t min_value = 1;
521 int32_t max_value = report_interval_ / commit_interval_;
522 int32_t num_buckets = max_value + 1;
523
524 // NOTE: These values should NOT be changed without renaming the histogram
525 // otherwise it will create incompatible buckets.
526 DCHECK_EQ(30, max_value);
527 DCHECK_EQ(31, num_buckets);
528
529 // The histogram below is an expansion of the UMA_HISTOGRAM_CUSTOM_COUNTS
530 // macro adapted to allow for a dynamically suffixed histogram name.
531 // Note: The factory creates and owns the histogram.
532 base::HistogramBase* histogram = base::Histogram::FactoryGet(
533 histogram_name, min_value, max_value, num_buckets,
534 base::HistogramBase::kUmaTargetedHistogramFlag);
535 return histogram;
536}