cronet_prefs_manager.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. // Copyright 2017 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. #include "components/cronet/cronet_prefs_manager.h"
  5. #include <memory>
  6. #include "base/bind.h"
  7. #include "base/callback.h"
  8. #include "base/files/file_path.h"
  9. #include "base/files/file_util.h"
  10. #include "base/location.h"
  11. #include "base/memory/raw_ptr.h"
  12. #include "base/metrics/histogram_macros.h"
  13. #include "base/threading/sequenced_task_runner_handle.h"
  14. #include "base/threading/thread_restrictions.h"
  15. #include "base/threading/thread_task_runner_handle.h"
  16. #include "base/time/time.h"
  17. #include "build/build_config.h"
  18. #include "components/cronet/host_cache_persistence_manager.h"
  19. #include "components/prefs/json_pref_store.h"
  20. #include "components/prefs/pref_change_registrar.h"
  21. #include "components/prefs/pref_registry_simple.h"
  22. #include "components/prefs/pref_service.h"
  23. #include "components/prefs/pref_service_factory.h"
  24. #include "net/http/http_server_properties.h"
  25. #include "net/nqe/network_qualities_prefs_manager.h"
  26. #include "net/url_request/url_request_context_builder.h"
  27. namespace cronet {
  28. namespace {
  29. // Name of the pref used for HTTP server properties persistence.
  30. const char kHttpServerPropertiesPref[] = "net.http_server_properties";
  31. // Name of preference directory.
  32. const base::FilePath::CharType kPrefsDirectoryName[] =
  33. FILE_PATH_LITERAL("prefs");
  34. // Name of preference file.
  35. const base::FilePath::CharType kPrefsFileName[] =
  36. FILE_PATH_LITERAL("local_prefs.json");
  37. // Current version of disk storage.
  38. const int32_t kStorageVersion = 1;
  39. // Version number used when the version of disk storage is unknown.
  40. const uint32_t kStorageVersionUnknown = 0;
  41. // Name of the pref used for host cache persistence.
  42. const char kHostCachePref[] = "net.host_cache";
  43. // Name of the pref used for NQE persistence.
  44. const char kNetworkQualitiesPref[] = "net.network_qualities";
  45. bool IsCurrentVersion(const base::FilePath& version_filepath) {
  46. if (!base::PathExists(version_filepath))
  47. return false;
  48. base::File version_file(version_filepath,
  49. base::File::FLAG_OPEN | base::File::FLAG_READ);
  50. uint32_t version = kStorageVersionUnknown;
  51. int bytes_read =
  52. version_file.Read(0, reinterpret_cast<char*>(&version), sizeof(version));
  53. if (bytes_read != sizeof(version)) {
  54. DLOG(WARNING) << "Cannot read from version file.";
  55. return false;
  56. }
  57. return version == kStorageVersion;
  58. }
  59. // TODO(xunjieli): Handle failures.
  60. void InitializeStorageDirectory(const base::FilePath& dir) {
  61. // Checks version file and clear old storage.
  62. base::FilePath version_filepath(dir.AppendASCII("version"));
  63. if (IsCurrentVersion(version_filepath)) {
  64. // The version is up to date, so there is nothing to do.
  65. return;
  66. }
  67. // Delete old directory recursively and create a new directory.
  68. // base::DeletePathRecursively() returns true if the directory does not exist,
  69. // so it is fine if there is nothing on disk.
  70. if (!(base::DeletePathRecursively(dir) && base::CreateDirectory(dir))) {
  71. DLOG(WARNING) << "Cannot purge directory.";
  72. return;
  73. }
  74. base::File new_version_file(version_filepath, base::File::FLAG_CREATE_ALWAYS |
  75. base::File::FLAG_WRITE);
  76. if (!new_version_file.IsValid()) {
  77. DLOG(WARNING) << "Cannot create a version file.";
  78. return;
  79. }
  80. DCHECK(new_version_file.created());
  81. uint32_t new_version = kStorageVersion;
  82. int bytes_written = new_version_file.Write(
  83. 0, reinterpret_cast<char*>(&new_version), sizeof(new_version));
  84. if (bytes_written != sizeof(new_version)) {
  85. DLOG(WARNING) << "Cannot write to version file.";
  86. return;
  87. }
  88. base::FilePath prefs_dir = dir.Append(kPrefsDirectoryName);
  89. if (!base::CreateDirectory(prefs_dir)) {
  90. DLOG(WARNING) << "Cannot create prefs directory";
  91. return;
  92. }
  93. }
  94. // Connects the HttpServerProperties's storage to the prefs.
  95. class PrefServiceAdapter : public net::HttpServerProperties::PrefDelegate {
  96. public:
  97. explicit PrefServiceAdapter(PrefService* pref_service)
  98. : pref_service_(pref_service), path_(kHttpServerPropertiesPref) {
  99. pref_change_registrar_.Init(pref_service_);
  100. }
  101. PrefServiceAdapter(const PrefServiceAdapter&) = delete;
  102. PrefServiceAdapter& operator=(const PrefServiceAdapter&) = delete;
  103. ~PrefServiceAdapter() override {}
  104. // PrefDelegate implementation.
  105. const base::Value* GetServerProperties() const override {
  106. return &pref_service_->GetValue(path_);
  107. }
  108. void SetServerProperties(const base::Value& value,
  109. base::OnceClosure callback) override {
  110. pref_service_->Set(path_, value);
  111. if (callback)
  112. pref_service_->CommitPendingWrite(std::move(callback));
  113. }
  114. void WaitForPrefLoad(base::OnceClosure callback) override {
  115. // Notify the pref manager that settings are already loaded, as a result
  116. // of initializing the pref store synchronously.
  117. base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE,
  118. std::move(callback));
  119. }
  120. private:
  121. raw_ptr<PrefService> pref_service_;
  122. const std::string path_;
  123. PrefChangeRegistrar pref_change_registrar_;
  124. }; // class PrefServiceAdapter
  125. class NetworkQualitiesPrefDelegateImpl
  126. : public net::NetworkQualitiesPrefsManager::PrefDelegate {
  127. public:
  128. // Caller must guarantee that |pref_service| outlives |this|.
  129. explicit NetworkQualitiesPrefDelegateImpl(PrefService* pref_service)
  130. : pref_service_(pref_service), lossy_prefs_writing_task_posted_(false) {
  131. DCHECK(pref_service_);
  132. }
  133. NetworkQualitiesPrefDelegateImpl(const NetworkQualitiesPrefDelegateImpl&) =
  134. delete;
  135. NetworkQualitiesPrefDelegateImpl& operator=(
  136. const NetworkQualitiesPrefDelegateImpl&) = delete;
  137. ~NetworkQualitiesPrefDelegateImpl() override {}
  138. // net::NetworkQualitiesPrefsManager::PrefDelegate implementation.
  139. void SetDictionaryValue(const base::Value::Dict& dict) override {
  140. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  141. pref_service_->SetDict(kNetworkQualitiesPref, dict.Clone());
  142. if (lossy_prefs_writing_task_posted_)
  143. return;
  144. // Post the task that schedules the writing of the lossy prefs.
  145. lossy_prefs_writing_task_posted_ = true;
  146. // Delay after which the task that schedules the writing of the lossy prefs.
  147. // This is needed in case the writing of the lossy prefs is not scheduled
  148. // automatically. The delay was chosen so that it is large enough that it
  149. // does not affect the startup performance.
  150. static const int32_t kUpdatePrefsDelaySeconds = 10;
  151. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  152. FROM_HERE,
  153. base::BindOnce(
  154. &NetworkQualitiesPrefDelegateImpl::SchedulePendingLossyWrites,
  155. weak_ptr_factory_.GetWeakPtr()),
  156. base::Seconds(kUpdatePrefsDelaySeconds));
  157. }
  158. base::Value::Dict GetDictionaryValue() override {
  159. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  160. UMA_HISTOGRAM_EXACT_LINEAR("NQE.Prefs.ReadCount", 1, 2);
  161. return pref_service_->GetValueDict(kNetworkQualitiesPref).Clone();
  162. }
  163. private:
  164. // Schedules the writing of the lossy prefs.
  165. void SchedulePendingLossyWrites() {
  166. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  167. UMA_HISTOGRAM_EXACT_LINEAR("NQE.Prefs.WriteCount", 1, 2);
  168. pref_service_->SchedulePendingLossyWrites();
  169. lossy_prefs_writing_task_posted_ = false;
  170. }
  171. raw_ptr<PrefService> pref_service_;
  172. // True if the task that schedules the writing of the lossy prefs has been
  173. // posted.
  174. bool lossy_prefs_writing_task_posted_;
  175. THREAD_CHECKER(thread_checker_);
  176. base::WeakPtrFactory<NetworkQualitiesPrefDelegateImpl> weak_ptr_factory_{
  177. this};
  178. };
  179. } // namespace
  180. CronetPrefsManager::CronetPrefsManager(
  181. const std::string& storage_path,
  182. scoped_refptr<base::SingleThreadTaskRunner> network_task_runner,
  183. scoped_refptr<base::SequencedTaskRunner> file_task_runner,
  184. bool enable_network_quality_estimator,
  185. bool enable_host_cache_persistence,
  186. net::NetLog* net_log,
  187. net::URLRequestContextBuilder* context_builder) {
  188. DCHECK(network_task_runner->BelongsToCurrentThread());
  189. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  190. #if BUILDFLAG(IS_WIN)
  191. base::FilePath storage_file_path(
  192. base::FilePath::FromUTF8Unsafe(storage_path));
  193. #else
  194. base::FilePath storage_file_path(storage_path);
  195. #endif
  196. // Make sure storage directory has correct version.
  197. {
  198. base::ScopedAllowBlocking allow_blocking;
  199. InitializeStorageDirectory(storage_file_path);
  200. }
  201. base::FilePath filepath =
  202. storage_file_path.Append(kPrefsDirectoryName).Append(kPrefsFileName);
  203. json_pref_store_ = new JsonPrefStore(filepath, std::unique_ptr<PrefFilter>(),
  204. file_task_runner);
  205. // Register prefs and set up the PrefService.
  206. PrefServiceFactory factory;
  207. factory.set_user_prefs(json_pref_store_);
  208. scoped_refptr<PrefRegistrySimple> registry(new PrefRegistrySimple());
  209. registry->RegisterDictionaryPref(kHttpServerPropertiesPref);
  210. if (enable_network_quality_estimator) {
  211. // Use lossy prefs to limit the overhead of reading/writing the prefs.
  212. registry->RegisterDictionaryPref(kNetworkQualitiesPref,
  213. PrefRegistry::LOSSY_PREF);
  214. }
  215. if (enable_host_cache_persistence) {
  216. registry->RegisterListPref(kHostCachePref);
  217. }
  218. {
  219. base::ScopedAllowBlocking allow_blocking;
  220. pref_service_ = factory.Create(registry.get());
  221. }
  222. context_builder->SetHttpServerProperties(
  223. std::make_unique<net::HttpServerProperties>(
  224. std::make_unique<PrefServiceAdapter>(pref_service_.get()), net_log));
  225. }
  226. CronetPrefsManager::~CronetPrefsManager() {
  227. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  228. }
  229. void CronetPrefsManager::SetupNqePersistence(
  230. net::NetworkQualityEstimator* nqe) {
  231. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  232. network_qualities_prefs_manager_ =
  233. std::make_unique<net::NetworkQualitiesPrefsManager>(
  234. std::make_unique<NetworkQualitiesPrefDelegateImpl>(
  235. pref_service_.get()));
  236. network_qualities_prefs_manager_->InitializeOnNetworkThread(nqe);
  237. }
  238. void CronetPrefsManager::SetupHostCachePersistence(
  239. net::HostCache* host_cache,
  240. int host_cache_persistence_delay_ms,
  241. net::NetLog* net_log) {
  242. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  243. host_cache_persistence_manager_ =
  244. std::make_unique<HostCachePersistenceManager>(
  245. host_cache, pref_service_.get(), kHostCachePref,
  246. base::Milliseconds(host_cache_persistence_delay_ms), net_log);
  247. }
  248. void CronetPrefsManager::PrepareForShutdown() {
  249. DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  250. if (pref_service_)
  251. pref_service_->CommitPendingWrite();
  252. // Shutdown managers on the Pref sequence.
  253. if (network_qualities_prefs_manager_)
  254. network_qualities_prefs_manager_->ShutdownOnPrefSequence();
  255. host_cache_persistence_manager_.reset();
  256. }
  257. } // namespace cronet