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/sys_info.h"
16 #include "base/task_runner_util.h"
17 #include "base/timer/elapsed_timer.h"
18 #include "base/version.h"
19 #include "chrome/browser/browser_process.h"
20 #include "chrome/browser/metrics/variations/generated_resources_map.h"
21 #include "chrome/common/chrome_switches.h"
22 #include "chrome/common/pref_names.h"
23 #include "components/metrics/metrics_state_manager.h"
24 #include "components/network_time/network_time_tracker.h"
25 #include "components/pref_registry/pref_registry_syncable.h"
26 #include "components/variations/proto/variations_seed.pb.h"
27 #include "components/variations/variations_seed_processor.h"
28 #include "components/variations/variations_seed_simulator.h"
29 #include "content/public/browser/browser_thread.h"
30 #include "net/base/load_flags.h"
31 #include "net/base/net_errors.h"
32 #include "net/base/network_change_notifier.h"
33 #include "net/base/url_util.h"
34 #include "net/http/http_response_headers.h"
35 #include "net/http/http_status_code.h"
36 #include "net/http/http_util.h"
37 #include "net/url_request/url_fetcher.h"
38 #include "net/url_request/url_request_status.h"
39 #include "ui/base/device_form_factor.h"
40 #include "ui/base/resource/resource_bundle.h"
43 #if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_CHROMEOS)
44 #include "chrome/browser/upgrade_detector_impl.h"
47 #if defined(OS_CHROMEOS)
48 #include "chrome/browser/chromeos/settings/cros_settings.h"
51 namespace chrome_variations {
55 // Default server of Variations seed info.
56 const char kDefaultVariationsServerURL[] =
57 "https://clients4.google.com/chrome-variations/seed";
58 const int kMaxRetrySeedFetch = 5;
60 // TODO(mad): To be removed when we stop updating the NetworkTimeTracker.
61 // For the HTTP date headers, the resolution of the server time is 1 second.
62 const int64 kServerTimeResolutionMs = 1000;
64 // Name of the field trial to control which experiments Canary users use.
65 const char kChannelOverrideTrialName[] = "UMA-Variations-ChannelOverride";
66 // This is the default behavior.
67 const char kNoOverrideGroupName[] = "NoOverride";
68 // Users in this group get Stable variation configs.
69 const char kStableOverrideGroupName[] = "StableOverride";
70 // Users in this group do not create any field trials from variation configs.
71 const char kNoExperimentsGroupName[] = "NoExperiments";
73 // Creates a field trial the first time it's called to control how Canary will
74 // evaluate experiment configs, to determine impact on stability. Currently,
75 // this makes 50% of Canary users not use server side experiments. The field
76 // trial is set up in the client code because it has to run before server-side
77 // configs are processed.
78 void CreateChannelOverrideFieldTrial() {
79 static bool created = false;
81 scoped_refptr<base::FieldTrial> trial(
82 base::FieldTrialList::FactoryGetFieldTrial(
83 kChannelOverrideTrialName, 100, kNoOverrideGroupName, 2015, 1, 1,
84 base::FieldTrial::SESSION_RANDOMIZED, NULL));
85 // Currently, experimenting with 50% no experiments and 50% default, with
86 // the |kStableOverrideGroupName| intentionally at 0 for now.
87 trial->AppendGroup(kStableOverrideGroupName, 0);
88 trial->AppendGroup(kNoExperimentsGroupName, 50);
93 // Returns the group name of the channel override field trial.
94 std::string GetChannelOverrideFieldTrialGroup() {
95 return base::FieldTrialList::FindFullName(kChannelOverrideTrialName);
98 // Whether field trials should be created from server configs.
99 bool ShouldCreateServerTrials() {
100 // Always use server trials if not on Canary.
101 if (chrome::VersionInfo::GetChannel() != chrome::VersionInfo::CHANNEL_CANARY)
103 // On Canary, use server trials unless in |kNoExperimentsGroupName| group.
104 CreateChannelOverrideFieldTrial();
105 return GetChannelOverrideFieldTrialGroup() != kNoExperimentsGroupName;
108 // Returns the channel that should be on for evaluating variation configs when
109 // running the Canary version, based on an experiment.
110 variations::Study_Channel GetOverrideCanaryChannel() {
111 CreateChannelOverrideFieldTrial();
112 if (GetChannelOverrideFieldTrialGroup() == kStableOverrideGroupName)
113 return variations::Study_Channel_STABLE;
114 return variations::Study_Channel_CANARY;
117 // Wrapper around channel checking, used to enable channel mocking for
118 // testing. If the current browser channel is not UNKNOWN, this will return
119 // that channel value. Otherwise, if the fake channel flag is provided, this
120 // will return the fake channel. Failing that, this will return the UNKNOWN
122 variations::Study_Channel GetChannelForVariations() {
123 switch (chrome::VersionInfo::GetChannel()) {
124 case chrome::VersionInfo::CHANNEL_CANARY:
125 return GetOverrideCanaryChannel();
126 case chrome::VersionInfo::CHANNEL_DEV:
127 return variations::Study_Channel_DEV;
128 case chrome::VersionInfo::CHANNEL_BETA:
129 return variations::Study_Channel_BETA;
130 case chrome::VersionInfo::CHANNEL_STABLE:
131 return variations::Study_Channel_STABLE;
132 case chrome::VersionInfo::CHANNEL_UNKNOWN:
135 const std::string forced_channel =
136 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
137 switches::kFakeVariationsChannel);
138 if (forced_channel == "stable")
139 return variations::Study_Channel_STABLE;
140 if (forced_channel == "beta")
141 return variations::Study_Channel_BETA;
142 if (forced_channel == "dev")
143 return variations::Study_Channel_DEV;
144 if (forced_channel == "canary")
145 return variations::Study_Channel_CANARY;
146 DVLOG(1) << "Invalid channel provided: " << forced_channel;
147 return variations::Study_Channel_UNKNOWN;
150 // Returns a string that will be used for the value of the 'osname' URL param
151 // to the variations server.
152 std::string GetPlatformString() {
155 #elif defined(OS_IOS)
157 #elif defined(OS_MACOSX)
159 #elif defined(OS_CHROMEOS)
161 #elif defined(OS_ANDROID)
163 #elif defined(OS_LINUX) || defined(OS_BSD) || defined(OS_SOLARIS)
164 // Default BSD and SOLARIS to Linux to not break those builds, although these
165 // platforms are not officially supported by Chrome.
168 #error Unknown platform
172 // Gets the version number to use for variations seed simulation. Must be called
173 // on a thread where IO is allowed.
174 base::Version GetVersionForSimulation() {
175 #if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_CHROMEOS)
176 const base::Version installed_version =
177 UpgradeDetectorImpl::GetCurrentlyInstalledVersion();
178 if (installed_version.IsValid())
179 return installed_version;
180 #endif // !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_CHROMEOS)
182 // TODO(asvitkine): Get the version that will be used on restart instead of
183 // the current version on Android, iOS and ChromeOS.
184 return base::Version(chrome::VersionInfo().Version());
187 // Gets the restrict parameter from |policy_pref_service| or from Chrome OS
188 // settings in the case of that platform.
189 std::string GetRestrictParameterPref(PrefService* policy_pref_service) {
190 std::string parameter;
191 #if defined(OS_CHROMEOS)
192 chromeos::CrosSettings::Get()->GetString(
193 chromeos::kVariationsRestrictParameter, ¶meter);
195 if (policy_pref_service) {
197 policy_pref_service->GetString(prefs::kVariationsRestrictParameter);
203 enum ResourceRequestsAllowedState {
204 RESOURCE_REQUESTS_ALLOWED,
205 RESOURCE_REQUESTS_NOT_ALLOWED,
206 RESOURCE_REQUESTS_ALLOWED_NOTIFIED,
207 RESOURCE_REQUESTS_NOT_ALLOWED_EULA_NOT_ACCEPTED,
208 RESOURCE_REQUESTS_NOT_ALLOWED_NETWORK_DOWN,
209 RESOURCE_REQUESTS_NOT_ALLOWED_COMMAND_LINE_DISABLED,
210 RESOURCE_REQUESTS_ALLOWED_ENUM_SIZE,
213 // Records UMA histogram with the current resource requests allowed state.
214 void RecordRequestsAllowedHistogram(ResourceRequestsAllowedState state) {
215 UMA_HISTOGRAM_ENUMERATION("Variations.ResourceRequestsAllowed", state,
216 RESOURCE_REQUESTS_ALLOWED_ENUM_SIZE);
219 // Converts ResourceRequestAllowedNotifier::State to the corresponding
220 // ResourceRequestsAllowedState value.
221 ResourceRequestsAllowedState ResourceRequestStateToHistogramValue(
222 ResourceRequestAllowedNotifier::State state) {
224 case ResourceRequestAllowedNotifier::DISALLOWED_EULA_NOT_ACCEPTED:
225 return RESOURCE_REQUESTS_NOT_ALLOWED_EULA_NOT_ACCEPTED;
226 case ResourceRequestAllowedNotifier::DISALLOWED_NETWORK_DOWN:
227 return RESOURCE_REQUESTS_NOT_ALLOWED_NETWORK_DOWN;
228 case ResourceRequestAllowedNotifier::DISALLOWED_COMMAND_LINE_DISABLED:
229 return RESOURCE_REQUESTS_NOT_ALLOWED_COMMAND_LINE_DISABLED;
230 case ResourceRequestAllowedNotifier::ALLOWED:
231 return RESOURCE_REQUESTS_ALLOWED;
234 return RESOURCE_REQUESTS_NOT_ALLOWED;
238 // Gets current form factor and converts it from enum DeviceFormFactor to enum
240 variations::Study_FormFactor GetCurrentFormFactor() {
241 switch (ui::GetDeviceFormFactor()) {
242 case ui::DEVICE_FORM_FACTOR_PHONE:
243 return variations::Study_FormFactor_PHONE;
244 case ui::DEVICE_FORM_FACTOR_TABLET:
245 return variations::Study_FormFactor_TABLET;
246 case ui::DEVICE_FORM_FACTOR_DESKTOP:
247 return variations::Study_FormFactor_DESKTOP;
250 return variations::Study_FormFactor_DESKTOP;
253 // Gets the hardware class and returns it as a string. This returns an empty
254 // string if the client is not ChromeOS.
255 std::string GetHardwareClass() {
256 #if defined(OS_CHROMEOS)
257 return base::SysInfo::GetLsbReleaseBoard();
258 #endif // OS_CHROMEOS
259 return std::string();
262 // Returns the date that should be used by the VariationsSeedProcessor to do
263 // expiry and start date checks.
264 base::Time GetReferenceDateForExpiryChecks(PrefService* local_state) {
265 const int64 date_value = local_state->GetInt64(prefs::kVariationsSeedDate);
266 const base::Time seed_date = base::Time::FromInternalValue(date_value);
267 const base::Time build_time = base::GetBuildTime();
268 // Use the build time for date checks if either the seed date is invalid or
269 // the build time is newer than the seed date.
270 base::Time reference_date = seed_date;
271 if (seed_date.is_null() || seed_date < build_time)
272 reference_date = build_time;
273 return reference_date;
276 // Overrides the string resource sepecified by |hash| with |string| in the
277 // resource bundle. Used as a callback passed to the variations seed processor.
278 void OverrideUIString(uint32_t hash, const base::string16& string) {
279 int resource_id = GetResourceIndex(hash);
280 if (resource_id == -1)
283 ui::ResourceBundle::GetSharedInstance().OverrideLocaleStringResource(
284 resource_id, string);
289 VariationsService::VariationsService(
290 ResourceRequestAllowedNotifier* notifier,
291 PrefService* local_state,
292 metrics::MetricsStateManager* state_manager)
293 : local_state_(local_state),
294 state_manager_(state_manager),
295 policy_pref_service_(local_state),
296 seed_store_(local_state),
297 create_trials_from_seed_called_(false),
298 initial_request_completed_(false),
299 resource_request_allowed_notifier_(notifier),
300 weak_ptr_factory_(this) {
301 resource_request_allowed_notifier_->Init(this);
304 VariationsService::~VariationsService() {
307 bool VariationsService::CreateTrialsFromSeed() {
308 create_trials_from_seed_called_ = true;
310 variations::VariationsSeed seed;
311 if (!seed_store_.LoadSeed(&seed))
314 const chrome::VersionInfo current_version_info;
315 const base::Version current_version(current_version_info.Version());
316 if (!current_version.IsValid())
319 variations::Study_Channel channel = GetChannelForVariations();
320 UMA_HISTOGRAM_SPARSE_SLOWLY("Variations.UserChannel", channel);
322 if (ShouldCreateServerTrials()) {
323 variations::VariationsSeedProcessor().CreateTrialsFromSeed(
325 g_browser_process->GetApplicationLocale(),
326 GetReferenceDateForExpiryChecks(local_state_),
329 GetCurrentFormFactor(),
331 base::Bind(&OverrideUIString));
334 const base::Time now = base::Time::Now();
336 // Log the "freshness" of the seed that was just used. The freshness is the
337 // time between the last successful seed download and now.
338 const int64 last_fetch_time_internal =
339 local_state_->GetInt64(prefs::kVariationsLastFetchTime);
340 if (last_fetch_time_internal) {
341 const base::TimeDelta delta =
342 now - base::Time::FromInternalValue(last_fetch_time_internal);
343 // Log the value in number of minutes.
344 UMA_HISTOGRAM_CUSTOM_COUNTS("Variations.SeedFreshness", delta.InMinutes(),
345 1, base::TimeDelta::FromDays(30).InMinutes(), 50);
348 // Log the skew between the seed date and the system clock/build time to
349 // analyze whether either could be used to make old variations seeds expire
351 const int64 seed_date_internal =
352 local_state_->GetInt64(prefs::kVariationsSeedDate);
353 if (seed_date_internal) {
354 const base::Time seed_date =
355 base::Time::FromInternalValue(seed_date_internal);
356 const int system_clock_delta_days = (now - seed_date).InDays();
357 if (system_clock_delta_days < 0) {
358 UMA_HISTOGRAM_COUNTS_100("Variations.SeedDateSkew.SystemClockBehindBy",
359 -system_clock_delta_days);
361 UMA_HISTOGRAM_COUNTS_100("Variations.SeedDateSkew.SystemClockAheadBy",
362 system_clock_delta_days);
365 const int build_time_delta_days =
366 (base::GetBuildTime() - seed_date).InDays();
367 if (build_time_delta_days < 0) {
368 UMA_HISTOGRAM_COUNTS_100("Variations.SeedDateSkew.BuildTimeBehindBy",
369 -build_time_delta_days);
371 UMA_HISTOGRAM_COUNTS_100("Variations.SeedDateSkew.BuildTimeAheadBy",
372 build_time_delta_days);
379 void VariationsService::StartRepeatedVariationsSeedFetch() {
380 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
382 // Initialize the Variations server URL.
383 variations_server_url_ = GetVariationsServerURL(policy_pref_service_);
385 // Check that |CreateTrialsFromSeed| was called, which is necessary to
386 // retrieve the serial number that will be sent to the server.
387 DCHECK(create_trials_from_seed_called_);
389 DCHECK(!request_scheduler_.get());
390 // Note that the act of instantiating the scheduler will start the fetch, if
391 // the scheduler deems appropriate. Using Unretained is fine here since the
392 // lifespan of request_scheduler_ is guaranteed to be shorter than that of
394 request_scheduler_.reset(VariationsRequestScheduler::Create(
395 base::Bind(&VariationsService::FetchVariationsSeed,
396 base::Unretained(this)), local_state_));
397 request_scheduler_->Start();
400 void VariationsService::AddObserver(Observer* observer) {
401 observer_list_.AddObserver(observer);
404 void VariationsService::RemoveObserver(Observer* observer) {
405 observer_list_.RemoveObserver(observer);
408 // TODO(rkaplow): Handle this and the similar event in metrics_service by
409 // observing an 'OnAppEnterForeground' event in RequestScheduler instead of
410 // requiring the frontend code to notify each service individually. Since the
411 // scheduler will handle it directly the VariationService shouldn't need to
412 // know details of this anymore.
413 void VariationsService::OnAppEnterForeground() {
414 request_scheduler_->OnAppEnterForeground();
418 void VariationsService::StartGoogleUpdateRegistrySync() {
419 registry_syncer_.RequestRegistrySync();
423 void VariationsService::SetCreateTrialsFromSeedCalledForTesting(bool called) {
424 create_trials_from_seed_called_ = called;
428 GURL VariationsService::GetVariationsServerURL(
429 PrefService* policy_pref_service) {
430 std::string server_url_string(CommandLine::ForCurrentProcess()->
431 GetSwitchValueASCII(switches::kVariationsServerURL));
432 if (server_url_string.empty())
433 server_url_string = kDefaultVariationsServerURL;
434 GURL server_url = GURL(server_url_string);
436 const std::string restrict_param =
437 GetRestrictParameterPref(policy_pref_service);
438 if (!restrict_param.empty()) {
439 server_url = net::AppendOrReplaceQueryParameter(server_url,
444 server_url = net::AppendOrReplaceQueryParameter(server_url, "osname",
445 GetPlatformString());
447 DCHECK(server_url.is_valid());
452 std::string VariationsService::GetDefaultVariationsServerURLForTesting() {
453 return kDefaultVariationsServerURL;
457 void VariationsService::RegisterPrefs(PrefRegistrySimple* registry) {
458 VariationsSeedStore::RegisterPrefs(registry);
459 registry->RegisterInt64Pref(prefs::kVariationsLastFetchTime, 0);
460 // This preference will only be written by the policy service, which will fill
461 // it according to a value stored in the User Policy.
462 registry->RegisterStringPref(prefs::kVariationsRestrictParameter,
467 void VariationsService::RegisterProfilePrefs(
468 user_prefs::PrefRegistrySyncable* registry) {
469 // This preference will only be written by the policy service, which will fill
470 // it according to a value stored in the User Policy.
471 registry->RegisterStringPref(
472 prefs::kVariationsRestrictParameter,
474 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
478 scoped_ptr<VariationsService> VariationsService::Create(
479 PrefService* local_state,
480 metrics::MetricsStateManager* state_manager) {
481 scoped_ptr<VariationsService> result;
482 #if !defined(GOOGLE_CHROME_BUILD)
483 // Unless the URL was provided, unsupported builds should return NULL to
484 // indicate that the service should not be used.
485 if (!CommandLine::ForCurrentProcess()->HasSwitch(
486 switches::kVariationsServerURL)) {
487 DVLOG(1) << "Not creating VariationsService in unofficial build without --"
488 << switches::kVariationsServerURL << " specified.";
489 return result.Pass();
492 result.reset(new VariationsService(
493 new ResourceRequestAllowedNotifier, local_state, state_manager));
494 return result.Pass();
497 void VariationsService::DoActualFetch() {
498 pending_seed_request_.reset(net::URLFetcher::Create(
499 0, variations_server_url_, net::URLFetcher::GET, this));
500 pending_seed_request_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
501 net::LOAD_DO_NOT_SAVE_COOKIES);
502 pending_seed_request_->SetRequestContext(
503 g_browser_process->system_request_context());
504 pending_seed_request_->SetMaxRetriesOn5xx(kMaxRetrySeedFetch);
505 if (!seed_store_.variations_serial_number().empty()) {
506 pending_seed_request_->AddExtraRequestHeader(
507 "If-Match:" + seed_store_.variations_serial_number());
509 pending_seed_request_->Start();
511 const base::TimeTicks now = base::TimeTicks::Now();
512 base::TimeDelta time_since_last_fetch;
513 // Record a time delta of 0 (default value) if there was no previous fetch.
514 if (!last_request_started_time_.is_null())
515 time_since_last_fetch = now - last_request_started_time_;
516 UMA_HISTOGRAM_CUSTOM_COUNTS("Variations.TimeSinceLastFetchAttempt",
517 time_since_last_fetch.InMinutes(), 0,
518 base::TimeDelta::FromDays(7).InMinutes(), 50);
519 last_request_started_time_ = now;
522 void VariationsService::StoreSeed(const std::string& seed_data,
523 const std::string& seed_signature,
524 const base::Time& date_fetched) {
525 scoped_ptr<variations::VariationsSeed> seed(new variations::VariationsSeed);
526 if (!seed_store_.StoreSeedData(seed_data, seed_signature, date_fetched,
530 RecordLastFetchTime();
532 // Perform seed simulation only if |state_manager_| is not-NULL. The state
533 // manager may be NULL for some unit tests.
537 base::PostTaskAndReplyWithResult(
538 content::BrowserThread::GetBlockingPool(),
540 base::Bind(&GetVersionForSimulation),
541 base::Bind(&VariationsService::PerformSimulationWithVersion,
542 weak_ptr_factory_.GetWeakPtr(), base::Passed(&seed)));
545 void VariationsService::FetchVariationsSeed() {
546 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
548 const ResourceRequestAllowedNotifier::State state =
549 resource_request_allowed_notifier_->GetResourceRequestsAllowedState();
550 RecordRequestsAllowedHistogram(ResourceRequestStateToHistogramValue(state));
551 if (state != ResourceRequestAllowedNotifier::ALLOWED) {
552 DVLOG(1) << "Resource requests were not allowed. Waiting for notification.";
559 void VariationsService::NotifyObservers(
560 const variations::VariationsSeedSimulator::Result& result) {
561 if (result.kill_critical_group_change_count > 0) {
562 FOR_EACH_OBSERVER(Observer, observer_list_,
563 OnExperimentChangesDetected(Observer::CRITICAL));
564 } else if (result.kill_best_effort_group_change_count > 0) {
565 FOR_EACH_OBSERVER(Observer, observer_list_,
566 OnExperimentChangesDetected(Observer::BEST_EFFORT));
570 void VariationsService::OnURLFetchComplete(const net::URLFetcher* source) {
571 DCHECK_EQ(pending_seed_request_.get(), source);
573 const bool is_first_request = !initial_request_completed_;
574 initial_request_completed_ = true;
576 // The fetcher will be deleted when the request is handled.
577 scoped_ptr<const net::URLFetcher> request(pending_seed_request_.release());
578 const net::URLRequestStatus& request_status = request->GetStatus();
579 if (request_status.status() != net::URLRequestStatus::SUCCESS) {
580 UMA_HISTOGRAM_SPARSE_SLOWLY("Variations.FailedRequestErrorCode",
581 -request_status.error());
582 DVLOG(1) << "Variations server request failed with error: "
583 << request_status.error() << ": "
584 << net::ErrorToString(request_status.error());
585 // It's common for the very first fetch attempt to fail (e.g. the network
586 // may not yet be available). In such a case, try again soon, rather than
587 // waiting the full time interval.
588 if (is_first_request)
589 request_scheduler_->ScheduleFetchShortly();
593 // Log the response code.
594 const int response_code = request->GetResponseCode();
595 UMA_HISTOGRAM_SPARSE_SLOWLY("Variations.SeedFetchResponseCode",
598 const base::TimeDelta latency =
599 base::TimeTicks::Now() - last_request_started_time_;
601 base::Time response_date;
602 if (response_code == net::HTTP_OK ||
603 response_code == net::HTTP_NOT_MODIFIED) {
604 bool success = request->GetResponseHeaders()->GetDateValue(&response_date);
605 DCHECK(success || response_date.is_null());
607 if (!response_date.is_null()) {
608 g_browser_process->network_time_tracker()->UpdateNetworkTime(
610 base::TimeDelta::FromMilliseconds(kServerTimeResolutionMs),
612 base::TimeTicks::Now());
616 if (response_code != net::HTTP_OK) {
617 DVLOG(1) << "Variations server request returned non-HTTP_OK response code: "
619 if (response_code == net::HTTP_NOT_MODIFIED) {
620 RecordLastFetchTime();
621 // Update the seed date value in local state (used for expiry check on
622 // next start up), since 304 is a successful response.
623 seed_store_.UpdateSeedDateAndLogDayChange(response_date);
628 std::string seed_data;
629 bool success = request->GetResponseAsString(&seed_data);
632 std::string seed_signature;
633 request->GetResponseHeaders()->EnumerateHeader(NULL,
636 StoreSeed(seed_data, seed_signature, response_date);
639 void VariationsService::OnResourceRequestsAllowed() {
640 // Note that this only attempts to fetch the seed at most once per period
641 // (kSeedFetchPeriodHours). This works because
642 // |resource_request_allowed_notifier_| only calls this method if an
643 // attempt was made earlier that fails (which implies that the period had
644 // elapsed). After a successful attempt is made, the notifier will know not
645 // to call this method again until another failed attempt occurs.
646 RecordRequestsAllowedHistogram(RESOURCE_REQUESTS_ALLOWED_NOTIFIED);
647 DVLOG(1) << "Retrying fetch.";
650 // This service must have created a scheduler in order for this to be called.
651 DCHECK(request_scheduler_.get());
652 request_scheduler_->Reset();
655 void VariationsService::PerformSimulationWithVersion(
656 scoped_ptr<variations::VariationsSeed> seed,
657 const base::Version& version) {
658 if (!version.IsValid())
661 if (!ShouldCreateServerTrials())
664 const base::ElapsedTimer timer;
666 scoped_ptr<const base::FieldTrial::EntropyProvider> entropy_provider =
667 state_manager_->CreateEntropyProvider();
668 variations::VariationsSeedSimulator seed_simulator(*entropy_provider);
670 const variations::VariationsSeedSimulator::Result result =
671 seed_simulator.SimulateSeedStudies(
672 *seed, g_browser_process->GetApplicationLocale(),
673 GetReferenceDateForExpiryChecks(local_state_), version,
674 GetChannelForVariations(), GetCurrentFormFactor(),
677 UMA_HISTOGRAM_COUNTS_100("Variations.SimulateSeed.NormalChanges",
678 result.normal_group_change_count);
679 UMA_HISTOGRAM_COUNTS_100("Variations.SimulateSeed.KillBestEffortChanges",
680 result.kill_best_effort_group_change_count);
681 UMA_HISTOGRAM_COUNTS_100("Variations.SimulateSeed.KillCriticalChanges",
682 result.kill_critical_group_change_count);
684 UMA_HISTOGRAM_TIMES("Variations.SimulateSeed.Duration", timer.Elapsed());
686 NotifyObservers(result);
689 void VariationsService::RecordLastFetchTime() {
690 // local_state_ is NULL in tests, so check it first.
692 local_state_->SetInt64(prefs::kVariationsLastFetchTime,
693 base::Time::Now().ToInternalValue());
697 } // namespace chrome_variations