blob: 8ce59745536d02fe4af6279a3d85312966a34937 [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>
8
[email protected]844a1002011-04-19 11:37:219#include "base/bind.h"
10#include "base/callback.h"
[email protected]ac771fb362014-07-16 06:04:4411#include "base/files/file_path.h"
[email protected]e3177dd52014-08-13 20:22:1412#include "base/files/file_util.h"
[email protected]ffbec692012-02-26 20:26:4213#include "base/json/json_file_value_serializer.h"
14#include "base/json/json_string_value_serializer.h"
[email protected]844a1002011-04-19 11:37:2115#include "base/memory/ref_counted.h"
[email protected]ac771fb362014-07-16 06:04:4416#include "base/metrics/histogram.h"
[email protected]56cbcb3a2013-12-23 21:24:4617#include "base/prefs/pref_filter.h"
[email protected]fb441962013-05-08 05:35:2418#include "base/sequenced_task_runner.h"
raymesbfb910a2015-04-29 07:43:0919#include "base/strings/string_number_conversions.h"
[email protected]ac771fb362014-07-16 06:04:4420#include "base/strings/string_util.h"
[email protected]f2456592014-07-22 19:30:1721#include "base/task_runner_util.h"
[email protected]0de615a2012-11-08 04:40:5922#include "base/threading/sequenced_worker_pool.h"
raymesbfb910a2015-04-29 07:43:0923#include "base/time/default_clock.h"
[email protected]277404c22010-04-22 13:09:4524#include "base/values.h"
[email protected]277404c22010-04-22 13:09:4525
[email protected]f2456592014-07-22 19:30:1726// Result returned from internal read tasks.
27struct JsonPrefStore::ReadResult {
28 public:
29 ReadResult();
30 ~ReadResult();
31
32 scoped_ptr<base::Value> value;
33 PrefReadError error;
34 bool no_dir;
35
36 private:
37 DISALLOW_COPY_AND_ASSIGN(ReadResult);
38};
39
40JsonPrefStore::ReadResult::ReadResult()
41 : error(PersistentPrefStore::PREF_READ_ERROR_NONE), no_dir(false) {
42}
43
44JsonPrefStore::ReadResult::~ReadResult() {
45}
46
[email protected]277404c22010-04-22 13:09:4547namespace {
48
49// Some extensions we'll tack on to copies of the Preferences files.
[email protected]f2456592014-07-22 19:30:1750const base::FilePath::CharType kBadExtension[] = FILE_PATH_LITERAL("bad");
[email protected]277404c22010-04-22 13:09:4551
[email protected]f2456592014-07-22 19:30:1752PersistentPrefStore::PrefReadError HandleReadErrors(
[email protected]a43a667b2013-06-14 17:56:0853 const base::Value* value,
[email protected]023ad6ab2013-02-17 05:07:2354 const base::FilePath& path,
[email protected]844a1002011-04-19 11:37:2155 int error_code,
[email protected]f2456592014-07-22 19:30:1756 const std::string& error_msg) {
[email protected]844a1002011-04-19 11:37:2157 if (!value) {
[email protected]0de615a2012-11-08 04:40:5958 DVLOG(1) << "Error while loading JSON file: " << error_msg
59 << ", file: " << path.value();
[email protected]844a1002011-04-19 11:37:2160 switch (error_code) {
prashhir54a994502015-03-05 09:30:5761 case JSONFileValueDeserializer::JSON_ACCESS_DENIED:
[email protected]f2456592014-07-22 19:30:1762 return PersistentPrefStore::PREF_READ_ERROR_ACCESS_DENIED;
[email protected]844a1002011-04-19 11:37:2163 break;
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;
[email protected]844a1002011-04-19 11:37:2166 break;
prashhir54a994502015-03-05 09:30:5767 case JSONFileValueDeserializer::JSON_FILE_LOCKED:
[email protected]f2456592014-07-22 19:30:1768 return PersistentPrefStore::PREF_READ_ERROR_FILE_LOCKED;
[email protected]844a1002011-04-19 11:37:2169 break;
prashhir54a994502015-03-05 09:30:5770 case JSONFileValueDeserializer::JSON_NO_SUCH_FILE:
[email protected]f2456592014-07-22 19:30:1771 return PersistentPrefStore::PREF_READ_ERROR_NO_FILE;
[email protected]844a1002011-04-19 11:37:2172 break;
73 default:
[email protected]844a1002011-04-19 11:37:2174 // JSON errors indicate file corruption of some sort.
75 // Since the file is corrupt, move it to the side and continue with
76 // empty preferences. This will result in them losing their settings.
77 // We keep the old file for possible support and debugging assistance
78 // as well as to detect if they're seeing these errors repeatedly.
79 // TODO(erikkay) Instead, use the last known good file.
[email protected]023ad6ab2013-02-17 05:07:2380 base::FilePath bad = path.ReplaceExtension(kBadExtension);
[email protected]844a1002011-04-19 11:37:2181
82 // If they've ever had a parse error before, put them in another bucket.
83 // TODO(erikkay) if we keep this error checking for very long, we may
84 // want to differentiate between recent and long ago errors.
[email protected]f2456592014-07-22 19:30:1785 bool bad_existed = base::PathExists(bad);
[email protected]5553d5b2013-07-01 23:07:3686 base::Move(path, bad);
[email protected]f2456592014-07-22 19:30:1787 return bad_existed ? PersistentPrefStore::PREF_READ_ERROR_JSON_REPEAT
88 : PersistentPrefStore::PREF_READ_ERROR_JSON_PARSE;
[email protected]844a1002011-04-19 11:37:2189 }
[email protected]a43a667b2013-06-14 17:56:0890 } else if (!value->IsType(base::Value::TYPE_DICTIONARY)) {
[email protected]f2456592014-07-22 19:30:1791 return PersistentPrefStore::PREF_READ_ERROR_JSON_TYPE;
[email protected]844a1002011-04-19 11:37:2192 }
[email protected]f2456592014-07-22 19:30:1793 return PersistentPrefStore::PREF_READ_ERROR_NONE;
94}
95
gabf16b59a2015-01-31 19:09:0296// Records a sample for |size| in the Settings.JsonDataReadSizeKilobytes
97// histogram suffixed with the base name of the JSON file under |path|.
98void RecordJsonDataSizeHistogram(const base::FilePath& path, size_t size) {
99 std::string spaceless_basename;
100 base::ReplaceChars(path.BaseName().MaybeAsASCII(), " ", "_",
101 &spaceless_basename);
102
103 // The histogram below is an expansion of the UMA_HISTOGRAM_CUSTOM_COUNTS
104 // macro adapted to allow for a dynamically suffixed histogram name.
105 // Note: The factory creates and owns the histogram.
106 base::HistogramBase* histogram = base::Histogram::FactoryGet(
107 "Settings.JsonDataReadSizeKilobytes." + spaceless_basename, 1, 10000, 50,
108 base::HistogramBase::kUmaTargetedHistogramFlag);
109 histogram->Add(static_cast<int>(size) / 1024);
110}
111
[email protected]f2456592014-07-22 19:30:17112scoped_ptr<JsonPrefStore::ReadResult> ReadPrefsFromDisk(
113 const base::FilePath& path,
114 const base::FilePath& alternate_path) {
115 if (!base::PathExists(path) && !alternate_path.empty() &&
116 base::PathExists(alternate_path)) {
117 base::Move(alternate_path, path);
118 }
119
120 int error_code;
121 std::string error_msg;
122 scoped_ptr<JsonPrefStore::ReadResult> read_result(
123 new JsonPrefStore::ReadResult);
prashhir54a994502015-03-05 09:30:57124 JSONFileValueDeserializer deserializer(path);
125 read_result->value.reset(deserializer.Deserialize(&error_code, &error_msg));
[email protected]f2456592014-07-22 19:30:17126 read_result->error =
127 HandleReadErrors(read_result->value.get(), path, error_code, error_msg);
128 read_result->no_dir = !base::PathExists(path.DirName());
gabf16b59a2015-01-31 19:09:02129
130 if (read_result->error == PersistentPrefStore::PREF_READ_ERROR_NONE)
prashhir54a994502015-03-05 09:30:57131 RecordJsonDataSizeHistogram(path, deserializer.get_last_read_size());
gabf16b59a2015-01-31 19:09:02132
[email protected]f2456592014-07-22 19:30:17133 return read_result.Pass();
[email protected]844a1002011-04-19 11:37:21134}
135
[email protected]277404c22010-04-22 13:09:45136} // namespace
137
[email protected]f2456592014-07-22 19:30:17138// static
[email protected]0de615a2012-11-08 04:40:59139scoped_refptr<base::SequencedTaskRunner> JsonPrefStore::GetTaskRunnerForFile(
[email protected]023ad6ab2013-02-17 05:07:23140 const base::FilePath& filename,
[email protected]0de615a2012-11-08 04:40:59141 base::SequencedWorkerPool* worker_pool) {
142 std::string token("json_pref_store-");
143 token.append(filename.AsUTF8Unsafe());
144 return worker_pool->GetSequencedTaskRunnerWithShutdownBehavior(
145 worker_pool->GetNamedSequenceToken(token),
146 base::SequencedWorkerPool::BLOCK_SHUTDOWN);
147}
148
dcheng077d1b22014-08-28 18:47:38149JsonPrefStore::JsonPrefStore(
150 const base::FilePath& filename,
151 const scoped_refptr<base::SequencedTaskRunner>& sequenced_task_runner,
152 scoped_ptr<PrefFilter> pref_filter)
[email protected]277404c22010-04-22 13:09:45153 : path_(filename),
[email protected]0de615a2012-11-08 04:40:59154 sequenced_task_runner_(sequenced_task_runner),
[email protected]a43a667b2013-06-14 17:56:08155 prefs_(new base::DictionaryValue()),
[email protected]277404c22010-04-22 13:09:45156 read_only_(false),
[email protected]0de615a2012-11-08 04:40:59157 writer_(filename, sequenced_task_runner),
[email protected]56cbcb3a2013-12-23 21:24:46158 pref_filter_(pref_filter.Pass()),
[email protected]59c10712012-03-13 02:10:34159 initialized_(false),
[email protected]e33c9512014-05-12 02:24:13160 filtering_in_progress_(false),
raymesbfb910a2015-04-29 07:43:09161 read_error_(PREF_READ_ERROR_NONE),
162 write_count_histogram_(writer_.commit_interval(), path_) {
bratell970f39d2015-01-07 16:40:58163 DCHECK(!path_.empty());
[email protected]e33c9512014-05-12 02:24:13164}
[email protected]277404c22010-04-22 13:09:45165
dcheng077d1b22014-08-28 18:47:38166JsonPrefStore::JsonPrefStore(
167 const base::FilePath& filename,
168 const base::FilePath& alternate_filename,
169 const scoped_refptr<base::SequencedTaskRunner>& sequenced_task_runner,
170 scoped_ptr<PrefFilter> pref_filter)
[email protected]cfcf0e52014-06-20 18:29:47171 : path_(filename),
172 alternate_path_(alternate_filename),
173 sequenced_task_runner_(sequenced_task_runner),
174 prefs_(new base::DictionaryValue()),
175 read_only_(false),
176 writer_(filename, sequenced_task_runner),
177 pref_filter_(pref_filter.Pass()),
178 initialized_(false),
179 filtering_in_progress_(false),
raymesbfb910a2015-04-29 07:43:09180 read_error_(PREF_READ_ERROR_NONE),
181 write_count_histogram_(writer_.commit_interval(), path_) {
bratell970f39d2015-01-07 16:40:58182 DCHECK(!path_.empty());
[email protected]cfcf0e52014-06-20 18:29:47183}
184
[email protected]892f1d62012-11-08 18:24:34185bool JsonPrefStore::GetValue(const std::string& key,
[email protected]a43a667b2013-06-14 17:56:08186 const base::Value** result) const {
[email protected]f2456592014-07-22 19:30:17187 DCHECK(CalledOnValidThread());
188
[email protected]a43a667b2013-06-14 17:56:08189 base::Value* tmp = NULL;
[email protected]892f1d62012-11-08 18:24:34190 if (!prefs_->Get(key, &tmp))
191 return false;
192
193 if (result)
194 *result = tmp;
195 return true;
[email protected]f2d1f612010-12-09 15:10:17196}
197
198void JsonPrefStore::AddObserver(PrefStore::Observer* observer) {
[email protected]f2456592014-07-22 19:30:17199 DCHECK(CalledOnValidThread());
200
[email protected]f2d1f612010-12-09 15:10:17201 observers_.AddObserver(observer);
202}
203
204void JsonPrefStore::RemoveObserver(PrefStore::Observer* observer) {
[email protected]f2456592014-07-22 19:30:17205 DCHECK(CalledOnValidThread());
206
[email protected]f2d1f612010-12-09 15:10:17207 observers_.RemoveObserver(observer);
208}
209
[email protected]14e0ec62013-08-26 22:01:39210bool JsonPrefStore::HasObservers() const {
[email protected]f2456592014-07-22 19:30:17211 DCHECK(CalledOnValidThread());
212
[email protected]14e0ec62013-08-26 22:01:39213 return observers_.might_have_observers();
[email protected]d3b05ea2012-01-24 22:57:05214}
215
[email protected]845b43a82011-05-11 10:14:43216bool JsonPrefStore::IsInitializationComplete() const {
[email protected]f2456592014-07-22 19:30:17217 DCHECK(CalledOnValidThread());
218
[email protected]845b43a82011-05-11 10:14:43219 return initialized_;
220}
221
[email protected]892f1d62012-11-08 18:24:34222bool JsonPrefStore::GetMutableValue(const std::string& key,
[email protected]a43a667b2013-06-14 17:56:08223 base::Value** result) {
[email protected]f2456592014-07-22 19:30:17224 DCHECK(CalledOnValidThread());
225
[email protected]892f1d62012-11-08 18:24:34226 return prefs_->Get(key, result);
[email protected]68bf41a2011-03-25 16:38:31227}
228
raymes76de1af2015-05-06 03:22:21229void JsonPrefStore::SetValue(const std::string& key,
230 base::Value* value,
231 uint32 flags) {
[email protected]f2456592014-07-22 19:30:17232 DCHECK(CalledOnValidThread());
233
[email protected]9b5f56b42011-08-24 21:17:59234 DCHECK(value);
[email protected]a43a667b2013-06-14 17:56:08235 scoped_ptr<base::Value> new_value(value);
236 base::Value* old_value = NULL;
[email protected]9b5f56b42011-08-24 21:17:59237 prefs_->Get(key, &old_value);
238 if (!old_value || !value->Equals(old_value)) {
239 prefs_->Set(key, new_value.release());
raymes76de1af2015-05-06 03:22:21240 ReportValueChanged(key, flags);
[email protected]9b5f56b42011-08-24 21:17:59241 }
[email protected]f2d1f612010-12-09 15:10:17242}
243
[email protected]a43a667b2013-06-14 17:56:08244void JsonPrefStore::SetValueSilently(const std::string& key,
raymes76de1af2015-05-06 03:22:21245 base::Value* value,
246 uint32 flags) {
[email protected]f2456592014-07-22 19:30:17247 DCHECK(CalledOnValidThread());
248
[email protected]9b5f56b42011-08-24 21:17:59249 DCHECK(value);
[email protected]a43a667b2013-06-14 17:56:08250 scoped_ptr<base::Value> new_value(value);
251 base::Value* old_value = NULL;
[email protected]9b5f56b42011-08-24 21:17:59252 prefs_->Get(key, &old_value);
[email protected]25308672011-10-10 17:22:50253 if (!old_value || !value->Equals(old_value)) {
[email protected]9b5f56b42011-08-24 21:17:59254 prefs_->Set(key, new_value.release());
[email protected]25308672011-10-10 17:22:50255 if (!read_only_)
256 writer_.ScheduleWrite(this);
257 }
[email protected]f2d1f612010-12-09 15:10:17258}
259
raymes76de1af2015-05-06 03:22:21260void JsonPrefStore::RemoveValue(const std::string& key, uint32 flags) {
[email protected]f2456592014-07-22 19:30:17261 DCHECK(CalledOnValidThread());
262
[email protected]aa3283392013-11-27 01:38:24263 if (prefs_->RemovePath(key, NULL))
raymes76de1af2015-05-06 03:22:21264 ReportValueChanged(key, flags);
[email protected]f2d1f612010-12-09 15:10:17265}
266
raymes76de1af2015-05-06 03:22:21267void JsonPrefStore::RemoveValueSilently(const std::string& key, uint32 flags) {
[email protected]f2456592014-07-22 19:30:17268 DCHECK(CalledOnValidThread());
269
[email protected]e33c9512014-05-12 02:24:13270 prefs_->RemovePath(key, NULL);
271 if (!read_only_)
272 writer_.ScheduleWrite(this);
273}
274
[email protected]ddb1e5a2010-12-13 20:10:45275bool JsonPrefStore::ReadOnly() const {
[email protected]f2456592014-07-22 19:30:17276 DCHECK(CalledOnValidThread());
277
[email protected]ddb1e5a2010-12-13 20:10:45278 return read_only_;
279}
280
[email protected]59c10712012-03-13 02:10:34281PersistentPrefStore::PrefReadError JsonPrefStore::GetReadError() const {
[email protected]f2456592014-07-22 19:30:17282 DCHECK(CalledOnValidThread());
283
[email protected]59c10712012-03-13 02:10:34284 return read_error_;
285}
286
[email protected]7b2720b2012-04-25 16:59:11287PersistentPrefStore::PrefReadError JsonPrefStore::ReadPrefs() {
[email protected]f2456592014-07-22 19:30:17288 DCHECK(CalledOnValidThread());
289
[email protected]f2456592014-07-22 19:30:17290 OnFileRead(ReadPrefsFromDisk(path_, alternate_path_));
291 return filtering_in_progress_ ? PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE
292 : read_error_;
[email protected]7b2720b2012-04-25 16:59:11293}
294
[email protected]e33c9512014-05-12 02:24:13295void JsonPrefStore::ReadPrefsAsync(ReadErrorDelegate* error_delegate) {
[email protected]f2456592014-07-22 19:30:17296 DCHECK(CalledOnValidThread());
297
[email protected]7b2720b2012-04-25 16:59:11298 initialized_ = false;
299 error_delegate_.reset(error_delegate);
[email protected]7b2720b2012-04-25 16:59:11300
[email protected]3b268bc2014-07-28 17:43:15301 // Weakly binds the read task so that it doesn't kick in during shutdown.
[email protected]f2456592014-07-22 19:30:17302 base::PostTaskAndReplyWithResult(
dchengd81e7d72014-08-27 00:23:23303 sequenced_task_runner_.get(),
[email protected]f2456592014-07-22 19:30:17304 FROM_HERE,
305 base::Bind(&ReadPrefsFromDisk, path_, alternate_path_),
[email protected]3b268bc2014-07-28 17:43:15306 base::Bind(&JsonPrefStore::OnFileRead, AsWeakPtr()));
[email protected]7b2720b2012-04-25 16:59:11307}
308
309void JsonPrefStore::CommitPendingWrite() {
[email protected]f2456592014-07-22 19:30:17310 DCHECK(CalledOnValidThread());
311
[email protected]7b2720b2012-04-25 16:59:11312 if (writer_.HasPendingWrite() && !read_only_)
313 writer_.DoScheduledWrite();
314}
315
raymes76de1af2015-05-06 03:22:21316void JsonPrefStore::ReportValueChanged(const std::string& key, uint32 flags) {
[email protected]f2456592014-07-22 19:30:17317 DCHECK(CalledOnValidThread());
318
[email protected]a0ce7e72014-01-21 16:50:56319 if (pref_filter_)
320 pref_filter_->FilterUpdate(key);
[email protected]56cbcb3a2013-12-23 21:24:46321
[email protected]7b2720b2012-04-25 16:59:11322 FOR_EACH_OBSERVER(PrefStore::Observer, observers_, OnPrefValueChanged(key));
[email protected]56cbcb3a2013-12-23 21:24:46323
[email protected]7b2720b2012-04-25 16:59:11324 if (!read_only_)
325 writer_.ScheduleWrite(this);
326}
327
[email protected]e33c9512014-05-12 02:24:13328void JsonPrefStore::RegisterOnNextSuccessfulWriteCallback(
329 const base::Closure& on_next_successful_write) {
[email protected]f2456592014-07-22 19:30:17330 DCHECK(CalledOnValidThread());
331
[email protected]e33c9512014-05-12 02:24:13332 writer_.RegisterOnNextSuccessfulWriteCallback(on_next_successful_write);
333}
334
[email protected]f2456592014-07-22 19:30:17335void JsonPrefStore::OnFileRead(scoped_ptr<ReadResult> read_result) {
336 DCHECK(CalledOnValidThread());
337
338 DCHECK(read_result);
339
[email protected]e33c9512014-05-12 02:24:13340 scoped_ptr<base::DictionaryValue> unfiltered_prefs(new base::DictionaryValue);
341
[email protected]f2456592014-07-22 19:30:17342 read_error_ = read_result->error;
[email protected]845b43a82011-05-11 10:14:43343
[email protected]f2456592014-07-22 19:30:17344 bool initialization_successful = !read_result->no_dir;
[email protected]e33c9512014-05-12 02:24:13345
346 if (initialization_successful) {
347 switch (read_error_) {
348 case PREF_READ_ERROR_ACCESS_DENIED:
349 case PREF_READ_ERROR_FILE_OTHER:
350 case PREF_READ_ERROR_FILE_LOCKED:
351 case PREF_READ_ERROR_JSON_TYPE:
352 case PREF_READ_ERROR_FILE_NOT_SPECIFIED:
353 read_only_ = true;
354 break;
355 case PREF_READ_ERROR_NONE:
[email protected]f2456592014-07-22 19:30:17356 DCHECK(read_result->value.get());
[email protected]e33c9512014-05-12 02:24:13357 unfiltered_prefs.reset(
[email protected]f2456592014-07-22 19:30:17358 static_cast<base::DictionaryValue*>(read_result->value.release()));
[email protected]e33c9512014-05-12 02:24:13359 break;
360 case PREF_READ_ERROR_NO_FILE:
361 // If the file just doesn't exist, maybe this is first run. In any case
362 // there's no harm in writing out default prefs in this case.
363 break;
364 case PREF_READ_ERROR_JSON_PARSE:
365 case PREF_READ_ERROR_JSON_REPEAT:
366 break;
367 case PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE:
368 // This is a special error code to be returned by ReadPrefs when it
369 // can't complete synchronously, it should never be returned by the read
370 // operation itself.
371 NOTREACHED();
372 break;
[email protected]3edebd952014-05-28 08:27:58373 case PREF_READ_ERROR_LEVELDB_IO:
374 case PREF_READ_ERROR_LEVELDB_CORRUPTION_READ_ONLY:
375 case PREF_READ_ERROR_LEVELDB_CORRUPTION:
376 // These are specific to LevelDBPrefStore.
377 NOTREACHED();
[email protected]e33c9512014-05-12 02:24:13378 case PREF_READ_ERROR_MAX_ENUM:
379 NOTREACHED();
380 break;
381 }
[email protected]845b43a82011-05-11 10:14:43382 }
383
[email protected]e33c9512014-05-12 02:24:13384 if (pref_filter_) {
385 filtering_in_progress_ = true;
386 const PrefFilter::PostFilterOnLoadCallback post_filter_on_load_callback(
387 base::Bind(
[email protected]3b268bc2014-07-28 17:43:15388 &JsonPrefStore::FinalizeFileRead, AsWeakPtr(),
389 initialization_successful));
[email protected]e33c9512014-05-12 02:24:13390 pref_filter_->FilterOnLoad(post_filter_on_load_callback,
391 unfiltered_prefs.Pass());
392 } else {
393 FinalizeFileRead(initialization_successful, unfiltered_prefs.Pass(), false);
[email protected]844a1002011-04-19 11:37:21394 }
[email protected]844a1002011-04-19 11:37:21395}
396
[email protected]7b2720b2012-04-25 16:59:11397JsonPrefStore::~JsonPrefStore() {
398 CommitPendingWrite();
[email protected]f89ee342011-03-07 09:28:27399}
400
[email protected]277404c22010-04-22 13:09:45401bool JsonPrefStore::SerializeData(std::string* output) {
[email protected]f2456592014-07-22 19:30:17402 DCHECK(CalledOnValidThread());
403
raymesbfb910a2015-04-29 07:43:09404 write_count_histogram_.RecordWriteOccured();
405
[email protected]bc831ff12014-01-31 20:48:33406 if (pref_filter_)
[email protected]a0ce7e72014-01-21 16:50:56407 pref_filter_->FilterSerializeData(prefs_.get());
408
[email protected]277404c22010-04-22 13:09:45409 JSONStringValueSerializer serializer(output);
gab97c50ac2015-03-06 20:41:43410 // Not pretty-printing prefs shrinks pref file size by ~30%. To obtain
411 // readable prefs for debugging purposes, you can dump your prefs into any
412 // command-line or online JSON pretty printing tool.
413 serializer.set_pretty_print(false);
gabf16b59a2015-01-31 19:09:02414 return serializer.Serialize(*prefs_);
[email protected]277404c22010-04-22 13:09:45415}
[email protected]e33c9512014-05-12 02:24:13416
417void JsonPrefStore::FinalizeFileRead(bool initialization_successful,
418 scoped_ptr<base::DictionaryValue> prefs,
419 bool schedule_write) {
[email protected]f2456592014-07-22 19:30:17420 DCHECK(CalledOnValidThread());
421
[email protected]e33c9512014-05-12 02:24:13422 filtering_in_progress_ = false;
423
424 if (!initialization_successful) {
425 FOR_EACH_OBSERVER(PrefStore::Observer,
426 observers_,
427 OnInitializationCompleted(false));
428 return;
429 }
430
431 prefs_ = prefs.Pass();
432
433 initialized_ = true;
434
435 if (schedule_write && !read_only_)
436 writer_.ScheduleWrite(this);
437
438 if (error_delegate_ && read_error_ != PREF_READ_ERROR_NONE)
439 error_delegate_->OnError(read_error_);
440
441 FOR_EACH_OBSERVER(PrefStore::Observer,
442 observers_,
443 OnInitializationCompleted(true));
444
445 return;
446}
raymesbfb910a2015-04-29 07:43:09447
448// NOTE: This value should NOT be changed without renaming the histogram
449// otherwise it will create incompatible buckets.
450const int32_t
451 JsonPrefStore::WriteCountHistogram::kHistogramWriteReportIntervalMins = 5;
452
453JsonPrefStore::WriteCountHistogram::WriteCountHistogram(
454 const base::TimeDelta& commit_interval,
455 const base::FilePath& path)
456 : WriteCountHistogram(commit_interval,
457 path,
458 scoped_ptr<base::Clock>(new base::DefaultClock)) {
459}
460
461JsonPrefStore::WriteCountHistogram::WriteCountHistogram(
462 const base::TimeDelta& commit_interval,
463 const base::FilePath& path,
464 scoped_ptr<base::Clock> clock)
465 : commit_interval_(commit_interval),
466 path_(path),
467 clock_(clock.release()),
468 report_interval_(
469 base::TimeDelta::FromMinutes(kHistogramWriteReportIntervalMins)),
470 last_report_time_(clock_->Now()),
471 writes_since_last_report_(0) {
472}
473
474JsonPrefStore::WriteCountHistogram::~WriteCountHistogram() {
475 ReportOutstandingWrites();
476}
477
478void JsonPrefStore::WriteCountHistogram::RecordWriteOccured() {
479 ReportOutstandingWrites();
480
481 ++writes_since_last_report_;
482}
483
484void JsonPrefStore::WriteCountHistogram::ReportOutstandingWrites() {
485 base::Time current_time = clock_->Now();
486 base::TimeDelta time_since_last_report = current_time - last_report_time_;
487
488 if (time_since_last_report <= report_interval_)
489 return;
490
491 // If the time since the last report exceeds the report interval, report all
492 // the writes since the last report. They must have all occurred in the same
493 // report interval.
494 base::HistogramBase* histogram = GetHistogram();
495 histogram->Add(writes_since_last_report_);
496
497 // There may be several report intervals that elapsed that don't have any
498 // writes in them. Report these too.
499 int64 total_num_intervals_elapsed =
500 (time_since_last_report / report_interval_);
501 for (int64 i = 0; i < total_num_intervals_elapsed - 1; ++i)
502 histogram->Add(0);
503
504 writes_since_last_report_ = 0;
505 last_report_time_ += total_num_intervals_elapsed * report_interval_;
506}
507
508base::HistogramBase* JsonPrefStore::WriteCountHistogram::GetHistogram() {
509 std::string spaceless_basename;
510 base::ReplaceChars(path_.BaseName().MaybeAsASCII(), " ", "_",
511 &spaceless_basename);
512 std::string histogram_name =
513 "Settings.JsonDataWriteCount." + spaceless_basename;
514
515 // The min value for a histogram is 1. The max value is the maximum number of
516 // writes that can occur in the window being recorded. The number of buckets
517 // used is the max value (plus the underflow/overflow buckets).
518 int32_t min_value = 1;
519 int32_t max_value = report_interval_ / commit_interval_;
520 int32_t num_buckets = max_value + 1;
521
522 // NOTE: These values should NOT be changed without renaming the histogram
523 // otherwise it will create incompatible buckets.
524 DCHECK_EQ(30, max_value);
525 DCHECK_EQ(31, num_buckets);
526
527 // The histogram below is an expansion of the UMA_HISTOGRAM_CUSTOM_COUNTS
528 // macro adapted to allow for a dynamically suffixed histogram name.
529 // Note: The factory creates and owns the histogram.
530 base::HistogramBase* histogram = base::Histogram::FactoryGet(
531 histogram_name, min_value, max_value, num_buckets,
532 base::HistogramBase::kUmaTargetedHistogramFlag);
533 return histogram;
534}