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 #include "chrome/browser/metrics/variations/variations_service.h"
9 #include "base/build_time.h"
10 #include "base/command_line.h"
11 #include "base/metrics/histogram.h"
12 #include "base/metrics/sparse_histogram.h"
13 #include "base/prefs/pref_registry_simple.h"
14 #include "base/prefs/pref_service.h"
15 #include "base/version.h"
16 #include "chrome/browser/browser_process.h"
17 #include "chrome/browser/network_time/network_time_tracker.h"
18 #include "chrome/common/chrome_switches.h"
19 #include "chrome/common/pref_names.h"
20 #include "components/user_prefs/pref_registry_syncable.h"
21 #include "components/variations/proto/variations_seed.pb.h"
22 #include "components/variations/variations_seed_processor.h"
23 #include "content/public/browser/browser_thread.h"
24 #include "net/base/load_flags.h"
25 #include "net/base/net_errors.h"
26 #include "net/base/network_change_notifier.h"
27 #include "net/base/url_util.h"
28 #include "net/http/http_response_headers.h"
29 #include "net/http/http_status_code.h"
30 #include "net/http/http_util.h"
31 #include "net/url_request/url_fetcher.h"
32 #include "net/url_request/url_request_status.h"
33 #include "ui/base/device_form_factor.h"
36 #if defined(OS_CHROMEOS)
37 #include "chrome/browser/chromeos/settings/cros_settings.h"
40 namespace chrome_variations {
44 // Default server of Variations seed info.
45 const char kDefaultVariationsServerURL[] =
46 "https://clients4.google.com/chrome-variations/seed";
47 const int kMaxRetrySeedFetch = 5;
49 // TODO(mad): To be removed when we stop updating the NetworkTimeTracker.
50 // For the HTTP date headers, the resolution of the server time is 1 second.
51 const int64 kServerTimeResolutionMs = 1000;
53 // Wrapper around channel checking, used to enable channel mocking for
54 // testing. If the current browser channel is not UNKNOWN, this will return
55 // that channel value. Otherwise, if the fake channel flag is provided, this
56 // will return the fake channel. Failing that, this will return the UNKNOWN
58 Study_Channel GetChannelForVariations() {
59 switch (chrome::VersionInfo::GetChannel()) {
60 case chrome::VersionInfo::CHANNEL_CANARY:
61 return Study_Channel_CANARY;
62 case chrome::VersionInfo::CHANNEL_DEV:
63 return Study_Channel_DEV;
64 case chrome::VersionInfo::CHANNEL_BETA:
65 return Study_Channel_BETA;
66 case chrome::VersionInfo::CHANNEL_STABLE:
67 return Study_Channel_STABLE;
68 case chrome::VersionInfo::CHANNEL_UNKNOWN:
71 const std::string forced_channel =
72 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
73 switches::kFakeVariationsChannel);
74 if (forced_channel == "stable")
75 return Study_Channel_STABLE;
76 if (forced_channel == "beta")
77 return Study_Channel_BETA;
78 if (forced_channel == "dev")
79 return Study_Channel_DEV;
80 if (forced_channel == "canary")
81 return Study_Channel_CANARY;
82 DVLOG(1) << "Invalid channel provided: " << forced_channel;
83 return Study_Channel_UNKNOWN;
86 // Returns a string that will be used for the value of the 'osname' URL param
87 // to the variations server.
88 std::string GetPlatformString() {
93 #elif defined(OS_MACOSX)
95 #elif defined(OS_CHROMEOS)
97 #elif defined(OS_ANDROID)
99 #elif defined(OS_LINUX) || defined(OS_BSD) || defined(OS_SOLARIS)
100 // Default BSD and SOLARIS to Linux to not break those builds, although these
101 // platforms are not officially supported by Chrome.
104 #error Unknown platform
108 // Gets the restrict parameter from |policy_pref_service| or from Chrome OS
109 // settings in the case of that platform.
110 std::string GetRestrictParameterPref(PrefService* policy_pref_service) {
111 std::string parameter;
112 #if defined(OS_CHROMEOS)
113 chromeos::CrosSettings::Get()->GetString(
114 chromeos::kVariationsRestrictParameter, ¶meter);
116 if (policy_pref_service) {
118 policy_pref_service->GetString(prefs::kVariationsRestrictParameter);
124 enum ResourceRequestsAllowedState {
125 RESOURCE_REQUESTS_ALLOWED,
126 RESOURCE_REQUESTS_NOT_ALLOWED,
127 RESOURCE_REQUESTS_ALLOWED_NOTIFIED,
128 RESOURCE_REQUESTS_NOT_ALLOWED_EULA_NOT_ACCEPTED,
129 RESOURCE_REQUESTS_NOT_ALLOWED_NETWORK_DOWN,
130 RESOURCE_REQUESTS_NOT_ALLOWED_COMMAND_LINE_DISABLED,
131 RESOURCE_REQUESTS_ALLOWED_ENUM_SIZE,
134 // Records UMA histogram with the current resource requests allowed state.
135 void RecordRequestsAllowedHistogram(ResourceRequestsAllowedState state) {
136 UMA_HISTOGRAM_ENUMERATION("Variations.ResourceRequestsAllowed", state,
137 RESOURCE_REQUESTS_ALLOWED_ENUM_SIZE);
140 // Converts ResourceRequestAllowedNotifier::State to the corresponding
141 // ResourceRequestsAllowedState value.
142 ResourceRequestsAllowedState ResourceRequestStateToHistogramValue(
143 ResourceRequestAllowedNotifier::State state) {
145 case ResourceRequestAllowedNotifier::DISALLOWED_EULA_NOT_ACCEPTED:
146 return RESOURCE_REQUESTS_NOT_ALLOWED_EULA_NOT_ACCEPTED;
147 case ResourceRequestAllowedNotifier::DISALLOWED_NETWORK_DOWN:
148 return RESOURCE_REQUESTS_NOT_ALLOWED_NETWORK_DOWN;
149 case ResourceRequestAllowedNotifier::DISALLOWED_COMMAND_LINE_DISABLED:
150 return RESOURCE_REQUESTS_NOT_ALLOWED_COMMAND_LINE_DISABLED;
151 case ResourceRequestAllowedNotifier::ALLOWED:
152 return RESOURCE_REQUESTS_ALLOWED;
155 return RESOURCE_REQUESTS_NOT_ALLOWED;
159 // Get current form factor and convert it from enum DeviceFormFactor to enum
161 Study_FormFactor GetCurrentFormFactor() {
162 switch (ui::GetDeviceFormFactor()) {
163 case ui::DEVICE_FORM_FACTOR_PHONE:
164 return Study_FormFactor_PHONE;
165 case ui::DEVICE_FORM_FACTOR_TABLET:
166 return Study_FormFactor_TABLET;
167 case ui::DEVICE_FORM_FACTOR_DESKTOP:
168 return Study_FormFactor_DESKTOP;
171 return Study_FormFactor_DESKTOP;
176 VariationsService::VariationsService(PrefService* local_state)
177 : local_state_(local_state),
178 policy_pref_service_(local_state),
179 seed_store_(local_state),
180 create_trials_from_seed_called_(false),
181 initial_request_completed_(false),
182 resource_request_allowed_notifier_(
183 new ResourceRequestAllowedNotifier) {
184 resource_request_allowed_notifier_->Init(this);
187 VariationsService::VariationsService(ResourceRequestAllowedNotifier* notifier,
188 PrefService* local_state)
189 : local_state_(local_state),
190 policy_pref_service_(local_state),
191 seed_store_(local_state),
192 create_trials_from_seed_called_(false),
193 initial_request_completed_(false),
194 resource_request_allowed_notifier_(notifier) {
195 resource_request_allowed_notifier_->Init(this);
198 VariationsService::~VariationsService() {
201 bool VariationsService::CreateTrialsFromSeed() {
202 create_trials_from_seed_called_ = true;
205 if (!seed_store_.LoadSeed(&seed))
208 const int64 date_value = local_state_->GetInt64(prefs::kVariationsSeedDate);
209 const base::Time seed_date = base::Time::FromInternalValue(date_value);
210 const base::Time build_time = base::GetBuildTime();
211 // Use the build time for date checks if either the seed date is invalid or
212 // the build time is newer than the seed date.
213 base::Time reference_date = seed_date;
214 if (seed_date.is_null() || seed_date < build_time)
215 reference_date = build_time;
217 const chrome::VersionInfo current_version_info;
218 if (!current_version_info.is_valid())
221 const base::Version current_version(current_version_info.Version());
222 if (!current_version.IsValid())
225 VariationsSeedProcessor().CreateTrialsFromSeed(
226 seed, g_browser_process->GetApplicationLocale(), reference_date,
227 current_version, GetChannelForVariations(), GetCurrentFormFactor());
229 // Log the "freshness" of the seed that was just used. The freshness is the
230 // time between the last successful seed download and now.
231 const int64 last_fetch_time_internal =
232 local_state_->GetInt64(prefs::kVariationsLastFetchTime);
233 if (last_fetch_time_internal) {
234 const base::Time now = base::Time::Now();
235 const base::TimeDelta delta =
236 now - base::Time::FromInternalValue(last_fetch_time_internal);
237 // Log the value in number of minutes.
238 UMA_HISTOGRAM_CUSTOM_COUNTS("Variations.SeedFreshness", delta.InMinutes(),
239 1, base::TimeDelta::FromDays(30).InMinutes(), 50);
245 void VariationsService::StartRepeatedVariationsSeedFetch() {
246 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
248 // Initialize the Variations server URL.
249 variations_server_url_ = GetVariationsServerURL(policy_pref_service_);
251 // Check that |CreateTrialsFromSeed| was called, which is necessary to
252 // retrieve the serial number that will be sent to the server.
253 DCHECK(create_trials_from_seed_called_);
255 DCHECK(!request_scheduler_.get());
256 // Note that the act of instantiating the scheduler will start the fetch, if
257 // the scheduler deems appropriate. Using Unretained is fine here since the
258 // lifespan of request_scheduler_ is guaranteed to be shorter than that of
260 request_scheduler_.reset(VariationsRequestScheduler::Create(
261 base::Bind(&VariationsService::FetchVariationsSeed,
262 base::Unretained(this)), local_state_));
263 request_scheduler_->Start();
266 // TODO(rkaplow): Handle this and the similar event in metrics_service by
267 // observing an 'OnAppEnterForeground' event in RequestScheduler instead of
268 // requiring the frontend code to notify each service individually. Since the
269 // scheduler will handle it directly the VariationService shouldn't need to
270 // know details of this anymore.
271 void VariationsService::OnAppEnterForeground() {
272 request_scheduler_->OnAppEnterForeground();
276 GURL VariationsService::GetVariationsServerURL(
277 PrefService* policy_pref_service) {
278 std::string server_url_string(CommandLine::ForCurrentProcess()->
279 GetSwitchValueASCII(switches::kVariationsServerURL));
280 if (server_url_string.empty())
281 server_url_string = kDefaultVariationsServerURL;
282 GURL server_url = GURL(server_url_string);
284 const std::string restrict_param =
285 GetRestrictParameterPref(policy_pref_service);
286 if (!restrict_param.empty()) {
287 server_url = net::AppendOrReplaceQueryParameter(server_url,
292 server_url = net::AppendOrReplaceQueryParameter(server_url, "osname",
293 GetPlatformString());
295 DCHECK(server_url.is_valid());
300 void VariationsService::StartGoogleUpdateRegistrySync() {
301 registry_syncer_.RequestRegistrySync();
305 void VariationsService::SetCreateTrialsFromSeedCalledForTesting(bool called) {
306 create_trials_from_seed_called_ = called;
310 std::string VariationsService::GetDefaultVariationsServerURLForTesting() {
311 return kDefaultVariationsServerURL;
315 void VariationsService::RegisterPrefs(PrefRegistrySimple* registry) {
316 VariationsSeedStore::RegisterPrefs(registry);
317 registry->RegisterInt64Pref(prefs::kVariationsLastFetchTime, 0);
318 // This preference will only be written by the policy service, which will fill
319 // it according to a value stored in the User Policy.
320 registry->RegisterStringPref(prefs::kVariationsRestrictParameter,
325 void VariationsService::RegisterProfilePrefs(
326 user_prefs::PrefRegistrySyncable* registry) {
327 // This preference will only be written by the policy service, which will fill
328 // it according to a value stored in the User Policy.
329 registry->RegisterStringPref(
330 prefs::kVariationsRestrictParameter,
332 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
336 VariationsService* VariationsService::Create(PrefService* local_state) {
337 #if !defined(GOOGLE_CHROME_BUILD)
338 // Unless the URL was provided, unsupported builds should return NULL to
339 // indicate that the service should not be used.
340 if (!CommandLine::ForCurrentProcess()->HasSwitch(
341 switches::kVariationsServerURL)) {
342 DVLOG(1) << "Not creating VariationsService in unofficial build without --"
343 << switches::kVariationsServerURL << " specified.";
347 return new VariationsService(local_state);
350 void VariationsService::DoActualFetch() {
351 pending_seed_request_.reset(net::URLFetcher::Create(
352 0, variations_server_url_, net::URLFetcher::GET, this));
353 pending_seed_request_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
354 net::LOAD_DO_NOT_SAVE_COOKIES);
355 pending_seed_request_->SetRequestContext(
356 g_browser_process->system_request_context());
357 pending_seed_request_->SetMaxRetriesOn5xx(kMaxRetrySeedFetch);
358 if (!seed_store_.variations_serial_number().empty()) {
359 pending_seed_request_->AddExtraRequestHeader(
360 "If-Match:" + seed_store_.variations_serial_number());
362 pending_seed_request_->Start();
364 const base::TimeTicks now = base::TimeTicks::Now();
365 base::TimeDelta time_since_last_fetch;
366 // Record a time delta of 0 (default value) if there was no previous fetch.
367 if (!last_request_started_time_.is_null())
368 time_since_last_fetch = now - last_request_started_time_;
369 UMA_HISTOGRAM_CUSTOM_COUNTS("Variations.TimeSinceLastFetchAttempt",
370 time_since_last_fetch.InMinutes(), 0,
371 base::TimeDelta::FromDays(7).InMinutes(), 50);
372 last_request_started_time_ = now;
375 void VariationsService::FetchVariationsSeed() {
376 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
378 const ResourceRequestAllowedNotifier::State state =
379 resource_request_allowed_notifier_->GetResourceRequestsAllowedState();
380 RecordRequestsAllowedHistogram(ResourceRequestStateToHistogramValue(state));
381 if (state != ResourceRequestAllowedNotifier::ALLOWED) {
382 DVLOG(1) << "Resource requests were not allowed. Waiting for notification.";
389 void VariationsService::OnURLFetchComplete(const net::URLFetcher* source) {
390 DCHECK_EQ(pending_seed_request_.get(), source);
392 const bool is_first_request = !initial_request_completed_;
393 initial_request_completed_ = true;
395 // The fetcher will be deleted when the request is handled.
396 scoped_ptr<const net::URLFetcher> request(pending_seed_request_.release());
397 const net::URLRequestStatus& request_status = request->GetStatus();
398 if (request_status.status() != net::URLRequestStatus::SUCCESS) {
399 UMA_HISTOGRAM_SPARSE_SLOWLY("Variations.FailedRequestErrorCode",
400 -request_status.error());
401 DVLOG(1) << "Variations server request failed with error: "
402 << request_status.error() << ": "
403 << net::ErrorToString(request_status.error());
404 // It's common for the very first fetch attempt to fail (e.g. the network
405 // may not yet be available). In such a case, try again soon, rather than
406 // waiting the full time interval.
407 if (is_first_request)
408 request_scheduler_->ScheduleFetchShortly();
412 // Log the response code.
413 const int response_code = request->GetResponseCode();
414 UMA_HISTOGRAM_SPARSE_SLOWLY("Variations.SeedFetchResponseCode",
417 const base::TimeDelta latency =
418 base::TimeTicks::Now() - last_request_started_time_;
420 base::Time response_date;
421 if (response_code == net::HTTP_OK ||
422 response_code == net::HTTP_NOT_MODIFIED) {
423 bool success = request->GetResponseHeaders()->GetDateValue(&response_date);
424 DCHECK(success || response_date.is_null());
426 if (!response_date.is_null()) {
427 NetworkTimeTracker::BuildNotifierUpdateCallback().Run(
429 base::TimeDelta::FromMilliseconds(kServerTimeResolutionMs),
434 if (response_code != net::HTTP_OK) {
435 DVLOG(1) << "Variations server request returned non-HTTP_OK response code: "
437 if (response_code == net::HTTP_NOT_MODIFIED) {
438 UMA_HISTOGRAM_MEDIUM_TIMES("Variations.FetchNotModifiedLatency", latency);
439 RecordLastFetchTime();
440 // Update the seed date value in local state (used for expiry check on
441 // next start up), since 304 is a successful response.
442 local_state_->SetInt64(prefs::kVariationsSeedDate,
443 response_date.ToInternalValue());
445 UMA_HISTOGRAM_MEDIUM_TIMES("Variations.FetchOtherLatency", latency);
449 UMA_HISTOGRAM_MEDIUM_TIMES("Variations.FetchSuccessLatency", latency);
451 std::string seed_data;
452 bool success = request->GetResponseAsString(&seed_data);
455 std::string seed_signature;
456 request->GetResponseHeaders()->EnumerateHeader(NULL,
459 if (seed_store_.StoreSeedData(seed_data, seed_signature, response_date))
460 RecordLastFetchTime();
463 void VariationsService::OnResourceRequestsAllowed() {
464 // Note that this only attempts to fetch the seed at most once per period
465 // (kSeedFetchPeriodHours). This works because
466 // |resource_request_allowed_notifier_| only calls this method if an
467 // attempt was made earlier that fails (which implies that the period had
468 // elapsed). After a successful attempt is made, the notifier will know not
469 // to call this method again until another failed attempt occurs.
470 RecordRequestsAllowedHistogram(RESOURCE_REQUESTS_ALLOWED_NOTIFIED);
471 DVLOG(1) << "Retrying fetch.";
474 // This service must have created a scheduler in order for this to be called.
475 DCHECK(request_scheduler_.get());
476 request_scheduler_->Reset();
479 void VariationsService::RecordLastFetchTime() {
480 // local_state_ is NULL in tests, so check it first.
482 local_state_->SetInt64(prefs::kVariationsLastFetchTime,
483 base::Time::Now().ToInternalValue());
487 } // namespace chrome_variations