blob: 779c2009730366aba4d8fae689d340b2fb81ad71 [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
brettwf00b9b42016-02-01 22:11:385#include "components/prefs/json_pref_store.h"
[email protected]277404c22010-04-22 13:09:456
avi9ef8bb02015-12-24 05:29:367#include <stddef.h>
8
[email protected]277404c22010-04-22 13:09:459#include <algorithm>
danakj0c8d4aa2015-11-25 05:29:5810#include <utility>
[email protected]277404c22010-04-22 13:09:4511
[email protected]844a1002011-04-19 11:37:2112#include "base/bind.h"
13#include "base/callback.h"
[email protected]ac771fb362014-07-16 06:04:4414#include "base/files/file_path.h"
[email protected]e3177dd52014-08-13 20:22:1415#include "base/files/file_util.h"
[email protected]ffbec692012-02-26 20:26:4216#include "base/json/json_file_value_serializer.h"
17#include "base/json/json_string_value_serializer.h"
avi9ef8bb02015-12-24 05:29:3618#include "base/macros.h"
[email protected]844a1002011-04-19 11:37:2119#include "base/memory/ref_counted.h"
[email protected]ac771fb362014-07-16 06:04:4420#include "base/metrics/histogram.h"
[email protected]fb441962013-05-08 05:35:2421#include "base/sequenced_task_runner.h"
raymesbfb910a2015-04-29 07:43:0922#include "base/strings/string_number_conversions.h"
[email protected]ac771fb362014-07-16 06:04:4423#include "base/strings/string_util.h"
[email protected]f2456592014-07-22 19:30:1724#include "base/task_runner_util.h"
[email protected]0de615a2012-11-08 04:40:5925#include "base/threading/sequenced_worker_pool.h"
raymesbfb910a2015-04-29 07:43:0926#include "base/time/default_clock.h"
[email protected]277404c22010-04-22 13:09:4527#include "base/values.h"
brettwf00b9b42016-02-01 22:11:3828#include "components/prefs/pref_filter.h"
[email protected]277404c22010-04-22 13:09:4529
[email protected]f2456592014-07-22 19:30:1730// Result returned from internal read tasks.
31struct JsonPrefStore::ReadResult {
32 public:
33 ReadResult();
34 ~ReadResult();
35
dcheng5f043bc2016-04-22 19:09:0636 std::unique_ptr<base::Value> value;
[email protected]f2456592014-07-22 19:30:1737 PrefReadError error;
38 bool no_dir;
39
40 private:
41 DISALLOW_COPY_AND_ASSIGN(ReadResult);
42};
43
44JsonPrefStore::ReadResult::ReadResult()
45 : error(PersistentPrefStore::PREF_READ_ERROR_NONE), no_dir(false) {
46}
47
48JsonPrefStore::ReadResult::~ReadResult() {
49}
50
[email protected]277404c22010-04-22 13:09:4551namespace {
52
53// Some extensions we'll tack on to copies of the Preferences files.
[email protected]f2456592014-07-22 19:30:1754const base::FilePath::CharType kBadExtension[] = FILE_PATH_LITERAL("bad");
[email protected]277404c22010-04-22 13:09:4555
[email protected]f2456592014-07-22 19:30:1756PersistentPrefStore::PrefReadError HandleReadErrors(
[email protected]a43a667b2013-06-14 17:56:0857 const base::Value* value,
[email protected]023ad6ab2013-02-17 05:07:2358 const base::FilePath& path,
[email protected]844a1002011-04-19 11:37:2159 int error_code,
[email protected]f2456592014-07-22 19:30:1760 const std::string& error_msg) {
[email protected]844a1002011-04-19 11:37:2161 if (!value) {
[email protected]0de615a2012-11-08 04:40:5962 DVLOG(1) << "Error while loading JSON file: " << error_msg
63 << ", file: " << path.value();
[email protected]844a1002011-04-19 11:37:2164 switch (error_code) {
prashhir54a994502015-03-05 09:30:5765 case JSONFileValueDeserializer::JSON_ACCESS_DENIED:
[email protected]f2456592014-07-22 19:30:1766 return PersistentPrefStore::PREF_READ_ERROR_ACCESS_DENIED;
prashhir54a994502015-03-05 09:30:5767 case JSONFileValueDeserializer::JSON_CANNOT_READ_FILE:
[email protected]f2456592014-07-22 19:30:1768 return PersistentPrefStore::PREF_READ_ERROR_FILE_OTHER;
prashhir54a994502015-03-05 09:30:5769 case JSONFileValueDeserializer::JSON_FILE_LOCKED:
[email protected]f2456592014-07-22 19:30:1770 return PersistentPrefStore::PREF_READ_ERROR_FILE_LOCKED;
prashhir54a994502015-03-05 09:30:5771 case JSONFileValueDeserializer::JSON_NO_SUCH_FILE:
[email protected]f2456592014-07-22 19:30:1772 return PersistentPrefStore::PREF_READ_ERROR_NO_FILE;
[email protected]844a1002011-04-19 11:37:2173 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]844a1002011-04-19 11:37:2190 }
thestig1433edb2015-08-06 21:45:2791 if (!value->IsType(base::Value::TYPE_DICTIONARY))
92 return PersistentPrefStore::PREF_READ_ERROR_JSON_TYPE;
[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
dcheng5f043bc2016-04-22 19:09:06112std::unique_ptr<JsonPrefStore::ReadResult> ReadPrefsFromDisk(
[email protected]f2456592014-07-22 19:30:17113 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;
dcheng5f043bc2016-04-22 19:09:06122 std::unique_ptr<JsonPrefStore::ReadResult> read_result(
[email protected]f2456592014-07-22 19:30:17123 new JsonPrefStore::ReadResult);
prashhir54a994502015-03-05 09:30:57124 JSONFileValueDeserializer deserializer(path);
olli.raulaba045252015-10-16 06:16:40125 read_result->value = 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
danakj0c8d4aa2015-11-25 05:29:58133 return read_result;
[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(
thestig1433edb2015-08-06 21:45:27150 const base::FilePath& pref_filename,
dcheng077d1b22014-08-28 18:47:38151 const scoped_refptr<base::SequencedTaskRunner>& sequenced_task_runner,
dcheng5f043bc2016-04-22 19:09:06152 std::unique_ptr<PrefFilter> pref_filter)
thestig1433edb2015-08-06 21:45:27153 : JsonPrefStore(pref_filename,
raymes4b6e14e2015-05-12 00:10:30154 base::FilePath(),
155 sequenced_task_runner,
danakj0c8d4aa2015-11-25 05:29:58156 std::move(pref_filter)) {}
[email protected]277404c22010-04-22 13:09:45157
dcheng077d1b22014-08-28 18:47:38158JsonPrefStore::JsonPrefStore(
thestig1433edb2015-08-06 21:45:27159 const base::FilePath& pref_filename,
160 const base::FilePath& pref_alternate_filename,
dcheng077d1b22014-08-28 18:47:38161 const scoped_refptr<base::SequencedTaskRunner>& sequenced_task_runner,
dcheng5f043bc2016-04-22 19:09:06162 std::unique_ptr<PrefFilter> pref_filter)
thestig1433edb2015-08-06 21:45:27163 : path_(pref_filename),
164 alternate_path_(pref_alternate_filename),
[email protected]cfcf0e52014-06-20 18:29:47165 sequenced_task_runner_(sequenced_task_runner),
166 prefs_(new base::DictionaryValue()),
167 read_only_(false),
thestig1433edb2015-08-06 21:45:27168 writer_(pref_filename, sequenced_task_runner),
danakj0c8d4aa2015-11-25 05:29:58169 pref_filter_(std::move(pref_filter)),
[email protected]cfcf0e52014-06-20 18:29:47170 initialized_(false),
171 filtering_in_progress_(false),
raymes4b6e14e2015-05-12 00:10:30172 pending_lossy_write_(false),
raymesbfb910a2015-04-29 07:43:09173 read_error_(PREF_READ_ERROR_NONE),
174 write_count_histogram_(writer_.commit_interval(), path_) {
bratell970f39d2015-01-07 16:40:58175 DCHECK(!path_.empty());
[email protected]cfcf0e52014-06-20 18:29:47176}
177
[email protected]892f1d62012-11-08 18:24:34178bool JsonPrefStore::GetValue(const std::string& key,
[email protected]a43a667b2013-06-14 17:56:08179 const base::Value** result) const {
[email protected]f2456592014-07-22 19:30:17180 DCHECK(CalledOnValidThread());
181
thestig1433edb2015-08-06 21:45:27182 base::Value* tmp = nullptr;
[email protected]892f1d62012-11-08 18:24:34183 if (!prefs_->Get(key, &tmp))
184 return false;
185
186 if (result)
187 *result = tmp;
188 return true;
[email protected]f2d1f612010-12-09 15:10:17189}
190
191void JsonPrefStore::AddObserver(PrefStore::Observer* observer) {
[email protected]f2456592014-07-22 19:30:17192 DCHECK(CalledOnValidThread());
193
[email protected]f2d1f612010-12-09 15:10:17194 observers_.AddObserver(observer);
195}
196
197void JsonPrefStore::RemoveObserver(PrefStore::Observer* observer) {
[email protected]f2456592014-07-22 19:30:17198 DCHECK(CalledOnValidThread());
199
[email protected]f2d1f612010-12-09 15:10:17200 observers_.RemoveObserver(observer);
201}
202
[email protected]14e0ec62013-08-26 22:01:39203bool JsonPrefStore::HasObservers() const {
[email protected]f2456592014-07-22 19:30:17204 DCHECK(CalledOnValidThread());
205
[email protected]14e0ec62013-08-26 22:01:39206 return observers_.might_have_observers();
[email protected]d3b05ea2012-01-24 22:57:05207}
208
[email protected]845b43a82011-05-11 10:14:43209bool JsonPrefStore::IsInitializationComplete() const {
[email protected]f2456592014-07-22 19:30:17210 DCHECK(CalledOnValidThread());
211
[email protected]845b43a82011-05-11 10:14:43212 return initialized_;
213}
214
[email protected]892f1d62012-11-08 18:24:34215bool JsonPrefStore::GetMutableValue(const std::string& key,
[email protected]a43a667b2013-06-14 17:56:08216 base::Value** result) {
[email protected]f2456592014-07-22 19:30:17217 DCHECK(CalledOnValidThread());
218
[email protected]892f1d62012-11-08 18:24:34219 return prefs_->Get(key, result);
[email protected]68bf41a2011-03-25 16:38:31220}
221
raymes76de1af2015-05-06 03:22:21222void JsonPrefStore::SetValue(const std::string& key,
dcheng5f043bc2016-04-22 19:09:06223 std::unique_ptr<base::Value> value,
avi9ef8bb02015-12-24 05:29:36224 uint32_t flags) {
[email protected]f2456592014-07-22 19:30:17225 DCHECK(CalledOnValidThread());
226
[email protected]9b5f56b42011-08-24 21:17:59227 DCHECK(value);
thestig1433edb2015-08-06 21:45:27228 base::Value* old_value = nullptr;
[email protected]9b5f56b42011-08-24 21:17:59229 prefs_->Get(key, &old_value);
230 if (!old_value || !value->Equals(old_value)) {
danakj0c8d4aa2015-11-25 05:29:58231 prefs_->Set(key, std::move(value));
raymes76de1af2015-05-06 03:22:21232 ReportValueChanged(key, flags);
[email protected]9b5f56b42011-08-24 21:17:59233 }
[email protected]f2d1f612010-12-09 15:10:17234}
235
[email protected]a43a667b2013-06-14 17:56:08236void JsonPrefStore::SetValueSilently(const std::string& key,
dcheng5f043bc2016-04-22 19:09:06237 std::unique_ptr<base::Value> value,
avi9ef8bb02015-12-24 05:29:36238 uint32_t flags) {
[email protected]f2456592014-07-22 19:30:17239 DCHECK(CalledOnValidThread());
240
[email protected]9b5f56b42011-08-24 21:17:59241 DCHECK(value);
thestig1433edb2015-08-06 21:45:27242 base::Value* old_value = nullptr;
[email protected]9b5f56b42011-08-24 21:17:59243 prefs_->Get(key, &old_value);
[email protected]25308672011-10-10 17:22:50244 if (!old_value || !value->Equals(old_value)) {
danakj0c8d4aa2015-11-25 05:29:58245 prefs_->Set(key, std::move(value));
raymes4b6e14e2015-05-12 00:10:30246 ScheduleWrite(flags);
[email protected]25308672011-10-10 17:22:50247 }
[email protected]f2d1f612010-12-09 15:10:17248}
249
avi9ef8bb02015-12-24 05:29:36250void JsonPrefStore::RemoveValue(const std::string& key, uint32_t flags) {
[email protected]f2456592014-07-22 19:30:17251 DCHECK(CalledOnValidThread());
252
thestig1433edb2015-08-06 21:45:27253 if (prefs_->RemovePath(key, nullptr))
raymes76de1af2015-05-06 03:22:21254 ReportValueChanged(key, flags);
[email protected]f2d1f612010-12-09 15:10:17255}
256
avi9ef8bb02015-12-24 05:29:36257void JsonPrefStore::RemoveValueSilently(const std::string& key,
258 uint32_t flags) {
[email protected]f2456592014-07-22 19:30:17259 DCHECK(CalledOnValidThread());
260
thestig1433edb2015-08-06 21:45:27261 prefs_->RemovePath(key, nullptr);
raymes4b6e14e2015-05-12 00:10:30262 ScheduleWrite(flags);
[email protected]e33c9512014-05-12 02:24:13263}
264
[email protected]ddb1e5a2010-12-13 20:10:45265bool JsonPrefStore::ReadOnly() const {
[email protected]f2456592014-07-22 19:30:17266 DCHECK(CalledOnValidThread());
267
[email protected]ddb1e5a2010-12-13 20:10:45268 return read_only_;
269}
270
[email protected]59c10712012-03-13 02:10:34271PersistentPrefStore::PrefReadError JsonPrefStore::GetReadError() const {
[email protected]f2456592014-07-22 19:30:17272 DCHECK(CalledOnValidThread());
273
[email protected]59c10712012-03-13 02:10:34274 return read_error_;
275}
276
[email protected]7b2720b2012-04-25 16:59:11277PersistentPrefStore::PrefReadError JsonPrefStore::ReadPrefs() {
[email protected]f2456592014-07-22 19:30:17278 DCHECK(CalledOnValidThread());
279
[email protected]f2456592014-07-22 19:30:17280 OnFileRead(ReadPrefsFromDisk(path_, alternate_path_));
281 return filtering_in_progress_ ? PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE
282 : read_error_;
[email protected]7b2720b2012-04-25 16:59:11283}
284
[email protected]e33c9512014-05-12 02:24:13285void JsonPrefStore::ReadPrefsAsync(ReadErrorDelegate* error_delegate) {
[email protected]f2456592014-07-22 19:30:17286 DCHECK(CalledOnValidThread());
287
[email protected]7b2720b2012-04-25 16:59:11288 initialized_ = false;
289 error_delegate_.reset(error_delegate);
[email protected]7b2720b2012-04-25 16:59:11290
[email protected]3b268bc2014-07-28 17:43:15291 // Weakly binds the read task so that it doesn't kick in during shutdown.
[email protected]f2456592014-07-22 19:30:17292 base::PostTaskAndReplyWithResult(
dchengd81e7d72014-08-27 00:23:23293 sequenced_task_runner_.get(),
[email protected]f2456592014-07-22 19:30:17294 FROM_HERE,
295 base::Bind(&ReadPrefsFromDisk, path_, alternate_path_),
[email protected]3b268bc2014-07-28 17:43:15296 base::Bind(&JsonPrefStore::OnFileRead, AsWeakPtr()));
[email protected]7b2720b2012-04-25 16:59:11297}
298
299void JsonPrefStore::CommitPendingWrite() {
[email protected]f2456592014-07-22 19:30:17300 DCHECK(CalledOnValidThread());
301
raymes4b6e14e2015-05-12 00:10:30302 // Schedule a write for any lossy writes that are outstanding to ensure that
303 // they get flushed when this function is called.
benwells26730592015-05-28 13:08:08304 SchedulePendingLossyWrites();
raymes4b6e14e2015-05-12 00:10:30305
[email protected]7b2720b2012-04-25 16:59:11306 if (writer_.HasPendingWrite() && !read_only_)
307 writer_.DoScheduledWrite();
308}
309
benwells26730592015-05-28 13:08:08310void JsonPrefStore::SchedulePendingLossyWrites() {
311 if (pending_lossy_write_)
312 writer_.ScheduleWrite(this);
313}
314
avi9ef8bb02015-12-24 05:29:36315void JsonPrefStore::ReportValueChanged(const std::string& key, uint32_t flags) {
[email protected]f2456592014-07-22 19:30:17316 DCHECK(CalledOnValidThread());
317
[email protected]a0ce7e72014-01-21 16:50:56318 if (pref_filter_)
319 pref_filter_->FilterUpdate(key);
[email protected]56cbcb3a2013-12-23 21:24:46320
[email protected]7b2720b2012-04-25 16:59:11321 FOR_EACH_OBSERVER(PrefStore::Observer, observers_, OnPrefValueChanged(key));
[email protected]56cbcb3a2013-12-23 21:24:46322
raymes4b6e14e2015-05-12 00:10:30323 ScheduleWrite(flags);
[email protected]7b2720b2012-04-25 16:59:11324}
325
[email protected]e33c9512014-05-12 02:24:13326void JsonPrefStore::RegisterOnNextSuccessfulWriteCallback(
327 const base::Closure& on_next_successful_write) {
[email protected]f2456592014-07-22 19:30:17328 DCHECK(CalledOnValidThread());
329
[email protected]e33c9512014-05-12 02:24:13330 writer_.RegisterOnNextSuccessfulWriteCallback(on_next_successful_write);
331}
332
dvadym53fc0d42016-02-05 13:34:57333void JsonPrefStore::ClearMutableValues() {
334 NOTIMPLEMENTED();
335}
336
dcheng5f043bc2016-04-22 19:09:06337void JsonPrefStore::OnFileRead(std::unique_ptr<ReadResult> read_result) {
[email protected]f2456592014-07-22 19:30:17338 DCHECK(CalledOnValidThread());
339
340 DCHECK(read_result);
341
dcheng5f043bc2016-04-22 19:09:06342 std::unique_ptr<base::DictionaryValue> unfiltered_prefs(
343 new base::DictionaryValue);
[email protected]e33c9512014-05-12 02:24:13344
[email protected]f2456592014-07-22 19:30:17345 read_error_ = read_result->error;
[email protected]845b43a82011-05-11 10:14:43346
[email protected]f2456592014-07-22 19:30:17347 bool initialization_successful = !read_result->no_dir;
[email protected]e33c9512014-05-12 02:24:13348
349 if (initialization_successful) {
350 switch (read_error_) {
351 case PREF_READ_ERROR_ACCESS_DENIED:
352 case PREF_READ_ERROR_FILE_OTHER:
353 case PREF_READ_ERROR_FILE_LOCKED:
354 case PREF_READ_ERROR_JSON_TYPE:
355 case PREF_READ_ERROR_FILE_NOT_SPECIFIED:
356 read_only_ = true;
357 break;
358 case PREF_READ_ERROR_NONE:
[email protected]f2456592014-07-22 19:30:17359 DCHECK(read_result->value.get());
[email protected]e33c9512014-05-12 02:24:13360 unfiltered_prefs.reset(
[email protected]f2456592014-07-22 19:30:17361 static_cast<base::DictionaryValue*>(read_result->value.release()));
[email protected]e33c9512014-05-12 02:24:13362 break;
363 case PREF_READ_ERROR_NO_FILE:
364 // If the file just doesn't exist, maybe this is first run. In any case
365 // there's no harm in writing out default prefs in this case.
[email protected]e33c9512014-05-12 02:24:13366 case PREF_READ_ERROR_JSON_PARSE:
367 case PREF_READ_ERROR_JSON_REPEAT:
368 break;
369 case PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE:
370 // This is a special error code to be returned by ReadPrefs when it
371 // can't complete synchronously, it should never be returned by the read
372 // operation itself.
[email protected]e33c9512014-05-12 02:24:13373 case PREF_READ_ERROR_MAX_ENUM:
374 NOTREACHED();
375 break;
376 }
[email protected]845b43a82011-05-11 10:14:43377 }
378
[email protected]e33c9512014-05-12 02:24:13379 if (pref_filter_) {
380 filtering_in_progress_ = true;
381 const PrefFilter::PostFilterOnLoadCallback post_filter_on_load_callback(
382 base::Bind(
[email protected]3b268bc2014-07-28 17:43:15383 &JsonPrefStore::FinalizeFileRead, AsWeakPtr(),
384 initialization_successful));
[email protected]e33c9512014-05-12 02:24:13385 pref_filter_->FilterOnLoad(post_filter_on_load_callback,
danakj0c8d4aa2015-11-25 05:29:58386 std::move(unfiltered_prefs));
[email protected]e33c9512014-05-12 02:24:13387 } else {
danakj0c8d4aa2015-11-25 05:29:58388 FinalizeFileRead(initialization_successful, std::move(unfiltered_prefs),
389 false);
[email protected]844a1002011-04-19 11:37:21390 }
[email protected]844a1002011-04-19 11:37:21391}
392
[email protected]7b2720b2012-04-25 16:59:11393JsonPrefStore::~JsonPrefStore() {
394 CommitPendingWrite();
[email protected]f89ee342011-03-07 09:28:27395}
396
[email protected]277404c22010-04-22 13:09:45397bool JsonPrefStore::SerializeData(std::string* output) {
[email protected]f2456592014-07-22 19:30:17398 DCHECK(CalledOnValidThread());
399
raymes4b6e14e2015-05-12 00:10:30400 pending_lossy_write_ = false;
401
raymesbfb910a2015-04-29 07:43:09402 write_count_histogram_.RecordWriteOccured();
403
[email protected]bc831ff12014-01-31 20:48:33404 if (pref_filter_)
[email protected]a0ce7e72014-01-21 16:50:56405 pref_filter_->FilterSerializeData(prefs_.get());
406
[email protected]277404c22010-04-22 13:09:45407 JSONStringValueSerializer serializer(output);
gab97c50ac2015-03-06 20:41:43408 // Not pretty-printing prefs shrinks pref file size by ~30%. To obtain
409 // readable prefs for debugging purposes, you can dump your prefs into any
410 // command-line or online JSON pretty printing tool.
411 serializer.set_pretty_print(false);
gabf16b59a2015-01-31 19:09:02412 return serializer.Serialize(*prefs_);
[email protected]277404c22010-04-22 13:09:45413}
[email protected]e33c9512014-05-12 02:24:13414
dcheng5f043bc2016-04-22 19:09:06415void JsonPrefStore::FinalizeFileRead(
416 bool initialization_successful,
417 std::unique_ptr<base::DictionaryValue> prefs,
418 bool schedule_write) {
[email protected]f2456592014-07-22 19:30:17419 DCHECK(CalledOnValidThread());
420
[email protected]e33c9512014-05-12 02:24:13421 filtering_in_progress_ = false;
422
423 if (!initialization_successful) {
424 FOR_EACH_OBSERVER(PrefStore::Observer,
425 observers_,
426 OnInitializationCompleted(false));
427 return;
428 }
429
danakj0c8d4aa2015-11-25 05:29:58430 prefs_ = std::move(prefs);
[email protected]e33c9512014-05-12 02:24:13431
432 initialized_ = true;
433
raymes4b6e14e2015-05-12 00:10:30434 if (schedule_write)
435 ScheduleWrite(DEFAULT_PREF_WRITE_FLAGS);
[email protected]e33c9512014-05-12 02:24:13436
437 if (error_delegate_ && read_error_ != PREF_READ_ERROR_NONE)
438 error_delegate_->OnError(read_error_);
439
440 FOR_EACH_OBSERVER(PrefStore::Observer,
441 observers_,
442 OnInitializationCompleted(true));
443
444 return;
445}
raymesbfb910a2015-04-29 07:43:09446
avi9ef8bb02015-12-24 05:29:36447void JsonPrefStore::ScheduleWrite(uint32_t flags) {
raymes4b6e14e2015-05-12 00:10:30448 if (read_only_)
449 return;
450
451 if (flags & LOSSY_PREF_WRITE_FLAG)
452 pending_lossy_write_ = true;
453 else
454 writer_.ScheduleWrite(this);
455}
456
raymesbfb910a2015-04-29 07:43:09457// NOTE: This value should NOT be changed without renaming the histogram
458// otherwise it will create incompatible buckets.
459const int32_t
460 JsonPrefStore::WriteCountHistogram::kHistogramWriteReportIntervalMins = 5;
461
462JsonPrefStore::WriteCountHistogram::WriteCountHistogram(
463 const base::TimeDelta& commit_interval,
464 const base::FilePath& path)
dcheng5f043bc2016-04-22 19:09:06465 : WriteCountHistogram(
466 commit_interval,
467 path,
468 std::unique_ptr<base::Clock>(new base::DefaultClock)) {}
raymesbfb910a2015-04-29 07:43:09469
470JsonPrefStore::WriteCountHistogram::WriteCountHistogram(
471 const base::TimeDelta& commit_interval,
472 const base::FilePath& path,
dcheng5f043bc2016-04-22 19:09:06473 std::unique_ptr<base::Clock> clock)
raymesbfb910a2015-04-29 07:43:09474 : commit_interval_(commit_interval),
475 path_(path),
476 clock_(clock.release()),
477 report_interval_(
478 base::TimeDelta::FromMinutes(kHistogramWriteReportIntervalMins)),
479 last_report_time_(clock_->Now()),
dcheng5f043bc2016-04-22 19:09:06480 writes_since_last_report_(0) {}
raymesbfb910a2015-04-29 07:43:09481
482JsonPrefStore::WriteCountHistogram::~WriteCountHistogram() {
483 ReportOutstandingWrites();
484}
485
486void JsonPrefStore::WriteCountHistogram::RecordWriteOccured() {
487 ReportOutstandingWrites();
488
489 ++writes_since_last_report_;
490}
491
492void JsonPrefStore::WriteCountHistogram::ReportOutstandingWrites() {
493 base::Time current_time = clock_->Now();
494 base::TimeDelta time_since_last_report = current_time - last_report_time_;
495
496 if (time_since_last_report <= report_interval_)
497 return;
498
499 // If the time since the last report exceeds the report interval, report all
500 // the writes since the last report. They must have all occurred in the same
501 // report interval.
502 base::HistogramBase* histogram = GetHistogram();
503 histogram->Add(writes_since_last_report_);
504
505 // There may be several report intervals that elapsed that don't have any
506 // writes in them. Report these too.
avi9ef8bb02015-12-24 05:29:36507 int64_t total_num_intervals_elapsed =
raymesbfb910a2015-04-29 07:43:09508 (time_since_last_report / report_interval_);
avi9ef8bb02015-12-24 05:29:36509 for (int64_t i = 0; i < total_num_intervals_elapsed - 1; ++i)
raymesbfb910a2015-04-29 07:43:09510 histogram->Add(0);
511
512 writes_since_last_report_ = 0;
513 last_report_time_ += total_num_intervals_elapsed * report_interval_;
514}
515
516base::HistogramBase* JsonPrefStore::WriteCountHistogram::GetHistogram() {
517 std::string spaceless_basename;
518 base::ReplaceChars(path_.BaseName().MaybeAsASCII(), " ", "_",
519 &spaceless_basename);
520 std::string histogram_name =
521 "Settings.JsonDataWriteCount." + spaceless_basename;
522
523 // The min value for a histogram is 1. The max value is the maximum number of
524 // writes that can occur in the window being recorded. The number of buckets
525 // used is the max value (plus the underflow/overflow buckets).
526 int32_t min_value = 1;
527 int32_t max_value = report_interval_ / commit_interval_;
528 int32_t num_buckets = max_value + 1;
529
530 // NOTE: These values should NOT be changed without renaming the histogram
531 // otherwise it will create incompatible buckets.
532 DCHECK_EQ(30, max_value);
533 DCHECK_EQ(31, num_buckets);
534
535 // The histogram below is an expansion of the UMA_HISTOGRAM_CUSTOM_COUNTS
536 // macro adapted to allow for a dynamically suffixed histogram name.
537 // Note: The factory creates and owns the histogram.
538 base::HistogramBase* histogram = base::Histogram::FactoryGet(
539 histogram_name, min_value, max_value, num_buckets,
540 base::HistogramBase::kUmaTargetedHistogramFlag);
541 return histogram;
542}