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.
4
5#include "chrome/browser/metrics/variations/variations_service.h"
6
7#include <set>
8
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"
41#include "url/gurl.h"
42
43#if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_CHROMEOS)
44#include "chrome/browser/upgrade_detector_impl.h"
45#endif
46
47#if defined(OS_CHROMEOS)
48#include "chrome/browser/chromeos/settings/cros_settings.h"
49#endif
50
51namespace chrome_variations {
52
53namespace {
54
55// Default server of Variations seed info.
56const char kDefaultVariationsServerURL[] =
57    "https://clients4.google.com/chrome-variations/seed";
58const int kMaxRetrySeedFetch = 5;
59
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.
62const int64 kServerTimeResolutionMs = 1000;
63
64// Wrapper around channel checking, used to enable channel mocking for
65// testing. If the current browser channel is not UNKNOWN, this will return
66// that channel value. Otherwise, if the fake channel flag is provided, this
67// will return the fake channel. Failing that, this will return the UNKNOWN
68// channel.
69variations::Study_Channel GetChannelForVariations() {
70  switch (chrome::VersionInfo::GetChannel()) {
71    case chrome::VersionInfo::CHANNEL_CANARY:
72      return variations::Study_Channel_CANARY;
73    case chrome::VersionInfo::CHANNEL_DEV:
74      return variations::Study_Channel_DEV;
75    case chrome::VersionInfo::CHANNEL_BETA:
76      return variations::Study_Channel_BETA;
77    case chrome::VersionInfo::CHANNEL_STABLE:
78      return variations::Study_Channel_STABLE;
79    case chrome::VersionInfo::CHANNEL_UNKNOWN:
80      break;
81  }
82  const std::string forced_channel =
83      CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
84          switches::kFakeVariationsChannel);
85  if (forced_channel == "stable")
86    return variations::Study_Channel_STABLE;
87  if (forced_channel == "beta")
88    return variations::Study_Channel_BETA;
89  if (forced_channel == "dev")
90    return variations::Study_Channel_DEV;
91  if (forced_channel == "canary")
92    return variations::Study_Channel_CANARY;
93  DVLOG(1) << "Invalid channel provided: " << forced_channel;
94  return variations::Study_Channel_UNKNOWN;
95}
96
97// Returns a string that will be used for the value of the 'osname' URL param
98// to the variations server.
99std::string GetPlatformString() {
100#if defined(OS_WIN)
101  return "win";
102#elif defined(OS_IOS)
103  return "ios";
104#elif defined(OS_MACOSX)
105  return "mac";
106#elif defined(OS_CHROMEOS)
107  return "chromeos";
108#elif defined(OS_ANDROID)
109  return "android";
110#elif defined(OS_LINUX) || defined(OS_BSD) || defined(OS_SOLARIS)
111  // Default BSD and SOLARIS to Linux to not break those builds, although these
112  // platforms are not officially supported by Chrome.
113  return "linux";
114#else
115#error Unknown platform
116#endif
117}
118
119// Gets the version number to use for variations seed simulation. Must be called
120// on a thread where IO is allowed.
121base::Version GetVersionForSimulation() {
122#if !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_CHROMEOS)
123  const base::Version installed_version =
124      UpgradeDetectorImpl::GetCurrentlyInstalledVersion();
125  if (installed_version.IsValid())
126    return installed_version;
127#endif  // !defined(OS_ANDROID) && !defined(OS_IOS) && !defined(OS_CHROMEOS)
128
129  // TODO(asvitkine): Get the version that will be used on restart instead of
130  // the current version on Android, iOS and ChromeOS.
131  return base::Version(chrome::VersionInfo().Version());
132}
133
134// Gets the restrict parameter from |policy_pref_service| or from Chrome OS
135// settings in the case of that platform.
136std::string GetRestrictParameterPref(PrefService* policy_pref_service) {
137  std::string parameter;
138#if defined(OS_CHROMEOS)
139  chromeos::CrosSettings::Get()->GetString(
140      chromeos::kVariationsRestrictParameter, &parameter);
141#else
142  if (policy_pref_service) {
143    parameter =
144        policy_pref_service->GetString(prefs::kVariationsRestrictParameter);
145  }
146#endif
147  return parameter;
148}
149
150enum ResourceRequestsAllowedState {
151  RESOURCE_REQUESTS_ALLOWED,
152  RESOURCE_REQUESTS_NOT_ALLOWED,
153  RESOURCE_REQUESTS_ALLOWED_NOTIFIED,
154  RESOURCE_REQUESTS_NOT_ALLOWED_EULA_NOT_ACCEPTED,
155  RESOURCE_REQUESTS_NOT_ALLOWED_NETWORK_DOWN,
156  RESOURCE_REQUESTS_NOT_ALLOWED_COMMAND_LINE_DISABLED,
157  RESOURCE_REQUESTS_ALLOWED_ENUM_SIZE,
158};
159
160// Records UMA histogram with the current resource requests allowed state.
161void RecordRequestsAllowedHistogram(ResourceRequestsAllowedState state) {
162  UMA_HISTOGRAM_ENUMERATION("Variations.ResourceRequestsAllowed", state,
163                            RESOURCE_REQUESTS_ALLOWED_ENUM_SIZE);
164}
165
166// Converts ResourceRequestAllowedNotifier::State to the corresponding
167// ResourceRequestsAllowedState value.
168ResourceRequestsAllowedState ResourceRequestStateToHistogramValue(
169    ResourceRequestAllowedNotifier::State state) {
170  switch (state) {
171    case ResourceRequestAllowedNotifier::DISALLOWED_EULA_NOT_ACCEPTED:
172      return RESOURCE_REQUESTS_NOT_ALLOWED_EULA_NOT_ACCEPTED;
173    case ResourceRequestAllowedNotifier::DISALLOWED_NETWORK_DOWN:
174      return RESOURCE_REQUESTS_NOT_ALLOWED_NETWORK_DOWN;
175    case ResourceRequestAllowedNotifier::DISALLOWED_COMMAND_LINE_DISABLED:
176      return RESOURCE_REQUESTS_NOT_ALLOWED_COMMAND_LINE_DISABLED;
177    case ResourceRequestAllowedNotifier::ALLOWED:
178      return RESOURCE_REQUESTS_ALLOWED;
179  }
180  NOTREACHED();
181  return RESOURCE_REQUESTS_NOT_ALLOWED;
182}
183
184
185// Gets current form factor and converts it from enum DeviceFormFactor to enum
186// Study_FormFactor.
187variations::Study_FormFactor GetCurrentFormFactor() {
188  switch (ui::GetDeviceFormFactor()) {
189    case ui::DEVICE_FORM_FACTOR_PHONE:
190      return variations::Study_FormFactor_PHONE;
191    case ui::DEVICE_FORM_FACTOR_TABLET:
192      return variations::Study_FormFactor_TABLET;
193    case ui::DEVICE_FORM_FACTOR_DESKTOP:
194      return variations::Study_FormFactor_DESKTOP;
195  }
196  NOTREACHED();
197  return variations::Study_FormFactor_DESKTOP;
198}
199
200// Gets the hardware class and returns it as a string. This returns an empty
201// string if the client is not ChromeOS.
202std::string GetHardwareClass() {
203#if defined(OS_CHROMEOS)
204  return base::SysInfo::GetLsbReleaseBoard();
205#endif  // OS_CHROMEOS
206  return std::string();
207}
208
209// Returns the date that should be used by the VariationsSeedProcessor to do
210// expiry and start date checks.
211base::Time GetReferenceDateForExpiryChecks(PrefService* local_state) {
212  const int64 date_value = local_state->GetInt64(prefs::kVariationsSeedDate);
213  const base::Time seed_date = base::Time::FromInternalValue(date_value);
214  const base::Time build_time = base::GetBuildTime();
215  // Use the build time for date checks if either the seed date is invalid or
216  // the build time is newer than the seed date.
217  base::Time reference_date = seed_date;
218  if (seed_date.is_null() || seed_date < build_time)
219    reference_date = build_time;
220  return reference_date;
221}
222
223// Overrides the string resource sepecified by |hash| with |string| in the
224// resource bundle. Used as a callback passed to the variations seed processor.
225void OverrideUIString(uint32_t hash, const base::string16& string) {
226  int resource_id = GetResourceIndex(hash);
227  if (resource_id == -1)
228    return;
229
230  ui::ResourceBundle::GetSharedInstance().OverrideLocaleStringResource(
231      resource_id, string);
232}
233
234}  // namespace
235
236VariationsService::VariationsService(
237    ResourceRequestAllowedNotifier* notifier,
238    PrefService* local_state,
239    metrics::MetricsStateManager* state_manager)
240    : local_state_(local_state),
241      state_manager_(state_manager),
242      policy_pref_service_(local_state),
243      seed_store_(local_state),
244      create_trials_from_seed_called_(false),
245      initial_request_completed_(false),
246      resource_request_allowed_notifier_(notifier),
247      weak_ptr_factory_(this) {
248  resource_request_allowed_notifier_->Init(this);
249}
250
251VariationsService::~VariationsService() {
252}
253
254bool VariationsService::CreateTrialsFromSeed() {
255  create_trials_from_seed_called_ = true;
256
257  variations::VariationsSeed seed;
258  if (!seed_store_.LoadSeed(&seed))
259    return false;
260
261  const chrome::VersionInfo current_version_info;
262  if (!current_version_info.is_valid())
263    return false;
264
265  const base::Version current_version(current_version_info.Version());
266  if (!current_version.IsValid())
267    return false;
268
269  variations::VariationsSeedProcessor().CreateTrialsFromSeed(
270      seed,
271      g_browser_process->GetApplicationLocale(),
272      GetReferenceDateForExpiryChecks(local_state_),
273      current_version,
274      GetChannelForVariations(),
275      GetCurrentFormFactor(),
276      GetHardwareClass(),
277      base::Bind(&OverrideUIString));
278
279  const base::Time now = base::Time::Now();
280
281  // Log the "freshness" of the seed that was just used. The freshness is the
282  // time between the last successful seed download and now.
283  const int64 last_fetch_time_internal =
284      local_state_->GetInt64(prefs::kVariationsLastFetchTime);
285  if (last_fetch_time_internal) {
286    const base::TimeDelta delta =
287        now - base::Time::FromInternalValue(last_fetch_time_internal);
288    // Log the value in number of minutes.
289    UMA_HISTOGRAM_CUSTOM_COUNTS("Variations.SeedFreshness", delta.InMinutes(),
290        1, base::TimeDelta::FromDays(30).InMinutes(), 50);
291  }
292
293  // Log the skew between the seed date and the system clock/build time to
294  // analyze whether either could be used to make old variations seeds expire
295  // after some time.
296  const int64 seed_date_internal =
297      local_state_->GetInt64(prefs::kVariationsSeedDate);
298  if (seed_date_internal) {
299    const base::Time seed_date =
300        base::Time::FromInternalValue(seed_date_internal);
301    const int system_clock_delta_days = (now - seed_date).InDays();
302    if (system_clock_delta_days < 0) {
303      UMA_HISTOGRAM_COUNTS_100("Variations.SeedDateSkew.SystemClockBehindBy",
304                               -system_clock_delta_days);
305    } else {
306      UMA_HISTOGRAM_COUNTS_100("Variations.SeedDateSkew.SystemClockAheadBy",
307                               system_clock_delta_days);
308    }
309
310    const int build_time_delta_days =
311        (base::GetBuildTime() - seed_date).InDays();
312    if (build_time_delta_days < 0) {
313      UMA_HISTOGRAM_COUNTS_100("Variations.SeedDateSkew.BuildTimeBehindBy",
314                               -build_time_delta_days);
315    } else {
316      UMA_HISTOGRAM_COUNTS_100("Variations.SeedDateSkew.BuildTimeAheadBy",
317                               build_time_delta_days);
318    }
319  }
320
321  return true;
322}
323
324void VariationsService::StartRepeatedVariationsSeedFetch() {
325  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
326
327  // Initialize the Variations server URL.
328  variations_server_url_ = GetVariationsServerURL(policy_pref_service_);
329
330  // Check that |CreateTrialsFromSeed| was called, which is necessary to
331  // retrieve the serial number that will be sent to the server.
332  DCHECK(create_trials_from_seed_called_);
333
334  DCHECK(!request_scheduler_.get());
335  // Note that the act of instantiating the scheduler will start the fetch, if
336  // the scheduler deems appropriate. Using Unretained is fine here since the
337  // lifespan of request_scheduler_ is guaranteed to be shorter than that of
338  // this service.
339  request_scheduler_.reset(VariationsRequestScheduler::Create(
340      base::Bind(&VariationsService::FetchVariationsSeed,
341          base::Unretained(this)), local_state_));
342  request_scheduler_->Start();
343}
344
345void VariationsService::AddObserver(Observer* observer) {
346  observer_list_.AddObserver(observer);
347}
348
349void VariationsService::RemoveObserver(Observer* observer) {
350  observer_list_.RemoveObserver(observer);
351}
352
353// TODO(rkaplow): Handle this and the similar event in metrics_service by
354// observing an 'OnAppEnterForeground' event in RequestScheduler instead of
355// requiring the frontend code to notify each service individually. Since the
356// scheduler will handle it directly the VariationService shouldn't need to
357// know details of this anymore.
358void VariationsService::OnAppEnterForeground() {
359  request_scheduler_->OnAppEnterForeground();
360}
361
362#if defined(OS_WIN)
363void VariationsService::StartGoogleUpdateRegistrySync() {
364  registry_syncer_.RequestRegistrySync();
365}
366#endif
367
368void VariationsService::SetCreateTrialsFromSeedCalledForTesting(bool called) {
369  create_trials_from_seed_called_ = called;
370}
371
372// static
373GURL VariationsService::GetVariationsServerURL(
374    PrefService* policy_pref_service) {
375  std::string server_url_string(CommandLine::ForCurrentProcess()->
376      GetSwitchValueASCII(switches::kVariationsServerURL));
377  if (server_url_string.empty())
378    server_url_string = kDefaultVariationsServerURL;
379  GURL server_url = GURL(server_url_string);
380
381  const std::string restrict_param =
382      GetRestrictParameterPref(policy_pref_service);
383  if (!restrict_param.empty()) {
384    server_url = net::AppendOrReplaceQueryParameter(server_url,
385                                                    "restrict",
386                                                    restrict_param);
387  }
388
389  server_url = net::AppendOrReplaceQueryParameter(server_url, "osname",
390                                                  GetPlatformString());
391
392  DCHECK(server_url.is_valid());
393  return server_url;
394}
395
396// static
397std::string VariationsService::GetDefaultVariationsServerURLForTesting() {
398  return kDefaultVariationsServerURL;
399}
400
401// static
402void VariationsService::RegisterPrefs(PrefRegistrySimple* registry) {
403  VariationsSeedStore::RegisterPrefs(registry);
404  registry->RegisterInt64Pref(prefs::kVariationsLastFetchTime, 0);
405  // This preference will only be written by the policy service, which will fill
406  // it according to a value stored in the User Policy.
407  registry->RegisterStringPref(prefs::kVariationsRestrictParameter,
408                               std::string());
409}
410
411// static
412void VariationsService::RegisterProfilePrefs(
413    user_prefs::PrefRegistrySyncable* registry) {
414  // This preference will only be written by the policy service, which will fill
415  // it according to a value stored in the User Policy.
416  registry->RegisterStringPref(
417      prefs::kVariationsRestrictParameter,
418      std::string(),
419      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
420}
421
422// static
423scoped_ptr<VariationsService> VariationsService::Create(
424    PrefService* local_state,
425    metrics::MetricsStateManager* state_manager) {
426  scoped_ptr<VariationsService> result;
427#if !defined(GOOGLE_CHROME_BUILD)
428  // Unless the URL was provided, unsupported builds should return NULL to
429  // indicate that the service should not be used.
430  if (!CommandLine::ForCurrentProcess()->HasSwitch(
431          switches::kVariationsServerURL)) {
432    DVLOG(1) << "Not creating VariationsService in unofficial build without --"
433             << switches::kVariationsServerURL << " specified.";
434    return result.Pass();
435  }
436#endif
437  result.reset(new VariationsService(
438      new ResourceRequestAllowedNotifier, local_state, state_manager));
439  return result.Pass();
440}
441
442void VariationsService::DoActualFetch() {
443  pending_seed_request_.reset(net::URLFetcher::Create(
444      0, variations_server_url_, net::URLFetcher::GET, this));
445  pending_seed_request_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
446                                      net::LOAD_DO_NOT_SAVE_COOKIES);
447  pending_seed_request_->SetRequestContext(
448      g_browser_process->system_request_context());
449  pending_seed_request_->SetMaxRetriesOn5xx(kMaxRetrySeedFetch);
450  if (!seed_store_.variations_serial_number().empty()) {
451    pending_seed_request_->AddExtraRequestHeader(
452        "If-Match:" + seed_store_.variations_serial_number());
453  }
454  pending_seed_request_->Start();
455
456  const base::TimeTicks now = base::TimeTicks::Now();
457  base::TimeDelta time_since_last_fetch;
458  // Record a time delta of 0 (default value) if there was no previous fetch.
459  if (!last_request_started_time_.is_null())
460    time_since_last_fetch = now - last_request_started_time_;
461  UMA_HISTOGRAM_CUSTOM_COUNTS("Variations.TimeSinceLastFetchAttempt",
462                              time_since_last_fetch.InMinutes(), 0,
463                              base::TimeDelta::FromDays(7).InMinutes(), 50);
464  last_request_started_time_ = now;
465}
466
467void VariationsService::StoreSeed(const std::string& seed_data,
468                                  const std::string& seed_signature,
469                                  const base::Time& date_fetched) {
470  scoped_ptr<variations::VariationsSeed> seed(new variations::VariationsSeed);
471  if (!seed_store_.StoreSeedData(seed_data, seed_signature, date_fetched,
472                                 seed.get())) {
473    return;
474  }
475  RecordLastFetchTime();
476
477  // Perform seed simulation only if |state_manager_| is not-NULL. The state
478  // manager may be NULL for some unit tests.
479  if (!state_manager_)
480    return;
481
482  base::PostTaskAndReplyWithResult(
483      content::BrowserThread::GetBlockingPool(),
484      FROM_HERE,
485      base::Bind(&GetVersionForSimulation),
486      base::Bind(&VariationsService::PerformSimulationWithVersion,
487                 weak_ptr_factory_.GetWeakPtr(), base::Passed(&seed)));
488}
489
490void VariationsService::FetchVariationsSeed() {
491  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
492
493  const ResourceRequestAllowedNotifier::State state =
494      resource_request_allowed_notifier_->GetResourceRequestsAllowedState();
495  RecordRequestsAllowedHistogram(ResourceRequestStateToHistogramValue(state));
496  if (state != ResourceRequestAllowedNotifier::ALLOWED) {
497    DVLOG(1) << "Resource requests were not allowed. Waiting for notification.";
498    return;
499  }
500
501  DoActualFetch();
502}
503
504void VariationsService::NotifyObservers(
505    const variations::VariationsSeedSimulator::Result& result) {
506  if (result.kill_critical_group_change_count > 0) {
507    FOR_EACH_OBSERVER(Observer, observer_list_,
508                      OnExperimentChangesDetected(Observer::CRITICAL));
509  } else if (result.kill_best_effort_group_change_count > 0) {
510    FOR_EACH_OBSERVER(Observer, observer_list_,
511                      OnExperimentChangesDetected(Observer::BEST_EFFORT));
512  }
513}
514
515void VariationsService::OnURLFetchComplete(const net::URLFetcher* source) {
516  DCHECK_EQ(pending_seed_request_.get(), source);
517
518  const bool is_first_request = !initial_request_completed_;
519  initial_request_completed_ = true;
520
521  // The fetcher will be deleted when the request is handled.
522  scoped_ptr<const net::URLFetcher> request(pending_seed_request_.release());
523  const net::URLRequestStatus& request_status = request->GetStatus();
524  if (request_status.status() != net::URLRequestStatus::SUCCESS) {
525    UMA_HISTOGRAM_SPARSE_SLOWLY("Variations.FailedRequestErrorCode",
526                                -request_status.error());
527    DVLOG(1) << "Variations server request failed with error: "
528             << request_status.error() << ": "
529             << net::ErrorToString(request_status.error());
530    // It's common for the very first fetch attempt to fail (e.g. the network
531    // may not yet be available). In such a case, try again soon, rather than
532    // waiting the full time interval.
533    if (is_first_request)
534      request_scheduler_->ScheduleFetchShortly();
535    return;
536  }
537
538  // Log the response code.
539  const int response_code = request->GetResponseCode();
540  UMA_HISTOGRAM_SPARSE_SLOWLY("Variations.SeedFetchResponseCode",
541                              response_code);
542
543  const base::TimeDelta latency =
544      base::TimeTicks::Now() - last_request_started_time_;
545
546  base::Time response_date;
547  if (response_code == net::HTTP_OK ||
548      response_code == net::HTTP_NOT_MODIFIED) {
549    bool success = request->GetResponseHeaders()->GetDateValue(&response_date);
550    DCHECK(success || response_date.is_null());
551
552    if (!response_date.is_null()) {
553      g_browser_process->network_time_tracker()->UpdateNetworkTime(
554          response_date,
555          base::TimeDelta::FromMilliseconds(kServerTimeResolutionMs),
556          latency,
557          base::TimeTicks::Now());
558    }
559  }
560
561  if (response_code != net::HTTP_OK) {
562    DVLOG(1) << "Variations server request returned non-HTTP_OK response code: "
563             << response_code;
564    if (response_code == net::HTTP_NOT_MODIFIED) {
565      RecordLastFetchTime();
566      // Update the seed date value in local state (used for expiry check on
567      // next start up), since 304 is a successful response.
568      seed_store_.UpdateSeedDateAndLogDayChange(response_date);
569    }
570    return;
571  }
572
573  std::string seed_data;
574  bool success = request->GetResponseAsString(&seed_data);
575  DCHECK(success);
576
577  std::string seed_signature;
578  request->GetResponseHeaders()->EnumerateHeader(NULL,
579                                                 "X-Seed-Signature",
580                                                 &seed_signature);
581  StoreSeed(seed_data, seed_signature, response_date);
582}
583
584void VariationsService::OnResourceRequestsAllowed() {
585  // Note that this only attempts to fetch the seed at most once per period
586  // (kSeedFetchPeriodHours). This works because
587  // |resource_request_allowed_notifier_| only calls this method if an
588  // attempt was made earlier that fails (which implies that the period had
589  // elapsed). After a successful attempt is made, the notifier will know not
590  // to call this method again until another failed attempt occurs.
591  RecordRequestsAllowedHistogram(RESOURCE_REQUESTS_ALLOWED_NOTIFIED);
592  DVLOG(1) << "Retrying fetch.";
593  DoActualFetch();
594
595  // This service must have created a scheduler in order for this to be called.
596  DCHECK(request_scheduler_.get());
597  request_scheduler_->Reset();
598}
599
600void VariationsService::PerformSimulationWithVersion(
601    scoped_ptr<variations::VariationsSeed> seed,
602    const base::Version& version) {
603  if (!version.IsValid())
604    return;
605
606  const base::ElapsedTimer timer;
607
608  scoped_ptr<const base::FieldTrial::EntropyProvider> entropy_provider =
609      state_manager_->CreateEntropyProvider();
610  variations::VariationsSeedSimulator seed_simulator(*entropy_provider);
611
612  const variations::VariationsSeedSimulator::Result result =
613      seed_simulator.SimulateSeedStudies(
614          *seed, g_browser_process->GetApplicationLocale(),
615          GetReferenceDateForExpiryChecks(local_state_), version,
616          GetChannelForVariations(), GetCurrentFormFactor(),
617          GetHardwareClass());
618
619  UMA_HISTOGRAM_COUNTS_100("Variations.SimulateSeed.NormalChanges",
620                           result.normal_group_change_count);
621  UMA_HISTOGRAM_COUNTS_100("Variations.SimulateSeed.KillBestEffortChanges",
622                           result.kill_best_effort_group_change_count);
623  UMA_HISTOGRAM_COUNTS_100("Variations.SimulateSeed.KillCriticalChanges",
624                           result.kill_critical_group_change_count);
625
626  UMA_HISTOGRAM_TIMES("Variations.SimulateSeed.Duration", timer.Elapsed());
627
628  NotifyObservers(result);
629}
630
631void VariationsService::RecordLastFetchTime() {
632  // local_state_ is NULL in tests, so check it first.
633  if (local_state_) {
634    local_state_->SetInt64(prefs::kVariationsLastFetchTime,
635                           base::Time::Now().ToInternalValue());
636  }
637}
638
639}  // namespace chrome_variations
640