Check USB device path access when prompting users to select a device.
[chromium-blink-merge.git] / chrome / browser / metrics / variations / variations_service.h
blob542ebcda16b99786c40be90d888a5dde7f7d17fc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CHROME_BROWSER_METRICS_VARIATIONS_VARIATIONS_SERVICE_H_
6 #define CHROME_BROWSER_METRICS_VARIATIONS_VARIATIONS_SERVICE_H_
8 #include <string>
10 #include "base/compiler_specific.h"
11 #include "base/gtest_prod_util.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/memory/weak_ptr.h"
14 #include "base/metrics/field_trial.h"
15 #include "base/observer_list.h"
16 #include "base/time/time.h"
17 #include "chrome/browser/metrics/variations/variations_request_scheduler.h"
18 #include "chrome/browser/metrics/variations/variations_seed_store.h"
19 #include "chrome/common/chrome_version_info.h"
20 #include "components/variations/variations_seed_simulator.h"
21 #include "components/web_resource/resource_request_allowed_notifier.h"
22 #include "net/url_request/url_fetcher_delegate.h"
23 #include "url/gurl.h"
25 #if defined(OS_WIN)
26 #include "chrome/browser/metrics/variations/variations_registry_syncer_win.h"
27 #endif
29 class PrefService;
30 class PrefRegistrySimple;
32 namespace base {
33 class Version;
36 namespace metrics {
37 class MetricsStateManager;
40 namespace user_prefs {
41 class PrefRegistrySyncable;
44 namespace variations {
45 class VariationsSeed;
48 namespace chrome_variations {
50 // Used to setup field trials based on stored variations seed data, and fetch
51 // new seed data from the variations server.
52 class VariationsService
53 : public net::URLFetcherDelegate,
54 public web_resource::ResourceRequestAllowedNotifier::Observer {
55 public:
56 class Observer {
57 public:
58 // How critical a detected experiment change is. Whether it should be
59 // handled on a "best-effort" basis or, for a more critical change, if it
60 // should be given higher priority.
61 enum Severity {
62 BEST_EFFORT,
63 CRITICAL,
66 // Called when the VariationsService detects that there will be significant
67 // experiment changes on a restart. This notification can then be used to
68 // update UI (i.e. badging an icon).
69 virtual void OnExperimentChangesDetected(Severity severity) = 0;
71 protected:
72 virtual ~Observer() {}
75 ~VariationsService() override;
77 // Creates field trials based on Variations Seed loaded from local prefs. If
78 // there is a problem loading the seed data, all trials specified by the seed
79 // may not be created.
80 bool CreateTrialsFromSeed();
82 // Calls FetchVariationsSeed once and repeats this periodically. See
83 // implementation for details on the period. Must be called after
84 // |CreateTrialsFromSeed|.
85 void StartRepeatedVariationsSeedFetch();
87 // Adds an observer to listen for detected experiment changes.
88 void AddObserver(Observer* observer);
90 // Removes a previously-added observer.
91 void RemoveObserver(Observer* observer);
93 // Called when the application enters foreground. This may trigger a
94 // FetchVariationsSeed call.
95 // TODO(rkaplow): Handle this and the similar event in metrics_service by
96 // observing an 'OnAppEnterForeground' event instead of requiring the frontend
97 // code to notify each service individually.
98 void OnAppEnterForeground();
100 #if defined(OS_WIN)
101 // Starts syncing Google Update Variation IDs with the registry.
102 void StartGoogleUpdateRegistrySync();
103 #endif
105 // Sets the value of the "restrict" URL param to the variations service that
106 // should be used for variation seed requests. This takes precedence over any
107 // value coming from policy prefs. This should be called prior to any calls
108 // to |StartRepeatedVariationsSeedFetch|.
109 void SetRestrictMode(const std::string& restrict_mode);
111 // Exposed for testing.
112 void SetCreateTrialsFromSeedCalledForTesting(bool called);
114 // Returns the variations server URL, which can vary if a command-line flag is
115 // set and/or the variations restrict pref is set in |local_prefs|. Declared
116 // static for test purposes.
117 static GURL GetVariationsServerURL(PrefService* local_prefs,
118 const std::string& restrict_mode_override);
120 // Exposed for testing.
121 static std::string GetDefaultVariationsServerURLForTesting();
123 // Register Variations related prefs in Local State.
124 static void RegisterPrefs(PrefRegistrySimple* registry);
126 // Register Variations related prefs in the Profile prefs.
127 static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
129 // Factory method for creating a VariationsService. Does not take ownership of
130 // |state_manager|. Caller should ensure that |state_manager| is valid for the
131 // lifetime of this class.
132 static scoped_ptr<VariationsService> Create(
133 PrefService* local_state,
134 metrics::MetricsStateManager* state_manager);
136 // Set the PrefService responsible for getting policy-related preferences,
137 // such as the restrict parameter.
138 void set_policy_pref_service(PrefService* service) {
139 DCHECK(service);
140 policy_pref_service_ = service;
143 // Returns the invalid variations seed signature in base64 format, or an empty
144 // string if the signature was valid, missing, or if signature verification is
145 // disabled.
146 std::string GetInvalidVariationsSeedSignature() const;
148 protected:
149 // Starts the fetching process once, where |OnURLFetchComplete| is called with
150 // the response.
151 virtual void DoActualFetch();
153 // Stores the seed to prefs. Set as virtual and protected so that it can be
154 // overridden by tests.
155 virtual void StoreSeed(const std::string& seed_data,
156 const std::string& seed_signature,
157 const base::Time& date_fetched);
159 // Creates the VariationsService with the given |local_state| prefs service
160 // and |state_manager|. This instance will take ownership of |notifier|.
161 // Does not take ownership of |state_manager|. Caller should ensure that
162 // |state_manager| is valid for the lifetime of this class. Use the |Create|
163 // factory method to create a VariationsService.
164 VariationsService(web_resource::ResourceRequestAllowedNotifier* notifier,
165 PrefService* local_state,
166 metrics::MetricsStateManager* state_manager);
168 private:
169 FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, Observer);
170 FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, SeedStoredWhenOKStatus);
171 FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, SeedNotStoredWhenNonOKStatus);
172 FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, SeedDateUpdatedOn304Status);
174 // Checks if prerequisites for fetching the Variations seed are met, and if
175 // so, performs the actual fetch using |DoActualFetch|.
176 void FetchVariationsSeed();
178 // Notify any observers of this service based on the simulation |result|.
179 void NotifyObservers(
180 const variations::VariationsSeedSimulator::Result& result);
182 // net::URLFetcherDelegate implementation:
183 void OnURLFetchComplete(const net::URLFetcher* source) override;
185 // ResourceRequestAllowedNotifier::Observer implementation:
186 void OnResourceRequestsAllowed() override;
188 // Performs a variations seed simulation with the given |seed| and |version|
189 // and logs the simulation results as histograms.
190 void PerformSimulationWithVersion(scoped_ptr<variations::VariationsSeed> seed,
191 const base::Version& version);
193 // Record the time of the most recent successful fetch.
194 void RecordLastFetchTime();
196 // The pref service used to store persist the variations seed.
197 PrefService* local_state_;
199 // Used for instantiating entropy providers for variations seed simulation.
200 // Weak pointer.
201 metrics::MetricsStateManager* state_manager_;
203 // Used to obtain policy-related preferences. Depending on the platform, will
204 // either be Local State or Profile prefs.
205 PrefService* policy_pref_service_;
207 VariationsSeedStore seed_store_;
209 // Contains the scheduler instance that handles timing for requests to the
210 // server. Initially NULL and instantiated when the initial fetch is
211 // requested.
212 scoped_ptr<VariationsRequestScheduler> request_scheduler_;
214 // Contains the current seed request. Will only have a value while a request
215 // is pending, and will be reset by |OnURLFetchComplete|.
216 scoped_ptr<net::URLFetcher> pending_seed_request_;
218 // The value of the "restrict" URL param to the variations server that has
219 // been specified via |SetRestrictMode|. If empty, the URL param will be set
220 // based on policy prefs.
221 std::string restrict_mode_;
223 // The URL to use for querying the variations server.
224 GURL variations_server_url_;
226 // Tracks whether |CreateTrialsFromSeed| has been called, to ensure that
227 // it gets called prior to |StartRepeatedVariationsSeedFetch|.
228 bool create_trials_from_seed_called_;
230 // Tracks whether the initial request to the variations server had completed.
231 bool initial_request_completed_;
233 // Helper class used to tell this service if it's allowed to make network
234 // resource requests.
235 scoped_ptr<web_resource::ResourceRequestAllowedNotifier>
236 resource_request_allowed_notifier_;
238 // The start time of the last seed request. This is used to measure the
239 // latency of seed requests. Initially zero.
240 base::TimeTicks last_request_started_time_;
242 // List of observers of the VariationsService.
243 ObserverList<Observer> observer_list_;
245 #if defined(OS_WIN)
246 // Helper that handles synchronizing Variations with the Registry.
247 VariationsRegistrySyncer registry_syncer_;
248 #endif
250 base::WeakPtrFactory<VariationsService> weak_ptr_factory_;
252 DISALLOW_COPY_AND_ASSIGN(VariationsService);
255 } // namespace chrome_variations
257 #endif // CHROME_BROWSER_METRICS_VARIATIONS_VARIATIONS_SERVICE_H_