diff options
author | blundell@chromium.org <blundell@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2014-05-26 15:59:34 +0000 |
---|---|---|
committer | blundell@chromium.org <blundell@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2014-05-26 15:59:34 +0000 |
commit | 24f81cad13af6e0ba08ac2335cb27ad280f1143e (patch) | |
tree | 35ce59ff9bd99ef630450c0efe1a53eafe2bea60 /chrome/browser/metrics | |
parent | cbbdeef85b213545ddc022610f3fb308a738123b (diff) | |
download | chromium_src-24f81cad13af6e0ba08ac2335cb27ad280f1143e.zip chromium_src-24f81cad13af6e0ba08ac2335cb27ad280f1143e.tar.gz chromium_src-24f81cad13af6e0ba08ac2335cb27ad280f1143e.tar.bz2 |
Remove dependencies of Metrics{Service,Log} on g_browser_process->local_state()
This CL changes MetricsService and MetricsLog to take in a |local_state| param
in their constructors. It additionally changes several static MetricsService
functions to take in a |local_state| param.
BUG=374299,374300
TBR=jochen
Review URL: https://codereview.chromium.org/282093012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272833 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'chrome/browser/metrics')
-rw-r--r-- | chrome/browser/metrics/metrics_log.cc | 22 | ||||
-rw-r--r-- | chrome/browser/metrics/metrics_log.h | 9 | ||||
-rw-r--r-- | chrome/browser/metrics/metrics_log_unittest.cc | 74 | ||||
-rw-r--r-- | chrome/browser/metrics/metrics_service.cc | 122 | ||||
-rw-r--r-- | chrome/browser/metrics/metrics_service.h | 19 | ||||
-rw-r--r-- | chrome/browser/metrics/metrics_service_unittest.cc | 84 | ||||
-rw-r--r-- | chrome/browser/metrics/metrics_services_manager.cc | 4 |
7 files changed, 163 insertions, 171 deletions
diff --git a/chrome/browser/metrics/metrics_log.cc b/chrome/browser/metrics/metrics_log.cc index d647bac..d9e11a8 100644 --- a/chrome/browser/metrics/metrics_log.cc +++ b/chrome/browser/metrics/metrics_log.cc @@ -181,13 +181,15 @@ int64 RoundSecondsToHour(int64 time_in_seconds) { MetricsLog::MetricsLog(const std::string& client_id, int session_id, LogType log_type, - metrics::MetricsServiceClient* client) + metrics::MetricsServiceClient* client, + PrefService* local_state) : MetricsLogBase(client_id, session_id, log_type, client->GetVersionString()), client_(client), - creation_time_(base::TimeTicks::Now()) { + creation_time_(base::TimeTicks::Now()), + local_state_(local_state) { uma_proto()->mutable_system_profile()->set_channel(client_->GetChannel()); } @@ -201,7 +203,7 @@ void MetricsLog::RecordStabilityMetrics( DCHECK(HasEnvironment()); DCHECK(!HasStabilityMetrics()); - PrefService* pref = GetPrefService(); + PrefService* pref = local_state_; DCHECK(pref); // Get stability attributes out of Local State, zeroing out stored values. @@ -259,10 +261,6 @@ void MetricsLog::RecordGeneralMetrics( metrics_providers[i]->ProvideGeneralMetrics(uma_proto()); } -PrefService* MetricsLog::GetPrefService() { - return g_browser_process->local_state(); -} - void MetricsLog::GetFieldTrialIds( std::vector<ActiveGroupId>* field_trial_ids) const { variations::GetFieldTrialActiveGroupIds(field_trial_ids); @@ -329,14 +327,14 @@ void MetricsLog::RecordEnvironment( system_profile->set_brand_code(brand_code); int enabled_date; - bool success = base::StringToInt(GetMetricsEnabledDate(GetPrefService()), - &enabled_date); + bool success = + base::StringToInt(GetMetricsEnabledDate(local_state_), &enabled_date); DCHECK(success); // Reduce granularity of the enabled_date field to nearest hour. system_profile->set_uma_enabled_date(RoundSecondsToHour(enabled_date)); - int64 install_date = GetPrefService()->GetInt64(prefs::kInstallDate); + int64 install_date = local_state_->GetInt64(prefs::kInstallDate); // Reduce granularity of the install_date field to nearest hour. system_profile->set_install_date(RoundSecondsToHour(install_date)); @@ -385,7 +383,7 @@ void MetricsLog::RecordEnvironment( std::string base64_system_profile; if (system_profile->SerializeToString(&serialied_system_profile)) { base::Base64Encode(serialied_system_profile, &base64_system_profile); - PrefService* local_state = GetPrefService(); + PrefService* local_state = local_state_; local_state->SetString(prefs::kStabilitySavedSystemProfile, base64_system_profile); local_state->SetString(prefs::kStabilitySavedSystemProfileHash, @@ -394,7 +392,7 @@ void MetricsLog::RecordEnvironment( } bool MetricsLog::LoadSavedEnvironmentFromPrefs() { - PrefService* local_state = GetPrefService(); + PrefService* local_state = local_state_; const std::string base64_system_profile = local_state->GetString(prefs::kStabilitySavedSystemProfile); if (base64_system_profile.empty()) diff --git a/chrome/browser/metrics/metrics_log.h b/chrome/browser/metrics/metrics_log.h index 25102d8..0e7c8f9 100644 --- a/chrome/browser/metrics/metrics_log.h +++ b/chrome/browser/metrics/metrics_log.h @@ -45,13 +45,15 @@ class MetricsLog : public metrics::MetricsLogBase { // |client_id| is the identifier for this profile on this installation // |session_id| is an integer that's incremented on each application launch // |client| is used to interact with the embedder. + // |local_state| is the PrefService that this instance should use. // Note: |this| instance does not take ownership of the |client|, but rather // stores a weak pointer to it. The caller should ensure that the |client| is // valid for the lifetime of this class. MetricsLog(const std::string& client_id, int session_id, LogType log_type, - metrics::MetricsServiceClient* client); + metrics::MetricsServiceClient* client, + PrefService* local_state); virtual ~MetricsLog(); // Records the current operating environment, including metrics provided by @@ -101,9 +103,6 @@ class MetricsLog : public metrics::MetricsLogBase { protected: // Exposed for the sake of mocking in test code. - // Returns the PrefService from which to log metrics data. - virtual PrefService* GetPrefService(); - // Fills |field_trial_ids| with the list of initialized field trials name and // group ids. virtual void GetFieldTrialIds( @@ -138,6 +137,8 @@ class MetricsLog : public metrics::MetricsLogBase { // The time when the current log was created. const base::TimeTicks creation_time_; + PrefService* local_state_; + DISALLOW_COPY_AND_ASSIGN(MetricsLog); }; diff --git a/chrome/browser/metrics/metrics_log_unittest.cc b/chrome/browser/metrics/metrics_log_unittest.cc index dd8ade1..410329f 100644 --- a/chrome/browser/metrics/metrics_log_unittest.cc +++ b/chrome/browser/metrics/metrics_log_unittest.cc @@ -19,6 +19,7 @@ #include "base/time/time.h" #include "base/tracked_objects.h" #include "chrome/browser/google/google_util.h" +#include "chrome/browser/metrics/metrics_service.h" #include "chrome/browser/prefs/browser_prefs.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/pref_names.h" @@ -63,30 +64,15 @@ class TestMetricsLog : public MetricsLog { TestMetricsLog(const std::string& client_id, int session_id, LogType log_type, - metrics::MetricsServiceClient* client) - : MetricsLog(client_id, session_id, log_type, client), - prefs_(&scoped_prefs_) { - chrome::RegisterLocalState(scoped_prefs_.registry()); - InitPrefs(); - } - - // Creates a TestMetricsLog that will use |prefs| as the fake local state. - // Useful for tests that need to re-use the local state prefs between logs. - TestMetricsLog(const std::string& client_id, - int session_id, - LogType log_type, metrics::MetricsServiceClient* client, TestingPrefServiceSimple* prefs) - : MetricsLog(client_id, session_id, log_type, client), prefs_(prefs) { + : MetricsLog(client_id, session_id, log_type, client, prefs), + prefs_(prefs) { InitPrefs(); } virtual ~TestMetricsLog() {} - virtual PrefService* GetPrefService() OVERRIDE { - return prefs_; - } - const metrics::ChromeUserMetricsExtension& uma_proto() const { return *MetricsLog::uma_proto(); } @@ -112,8 +98,6 @@ class TestMetricsLog : public MetricsLog { } } - // Scoped PrefsService, which may not be used if |prefs_ != &scoped_prefs|. - TestingPrefServiceSimple scoped_prefs_; // Weak pointer to the PrefsService used by this log. TestingPrefServiceSimple* prefs_; @@ -124,7 +108,7 @@ class TestMetricsLog : public MetricsLog { class MetricsLogTest : public testing::Test { public: - MetricsLogTest() {} + MetricsLogTest() { MetricsService::RegisterPrefs(prefs_.registry()); } protected: // Check that the values in |system_values| correspond to the test data @@ -163,6 +147,9 @@ class MetricsLogTest : public testing::Test { // of this call. } + protected: + TestingPrefServiceSimple prefs_; + private: content::TestBrowserThreadBundle thread_bundle_; @@ -171,7 +158,8 @@ class MetricsLogTest : public testing::Test { TEST_F(MetricsLogTest, RecordEnvironment) { metrics::TestMetricsServiceClient client; - TestMetricsLog log(kClientId, kSessionId, MetricsLog::ONGOING_LOG, &client); + TestMetricsLog log( + kClientId, kSessionId, MetricsLog::ONGOING_LOG, &client, &prefs_); std::vector<variations::ActiveGroupId> synthetic_trials; // Add two synthetic trials. @@ -184,9 +172,8 @@ TEST_F(MetricsLogTest, RecordEnvironment) { CheckSystemProfile(log.system_profile()); // Check that the system profile has also been written to prefs. - PrefService* local_state = log.GetPrefService(); const std::string base64_system_profile = - local_state->GetString(prefs::kStabilitySavedSystemProfile); + prefs_.GetString(prefs::kStabilitySavedSystemProfile); EXPECT_FALSE(base64_system_profile.empty()); std::string serialied_system_profile; EXPECT_TRUE(base::Base64Decode(base64_system_profile, @@ -201,42 +188,40 @@ TEST_F(MetricsLogTest, LoadSavedEnvironmentFromPrefs) { const char* kSystemProfileHashPref = prefs::kStabilitySavedSystemProfileHash; metrics::TestMetricsServiceClient client; - TestingPrefServiceSimple prefs; - chrome::RegisterLocalState(prefs.registry()); // The pref value is empty, so loading it from prefs should fail. { TestMetricsLog log( - kClientId, kSessionId, MetricsLog::ONGOING_LOG, &client, &prefs); + kClientId, kSessionId, MetricsLog::ONGOING_LOG, &client, &prefs_); EXPECT_FALSE(log.LoadSavedEnvironmentFromPrefs()); } // Do a RecordEnvironment() call and check whether the pref is recorded. { TestMetricsLog log( - kClientId, kSessionId, MetricsLog::ONGOING_LOG, &client, &prefs); + kClientId, kSessionId, MetricsLog::ONGOING_LOG, &client, &prefs_); log.RecordEnvironment(std::vector<metrics::MetricsProvider*>(), std::vector<variations::ActiveGroupId>()); - EXPECT_FALSE(prefs.GetString(kSystemProfilePref).empty()); - EXPECT_FALSE(prefs.GetString(kSystemProfileHashPref).empty()); + EXPECT_FALSE(prefs_.GetString(kSystemProfilePref).empty()); + EXPECT_FALSE(prefs_.GetString(kSystemProfileHashPref).empty()); } { TestMetricsLog log( - kClientId, kSessionId, MetricsLog::ONGOING_LOG, &client, &prefs); + kClientId, kSessionId, MetricsLog::ONGOING_LOG, &client, &prefs_); EXPECT_TRUE(log.LoadSavedEnvironmentFromPrefs()); // Check some values in the system profile. EXPECT_EQ(kInstallDateExpected, log.system_profile().install_date()); EXPECT_EQ(kEnabledDateExpected, log.system_profile().uma_enabled_date()); // Ensure that the call cleared the prefs. - EXPECT_TRUE(prefs.GetString(kSystemProfilePref).empty()); - EXPECT_TRUE(prefs.GetString(kSystemProfileHashPref).empty()); + EXPECT_TRUE(prefs_.GetString(kSystemProfilePref).empty()); + EXPECT_TRUE(prefs_.GetString(kSystemProfileHashPref).empty()); } // Ensure that a non-matching hash results in the pref being invalid. { TestMetricsLog log( - kClientId, kSessionId, MetricsLog::ONGOING_LOG, &client, &prefs); + kClientId, kSessionId, MetricsLog::ONGOING_LOG, &client, &prefs_); // Call RecordEnvironment() to record the pref again. log.RecordEnvironment(std::vector<metrics::MetricsProvider*>(), std::vector<variations::ActiveGroupId>()); @@ -244,20 +229,23 @@ TEST_F(MetricsLogTest, LoadSavedEnvironmentFromPrefs) { { // Set the hash to a bad value. - prefs.SetString(kSystemProfileHashPref, "deadbeef"); + prefs_.SetString(kSystemProfileHashPref, "deadbeef"); TestMetricsLog log( - kClientId, kSessionId, MetricsLog::ONGOING_LOG, &client, &prefs); + kClientId, kSessionId, MetricsLog::ONGOING_LOG, &client, &prefs_); EXPECT_FALSE(log.LoadSavedEnvironmentFromPrefs()); // Ensure that the prefs are cleared, even if the call failed. - EXPECT_TRUE(prefs.GetString(kSystemProfilePref).empty()); - EXPECT_TRUE(prefs.GetString(kSystemProfileHashPref).empty()); + EXPECT_TRUE(prefs_.GetString(kSystemProfilePref).empty()); + EXPECT_TRUE(prefs_.GetString(kSystemProfileHashPref).empty()); } } TEST_F(MetricsLogTest, InitialLogStabilityMetrics) { metrics::TestMetricsServiceClient client; - TestMetricsLog log( - kClientId, kSessionId, MetricsLog::INITIAL_STABILITY_LOG, &client); + TestMetricsLog log(kClientId, + kSessionId, + MetricsLog::INITIAL_STABILITY_LOG, + &client, + &prefs_); std::vector<metrics::MetricsProvider*> metrics_providers; log.RecordEnvironment(metrics_providers, std::vector<variations::ActiveGroupId>()); @@ -278,7 +266,8 @@ TEST_F(MetricsLogTest, InitialLogStabilityMetrics) { TEST_F(MetricsLogTest, OngoingLogStabilityMetrics) { metrics::TestMetricsServiceClient client; - TestMetricsLog log(kClientId, kSessionId, MetricsLog::ONGOING_LOG, &client); + TestMetricsLog log( + kClientId, kSessionId, MetricsLog::ONGOING_LOG, &client, &prefs_); std::vector<metrics::MetricsProvider*> metrics_providers; log.RecordEnvironment(metrics_providers, std::vector<variations::ActiveGroupId>()); @@ -306,7 +295,8 @@ TEST_F(MetricsLogTest, RecordProfilerData) { metrics::HashMetricName("birth_thread*")); metrics::TestMetricsServiceClient client; - TestMetricsLog log(kClientId, kSessionId, MetricsLog::ONGOING_LOG, &client); + TestMetricsLog log( + kClientId, kSessionId, MetricsLog::ONGOING_LOG, &client, &prefs_); EXPECT_EQ(0, log.uma_proto().profiler_event_size()); { @@ -469,6 +459,6 @@ TEST_F(MetricsLogTest, RecordProfilerData) { TEST_F(MetricsLogTest, ChromeChannelWrittenToProtobuf) { metrics::TestMetricsServiceClient client; TestMetricsLog log( - "user@test.com", kSessionId, MetricsLog::ONGOING_LOG, &client); + "user@test.com", kSessionId, MetricsLog::ONGOING_LOG, &client, &prefs_); EXPECT_TRUE(log.uma_proto().system_profile().has_channel()); } diff --git a/chrome/browser/metrics/metrics_service.cc b/chrome/browser/metrics/metrics_service.cc index 2b31524..5326973 100644 --- a/chrome/browser/metrics/metrics_service.cc +++ b/chrome/browser/metrics/metrics_service.cc @@ -288,13 +288,12 @@ ResponseStatus ResponseCodeToStatus(int response_code) { } } -void MarkAppCleanShutdownAndCommit() { - PrefService* pref = g_browser_process->local_state(); - pref->SetBoolean(prefs::kStabilityExitedCleanly, true); - pref->SetInteger(prefs::kStabilityExecutionPhase, - MetricsService::SHUTDOWN_COMPLETE); +void MarkAppCleanShutdownAndCommit(PrefService* local_state) { + local_state->SetBoolean(prefs::kStabilityExitedCleanly, true); + local_state->SetInteger(prefs::kStabilityExecutionPhase, + MetricsService::SHUTDOWN_COMPLETE); // Start writing right away (write happens on a different thread). - pref->CommitPendingWrite(); + local_state->CommitPendingWrite(); } } // namespace @@ -367,12 +366,13 @@ void MetricsService::RegisterPrefs(PrefRegistrySimple* registry) { } MetricsService::MetricsService(metrics::MetricsStateManager* state_manager, - metrics::MetricsServiceClient* client) - : log_manager_(g_browser_process->local_state(), - kUploadLogAvoidRetransmitSize), + metrics::MetricsServiceClient* client, + PrefService* local_state) + : log_manager_(local_state, kUploadLogAvoidRetransmitSize), histogram_snapshot_manager_(this), state_manager_(state_manager), client_(client), + local_state_(local_state), recording_active_(false), reporting_active_(false), test_mode_active_(false), @@ -387,12 +387,13 @@ MetricsService::MetricsService(metrics::MetricsStateManager* state_manager, DCHECK(IsSingleThreaded()); DCHECK(state_manager_); DCHECK(client_); + DCHECK(local_state_); #if defined(OS_ANDROID) // TODO(asvitkine): Move this out of MetricsService. RegisterMetricsProvider( scoped_ptr<metrics::MetricsProvider>(new AndroidMetricsProvider( - g_browser_process->local_state()))); + local_state_))); #endif // defined(OS_ANDROID) // TODO(asvitkine): Move these out of MetricsService. @@ -412,8 +413,7 @@ MetricsService::MetricsService(metrics::MetricsStateManager* state_manager, #endif #if defined(ENABLE_PLUGINS) - plugin_metrics_provider_ = new PluginMetricsProvider( - g_browser_process->local_state()); + plugin_metrics_provider_ = new PluginMetricsProvider(local_state_); RegisterMetricsProvider(scoped_ptr<metrics::MetricsProvider>( plugin_metrics_provider_)); #endif @@ -581,7 +581,7 @@ void MetricsService::RecordCompletedSessionEnd() { void MetricsService::OnAppEnterBackground() { scheduler_->Stop(); - MarkAppCleanShutdownAndCommit(); + MarkAppCleanShutdownAndCommit(local_state_); // At this point, there's no way of knowing when the process will be // killed, so this has to be treated similar to a shutdown, closing and @@ -597,25 +597,22 @@ void MetricsService::OnAppEnterBackground() { } void MetricsService::OnAppEnterForeground() { - PrefService* pref = g_browser_process->local_state(); - pref->SetBoolean(prefs::kStabilityExitedCleanly, false); - + local_state_->SetBoolean(prefs::kStabilityExitedCleanly, false); StartSchedulerIfNecessary(); } #else -void MetricsService::LogNeedForCleanShutdown() { - PrefService* pref = g_browser_process->local_state(); - pref->SetBoolean(prefs::kStabilityExitedCleanly, false); +void MetricsService::LogNeedForCleanShutdown(PrefService* local_state) { + local_state->SetBoolean(prefs::kStabilityExitedCleanly, false); // Redundant setting to be sure we call for a clean shutdown. clean_shutdown_status_ = NEED_TO_SHUTDOWN; } #endif // defined(OS_ANDROID) || defined(OS_IOS) // static -void MetricsService::SetExecutionPhase(ExecutionPhase execution_phase) { +void MetricsService::SetExecutionPhase(ExecutionPhase execution_phase, + PrefService* local_state) { execution_phase_ = execution_phase; - PrefService* pref = g_browser_process->local_state(); - pref->SetInteger(prefs::kStabilityExecutionPhase, execution_phase_); + local_state->SetInteger(prefs::kStabilityExecutionPhase, execution_phase_); } void MetricsService::RecordBreakpadRegistration(bool success) { @@ -641,23 +638,23 @@ void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) { // Initialization methods void MetricsService::InitializeMetricsState() { - PrefService* pref = g_browser_process->local_state(); - DCHECK(pref); - - pref->SetString(prefs::kStabilityStatsVersion, client_->GetVersionString()); - pref->SetInt64(prefs::kStabilityStatsBuildTime, MetricsLog::GetBuildTime()); + local_state_->SetString(prefs::kStabilityStatsVersion, + client_->GetVersionString()); + local_state_->SetInt64(prefs::kStabilityStatsBuildTime, + MetricsLog::GetBuildTime()); - session_id_ = pref->GetInteger(prefs::kMetricsSessionID); + session_id_ = local_state_->GetInteger(prefs::kMetricsSessionID); - if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) { + if (!local_state_->GetBoolean(prefs::kStabilityExitedCleanly)) { IncrementPrefValue(prefs::kStabilityCrashCount); // Reset flag, and wait until we call LogNeedForCleanShutdown() before // monitoring. - pref->SetBoolean(prefs::kStabilityExitedCleanly, true); + local_state_->SetBoolean(prefs::kStabilityExitedCleanly, true); // TODO(rtenneti): On windows, consider saving/getting execution_phase from // the registry. - int execution_phase = pref->GetInteger(prefs::kStabilityExecutionPhase); + int execution_phase = + local_state_->GetInteger(prefs::kStabilityExecutionPhase); UMA_HISTOGRAM_SPARSE_SLOWLY("Chrome.Browser.CrashedExecutionPhase", execution_phase); @@ -669,30 +666,30 @@ void MetricsService::InitializeMetricsState() { // Update session ID. ++session_id_; - pref->SetInteger(prefs::kMetricsSessionID, session_id_); + local_state_->SetInteger(prefs::kMetricsSessionID, session_id_); // Stability bookkeeping IncrementPrefValue(prefs::kStabilityLaunchCount); DCHECK_EQ(UNINITIALIZED_PHASE, execution_phase_); - SetExecutionPhase(START_METRICS_RECORDING); + SetExecutionPhase(START_METRICS_RECORDING, local_state_); - if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) { + if (!local_state_->GetBoolean(prefs::kStabilitySessionEndCompleted)) { IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount); // This is marked false when we get a WM_ENDSESSION. - pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true); + local_state_->SetBoolean(prefs::kStabilitySessionEndCompleted, true); } // Call GetUptimes() for the first time, thus allowing all later calls // to record incremental uptimes accurately. base::TimeDelta ignored_uptime_parameter; base::TimeDelta startup_uptime; - GetUptimes(pref, &startup_uptime, &ignored_uptime_parameter); + GetUptimes(local_state_, &startup_uptime, &ignored_uptime_parameter); DCHECK_EQ(0, startup_uptime.InMicroseconds()); // For backwards compatibility, leave this intact in case Omaha is checking // them. prefs::kStabilityLastTimestampSec may also be useless now. // TODO(jar): Delete these if they have no uses. - pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT()); + local_state_->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT()); // Bookkeeping for the uninstall metrics. IncrementLongPrefsValue(prefs::kUninstallLaunchCount); @@ -840,13 +837,7 @@ void MetricsService::ScheduleNextStateSave() { } void MetricsService::SaveLocalState() { - PrefService* pref = g_browser_process->local_state(); - if (!pref) { - NOTREACHED(); - return; - } - - RecordCurrentState(pref); + RecordCurrentState(local_state_); // TODO(jar):110021 Does this run down the batteries???? ScheduleNextStateSave(); @@ -911,10 +902,9 @@ void MetricsService::CloseCurrentLog() { std::vector<variations::ActiveGroupId> synthetic_trials; GetCurrentSyntheticFieldTrials(&synthetic_trials); current_log->RecordEnvironment(metrics_providers_.get(), synthetic_trials); - PrefService* pref = g_browser_process->local_state(); base::TimeDelta incremental_uptime; base::TimeDelta uptime; - GetUptimes(pref, &incremental_uptime, &uptime); + GetUptimes(local_state_, &incremental_uptime, &uptime); current_log->RecordStabilityMetrics(metrics_providers_.get(), incremental_uptime, uptime); @@ -1083,8 +1073,7 @@ void MetricsService::StageNewLog() { void MetricsService::PrepareInitialStabilityLog() { DCHECK_EQ(INITIALIZED, state_); - PrefService* pref = g_browser_process->local_state(); - DCHECK_NE(0, pref->GetInteger(prefs::kStabilityCrashCount)); + DCHECK_NE(0, local_state_->GetInteger(prefs::kStabilityCrashCount)); scoped_ptr<MetricsLog> initial_stability_log( CreateLog(MetricsLog::INITIAL_STABILITY_LOG)); @@ -1130,10 +1119,9 @@ void MetricsService::PrepareInitialMetricsLog() { GetCurrentSyntheticFieldTrials(&synthetic_trials); initial_metrics_log_->RecordEnvironment(metrics_providers_.get(), synthetic_trials); - PrefService* pref = g_browser_process->local_state(); base::TimeDelta incremental_uptime; base::TimeDelta uptime; - GetUptimes(pref, &incremental_uptime, &uptime); + GetUptimes(local_state_, &incremental_uptime, &uptime); // Histograms only get written to the current log, so make the new log current // before writing them. @@ -1315,17 +1303,13 @@ void MetricsService::OnURLFetchComplete(const net::URLFetcher* source) { } void MetricsService::IncrementPrefValue(const char* path) { - PrefService* pref = g_browser_process->local_state(); - DCHECK(pref); - int value = pref->GetInteger(path); - pref->SetInteger(path, value + 1); + int value = local_state_->GetInteger(path); + local_state_->SetInteger(path, value + 1); } void MetricsService::IncrementLongPrefsValue(const char* path) { - PrefService* pref = g_browser_process->local_state(); - DCHECK(pref); - int64 value = pref->GetInt64(path); - pref->SetInt64(path, value + 1); + int64 value = local_state_->GetInt64(path); + local_state_->SetInt64(path, value + 1); } bool MetricsService::UmaMetricsProperlyShutdown() { @@ -1375,8 +1359,11 @@ void MetricsService::GetCurrentSyntheticFieldTrials( } scoped_ptr<MetricsLog> MetricsService::CreateLog(MetricsLog::LogType log_type) { - return make_scoped_ptr(new MetricsLog( - state_manager_->client_id(), session_id_, log_type, client_)); + return make_scoped_ptr(new MetricsLog(state_manager_->client_id(), + session_id_, + log_type, + client_, + local_state_)); } void MetricsService::RecordCurrentHistograms() { @@ -1393,16 +1380,15 @@ void MetricsService::RecordCurrentStabilityHistograms() { void MetricsService::LogCleanShutdown() { // Redundant hack to write pref ASAP. - MarkAppCleanShutdownAndCommit(); + MarkAppCleanShutdownAndCommit(local_state_); // Redundant setting to assure that we always reset this value at shutdown // (and that we don't use some alternate path, and not call LogCleanShutdown). clean_shutdown_status_ = CLEANLY_SHUTDOWN; RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true); - PrefService* pref = g_browser_process->local_state(); - pref->SetInteger(prefs::kStabilityExecutionPhase, - MetricsService::SHUTDOWN_COMPLETE); + local_state_->SetInteger(prefs::kStabilityExecutionPhase, + MetricsService::SHUTDOWN_COMPLETE); } void MetricsService::LogPluginLoadingError(const base::FilePath& plugin_path) { @@ -1421,12 +1407,8 @@ bool MetricsService::ShouldLogEvents() { void MetricsService::RecordBooleanPrefValue(const char* path, bool value) { DCHECK(IsSingleThreaded()); - - PrefService* pref = g_browser_process->local_state(); - DCHECK(pref); - - pref->SetBoolean(path, value); - RecordCurrentState(pref); + local_state_->SetBoolean(path, value); + RecordCurrentState(local_state_); } void MetricsService::RecordCurrentState(PrefService* pref) { diff --git a/chrome/browser/metrics/metrics_service.h b/chrome/browser/metrics/metrics_service.h index 3272264..9af1b4b 100644 --- a/chrome/browser/metrics/metrics_service.h +++ b/chrome/browser/metrics/metrics_service.h @@ -44,6 +44,7 @@ namespace base { class DictionaryValue; class HistogramSamples; class MessageLoopProxy; +class PrefService; } namespace variations { @@ -103,12 +104,13 @@ class MetricsService SHUTDOWN_COMPLETE = 700, }; - // Creates the MetricsService with the given |state_manager| and |client|. - // Does not take ownership of |state_manager| or |client|; instead stores a - // weak pointer to each. Caller should ensure that |state_manager| and - // |client| are valid for the lifetime of this class. + // Creates the MetricsService with the given |state_manager|, |client|, and + // |local_state|. Does not take ownership of the paramaters; instead stores + // a weak pointer to each. Caller should ensure that the parameters are valid + // for the lifetime of this class. MetricsService(metrics::MetricsStateManager* state_manager, - metrics::MetricsServiceClient* client); + metrics::MetricsServiceClient* client, + PrefService* local_state); virtual ~MetricsService(); // Initializes metrics recording state. Updates various bookkeeping values in @@ -188,10 +190,11 @@ class MetricsService void OnAppEnterForeground(); #else // Set the dirty flag, which will require a later call to LogCleanShutdown(). - static void LogNeedForCleanShutdown(); + static void LogNeedForCleanShutdown(PrefService* local_state); #endif // defined(OS_ANDROID) || defined(OS_IOS) - static void SetExecutionPhase(ExecutionPhase execution_phase); + static void SetExecutionPhase(ExecutionPhase execution_phase, + PrefService* local_state); // Saves in the preferences if the crash report registration was successful. // This count is eventually send via UMA logs. @@ -419,6 +422,8 @@ class MetricsService // Registered metrics providers. ScopedVector<metrics::MetricsProvider> metrics_providers_; + PrefService* local_state_; + base::ActionCallback action_callback_; // Indicate whether recording and reporting are currently happening. diff --git a/chrome/browser/metrics/metrics_service_unittest.cc b/chrome/browser/metrics/metrics_service_unittest.cc index f0960bf..aebb05a 100644 --- a/chrome/browser/metrics/metrics_service_unittest.cc +++ b/chrome/browser/metrics/metrics_service_unittest.cc @@ -7,7 +7,9 @@ #include <string> #include "base/bind.h" +#include "base/prefs/testing_pref_service.h" #include "base/threading/platform_thread.h" +#include "chrome/browser/google/google_util.h" #include "chrome/browser/metrics/metrics_state_manager.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/scoped_testing_local_state.h" @@ -26,8 +28,9 @@ using metrics::MetricsLogManager; class TestMetricsService : public MetricsService { public: TestMetricsService(metrics::MetricsStateManager* state_manager, - metrics::MetricsServiceClient* client) - : MetricsService(state_manager, client) {} + metrics::MetricsServiceClient* client, + PrefService* local_state) + : MetricsService(state_manager, client, local_state) {} virtual ~TestMetricsService() {} using MetricsService::log_manager; @@ -40,9 +43,13 @@ class TestMetricsLog : public MetricsLog { public: TestMetricsLog(const std::string& client_id, int session_id, - metrics::MetricsServiceClient* client) - : MetricsLog(client_id, session_id, MetricsLog::ONGOING_LOG, client) { - } + metrics::MetricsServiceClient* client, + PrefService* local_state) + : MetricsLog(client_id, + session_id, + MetricsLog::ONGOING_LOG, + client, + local_state) {} virtual ~TestMetricsLog() {} @@ -52,27 +59,24 @@ class TestMetricsLog : public MetricsLog { class MetricsServiceTest : public testing::Test { public: - MetricsServiceTest() - : testing_local_state_(TestingBrowserProcess::GetGlobal()), - is_metrics_reporting_enabled_(false), - metrics_state_manager_( - metrics::MetricsStateManager::Create( - GetLocalState(), - base::Bind(&MetricsServiceTest::is_metrics_reporting_enabled, - base::Unretained(this)))) { + MetricsServiceTest() : is_metrics_reporting_enabled_(false) { + MetricsService::RegisterPrefs(testing_local_state_.registry()); + metrics_state_manager_ = metrics::MetricsStateManager::Create( + GetLocalState(), + base::Bind(&MetricsServiceTest::is_metrics_reporting_enabled, + base::Unretained(this))); } virtual ~MetricsServiceTest() { - MetricsService::SetExecutionPhase(MetricsService::UNINITIALIZED_PHASE); + MetricsService::SetExecutionPhase(MetricsService::UNINITIALIZED_PHASE, + GetLocalState()); } metrics::MetricsStateManager* GetMetricsStateManager() { return metrics_state_manager_.get(); } - PrefService* GetLocalState() { - return testing_local_state_.Get(); - } + PrefService* GetLocalState() { return &testing_local_state_; } // Sets metrics reporting as enabled for testing. void EnableMetricsReporting() { @@ -110,8 +114,8 @@ class MetricsServiceTest : public testing::Test { } content::TestBrowserThreadBundle thread_bundle_; - ScopedTestingLocalState testing_local_state_; bool is_metrics_reporting_enabled_; + TestingPrefServiceSimple testing_local_state_; scoped_ptr<metrics::MetricsStateManager> metrics_state_manager_; DISALLOW_COPY_AND_ASSIGN(MetricsServiceTest); @@ -140,7 +144,8 @@ TEST_F(MetricsServiceTest, InitialStabilityLogAfterCleanShutDown) { GetLocalState()->SetBoolean(prefs::kStabilityExitedCleanly, true); metrics::TestMetricsServiceClient client; - TestMetricsService service(GetMetricsStateManager(), &client); + TestMetricsService service( + GetMetricsStateManager(), &client, GetLocalState()); service.InitializeMetricsRecordingState(); // No initial stability log should be generated. EXPECT_FALSE(service.log_manager()->has_unsent_logs()); @@ -148,28 +153,35 @@ TEST_F(MetricsServiceTest, InitialStabilityLogAfterCleanShutDown) { } TEST_F(MetricsServiceTest, InitialStabilityLogAfterCrash) { + // TODO(asvitkine): Eliminate using |testing_local_state| in favor of using + // |GetLocalState()| once MetricsService no longer internally creates metrics + // providers that rely on g_browser_process->local_state() being correctly + // set up. crbug.com/375776. + ScopedTestingLocalState testing_local_state( + TestingBrowserProcess::GetGlobal()); + TestingPrefServiceSimple* local_state = testing_local_state.Get(); EnableMetricsReporting(); - GetLocalState()->ClearPref(prefs::kStabilityExitedCleanly); + local_state->ClearPref(prefs::kStabilityExitedCleanly); // Set up prefs to simulate restarting after a crash. // Save an existing system profile to prefs, to correspond to what would be // saved from a previous session. metrics::TestMetricsServiceClient client; - TestMetricsLog log("client", 1, &client); + TestMetricsLog log("client", 1, &client, local_state); log.RecordEnvironment(std::vector<metrics::MetricsProvider*>(), std::vector<variations::ActiveGroupId>()); // Record stability build time and version from previous session, so that // stability metrics (including exited cleanly flag) won't be cleared. - GetLocalState()->SetInt64(prefs::kStabilityStatsBuildTime, - MetricsLog::GetBuildTime()); - GetLocalState()->SetString(prefs::kStabilityStatsVersion, - client.GetVersionString()); + local_state->SetInt64(prefs::kStabilityStatsBuildTime, + MetricsLog::GetBuildTime()); + local_state->SetString(prefs::kStabilityStatsVersion, + client.GetVersionString()); - GetLocalState()->SetBoolean(prefs::kStabilityExitedCleanly, false); + local_state->SetBoolean(prefs::kStabilityExitedCleanly, false); - TestMetricsService service(GetMetricsStateManager(), &client); + TestMetricsService service(GetMetricsStateManager(), &client, local_state); service.InitializeMetricsRecordingState(); // The initial stability log should be generated and persisted in unsent logs. @@ -198,7 +210,7 @@ TEST_F(MetricsServiceTest, InitialStabilityLogAfterCrash) { TEST_F(MetricsServiceTest, RegisterSyntheticTrial) { metrics::TestMetricsServiceClient client; - MetricsService service(GetMetricsStateManager(), &client); + MetricsService service(GetMetricsStateManager(), &client, GetLocalState()); // Add two synthetic trials and confirm that they show up in the list. SyntheticTrialGroup trial1(metrics::HashName("TestTrial1"), @@ -211,9 +223,12 @@ TEST_F(MetricsServiceTest, RegisterSyntheticTrial) { // Ensure that time has advanced by at least a tick before proceeding. WaitUntilTimeChanges(base::TimeTicks::Now()); - service.log_manager_.BeginLoggingWithLog( - scoped_ptr<metrics::MetricsLogBase>(new MetricsLog( - "clientID", 1, MetricsLog::INITIAL_STABILITY_LOG, &client))); + service.log_manager_.BeginLoggingWithLog(scoped_ptr<metrics::MetricsLogBase>( + new MetricsLog("clientID", + 1, + MetricsLog::INITIAL_STABILITY_LOG, + &client, + GetLocalState()))); // Save the time when the log was started (it's okay for this to be greater // than the time recorded by the above call since it's used to ensure the // value changes). @@ -249,8 +264,9 @@ TEST_F(MetricsServiceTest, RegisterSyntheticTrial) { // Start a new log and ensure all three trials appear in it. service.log_manager_.FinishCurrentLog(); - service.log_manager_.BeginLoggingWithLog(scoped_ptr<metrics::MetricsLogBase>( - new MetricsLog("clientID", 1, MetricsLog::ONGOING_LOG, &client))); + service.log_manager_.BeginLoggingWithLog( + scoped_ptr<metrics::MetricsLogBase>(new MetricsLog( + "clientID", 1, MetricsLog::ONGOING_LOG, &client, GetLocalState()))); service.GetCurrentSyntheticFieldTrials(&synthetic_trials); EXPECT_EQ(3U, synthetic_trials.size()); EXPECT_TRUE(HasSyntheticTrial(synthetic_trials, "TestTrial1", "Group2")); @@ -261,7 +277,7 @@ TEST_F(MetricsServiceTest, RegisterSyntheticTrial) { TEST_F(MetricsServiceTest, MetricsServiceObserver) { metrics::TestMetricsServiceClient client; - MetricsService service(GetMetricsStateManager(), &client); + MetricsService service(GetMetricsStateManager(), &client, GetLocalState()); TestMetricsServiceObserver observer1; TestMetricsServiceObserver observer2; diff --git a/chrome/browser/metrics/metrics_services_manager.cc b/chrome/browser/metrics/metrics_services_manager.cc index 276c3db4..9820ffb 100644 --- a/chrome/browser/metrics/metrics_services_manager.cc +++ b/chrome/browser/metrics/metrics_services_manager.cc @@ -29,8 +29,8 @@ MetricsServicesManager::~MetricsServicesManager() { MetricsService* MetricsServicesManager::GetMetricsService() { DCHECK(thread_checker_.CalledOnValidThread()); if (!metrics_service_) { - metrics_service_.reset( - new MetricsService(GetMetricsStateManager(), &metrics_service_client_)); + metrics_service_.reset(new MetricsService( + GetMetricsStateManager(), &metrics_service_client_, local_state_)); metrics_service_client_.set_service(metrics_service_.get()); metrics_service_->RegisterMetricsProvider( scoped_ptr<metrics::MetricsProvider>( |