This source file includes following definitions.
- IsSingleThreaded
- ResponseCodeToStatus
- GenerateLowEntropySource
- MapCrashExitCodeForHistogram
- MarkAppCleanShutdownAndCommit
- SendSeparateInitialStabilityLog
- OnDetailsAvailable
- RegisterPrefs
- DiscardOldStabilityStats
- entropy_source_returned_
- InitializeMetricsRecordingState
- Start
- StartRecordingForTests
- Stop
- EnableReporting
- DisableReporting
- GetClientId
- CreateEntropyProvider
- ForceClientIdCreation
- EnableRecording
- DisableRecording
- recording_active
- reporting_active
- SetUpNotifications
- BrowserChildProcessHostConnected
- BrowserChildProcessCrashed
- BrowserChildProcessInstanceCreated
- Observe
- HandleIdleSinceLastTransmission
- RecordStartOfSessionEnd
- RecordCompletedSessionEnd
- OnAppEnterBackground
- OnAppEnterForeground
- LogNeedForCleanShutdown
- SetExecutionPhase
- RecordBreakpadRegistration
- RecordBreakpadHasDebugger
- CountBrowserCrashDumpAttempts
- InitializeMetricsState
- InitTaskGetHardwareClass
- OnInitTaskGotHardwareClass
- OnInitTaskGotPluginInfo
- InitTaskGetGoogleUpdateData
- OnInitTaskGotGoogleUpdateData
- OnUserAction
- ReceivedProfilerData
- FinishedReceivingProfilerData
- GetUptimes
- ResetMetricsIDsIfNecessary
- GetLowEntropySource
- GenerateClientID
- ScheduleNextStateSave
- SaveLocalState
- OpenNewLog
- CloseCurrentLog
- PushPendingLogsToPersistentStorage
- StartSchedulerIfNecessary
- StartScheduledUpload
- StartFinalLogInfoCollection
- OnMemoryDetailCollectionDone
- OnHistogramSynchronizationDone
- OnFinalLogInfoCollectionDone
- StageNewLog
- PrepareInitialStabilityLog
- PrepareInitialMetricsLog
- SendStagedLog
- PrepareFetchWithStagedLog
- OnURLFetchComplete
- IncrementPrefValue
- IncrementLongPrefsValue
- LogLoadStarted
- LogRendererCrash
- LogRendererHang
- UmaMetricsProperlyShutdown
- RegisterSyntheticFieldTrial
- CheckForClonedInstall
- GetCurrentSyntheticFieldTrials
- LogCleanShutdown
- LogChromeOSCrash
- LogPluginLoadingError
- GetChildProcessStats
- RecordPluginChanges
- ShouldLogEvents
- RecordBooleanPrefValue
- RecordCurrentState
- IsPluginProcess
- StartExternalMetrics
- IsMetricsReportingEnabled
- IsCrashReportingEnabled
#include "chrome/browser/metrics/metrics_service.h"
#include <algorithm>
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/guid.h"
#include "base/md5.h"
#include "base/metrics/histogram.h"
#include "base/metrics/sparse_histogram.h"
#include "base/metrics/statistics_recorder.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "base/rand_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "base/tracked_objects.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/io_thread.h"
#include "chrome/browser/memory_details.h"
#include "chrome/browser/metrics/cloned_install_detector.h"
#include "chrome/browser/metrics/compression_utils.h"
#include "chrome/browser/metrics/machine_id_provider.h"
#include "chrome/browser/metrics/metrics_log.h"
#include "chrome/browser/metrics/metrics_log_serializer.h"
#include "chrome/browser/metrics/metrics_reporting_scheduler.h"
#include "chrome/browser/metrics/time_ticks_experiment_win.h"
#include "chrome/browser/metrics/tracking_synchronizer.h"
#include "chrome/common/metrics/variations/variations_util.h"
#include "chrome/browser/net/http_pipelining_compatibility_client.h"
#include "chrome/browser/net/network_stats.h"
#include "chrome/browser/omnibox/omnibox_log.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_otr_state.h"
#include "chrome/browser/ui/search/search_tab_helper.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_result_codes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/crash_keys.h"
#include "chrome/common/metrics/caching_permuted_entropy_provider.h"
#include "chrome/common/metrics/metrics_log_manager.h"
#include "chrome/common/net/test_server_locations.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/render_messages.h"
#include "components/variations/entropy_provider.h"
#include "components/variations/metrics_util.h"
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/histogram_fetcher.h"
#include "content/public/browser/load_notification_details.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/process_type.h"
#include "content/public/common/webplugininfo.h"
#include "extensions/browser/process_map.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_fetcher.h"
#if !defined(OS_POSIX)
#include "chrome/installer/util/browser_distribution.h"
#endif
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/external_metrics.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chromeos/system/statistics_provider.h"
#endif
#if defined(OS_WIN)
#include <windows.h>
#include "base/win/registry.h"
#endif
#if !defined(OS_ANDROID)
#include "chrome/browser/service_process/service_process_control.h"
#endif
using base::Time;
using content::BrowserThread;
using content::ChildProcessData;
using content::LoadNotificationDetails;
using content::PluginService;
namespace {
bool IsSingleThreaded() {
static base::PlatformThreadId thread_id = 0;
if (!thread_id)
thread_id = base::PlatformThread::CurrentId();
return base::PlatformThread::CurrentId() == thread_id;
}
#if defined(OS_ANDROID) || defined(OS_IOS)
const int kInitializationDelaySeconds = 5;
#else
const int kInitializationDelaySeconds = 30;
#endif
const int kMaxHistogramGatheringWaitDuration = 60000;
const int kEventLimit = 2400;
const size_t kUploadLogAvoidRetransmitSize = 50000;
const int kSaveStateIntervalMinutes = 5;
enum ResponseStatus {
UNKNOWN_FAILURE,
SUCCESS,
BAD_REQUEST,
NO_RESPONSE,
NUM_RESPONSE_STATUSES
};
ResponseStatus ResponseCodeToStatus(int response_code) {
switch (response_code) {
case 200:
return SUCCESS;
case 400:
return BAD_REQUEST;
case net::URLFetcher::RESPONSE_CODE_INVALID:
return NO_RESPONSE;
default:
return UNKNOWN_FAILURE;
}
}
const int kMaxLowEntropySize = 8000;
const int kLowEntropySourceNotSet = -1;
int GenerateLowEntropySource() {
return base::RandInt(0, kMaxLowEntropySize - 1);
}
int MapCrashExitCodeForHistogram(int exit_code) {
#if defined(OS_WIN)
if (exit_code == STATUS_GUARD_PAGE_VIOLATION)
return 0x1FCF7EC3;
#endif
return std::abs(exit_code);
}
void MarkAppCleanShutdownAndCommit() {
PrefService* pref = g_browser_process->local_state();
pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
pref->SetInteger(prefs::kStabilityExecutionPhase,
MetricsService::SHUTDOWN_COMPLETE);
pref->CommitPendingWrite();
}
bool SendSeparateInitialStabilityLog() {
return base::FieldTrialList::FindFullName("UMAStability") == "SeparateLog";
}
}
SyntheticTrialGroup::SyntheticTrialGroup(uint32 trial, uint32 group) {
id.name = trial;
id.group = group;
}
SyntheticTrialGroup::~SyntheticTrialGroup() {
}
MetricsService::ShutdownCleanliness MetricsService::clean_shutdown_status_ =
MetricsService::CLEANLY_SHUTDOWN;
MetricsService::ExecutionPhase MetricsService::execution_phase_ =
MetricsService::UNINITIALIZED_PHASE;
struct MetricsService::ChildProcessStats {
public:
explicit ChildProcessStats(int process_type)
: process_launches(0),
process_crashes(0),
instances(0),
loading_errors(0),
process_type(process_type) {}
ChildProcessStats()
: process_launches(0),
process_crashes(0),
instances(0),
loading_errors(0),
process_type(content::PROCESS_TYPE_UNKNOWN) {}
int process_launches;
int process_crashes;
int instances;
int loading_errors;
int process_type;
};
class MetricsMemoryDetails : public MemoryDetails {
public:
explicit MetricsMemoryDetails(const base::Closure& callback)
: callback_(callback) {}
virtual void OnDetailsAvailable() OVERRIDE {
base::MessageLoop::current()->PostTask(FROM_HERE, callback_);
}
private:
virtual ~MetricsMemoryDetails() {}
base::Closure callback_;
DISALLOW_COPY_AND_ASSIGN(MetricsMemoryDetails);
};
void MetricsService::RegisterPrefs(PrefRegistrySimple* registry) {
DCHECK(IsSingleThreaded());
registry->RegisterBooleanPref(prefs::kMetricsResetIds, false);
registry->RegisterStringPref(prefs::kMetricsClientID, std::string());
registry->RegisterInt64Pref(prefs::kMetricsReportingEnabledTimestamp, 0);
registry->RegisterIntegerPref(prefs::kMetricsLowEntropySource,
kLowEntropySourceNotSet);
registry->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
registry->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
registry->RegisterStringPref(prefs::kStabilityStatsVersion, std::string());
registry->RegisterInt64Pref(prefs::kStabilityStatsBuildTime, 0);
registry->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
registry->RegisterIntegerPref(prefs::kStabilityExecutionPhase,
UNINITIALIZED_PHASE);
registry->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
registry->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
registry->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
registry->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
registry->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount, 0);
registry->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
registry->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
registry->RegisterIntegerPref(prefs::kStabilityExtensionRendererCrashCount,
0);
registry->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
registry->RegisterIntegerPref(prefs::kStabilityChildProcessCrashCount, 0);
registry->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail, 0);
registry->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
0);
registry->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
registry->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
#if defined(OS_CHROMEOS)
registry->RegisterIntegerPref(prefs::kStabilityOtherUserCrashCount, 0);
registry->RegisterIntegerPref(prefs::kStabilityKernelCrashCount, 0);
registry->RegisterIntegerPref(prefs::kStabilitySystemUncleanShutdownCount, 0);
#endif
registry->RegisterStringPref(prefs::kStabilitySavedSystemProfile,
std::string());
registry->RegisterStringPref(prefs::kStabilitySavedSystemProfileHash,
std::string());
registry->RegisterListPref(prefs::kMetricsInitialLogs);
registry->RegisterListPref(prefs::kMetricsOngoingLogs);
registry->RegisterInt64Pref(prefs::kInstallDate, 0);
registry->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
registry->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
registry->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
registry->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
registry->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
registry->RegisterStringPref(prefs::kMetricsOldClientID, std::string());
registry->RegisterIntegerPref(prefs::kMetricsOldLowEntropySource, 0);
#if defined(OS_ANDROID)
RegisterPrefsAndroid(registry);
#endif
}
void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
local_state->SetInteger(prefs::kStabilityExecutionPhase, UNINITIALIZED_PHASE);
local_state->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
local_state->SetInteger(prefs::kStabilityCrashCount, 0);
local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
local_state->SetInt64(prefs::kStabilityLaunchTimeSec, 0);
local_state->SetInt64(prefs::kStabilityLastTimestampSec, 0);
local_state->ClearPref(prefs::kStabilityPluginStats);
local_state->ClearPref(prefs::kMetricsInitialLogs);
local_state->ClearPref(prefs::kMetricsOngoingLogs);
#if defined(OS_ANDROID)
DiscardOldStabilityStatsAndroid(local_state);
#endif
}
MetricsService::MetricsService()
: metrics_ids_reset_check_performed_(false),
recording_active_(false),
reporting_active_(false),
test_mode_active_(false),
state_(INITIALIZED),
has_initial_stability_log_(false),
low_entropy_source_(kLowEntropySourceNotSet),
idle_since_last_transmission_(false),
session_id_(-1),
next_window_id_(0),
self_ptr_factory_(this),
state_saver_factory_(this),
waiting_for_asynchronous_reporting_step_(false),
num_async_histogram_fetches_in_progress_(0),
entropy_source_returned_(LAST_ENTROPY_NONE) {
DCHECK(IsSingleThreaded());
log_manager_.set_log_serializer(new MetricsLogSerializer);
log_manager_.set_max_ongoing_log_store_size(kUploadLogAvoidRetransmitSize);
BrowserChildProcessObserver::Add(this);
}
MetricsService::~MetricsService() {
DisableRecording();
BrowserChildProcessObserver::Remove(this);
}
void MetricsService::InitializeMetricsRecordingState(
ReportingState reporting_state) {
InitializeMetricsState(reporting_state);
base::Closure callback = base::Bind(&MetricsService::StartScheduledUpload,
self_ptr_factory_.GetWeakPtr());
scheduler_.reset(new MetricsReportingScheduler(callback));
}
void MetricsService::Start() {
HandleIdleSinceLastTransmission(false);
EnableRecording();
EnableReporting();
}
void MetricsService::StartRecordingForTests() {
test_mode_active_ = true;
EnableRecording();
DisableReporting();
}
void MetricsService::Stop() {
HandleIdleSinceLastTransmission(false);
DisableReporting();
DisableRecording();
}
void MetricsService::EnableReporting() {
if (reporting_active_)
return;
reporting_active_ = true;
StartSchedulerIfNecessary();
}
void MetricsService::DisableReporting() {
reporting_active_ = false;
}
std::string MetricsService::GetClientId() {
return client_id_;
}
scoped_ptr<const base::FieldTrial::EntropyProvider>
MetricsService::CreateEntropyProvider(ReportingState reporting_state) {
const int low_entropy_source_value = GetLowEntropySource();
UMA_HISTOGRAM_SPARSE_SLOWLY("UMA.LowEntropySourceValue",
low_entropy_source_value);
if (reporting_state == REPORTING_ENABLED) {
if (entropy_source_returned_ == LAST_ENTROPY_NONE)
entropy_source_returned_ = LAST_ENTROPY_HIGH;
DCHECK_EQ(LAST_ENTROPY_HIGH, entropy_source_returned_);
const std::string high_entropy_source =
client_id_ + base::IntToString(low_entropy_source_value);
return scoped_ptr<const base::FieldTrial::EntropyProvider>(
new metrics::SHA1EntropyProvider(high_entropy_source));
}
if (entropy_source_returned_ == LAST_ENTROPY_NONE)
entropy_source_returned_ = LAST_ENTROPY_LOW;
DCHECK_EQ(LAST_ENTROPY_LOW, entropy_source_returned_);
#if defined(OS_ANDROID) || defined(OS_IOS)
return scoped_ptr<const base::FieldTrial::EntropyProvider>(
new metrics::CachingPermutedEntropyProvider(
g_browser_process->local_state(),
low_entropy_source_value,
kMaxLowEntropySize));
#else
return scoped_ptr<const base::FieldTrial::EntropyProvider>(
new metrics::PermutedEntropyProvider(low_entropy_source_value,
kMaxLowEntropySize));
#endif
}
void MetricsService::ForceClientIdCreation() {
if (!client_id_.empty())
return;
ResetMetricsIDsIfNecessary();
PrefService* pref = g_browser_process->local_state();
client_id_ = pref->GetString(prefs::kMetricsClientID);
if (!client_id_.empty())
return;
client_id_ = GenerateClientID();
pref->SetString(prefs::kMetricsClientID, client_id_);
if (pref->GetString(prefs::kMetricsOldClientID).empty()) {
pref->SetInt64(prefs::kMetricsReportingEnabledTimestamp,
Time::Now().ToTimeT());
} else {
UMA_HISTOGRAM_BOOLEAN("UMA.ClientIdMigrated", true);
}
pref->ClearPref(prefs::kMetricsOldClientID);
}
void MetricsService::EnableRecording() {
DCHECK(IsSingleThreaded());
if (recording_active_)
return;
recording_active_ = true;
ForceClientIdCreation();
crash_keys::SetClientID(client_id_);
if (!log_manager_.current_log())
OpenNewLog();
SetUpNotifications(®istrar_, this);
base::RemoveActionCallback(action_callback_);
action_callback_ = base::Bind(&MetricsService::OnUserAction,
base::Unretained(this));
base::AddActionCallback(action_callback_);
}
void MetricsService::DisableRecording() {
DCHECK(IsSingleThreaded());
if (!recording_active_)
return;
recording_active_ = false;
base::RemoveActionCallback(action_callback_);
registrar_.RemoveAll();
PushPendingLogsToPersistentStorage();
DCHECK(!log_manager_.has_staged_log());
}
bool MetricsService::recording_active() const {
DCHECK(IsSingleThreaded());
return recording_active_;
}
bool MetricsService::reporting_active() const {
DCHECK(IsSingleThreaded());
return reporting_active_;
}
void MetricsService::SetUpNotifications(
content::NotificationRegistrar* registrar,
content::NotificationObserver* observer) {
registrar->Add(observer, chrome::NOTIFICATION_BROWSER_OPENED,
content::NotificationService::AllBrowserContextsAndSources());
registrar->Add(observer, chrome::NOTIFICATION_BROWSER_CLOSED,
content::NotificationService::AllSources());
registrar->Add(observer, chrome::NOTIFICATION_TAB_PARENTED,
content::NotificationService::AllSources());
registrar->Add(observer, chrome::NOTIFICATION_TAB_CLOSING,
content::NotificationService::AllSources());
registrar->Add(observer, content::NOTIFICATION_LOAD_START,
content::NotificationService::AllSources());
registrar->Add(observer, content::NOTIFICATION_LOAD_STOP,
content::NotificationService::AllSources());
registrar->Add(observer, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
content::NotificationService::AllSources());
registrar->Add(observer, content::NOTIFICATION_RENDER_WIDGET_HOST_HANG,
content::NotificationService::AllSources());
registrar->Add(observer, chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
content::NotificationService::AllSources());
}
void MetricsService::BrowserChildProcessHostConnected(
const content::ChildProcessData& data) {
GetChildProcessStats(data).process_launches++;
}
void MetricsService::BrowserChildProcessCrashed(
const content::ChildProcessData& data) {
GetChildProcessStats(data).process_crashes++;
if (!IsPluginProcess(data.process_type))
IncrementPrefValue(prefs::kStabilityChildProcessCrashCount);
}
void MetricsService::BrowserChildProcessInstanceCreated(
const content::ChildProcessData& data) {
GetChildProcessStats(data).instances++;
}
void MetricsService::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK(log_manager_.current_log());
DCHECK(IsSingleThreaded());
bool handled = false;
switch (type) {
case chrome::NOTIFICATION_BROWSER_OPENED:
case chrome::NOTIFICATION_BROWSER_CLOSED:
case chrome::NOTIFICATION_TAB_PARENTED:
case chrome::NOTIFICATION_TAB_CLOSING:
case content::NOTIFICATION_LOAD_STOP:
handled = true;
break;
case content::NOTIFICATION_LOAD_START: {
content::NavigationController* controller =
content::Source<content::NavigationController>(source).ptr();
content::WebContents* web_contents = controller->GetWebContents();
LogLoadStarted(web_contents);
handled = true;
break;
}
case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: {
content::RenderProcessHost::RendererClosedDetails* process_details =
content::Details<
content::RenderProcessHost::RendererClosedDetails>(
details).ptr();
content::RenderProcessHost* host =
content::Source<content::RenderProcessHost>(source).ptr();
LogRendererCrash(
host, process_details->status, process_details->exit_code);
handled = true;
break;
}
case content::NOTIFICATION_RENDER_WIDGET_HOST_HANG:
LogRendererHang();
handled = true;
break;
default:
break;
}
if (!handled && ShouldLogEvents()) {
switch (type) {
case chrome::NOTIFICATION_OMNIBOX_OPENED_URL: {
MetricsLog* current_log =
static_cast<MetricsLog*>(log_manager_.current_log());
DCHECK(current_log);
current_log->RecordOmniboxOpenedURL(
*content::Details<OmniboxLog>(details).ptr());
break;
}
default:
NOTREACHED();
break;
}
}
HandleIdleSinceLastTransmission(false);
}
void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
if (!in_idle && idle_since_last_transmission_)
StartSchedulerIfNecessary();
idle_since_last_transmission_ = in_idle;
}
void MetricsService::RecordStartOfSessionEnd() {
LogCleanShutdown();
RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
}
void MetricsService::RecordCompletedSessionEnd() {
LogCleanShutdown();
RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
}
#if defined(OS_ANDROID) || defined(OS_IOS)
void MetricsService::OnAppEnterBackground() {
scheduler_->Stop();
MarkAppCleanShutdownAndCommit();
if (recording_active() && state_ >= SENDING_INITIAL_STABILITY_LOG) {
PushPendingLogsToPersistentStorage();
OpenNewLog();
}
}
void MetricsService::OnAppEnterForeground() {
PrefService* pref = g_browser_process->local_state();
pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
StartSchedulerIfNecessary();
}
#else
void MetricsService::LogNeedForCleanShutdown() {
PrefService* pref = g_browser_process->local_state();
pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
clean_shutdown_status_ = NEED_TO_SHUTDOWN;
}
#endif
void MetricsService::SetExecutionPhase(ExecutionPhase execution_phase) {
execution_phase_ = execution_phase;
PrefService* pref = g_browser_process->local_state();
pref->SetInteger(prefs::kStabilityExecutionPhase, execution_phase_);
}
void MetricsService::RecordBreakpadRegistration(bool success) {
if (!success)
IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
else
IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
}
void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
if (!has_debugger)
IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
else
IncrementPrefValue(prefs::kStabilityDebuggerPresent);
}
#if defined(OS_WIN)
void MetricsService::CountBrowserCrashDumpAttempts() {
base::win::RegKey regkey;
if (regkey.Open(HKEY_CURRENT_USER,
chrome::kBrowserCrashDumpAttemptsRegistryPath,
KEY_ALL_ACCESS) != ERROR_SUCCESS) {
return;
}
base::string16 chrome_version(base::ASCIIToUTF16(chrome::kChromeVersion));
typedef std::vector<base::string16> StringVector;
StringVector to_delete;
base::string16 name;
DWORD value = 0;
int dumps_with_crash = 0;
int dumps_with_no_crash = 0;
for (int i = regkey.GetValueCount() - 1; i >= 0; --i) {
if (regkey.GetValueNameAt(i, &name) == ERROR_SUCCESS &&
StartsWith(name, chrome_version, false) &&
regkey.ReadValueDW(name.c_str(), &value) == ERROR_SUCCESS) {
to_delete.push_back(name);
if (value == 0)
++dumps_with_no_crash;
else
++dumps_with_crash;
}
}
for (StringVector::iterator i = to_delete.begin(); i != to_delete.end(); ++i)
regkey.DeleteValue(i->c_str());
if (dumps_with_crash != 0)
UMA_HISTOGRAM_COUNTS("Chrome.BrowserDumpsWithCrash", dumps_with_crash);
if (dumps_with_no_crash != 0)
UMA_HISTOGRAM_COUNTS("Chrome.BrowserDumpsWithNoCrash", dumps_with_no_crash);
int total_dumps = dumps_with_crash + dumps_with_no_crash;
if (total_dumps != 0)
UMA_HISTOGRAM_COUNTS("Chrome.BrowserCrashDumpAttempts", total_dumps);
}
#endif
void MetricsService::InitializeMetricsState(ReportingState reporting_state) {
#if defined(OS_POSIX)
network_stats_server_ = chrome_common_net::kEchoTestServerLocation;
http_pipelining_test_server_ = chrome_common_net::kPipelineTestServerBaseUrl;
#else
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
network_stats_server_ = dist->GetNetworkStatsServer();
http_pipelining_test_server_ = dist->GetHttpPipeliningTestServer();
#endif
PrefService* pref = g_browser_process->local_state();
DCHECK(pref);
if ((pref->GetInt64(prefs::kStabilityStatsBuildTime)
!= MetricsLog::GetBuildTime()) ||
(pref->GetString(prefs::kStabilityStatsVersion)
!= MetricsLog::GetVersionString())) {
DiscardOldStabilityStats(pref);
pref->SetString(prefs::kStabilityStatsVersion,
MetricsLog::GetVersionString());
pref->SetInt64(prefs::kStabilityStatsBuildTime,
MetricsLog::GetBuildTime());
}
session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
#if defined(OS_ANDROID)
LogAndroidStabilityToPrefs(pref);
#endif
if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
IncrementPrefValue(prefs::kStabilityCrashCount);
pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
int execution_phase = pref->GetInteger(prefs::kStabilityExecutionPhase);
UMA_HISTOGRAM_SPARSE_SLOWLY("Chrome.Browser.CrashedExecutionPhase",
execution_phase);
bool reporting_will_be_enabled = (reporting_state == REPORTING_ENABLED);
if (reporting_will_be_enabled && SendSeparateInitialStabilityLog())
PrepareInitialStabilityLog();
}
++session_id_;
pref->SetInteger(prefs::kMetricsSessionID, session_id_);
IncrementPrefValue(prefs::kStabilityLaunchCount);
DCHECK_EQ(UNINITIALIZED_PHASE, execution_phase_);
SetExecutionPhase(START_METRICS_RECORDING);
#if defined(OS_WIN)
CountBrowserCrashDumpAttempts();
#endif
if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
}
base::TimeDelta ignored_uptime_parameter;
base::TimeDelta startup_uptime;
GetUptimes(pref, &startup_uptime, &ignored_uptime_parameter);
DCHECK_EQ(0, startup_uptime.InMicroseconds());
pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
const CommandLine* command_line(CommandLine::ForCurrentProcess());
size_t common_commands = 0;
if (command_line->HasSwitch(switches::kUserDataDir)) {
++common_commands;
UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
}
if (command_line->HasSwitch(switches::kApp)) {
++common_commands;
UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
}
size_t switch_count = command_line->GetSwitches().size();
UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount", switch_count);
UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
switch_count - common_commands);
ScheduleNextStateSave();
}
void MetricsService::InitTaskGetHardwareClass(
base::WeakPtr<MetricsService> self,
base::MessageLoopProxy* target_loop) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
std::string hardware_class;
#if defined(OS_CHROMEOS)
chromeos::system::StatisticsProvider::GetInstance()->GetMachineStatistic(
"hardware_class", &hardware_class);
#endif
target_loop->PostTask(FROM_HERE,
base::Bind(&MetricsService::OnInitTaskGotHardwareClass,
self, hardware_class));
}
void MetricsService::OnInitTaskGotHardwareClass(
const std::string& hardware_class) {
DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
hardware_class_ = hardware_class;
#if defined(ENABLE_PLUGINS)
PluginService::GetInstance()->GetPlugins(
base::Bind(&MetricsService::OnInitTaskGotPluginInfo,
self_ptr_factory_.GetWeakPtr()));
#else
std::vector<content::WebPluginInfo> plugin_list_empty;
OnInitTaskGotPluginInfo(plugin_list_empty);
#endif
}
void MetricsService::OnInitTaskGotPluginInfo(
const std::vector<content::WebPluginInfo>& plugins) {
DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
plugins_ = plugins;
BrowserThread::PostBlockingPoolTask(
FROM_HERE,
base::Bind(&MetricsService::InitTaskGetGoogleUpdateData,
self_ptr_factory_.GetWeakPtr(),
base::MessageLoop::current()->message_loop_proxy()));
}
void MetricsService::InitTaskGetGoogleUpdateData(
base::WeakPtr<MetricsService> self,
base::MessageLoopProxy* target_loop) {
GoogleUpdateMetrics google_update_metrics;
#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
const bool system_install = GoogleUpdateSettings::IsSystemInstall();
google_update_metrics.is_system_install = system_install;
google_update_metrics.last_started_au =
GoogleUpdateSettings::GetGoogleUpdateLastStartedAU(system_install);
google_update_metrics.last_checked =
GoogleUpdateSettings::GetGoogleUpdateLastChecked(system_install);
GoogleUpdateSettings::GetUpdateDetailForGoogleUpdate(
system_install,
&google_update_metrics.google_update_data);
GoogleUpdateSettings::GetUpdateDetail(
system_install,
&google_update_metrics.product_data);
#endif
target_loop->PostTask(FROM_HERE,
base::Bind(&MetricsService::OnInitTaskGotGoogleUpdateData,
self, google_update_metrics));
}
void MetricsService::OnInitTaskGotGoogleUpdateData(
const GoogleUpdateMetrics& google_update_metrics) {
DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
google_update_metrics_ = google_update_metrics;
chrome_browser_metrics::TrackingSynchronizer::FetchProfilerDataAsynchronously(
self_ptr_factory_.GetWeakPtr());
}
void MetricsService::OnUserAction(const std::string& action) {
if (!ShouldLogEvents())
return;
log_manager_.current_log()->RecordUserAction(action.c_str());
HandleIdleSinceLastTransmission(false);
}
void MetricsService::ReceivedProfilerData(
const tracked_objects::ProcessDataSnapshot& process_data,
int process_type) {
DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
if (!initial_metrics_log_.get())
initial_metrics_log_.reset(new MetricsLog(client_id_, session_id_));
initial_metrics_log_->RecordProfilerData(process_data, process_type);
}
void MetricsService::FinishedReceivingProfilerData() {
DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
state_ = INIT_TASK_DONE;
scheduler_->InitTaskComplete();
}
void MetricsService::GetUptimes(PrefService* pref,
base::TimeDelta* incremental_uptime,
base::TimeDelta* uptime) {
base::TimeTicks now = base::TimeTicks::Now();
if (last_updated_time_.is_null()) {
first_updated_time_ = now;
last_updated_time_ = now;
}
*incremental_uptime = now - last_updated_time_;
*uptime = now - first_updated_time_;
last_updated_time_ = now;
const int64 incremental_time_secs = incremental_uptime->InSeconds();
if (incremental_time_secs > 0) {
int64 metrics_uptime = pref->GetInt64(prefs::kUninstallMetricsUptimeSec);
metrics_uptime += incremental_time_secs;
pref->SetInt64(prefs::kUninstallMetricsUptimeSec, metrics_uptime);
}
}
void MetricsService::ResetMetricsIDsIfNecessary() {
if (metrics_ids_reset_check_performed_)
return;
metrics_ids_reset_check_performed_ = true;
PrefService* local_state = g_browser_process->local_state();
if (!local_state->GetBoolean(prefs::kMetricsResetIds))
return;
UMA_HISTOGRAM_BOOLEAN("UMA.MetricsIDsReset", true);
DCHECK(client_id_.empty());
DCHECK_EQ(kLowEntropySourceNotSet, low_entropy_source_);
local_state->ClearPref(prefs::kMetricsClientID);
local_state->ClearPref(prefs::kMetricsLowEntropySource);
local_state->ClearPref(prefs::kMetricsResetIds);
}
int MetricsService::GetLowEntropySource() {
if (low_entropy_source_ != kLowEntropySourceNotSet)
return low_entropy_source_;
ResetMetricsIDsIfNecessary();
PrefService* local_state = g_browser_process->local_state();
const CommandLine* command_line(CommandLine::ForCurrentProcess());
if (!command_line->HasSwitch(switches::kResetVariationState)) {
int value = local_state->GetInteger(prefs::kMetricsLowEntropySource);
if (value >= 0 && value < kMaxLowEntropySize) {
low_entropy_source_ = value;
UMA_HISTOGRAM_BOOLEAN("UMA.GeneratedLowEntropySource", false);
return low_entropy_source_;
}
}
UMA_HISTOGRAM_BOOLEAN("UMA.GeneratedLowEntropySource", true);
low_entropy_source_ = GenerateLowEntropySource();
local_state->SetInteger(prefs::kMetricsLowEntropySource, low_entropy_source_);
local_state->ClearPref(prefs::kMetricsOldLowEntropySource);
metrics::CachingPermutedEntropyProvider::ClearCache(local_state);
return low_entropy_source_;
}
std::string MetricsService::GenerateClientID() {
return base::GenerateGUID();
}
void MetricsService::ScheduleNextStateSave() {
state_saver_factory_.InvalidateWeakPtrs();
base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
base::Bind(&MetricsService::SaveLocalState,
state_saver_factory_.GetWeakPtr()),
base::TimeDelta::FromMinutes(kSaveStateIntervalMinutes));
}
void MetricsService::SaveLocalState() {
PrefService* pref = g_browser_process->local_state();
if (!pref) {
NOTREACHED();
return;
}
RecordCurrentState(pref);
ScheduleNextStateSave();
}
void MetricsService::OpenNewLog() {
DCHECK(!log_manager_.current_log());
log_manager_.BeginLoggingWithLog(new MetricsLog(client_id_, session_id_),
MetricsLog::ONGOING_LOG);
if (state_ == INITIALIZED) {
state_ = INIT_TASK_SCHEDULED;
BrowserThread::PostDelayedTask(
BrowserThread::FILE,
FROM_HERE,
base::Bind(&MetricsService::InitTaskGetHardwareClass,
self_ptr_factory_.GetWeakPtr(),
base::MessageLoop::current()->message_loop_proxy()),
base::TimeDelta::FromSeconds(kInitializationDelaySeconds));
}
}
void MetricsService::CloseCurrentLog() {
if (!log_manager_.current_log())
return;
if (log_manager_.current_log()->num_events() > kEventLimit) {
UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
log_manager_.current_log()->num_events());
log_manager_.DiscardCurrentLog();
OpenNewLog();
}
log_manager_.current_log()->set_hardware_class(hardware_class_);
MetricsLog* current_log =
static_cast<MetricsLog*>(log_manager_.current_log());
DCHECK(current_log);
std::vector<chrome_variations::ActiveGroupId> synthetic_trials;
GetCurrentSyntheticFieldTrials(&synthetic_trials);
current_log->RecordEnvironment(plugins_, google_update_metrics_,
synthetic_trials);
PrefService* pref = g_browser_process->local_state();
base::TimeDelta incremental_uptime;
base::TimeDelta uptime;
GetUptimes(pref, &incremental_uptime, &uptime);
current_log->RecordStabilityMetrics(incremental_uptime, uptime,
MetricsLog::ONGOING_LOG);
RecordCurrentHistograms();
log_manager_.FinishCurrentLog();
}
void MetricsService::PushPendingLogsToPersistentStorage() {
if (state_ < SENDING_INITIAL_STABILITY_LOG)
return;
if (log_manager_.has_staged_log()) {
MetricsLogManager::StoreType store_type;
if (current_fetch_.get())
store_type = MetricsLogManager::PROVISIONAL_STORE;
else
store_type = MetricsLogManager::NORMAL_STORE;
log_manager_.StoreStagedLogAsUnsent(store_type);
}
DCHECK(!log_manager_.has_staged_log());
CloseCurrentLog();
log_manager_.PersistUnsentLogs();
if (log_manager_.has_unsent_logs())
state_ = SENDING_OLD_LOGS;
}
void MetricsService::StartSchedulerIfNecessary() {
if (test_mode_active_)
return;
if (recording_active() &&
(reporting_active() || state_ < SENDING_INITIAL_STABILITY_LOG)) {
scheduler_->Start();
}
}
void MetricsService::StartScheduledUpload() {
if (idle_since_last_transmission_ ||
!recording_active() ||
(!reporting_active() && state_ >= SENDING_INITIAL_STABILITY_LOG)) {
scheduler_->Stop();
scheduler_->UploadCancelled();
return;
}
if (state_ == SENDING_OLD_LOGS && !log_manager_.has_unsent_logs()) {
state_ = SENDING_CURRENT_LOGS;
scheduler_->UploadFinished(true , false );
return;
}
if (state_ == SENDING_OLD_LOGS) {
DCHECK(log_manager_.has_unsent_logs());
log_manager_.StageNextLogForUpload();
SendStagedLog();
} else {
StartFinalLogInfoCollection();
}
}
void MetricsService::StartFinalLogInfoCollection() {
DCHECK(!waiting_for_asynchronous_reporting_step_);
waiting_for_asynchronous_reporting_step_ = true;
base::Closure callback =
base::Bind(&MetricsService::OnMemoryDetailCollectionDone,
self_ptr_factory_.GetWeakPtr());
scoped_refptr<MetricsMemoryDetails> details(
new MetricsMemoryDetails(callback));
details->StartFetch(MemoryDetails::UPDATE_USER_METRICS);
for (content::RenderProcessHost::iterator i(
content::RenderProcessHost::AllHostsIterator());
!i.IsAtEnd(); i.Advance())
i.GetCurrentValue()->Send(new ChromeViewMsg_GetCacheResourceStats());
}
void MetricsService::OnMemoryDetailCollectionDone() {
DCHECK(IsSingleThreaded());
DCHECK(waiting_for_asynchronous_reporting_step_);
base::Closure callback = base::Bind(
&MetricsService::OnHistogramSynchronizationDone,
self_ptr_factory_.GetWeakPtr());
base::TimeDelta timeout =
base::TimeDelta::FromMilliseconds(kMaxHistogramGatheringWaitDuration);
DCHECK_EQ(num_async_histogram_fetches_in_progress_, 0);
#if defined(OS_ANDROID)
num_async_histogram_fetches_in_progress_ = 1;
#else
num_async_histogram_fetches_in_progress_ = 2;
if (!ServiceProcessControl::GetInstance()->GetHistograms(callback, timeout)) {
DCHECK_EQ(num_async_histogram_fetches_in_progress_, 2);
--num_async_histogram_fetches_in_progress_;
}
#endif
content::FetchHistogramsAsynchronously(base::MessageLoop::current(), callback,
timeout);
}
void MetricsService::OnHistogramSynchronizationDone() {
DCHECK(IsSingleThreaded());
DCHECK(waiting_for_asynchronous_reporting_step_);
DCHECK_GT(num_async_histogram_fetches_in_progress_, 0);
if (--num_async_histogram_fetches_in_progress_ > 0)
return;
waiting_for_asynchronous_reporting_step_ = false;
OnFinalLogInfoCollectionDone();
}
void MetricsService::OnFinalLogInfoCollectionDone() {
DCHECK(!current_fetch_.get());
if (current_fetch_.get())
return;
if (!recording_active()) {
scheduler_->Stop();
scheduler_->UploadCancelled();
return;
}
StageNewLog();
if (!reporting_active()) {
scheduler_->Stop();
scheduler_->UploadCancelled();
return;
}
SendStagedLog();
}
void MetricsService::StageNewLog() {
if (log_manager_.has_staged_log())
return;
switch (state_) {
case INITIALIZED:
case INIT_TASK_SCHEDULED:
NOTREACHED();
return;
case INIT_TASK_DONE:
if (has_initial_stability_log_) {
log_manager_.StageNextLogForUpload();
has_initial_stability_log_ = false;
state_ = SENDING_INITIAL_STABILITY_LOG;
} else {
MetricsLog::LogType log_type = SendSeparateInitialStabilityLog() ?
MetricsLog::ONGOING_LOG : MetricsLog::INITIAL_LOG;
PrepareInitialMetricsLog(log_type);
log_manager_.LoadPersistedUnsentLogs();
state_ = SENDING_INITIAL_METRICS_LOG;
}
break;
case SENDING_OLD_LOGS:
NOTREACHED();
return;
case SENDING_CURRENT_LOGS:
CloseCurrentLog();
OpenNewLog();
log_manager_.StageNextLogForUpload();
break;
default:
NOTREACHED();
return;
}
DCHECK(log_manager_.has_staged_log());
}
void MetricsService::PrepareInitialStabilityLog() {
DCHECK_EQ(INITIALIZED, state_);
PrefService* pref = g_browser_process->local_state();
DCHECK_NE(0, pref->GetInteger(prefs::kStabilityCrashCount));
scoped_ptr<MetricsLog> initial_stability_log(
new MetricsLog(client_id_, session_id_));
if (!initial_stability_log->LoadSavedEnvironmentFromPrefs())
return;
initial_stability_log->RecordStabilityMetrics(
base::TimeDelta(), base::TimeDelta(), MetricsLog::INITIAL_LOG);
log_manager_.LoadPersistedUnsentLogs();
log_manager_.PauseCurrentLog();
log_manager_.BeginLoggingWithLog(initial_stability_log.release(),
MetricsLog::INITIAL_LOG);
#if defined(OS_ANDROID)
ConvertAndroidStabilityPrefsToHistograms(pref);
RecordCurrentStabilityHistograms();
#endif
log_manager_.FinishCurrentLog();
log_manager_.ResumePausedLog();
log_manager_.PersistUnsentLogs();
has_initial_stability_log_ = true;
}
void MetricsService::PrepareInitialMetricsLog(MetricsLog::LogType log_type) {
DCHECK(state_ == INIT_TASK_DONE || state_ == SENDING_INITIAL_STABILITY_LOG);
initial_metrics_log_->set_hardware_class(hardware_class_);
std::vector<chrome_variations::ActiveGroupId> synthetic_trials;
GetCurrentSyntheticFieldTrials(&synthetic_trials);
initial_metrics_log_->RecordEnvironment(plugins_, google_update_metrics_,
synthetic_trials);
PrefService* pref = g_browser_process->local_state();
base::TimeDelta incremental_uptime;
base::TimeDelta uptime;
GetUptimes(pref, &incremental_uptime, &uptime);
initial_metrics_log_->RecordStabilityMetrics(incremental_uptime, uptime,
log_type);
log_manager_.PauseCurrentLog();
log_manager_.BeginLoggingWithLog(initial_metrics_log_.release(), log_type);
#if defined(OS_ANDROID)
ConvertAndroidStabilityPrefsToHistograms(pref);
#endif
RecordCurrentHistograms();
log_manager_.FinishCurrentLog();
log_manager_.ResumePausedLog();
DCHECK(!log_manager_.has_staged_log());
log_manager_.StageNextLogForUpload();
}
void MetricsService::SendStagedLog() {
DCHECK(log_manager_.has_staged_log());
PrepareFetchWithStagedLog();
bool upload_created = (current_fetch_.get() != NULL);
UMA_HISTOGRAM_BOOLEAN("UMA.UploadCreation", upload_created);
if (!upload_created) {
log_manager_.DiscardStagedLog();
scheduler_->UploadCancelled();
return;
}
DCHECK(!waiting_for_asynchronous_reporting_step_);
waiting_for_asynchronous_reporting_step_ = true;
current_fetch_->Start();
HandleIdleSinceLastTransmission(true);
}
void MetricsService::PrepareFetchWithStagedLog() {
DCHECK(log_manager_.has_staged_log());
DCHECK(!current_fetch_.get());
if (log_manager_.has_staged_log()) {
current_fetch_.reset(net::URLFetcher::Create(
GURL(kServerUrl), net::URLFetcher::POST, this));
current_fetch_->SetRequestContext(
g_browser_process->system_request_context());
std::string log_text = log_manager_.staged_log_text();
std::string compressed_log_text;
bool compression_successful = chrome::GzipCompress(log_text,
&compressed_log_text);
DCHECK(compression_successful);
if (compression_successful) {
current_fetch_->SetUploadData(kMimeType, compressed_log_text);
current_fetch_->SetExtraRequestHeaders("content-encoding: gzip");
const std::string hash =
base::HexEncode(log_manager_.staged_log_hash().data(),
log_manager_.staged_log_hash().size());
DCHECK(!hash.empty());
current_fetch_->AddExtraRequestHeader("X-Chrome-UMA-Log-SHA1: " + hash);
UMA_HISTOGRAM_PERCENTAGE(
"UMA.ProtoCompressionRatio",
100 * compressed_log_text.size() / log_text.size());
UMA_HISTOGRAM_CUSTOM_COUNTS(
"UMA.ProtoGzippedKBSaved",
(log_text.size() - compressed_log_text.size()) / 1024,
1, 2000, 50);
}
current_fetch_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES |
net::LOAD_DO_NOT_SEND_COOKIES);
}
}
void MetricsService::OnURLFetchComplete(const net::URLFetcher* source) {
DCHECK(waiting_for_asynchronous_reporting_step_);
DCHECK_EQ(current_fetch_.get(), source);
scoped_ptr<net::URLFetcher> s(current_fetch_.Pass());
int response_code = source->GetResponseCode();
UMA_HISTOGRAM_ENUMERATION("UMA.UploadResponseStatus.Protobuf",
ResponseCodeToStatus(response_code),
NUM_RESPONSE_STATUSES);
log_manager_.DiscardLastProvisionalStore();
bool upload_succeeded = response_code == 200;
bool discard_log = false;
const size_t log_size = log_manager_.staged_log_text().length();
if (!upload_succeeded && log_size > kUploadLogAvoidRetransmitSize) {
UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
static_cast<int>(log_size));
discard_log = true;
} else if (response_code == 400) {
discard_log = true;
}
if (upload_succeeded || discard_log)
log_manager_.DiscardStagedLog();
waiting_for_asynchronous_reporting_step_ = false;
if (!log_manager_.has_staged_log()) {
switch (state_) {
case SENDING_INITIAL_STABILITY_LOG:
log_manager_.PersistUnsentLogs();
PrepareInitialMetricsLog(MetricsLog::ONGOING_LOG);
SendStagedLog();
state_ = SENDING_INITIAL_METRICS_LOG;
break;
case SENDING_INITIAL_METRICS_LOG:
state_ = log_manager_.has_unsent_logs() ? SENDING_OLD_LOGS
: SENDING_CURRENT_LOGS;
break;
case SENDING_OLD_LOGS:
log_manager_.PersistUnsentLogs();
if (!log_manager_.has_unsent_logs())
state_ = SENDING_CURRENT_LOGS;
break;
case SENDING_CURRENT_LOGS:
break;
default:
NOTREACHED();
break;
}
if (log_manager_.has_unsent_logs())
DCHECK_LT(state_, SENDING_CURRENT_LOGS);
}
bool server_is_healthy = upload_succeeded || response_code == 400;
if (state_ != SENDING_INITIAL_METRICS_LOG) {
scheduler_->UploadFinished(server_is_healthy,
log_manager_.has_unsent_logs());
}
IOThread* io_thread = g_browser_process->io_thread();
if (server_is_healthy && io_thread) {
chrome_browser_net::CollectNetworkStats(network_stats_server_, io_thread);
chrome_browser_net::CollectPipeliningCapabilityStatsOnUIThread(
http_pipelining_test_server_, io_thread);
#if defined(OS_WIN)
chrome::CollectTimeTicksStats();
#endif
}
}
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);
}
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);
}
void MetricsService::LogLoadStarted(content::WebContents* web_contents) {
content::RecordAction(base::UserMetricsAction("PageLoad"));
HISTOGRAM_ENUMERATION("Chrome.UmaPageloadCounter", 1, 2);
IncrementPrefValue(prefs::kStabilityPageLoadCount);
IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
}
void MetricsService::LogRendererCrash(content::RenderProcessHost* host,
base::TerminationStatus status,
int exit_code) {
bool was_extension_process =
extensions::ProcessMap::Get(host->GetBrowserContext())
->Contains(host->GetID());
if (status == base::TERMINATION_STATUS_PROCESS_CRASHED ||
status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
if (was_extension_process) {
IncrementPrefValue(prefs::kStabilityExtensionRendererCrashCount);
UMA_HISTOGRAM_SPARSE_SLOWLY("CrashExitCodes.Extension",
MapCrashExitCodeForHistogram(exit_code));
} else {
IncrementPrefValue(prefs::kStabilityRendererCrashCount);
UMA_HISTOGRAM_SPARSE_SLOWLY("CrashExitCodes.Renderer",
MapCrashExitCodeForHistogram(exit_code));
}
UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildCrashes",
was_extension_process ? 2 : 1);
} else if (status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED) {
UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildKills",
was_extension_process ? 2 : 1);
} else if (status == base::TERMINATION_STATUS_STILL_RUNNING) {
UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.DisconnectedAlive",
was_extension_process ? 2 : 1);
}
}
void MetricsService::LogRendererHang() {
IncrementPrefValue(prefs::kStabilityRendererHangCount);
}
bool MetricsService::UmaMetricsProperlyShutdown() {
CHECK(clean_shutdown_status_ == CLEANLY_SHUTDOWN ||
clean_shutdown_status_ == NEED_TO_SHUTDOWN);
return clean_shutdown_status_ == CLEANLY_SHUTDOWN;
}
void MetricsService::RegisterSyntheticFieldTrial(
const SyntheticTrialGroup& trial) {
for (size_t i = 0; i < synthetic_trial_groups_.size(); ++i) {
if (synthetic_trial_groups_[i].id.name == trial.id.name) {
if (synthetic_trial_groups_[i].id.group != trial.id.group) {
synthetic_trial_groups_[i].id.group = trial.id.group;
synthetic_trial_groups_[i].start_time = base::TimeTicks::Now();
}
return;
}
}
SyntheticTrialGroup trial_group = trial;
trial_group.start_time = base::TimeTicks::Now();
synthetic_trial_groups_.push_back(trial_group);
}
void MetricsService::CheckForClonedInstall() {
DCHECK(!cloned_install_detector_);
metrics::MachineIdProvider* provider =
metrics::MachineIdProvider::CreateInstance();
if (!provider)
return;
cloned_install_detector_.reset(
new metrics::ClonedInstallDetector(provider));
PrefService* local_state = g_browser_process->local_state();
cloned_install_detector_->CheckForClonedInstall(local_state);
}
void MetricsService::GetCurrentSyntheticFieldTrials(
std::vector<chrome_variations::ActiveGroupId>* synthetic_trials) {
DCHECK(synthetic_trials);
synthetic_trials->clear();
const MetricsLog* current_log =
static_cast<const MetricsLog*>(log_manager_.current_log());
for (size_t i = 0; i < synthetic_trial_groups_.size(); ++i) {
if (synthetic_trial_groups_[i].start_time <= current_log->creation_time())
synthetic_trials->push_back(synthetic_trial_groups_[i].id);
}
}
void MetricsService::LogCleanShutdown() {
MarkAppCleanShutdownAndCommit();
clean_shutdown_status_ = CLEANLY_SHUTDOWN;
RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
PrefService* pref = g_browser_process->local_state();
pref->SetInteger(prefs::kStabilityExecutionPhase,
MetricsService::SHUTDOWN_COMPLETE);
}
#if defined(OS_CHROMEOS)
void MetricsService::LogChromeOSCrash(const std::string &crash_type) {
if (crash_type == "user")
IncrementPrefValue(prefs::kStabilityOtherUserCrashCount);
else if (crash_type == "kernel")
IncrementPrefValue(prefs::kStabilityKernelCrashCount);
else if (crash_type == "uncleanshutdown")
IncrementPrefValue(prefs::kStabilitySystemUncleanShutdownCount);
else
NOTREACHED() << "Unexpected Chrome OS crash type " << crash_type;
HandleIdleSinceLastTransmission(false);
}
#endif
void MetricsService::LogPluginLoadingError(const base::FilePath& plugin_path) {
content::WebPluginInfo plugin;
bool success =
content::PluginService::GetInstance()->GetPluginInfoByPath(plugin_path,
&plugin);
DCHECK(success);
ChildProcessStats& stats = child_process_stats_buffer_[plugin.name];
if (stats.process_type == content::PROCESS_TYPE_UNKNOWN) {
stats.process_type = content::PROCESS_TYPE_PLUGIN;
} else {
DCHECK(IsPluginProcess(stats.process_type));
}
stats.loading_errors++;
}
MetricsService::ChildProcessStats& MetricsService::GetChildProcessStats(
const content::ChildProcessData& data) {
const base::string16& child_name = data.name;
if (!ContainsKey(child_process_stats_buffer_, child_name)) {
child_process_stats_buffer_[child_name] =
ChildProcessStats(data.process_type);
}
return child_process_stats_buffer_[child_name];
}
void MetricsService::RecordPluginChanges(PrefService* pref) {
ListPrefUpdate update(pref, prefs::kStabilityPluginStats);
base::ListValue* plugins = update.Get();
DCHECK(plugins);
for (base::ListValue::iterator value_iter = plugins->begin();
value_iter != plugins->end(); ++value_iter) {
if (!(*value_iter)->IsType(base::Value::TYPE_DICTIONARY)) {
NOTREACHED();
continue;
}
base::DictionaryValue* plugin_dict =
static_cast<base::DictionaryValue*>(*value_iter);
std::string plugin_name;
plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
if (plugin_name.empty()) {
NOTREACHED();
continue;
}
base::string16 name16 = base::UTF8ToUTF16(plugin_name);
if (child_process_stats_buffer_.find(name16) ==
child_process_stats_buffer_.end()) {
continue;
}
ChildProcessStats stats = child_process_stats_buffer_[name16];
if (stats.process_launches) {
int launches = 0;
plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
launches += stats.process_launches;
plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
}
if (stats.process_crashes) {
int crashes = 0;
plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
crashes += stats.process_crashes;
plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
}
if (stats.instances) {
int instances = 0;
plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
instances += stats.instances;
plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
}
if (stats.loading_errors) {
int loading_errors = 0;
plugin_dict->GetInteger(prefs::kStabilityPluginLoadingErrors,
&loading_errors);
loading_errors += stats.loading_errors;
plugin_dict->SetInteger(prefs::kStabilityPluginLoadingErrors,
loading_errors);
}
child_process_stats_buffer_.erase(name16);
}
for (std::map<base::string16, ChildProcessStats>::iterator cache_iter =
child_process_stats_buffer_.begin();
cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
ChildProcessStats stats = cache_iter->second;
if (!IsPluginProcess(stats.process_type))
continue;
std::string plugin_name = base::UTF16ToUTF8(cache_iter->first);
base::DictionaryValue* plugin_dict = new base::DictionaryValue;
plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
stats.process_launches);
plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
stats.process_crashes);
plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
stats.instances);
plugin_dict->SetInteger(prefs::kStabilityPluginLoadingErrors,
stats.loading_errors);
plugins->Append(plugin_dict);
}
child_process_stats_buffer_.clear();
}
bool MetricsService::ShouldLogEvents() {
return !chrome::IsOffTheRecordSessionActive();
}
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);
}
void MetricsService::RecordCurrentState(PrefService* pref) {
pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
RecordPluginChanges(pref);
}
bool MetricsService::IsPluginProcess(int process_type) {
return (process_type == content::PROCESS_TYPE_PLUGIN ||
process_type == content::PROCESS_TYPE_PPAPI_PLUGIN ||
process_type == content::PROCESS_TYPE_PPAPI_BROKER);
}
#if defined(OS_CHROMEOS)
void MetricsService::StartExternalMetrics() {
external_metrics_ = new chromeos::ExternalMetrics;
external_metrics_->Start();
}
#endif
bool MetricsServiceHelper::IsMetricsReportingEnabled() {
bool result = false;
const PrefService* local_state = g_browser_process->local_state();
if (local_state) {
const PrefService::Preference* uma_pref =
local_state->FindPreference(prefs::kMetricsReportingEnabled);
if (uma_pref) {
bool success = uma_pref->GetValue()->GetAsBoolean(&result);
DCHECK(success);
}
}
return result;
}
bool MetricsServiceHelper::IsCrashReportingEnabled() {
#if defined(GOOGLE_CHROME_BUILD)
#if defined(OS_CHROMEOS)
bool reporting_enabled = false;
chromeos::CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref,
&reporting_enabled);
return reporting_enabled;
#elif defined(OS_ANDROID)
const PrefService* prefs = g_browser_process->local_state();
return prefs->GetBoolean(prefs::kCrashReportingEnabled);
#else
return MetricsServiceHelper::IsMetricsReportingEnabled();
#endif
#else
return false;
#endif
}