Home | History | Annotate | Download | only in metrics
      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/metrics_log.h"
      6 
      7 #include <algorithm>
      8 #include <string>
      9 #include <vector>
     10 
     11 #include "base/basictypes.h"
     12 #include "base/bind.h"
     13 #include "base/cpu.h"
     14 #include "base/lazy_instance.h"
     15 #include "base/memory/scoped_ptr.h"
     16 #include "base/perftimer.h"
     17 #include "base/prefs/pref_registry_simple.h"
     18 #include "base/prefs/pref_service.h"
     19 #include "base/profiler/alternate_timer.h"
     20 #include "base/strings/string_number_conversions.h"
     21 #include "base/strings/string_util.h"
     22 #include "base/strings/utf_string_conversions.h"
     23 #include "base/sys_info.h"
     24 #include "base/third_party/nspr/prtime.h"
     25 #include "base/time/time.h"
     26 #include "base/tracked_objects.h"
     27 #include "chrome/browser/autocomplete/autocomplete_input.h"
     28 #include "chrome/browser/autocomplete/autocomplete_match.h"
     29 #include "chrome/browser/autocomplete/autocomplete_provider.h"
     30 #include "chrome/browser/autocomplete/autocomplete_result.h"
     31 #include "chrome/browser/browser_process.h"
     32 #include "chrome/browser/google/google_util.h"
     33 #include "chrome/browser/omnibox/omnibox_log.h"
     34 #include "chrome/browser/plugins/plugin_prefs.h"
     35 #include "chrome/browser/profiles/profile_manager.h"
     36 #include "chrome/common/chrome_version_info.h"
     37 #include "chrome/common/logging_chrome.h"
     38 #include "chrome/common/metrics/proto/omnibox_event.pb.h"
     39 #include "chrome/common/metrics/proto/profiler_event.pb.h"
     40 #include "chrome/common/metrics/proto/system_profile.pb.h"
     41 #include "chrome/common/metrics/variations/variations_util.h"
     42 #include "chrome/common/pref_names.h"
     43 #include "chrome/installer/util/google_update_settings.h"
     44 #include "components/nacl/common/nacl_process_type.h"
     45 #include "content/public/browser/gpu_data_manager.h"
     46 #include "content/public/common/content_client.h"
     47 #include "content/public/common/webplugininfo.h"
     48 #include "device/bluetooth/bluetooth_adapter.h"
     49 #include "device/bluetooth/bluetooth_adapter_factory.h"
     50 #include "device/bluetooth/bluetooth_device.h"
     51 #include "gpu/config/gpu_info.h"
     52 #include "ui/gfx/screen.h"
     53 #include "url/gurl.h"
     54 
     55 #if defined(OS_ANDROID)
     56 #include "base/android/build_info.h"
     57 #endif
     58 
     59 #if defined(OS_WIN)
     60 #include "base/win/metro.h"
     61 #include "ui/base/win/dpi.h"
     62 
     63 // http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx
     64 extern "C" IMAGE_DOS_HEADER __ImageBase;
     65 #endif
     66 
     67 using content::GpuDataManager;
     68 using metrics::OmniboxEventProto;
     69 using metrics::PerfDataProto;
     70 using metrics::ProfilerEventProto;
     71 using metrics::SystemProfileProto;
     72 using tracked_objects::ProcessDataSnapshot;
     73 typedef chrome_variations::ActiveGroupId ActiveGroupId;
     74 typedef SystemProfileProto::GoogleUpdate::ProductInfo ProductInfo;
     75 typedef SystemProfileProto::Hardware::Bluetooth::PairedDevice PairedDevice;
     76 
     77 namespace {
     78 
     79 // Returns the date at which the current metrics client ID was created as
     80 // a string containing seconds since the epoch, or "0" if none was found.
     81 std::string GetMetricsEnabledDate(PrefService* pref) {
     82   if (!pref) {
     83     NOTREACHED();
     84     return "0";
     85   }
     86 
     87   return pref->GetString(prefs::kMetricsClientIDTimestamp);
     88 }
     89 
     90 OmniboxEventProto::InputType AsOmniboxEventInputType(
     91     AutocompleteInput::Type type) {
     92   switch (type) {
     93     case AutocompleteInput::INVALID:
     94       return OmniboxEventProto::INVALID;
     95     case AutocompleteInput::UNKNOWN:
     96       return OmniboxEventProto::UNKNOWN;
     97     case AutocompleteInput::URL:
     98       return OmniboxEventProto::URL;
     99     case AutocompleteInput::QUERY:
    100       return OmniboxEventProto::QUERY;
    101     case AutocompleteInput::FORCED_QUERY:
    102       return OmniboxEventProto::FORCED_QUERY;
    103     default:
    104       NOTREACHED();
    105       return OmniboxEventProto::INVALID;
    106   }
    107 }
    108 
    109 OmniboxEventProto::Suggestion::ResultType AsOmniboxEventResultType(
    110     AutocompleteMatch::Type type) {
    111   switch (type) {
    112     case AutocompleteMatchType::URL_WHAT_YOU_TYPED:
    113       return OmniboxEventProto::Suggestion::URL_WHAT_YOU_TYPED;
    114     case AutocompleteMatchType::HISTORY_URL:
    115       return OmniboxEventProto::Suggestion::HISTORY_URL;
    116     case AutocompleteMatchType::HISTORY_TITLE:
    117       return OmniboxEventProto::Suggestion::HISTORY_TITLE;
    118     case AutocompleteMatchType::HISTORY_BODY:
    119       return OmniboxEventProto::Suggestion::HISTORY_BODY;
    120     case AutocompleteMatchType::HISTORY_KEYWORD:
    121       return OmniboxEventProto::Suggestion::HISTORY_KEYWORD;
    122     case AutocompleteMatchType::NAVSUGGEST:
    123       return OmniboxEventProto::Suggestion::NAVSUGGEST;
    124     case AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED:
    125       return OmniboxEventProto::Suggestion::SEARCH_WHAT_YOU_TYPED;
    126     case AutocompleteMatchType::SEARCH_HISTORY:
    127       return OmniboxEventProto::Suggestion::SEARCH_HISTORY;
    128     case AutocompleteMatchType::SEARCH_SUGGEST:
    129       return OmniboxEventProto::Suggestion::SEARCH_SUGGEST;
    130     case AutocompleteMatchType::SEARCH_OTHER_ENGINE:
    131       return OmniboxEventProto::Suggestion::SEARCH_OTHER_ENGINE;
    132     case AutocompleteMatchType::EXTENSION_APP:
    133       return OmniboxEventProto::Suggestion::EXTENSION_APP;
    134     case AutocompleteMatchType::CONTACT:
    135       return OmniboxEventProto::Suggestion::CONTACT;
    136     case AutocompleteMatchType::BOOKMARK_TITLE:
    137       return OmniboxEventProto::Suggestion::BOOKMARK_TITLE;
    138     default:
    139       NOTREACHED();
    140       return OmniboxEventProto::Suggestion::UNKNOWN_RESULT_TYPE;
    141   }
    142 }
    143 
    144 OmniboxEventProto::PageClassification AsOmniboxEventPageClassification(
    145     AutocompleteInput::PageClassification page_classification) {
    146   switch (page_classification) {
    147     case AutocompleteInput::INVALID_SPEC:
    148       return OmniboxEventProto::INVALID_SPEC;
    149     case AutocompleteInput::NEW_TAB_PAGE:
    150       return OmniboxEventProto::NEW_TAB_PAGE;
    151     case AutocompleteInput::BLANK:
    152       return OmniboxEventProto::BLANK;
    153     case AutocompleteInput::HOMEPAGE:
    154       return OmniboxEventProto::HOMEPAGE;
    155     case AutocompleteInput::OTHER:
    156       return OmniboxEventProto::OTHER;
    157     case AutocompleteInput::SEARCH_RESULT_PAGE_DOING_SEARCH_TERM_REPLACEMENT:
    158       return OmniboxEventProto::
    159           SEARCH_RESULT_PAGE_DOING_SEARCH_TERM_REPLACEMENT;
    160     case AutocompleteInput::INSTANT_NEW_TAB_PAGE_WITH_OMNIBOX_AS_STARTING_FOCUS:
    161       return OmniboxEventProto::
    162           INSTANT_NEW_TAB_PAGE_WITH_OMNIBOX_AS_STARTING_FOCUS;
    163     case AutocompleteInput::INSTANT_NEW_TAB_PAGE_WITH_FAKEBOX_AS_STARTING_FOCUS:
    164       return OmniboxEventProto::
    165           INSTANT_NEW_TAB_PAGE_WITH_FAKEBOX_AS_STARTING_FOCUS;
    166     case AutocompleteInput::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT:
    167       return OmniboxEventProto::
    168           SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT;
    169   }
    170   return OmniboxEventProto::INVALID_SPEC;
    171 }
    172 
    173 ProfilerEventProto::TrackedObject::ProcessType AsProtobufProcessType(
    174     int process_type) {
    175   switch (process_type) {
    176     case content::PROCESS_TYPE_BROWSER:
    177       return ProfilerEventProto::TrackedObject::BROWSER;
    178     case content::PROCESS_TYPE_RENDERER:
    179       return ProfilerEventProto::TrackedObject::RENDERER;
    180     case content::PROCESS_TYPE_PLUGIN:
    181       return ProfilerEventProto::TrackedObject::PLUGIN;
    182     case content::PROCESS_TYPE_WORKER:
    183       return ProfilerEventProto::TrackedObject::WORKER;
    184     case content::PROCESS_TYPE_UTILITY:
    185       return ProfilerEventProto::TrackedObject::UTILITY;
    186     case content::PROCESS_TYPE_ZYGOTE:
    187       return ProfilerEventProto::TrackedObject::ZYGOTE;
    188     case content::PROCESS_TYPE_SANDBOX_HELPER:
    189       return ProfilerEventProto::TrackedObject::SANDBOX_HELPER;
    190     case content::PROCESS_TYPE_GPU:
    191       return ProfilerEventProto::TrackedObject::GPU;
    192     case content::PROCESS_TYPE_PPAPI_PLUGIN:
    193       return ProfilerEventProto::TrackedObject::PPAPI_PLUGIN;
    194     case content::PROCESS_TYPE_PPAPI_BROKER:
    195       return ProfilerEventProto::TrackedObject::PPAPI_BROKER;
    196     case PROCESS_TYPE_NACL_LOADER:
    197       return ProfilerEventProto::TrackedObject::NACL_LOADER;
    198     case PROCESS_TYPE_NACL_BROKER:
    199       return ProfilerEventProto::TrackedObject::NACL_BROKER;
    200     default:
    201       NOTREACHED();
    202       return ProfilerEventProto::TrackedObject::UNKNOWN;
    203   }
    204 }
    205 
    206 // Returns the plugin preferences corresponding for this user, if available.
    207 // If multiple user profiles are loaded, returns the preferences corresponding
    208 // to an arbitrary one of the profiles.
    209 PluginPrefs* GetPluginPrefs() {
    210   ProfileManager* profile_manager = g_browser_process->profile_manager();
    211 
    212   if (!profile_manager) {
    213     // The profile manager can be NULL when testing.
    214     return NULL;
    215   }
    216 
    217   std::vector<Profile*> profiles = profile_manager->GetLoadedProfiles();
    218   if (profiles.empty())
    219     return NULL;
    220 
    221   return PluginPrefs::GetForProfile(profiles.front()).get();
    222 }
    223 
    224 // Fills |plugin| with the info contained in |plugin_info| and |plugin_prefs|.
    225 void SetPluginInfo(const content::WebPluginInfo& plugin_info,
    226                    const PluginPrefs* plugin_prefs,
    227                    SystemProfileProto::Plugin* plugin) {
    228   plugin->set_name(UTF16ToUTF8(plugin_info.name));
    229   plugin->set_filename(plugin_info.path.BaseName().AsUTF8Unsafe());
    230   plugin->set_version(UTF16ToUTF8(plugin_info.version));
    231   if (plugin_prefs)
    232     plugin->set_is_disabled(!plugin_prefs->IsPluginEnabled(plugin_info));
    233 }
    234 
    235 void WriteFieldTrials(const std::vector<ActiveGroupId>& field_trial_ids,
    236                       SystemProfileProto* system_profile) {
    237   for (std::vector<ActiveGroupId>::const_iterator it =
    238        field_trial_ids.begin(); it != field_trial_ids.end(); ++it) {
    239     SystemProfileProto::FieldTrial* field_trial =
    240         system_profile->add_field_trial();
    241     field_trial->set_name_id(it->name);
    242     field_trial->set_group_id(it->group);
    243   }
    244 }
    245 
    246 void WriteProfilerData(const ProcessDataSnapshot& profiler_data,
    247                        int process_type,
    248                        ProfilerEventProto* performance_profile) {
    249   for (std::vector<tracked_objects::TaskSnapshot>::const_iterator it =
    250            profiler_data.tasks.begin();
    251        it != profiler_data.tasks.end(); ++it) {
    252     const tracked_objects::DeathDataSnapshot& death_data = it->death_data;
    253     ProfilerEventProto::TrackedObject* tracked_object =
    254         performance_profile->add_tracked_object();
    255     tracked_object->set_birth_thread_name_hash(
    256         MetricsLogBase::Hash(it->birth.thread_name));
    257     tracked_object->set_exec_thread_name_hash(
    258         MetricsLogBase::Hash(it->death_thread_name));
    259     tracked_object->set_source_file_name_hash(
    260         MetricsLogBase::Hash(it->birth.location.file_name));
    261     tracked_object->set_source_function_name_hash(
    262         MetricsLogBase::Hash(it->birth.location.function_name));
    263     tracked_object->set_source_line_number(it->birth.location.line_number);
    264     tracked_object->set_exec_count(death_data.count);
    265     tracked_object->set_exec_time_total(death_data.run_duration_sum);
    266     tracked_object->set_exec_time_sampled(death_data.run_duration_sample);
    267     tracked_object->set_queue_time_total(death_data.queue_duration_sum);
    268     tracked_object->set_queue_time_sampled(death_data.queue_duration_sample);
    269     tracked_object->set_process_type(AsProtobufProcessType(process_type));
    270     tracked_object->set_process_id(profiler_data.process_id);
    271   }
    272 }
    273 
    274 #if defined(GOOGLE_CHROME_BUILD) && defined(OS_WIN)
    275 void ProductDataToProto(const GoogleUpdateSettings::ProductData& product_data,
    276                         ProductInfo* product_info) {
    277   product_info->set_version(product_data.version);
    278   product_info->set_last_update_success_timestamp(
    279       product_data.last_success.ToTimeT());
    280   product_info->set_last_error(product_data.last_error_code);
    281   product_info->set_last_extra_error(product_data.last_extra_code);
    282   if (ProductInfo::InstallResult_IsValid(product_data.last_result)) {
    283     product_info->set_last_result(
    284         static_cast<ProductInfo::InstallResult>(product_data.last_result));
    285   }
    286 }
    287 #endif
    288 
    289 #if defined(OS_WIN)
    290 struct ScreenDPIInformation {
    291   double max_dpi_x;
    292   double max_dpi_y;
    293 };
    294 
    295 // Called once for each connected monitor.
    296 BOOL CALLBACK GetMonitorDPICallback(HMONITOR, HDC hdc, LPRECT, LPARAM dwData) {
    297   const double kMillimetersPerInch = 25.4;
    298   ScreenDPIInformation* screen_info =
    299       reinterpret_cast<ScreenDPIInformation*>(dwData);
    300   // Size of screen, in mm.
    301   DWORD size_x = GetDeviceCaps(hdc, HORZSIZE);
    302   DWORD size_y = GetDeviceCaps(hdc, VERTSIZE);
    303   double dpi_x = (size_x > 0) ?
    304       GetDeviceCaps(hdc, HORZRES) / (size_x / kMillimetersPerInch) : 0;
    305   double dpi_y = (size_y > 0) ?
    306       GetDeviceCaps(hdc, VERTRES) / (size_y / kMillimetersPerInch) : 0;
    307   dpi_x *= ui::win::GetUndocumentedDPIScale();
    308   dpi_y *= ui::win::GetUndocumentedDPIScale();
    309   screen_info->max_dpi_x = std::max(dpi_x, screen_info->max_dpi_x);
    310   screen_info->max_dpi_y = std::max(dpi_y, screen_info->max_dpi_y);
    311   return TRUE;
    312 }
    313 
    314 void WriteScreenDPIInformationProto(SystemProfileProto::Hardware* hardware) {
    315   HDC desktop_dc = GetDC(NULL);
    316   if (desktop_dc) {
    317     ScreenDPIInformation si = {0, 0};
    318     if (EnumDisplayMonitors(desktop_dc, NULL, GetMonitorDPICallback,
    319             reinterpret_cast<LPARAM>(&si))) {
    320       hardware->set_max_dpi_x(si.max_dpi_x);
    321       hardware->set_max_dpi_y(si.max_dpi_y);
    322     }
    323     ReleaseDC(GetDesktopWindow(), desktop_dc);
    324   }
    325 }
    326 
    327 #endif  // defined(OS_WIN)
    328 
    329 #if defined(OS_CHROMEOS)
    330 PairedDevice::Type AsBluetoothDeviceType(
    331     enum device::BluetoothDevice::DeviceType device_type) {
    332   switch (device_type) {
    333     case device::BluetoothDevice::DEVICE_UNKNOWN:
    334       return PairedDevice::DEVICE_UNKNOWN;
    335     case device::BluetoothDevice::DEVICE_COMPUTER:
    336       return PairedDevice::DEVICE_COMPUTER;
    337     case device::BluetoothDevice::DEVICE_PHONE:
    338       return PairedDevice::DEVICE_PHONE;
    339     case device::BluetoothDevice::DEVICE_MODEM:
    340       return PairedDevice::DEVICE_MODEM;
    341     case device::BluetoothDevice::DEVICE_AUDIO:
    342       return PairedDevice::DEVICE_AUDIO;
    343     case device::BluetoothDevice::DEVICE_CAR_AUDIO:
    344       return PairedDevice::DEVICE_CAR_AUDIO;
    345     case device::BluetoothDevice::DEVICE_VIDEO:
    346       return PairedDevice::DEVICE_VIDEO;
    347     case device::BluetoothDevice::DEVICE_PERIPHERAL:
    348       return PairedDevice::DEVICE_PERIPHERAL;
    349     case device::BluetoothDevice::DEVICE_JOYSTICK:
    350       return PairedDevice::DEVICE_JOYSTICK;
    351     case device::BluetoothDevice::DEVICE_GAMEPAD:
    352       return PairedDevice::DEVICE_GAMEPAD;
    353     case device::BluetoothDevice::DEVICE_KEYBOARD:
    354       return PairedDevice::DEVICE_KEYBOARD;
    355     case device::BluetoothDevice::DEVICE_MOUSE:
    356       return PairedDevice::DEVICE_MOUSE;
    357     case device::BluetoothDevice::DEVICE_TABLET:
    358       return PairedDevice::DEVICE_TABLET;
    359     case device::BluetoothDevice::DEVICE_KEYBOARD_MOUSE_COMBO:
    360       return PairedDevice::DEVICE_KEYBOARD_MOUSE_COMBO;
    361   }
    362 
    363   NOTREACHED();
    364   return PairedDevice::DEVICE_UNKNOWN;
    365 }
    366 #endif  // defined(OS_CHROMEOS)
    367 
    368 // Round a timestamp measured in seconds since epoch to one with a granularity
    369 // of an hour. This can be used before uploaded potentially sensitive
    370 // timestamps.
    371 int64 RoundSecondsToHour(int64 time_in_seconds) {
    372   return 3600 * (time_in_seconds / 3600);
    373 }
    374 
    375 }  // namespace
    376 
    377 GoogleUpdateMetrics::GoogleUpdateMetrics() : is_system_install(false) {}
    378 
    379 GoogleUpdateMetrics::~GoogleUpdateMetrics() {}
    380 
    381 static base::LazyInstance<std::string>::Leaky
    382   g_version_extension = LAZY_INSTANCE_INITIALIZER;
    383 
    384 MetricsLog::MetricsLog(const std::string& client_id, int session_id)
    385     : MetricsLogBase(client_id, session_id, MetricsLog::GetVersionString()) {}
    386 
    387 MetricsLog::~MetricsLog() {}
    388 
    389 // static
    390 void MetricsLog::RegisterPrefs(PrefRegistrySimple* registry) {
    391   registry->RegisterListPref(prefs::kStabilityPluginStats);
    392 }
    393 
    394 // static
    395 int64 MetricsLog::GetIncrementalUptime(PrefService* pref) {
    396   base::TimeTicks now = base::TimeTicks::Now();
    397   static base::TimeTicks last_updated_time(now);
    398   int64 incremental_time = (now - last_updated_time).InSeconds();
    399   last_updated_time = now;
    400 
    401   if (incremental_time > 0) {
    402     int64 metrics_uptime = pref->GetInt64(prefs::kUninstallMetricsUptimeSec);
    403     metrics_uptime += incremental_time;
    404     pref->SetInt64(prefs::kUninstallMetricsUptimeSec, metrics_uptime);
    405   }
    406 
    407   return incremental_time;
    408 }
    409 
    410 // static
    411 std::string MetricsLog::GetVersionString() {
    412   chrome::VersionInfo version_info;
    413   if (!version_info.is_valid()) {
    414     NOTREACHED() << "Unable to retrieve version info.";
    415     return std::string();
    416   }
    417 
    418   std::string version = version_info.Version();
    419   if (!version_extension().empty())
    420     version += version_extension();
    421   if (!version_info.IsOfficialBuild())
    422     version.append("-devel");
    423   return version;
    424 }
    425 
    426 // static
    427 void MetricsLog::set_version_extension(const std::string& extension) {
    428   g_version_extension.Get() = extension;
    429 }
    430 
    431 // static
    432 const std::string& MetricsLog::version_extension() {
    433   return g_version_extension.Get();
    434 }
    435 
    436 void MetricsLog::RecordIncrementalStabilityElements(
    437     const std::vector<content::WebPluginInfo>& plugin_list) {
    438   DCHECK(!locked());
    439 
    440   PrefService* pref = GetPrefService();
    441   DCHECK(pref);
    442 
    443   WriteRequiredStabilityAttributes(pref);
    444   WriteRealtimeStabilityAttributes(pref);
    445   WritePluginStabilityElements(plugin_list, pref);
    446 }
    447 
    448 PrefService* MetricsLog::GetPrefService() {
    449   return g_browser_process->local_state();
    450 }
    451 
    452 gfx::Size MetricsLog::GetScreenSize() const {
    453   return gfx::Screen::GetNativeScreen()->GetPrimaryDisplay().GetSizeInPixel();
    454 }
    455 
    456 float MetricsLog::GetScreenDeviceScaleFactor() const {
    457   return gfx::Screen::GetNativeScreen()->
    458       GetPrimaryDisplay().device_scale_factor();
    459 }
    460 
    461 int MetricsLog::GetScreenCount() const {
    462   // TODO(scottmg): NativeScreen maybe wrong. http://crbug.com/133312
    463   return gfx::Screen::GetNativeScreen()->GetNumDisplays();
    464 }
    465 
    466 void MetricsLog::GetFieldTrialIds(
    467     std::vector<ActiveGroupId>* field_trial_ids) const {
    468   chrome_variations::GetFieldTrialActiveGroupIds(field_trial_ids);
    469 }
    470 
    471 void MetricsLog::WriteStabilityElement(
    472     const std::vector<content::WebPluginInfo>& plugin_list,
    473     PrefService* pref) {
    474   DCHECK(!locked());
    475 
    476   // Get stability attributes out of Local State, zeroing out stored values.
    477   // NOTE: This could lead to some data loss if this report isn't successfully
    478   //       sent, but that's true for all the metrics.
    479 
    480   WriteRequiredStabilityAttributes(pref);
    481   WriteRealtimeStabilityAttributes(pref);
    482 
    483   int incomplete_shutdown_count =
    484       pref->GetInteger(prefs::kStabilityIncompleteSessionEndCount);
    485   pref->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
    486   int breakpad_registration_success_count =
    487       pref->GetInteger(prefs::kStabilityBreakpadRegistrationSuccess);
    488   pref->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
    489   int breakpad_registration_failure_count =
    490       pref->GetInteger(prefs::kStabilityBreakpadRegistrationFail);
    491   pref->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
    492   int debugger_present_count =
    493       pref->GetInteger(prefs::kStabilityDebuggerPresent);
    494   pref->SetInteger(prefs::kStabilityDebuggerPresent, 0);
    495   int debugger_not_present_count =
    496       pref->GetInteger(prefs::kStabilityDebuggerNotPresent);
    497   pref->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
    498 
    499   // TODO(jar): The following are all optional, so we *could* optimize them for
    500   // values of zero (and not include them).
    501   SystemProfileProto::Stability* stability =
    502       uma_proto()->mutable_system_profile()->mutable_stability();
    503   stability->set_incomplete_shutdown_count(incomplete_shutdown_count);
    504   stability->set_breakpad_registration_success_count(
    505       breakpad_registration_success_count);
    506   stability->set_breakpad_registration_failure_count(
    507       breakpad_registration_failure_count);
    508   stability->set_debugger_present_count(debugger_present_count);
    509   stability->set_debugger_not_present_count(debugger_not_present_count);
    510 
    511   WritePluginStabilityElements(plugin_list, pref);
    512 }
    513 
    514 void MetricsLog::WritePluginStabilityElements(
    515     const std::vector<content::WebPluginInfo>& plugin_list,
    516     PrefService* pref) {
    517   // Now log plugin stability info.
    518   const ListValue* plugin_stats_list = pref->GetList(
    519       prefs::kStabilityPluginStats);
    520   if (!plugin_stats_list)
    521     return;
    522 
    523 #if defined(ENABLE_PLUGINS)
    524   SystemProfileProto::Stability* stability =
    525       uma_proto()->mutable_system_profile()->mutable_stability();
    526   PluginPrefs* plugin_prefs = GetPluginPrefs();
    527   for (ListValue::const_iterator iter = plugin_stats_list->begin();
    528        iter != plugin_stats_list->end(); ++iter) {
    529     if (!(*iter)->IsType(Value::TYPE_DICTIONARY)) {
    530       NOTREACHED();
    531       continue;
    532     }
    533     DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*iter);
    534 
    535     // Write the protobuf version.
    536     // Note that this search is potentially a quadratic operation, but given the
    537     // low number of plugins installed on a "reasonable" setup, this should be
    538     // fine.
    539     // TODO(isherman): Verify that this does not show up as a hotspot in
    540     // profiler runs.
    541     const content::WebPluginInfo* plugin_info = NULL;
    542     std::string plugin_name;
    543     plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
    544     const string16 plugin_name_utf16 = UTF8ToUTF16(plugin_name);
    545     for (std::vector<content::WebPluginInfo>::const_iterator iter =
    546              plugin_list.begin();
    547          iter != plugin_list.end(); ++iter) {
    548       if (iter->name == plugin_name_utf16) {
    549         plugin_info = &(*iter);
    550         break;
    551       }
    552     }
    553 
    554     if (!plugin_info) {
    555       NOTREACHED();
    556       continue;
    557     }
    558 
    559     SystemProfileProto::Stability::PluginStability* plugin_stability =
    560         stability->add_plugin_stability();
    561     SetPluginInfo(*plugin_info, plugin_prefs,
    562                   plugin_stability->mutable_plugin());
    563 
    564     int launches = 0;
    565     plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
    566     if (launches > 0)
    567       plugin_stability->set_launch_count(launches);
    568 
    569     int instances = 0;
    570     plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
    571     if (instances > 0)
    572       plugin_stability->set_instance_count(instances);
    573 
    574     int crashes = 0;
    575     plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
    576     if (crashes > 0)
    577       plugin_stability->set_crash_count(crashes);
    578 
    579     int loading_errors = 0;
    580     plugin_dict->GetInteger(prefs::kStabilityPluginLoadingErrors,
    581                             &loading_errors);
    582     if (loading_errors > 0)
    583       plugin_stability->set_loading_error_count(loading_errors);
    584   }
    585 #endif  // defined(ENABLE_PLUGINS)
    586 
    587   pref->ClearPref(prefs::kStabilityPluginStats);
    588 }
    589 
    590 // The server refuses data that doesn't have certain values.  crashcount and
    591 // launchcount are currently "required" in the "stability" group.
    592 // TODO(isherman): Stop writing these attributes specially once the migration to
    593 // protobufs is complete.
    594 void MetricsLog::WriteRequiredStabilityAttributes(PrefService* pref) {
    595   int launch_count = pref->GetInteger(prefs::kStabilityLaunchCount);
    596   pref->SetInteger(prefs::kStabilityLaunchCount, 0);
    597   int crash_count = pref->GetInteger(prefs::kStabilityCrashCount);
    598   pref->SetInteger(prefs::kStabilityCrashCount, 0);
    599 
    600   SystemProfileProto::Stability* stability =
    601       uma_proto()->mutable_system_profile()->mutable_stability();
    602   stability->set_launch_count(launch_count);
    603   stability->set_crash_count(crash_count);
    604 }
    605 
    606 void MetricsLog::WriteRealtimeStabilityAttributes(PrefService* pref) {
    607   // Update the stats which are critical for real-time stability monitoring.
    608   // Since these are "optional," only list ones that are non-zero, as the counts
    609   // are aggergated (summed) server side.
    610 
    611   SystemProfileProto::Stability* stability =
    612       uma_proto()->mutable_system_profile()->mutable_stability();
    613   int count = pref->GetInteger(prefs::kStabilityPageLoadCount);
    614   if (count) {
    615     stability->set_page_load_count(count);
    616     pref->SetInteger(prefs::kStabilityPageLoadCount, 0);
    617   }
    618 
    619   count = pref->GetInteger(prefs::kStabilityRendererCrashCount);
    620   if (count) {
    621     stability->set_renderer_crash_count(count);
    622     pref->SetInteger(prefs::kStabilityRendererCrashCount, 0);
    623   }
    624 
    625   count = pref->GetInteger(prefs::kStabilityExtensionRendererCrashCount);
    626   if (count) {
    627     stability->set_extension_renderer_crash_count(count);
    628     pref->SetInteger(prefs::kStabilityExtensionRendererCrashCount, 0);
    629   }
    630 
    631   count = pref->GetInteger(prefs::kStabilityRendererHangCount);
    632   if (count) {
    633     stability->set_renderer_hang_count(count);
    634     pref->SetInteger(prefs::kStabilityRendererHangCount, 0);
    635   }
    636 
    637   count = pref->GetInteger(prefs::kStabilityChildProcessCrashCount);
    638   if (count) {
    639     stability->set_child_process_crash_count(count);
    640     pref->SetInteger(prefs::kStabilityChildProcessCrashCount, 0);
    641   }
    642 
    643 #if defined(OS_CHROMEOS)
    644   count = pref->GetInteger(prefs::kStabilityOtherUserCrashCount);
    645   if (count) {
    646     stability->set_other_user_crash_count(count);
    647     pref->SetInteger(prefs::kStabilityOtherUserCrashCount, 0);
    648   }
    649 
    650   count = pref->GetInteger(prefs::kStabilityKernelCrashCount);
    651   if (count) {
    652     stability->set_kernel_crash_count(count);
    653     pref->SetInteger(prefs::kStabilityKernelCrashCount, 0);
    654   }
    655 
    656   count = pref->GetInteger(prefs::kStabilitySystemUncleanShutdownCount);
    657   if (count) {
    658     stability->set_unclean_system_shutdown_count(count);
    659     pref->SetInteger(prefs::kStabilitySystemUncleanShutdownCount, 0);
    660   }
    661 #endif  // OS_CHROMEOS
    662 
    663   int64 recent_duration = GetIncrementalUptime(pref);
    664   if (recent_duration)
    665     stability->set_uptime_sec(recent_duration);
    666 }
    667 
    668 void MetricsLog::WritePluginList(
    669     const std::vector<content::WebPluginInfo>& plugin_list) {
    670   DCHECK(!locked());
    671 
    672 #if defined(ENABLE_PLUGINS)
    673   PluginPrefs* plugin_prefs = GetPluginPrefs();
    674   SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
    675   for (std::vector<content::WebPluginInfo>::const_iterator iter =
    676            plugin_list.begin();
    677        iter != plugin_list.end(); ++iter) {
    678     SystemProfileProto::Plugin* plugin = system_profile->add_plugin();
    679     SetPluginInfo(*iter, plugin_prefs, plugin);
    680   }
    681 #endif  // defined(ENABLE_PLUGINS)
    682 }
    683 
    684 void MetricsLog::RecordEnvironment(
    685          const std::vector<content::WebPluginInfo>& plugin_list,
    686          const GoogleUpdateMetrics& google_update_metrics) {
    687   DCHECK(!locked());
    688 
    689   PrefService* pref = GetPrefService();
    690   WriteStabilityElement(plugin_list, pref);
    691 
    692   RecordEnvironmentProto(plugin_list, google_update_metrics);
    693 }
    694 
    695 void MetricsLog::RecordEnvironmentProto(
    696     const std::vector<content::WebPluginInfo>& plugin_list,
    697     const GoogleUpdateMetrics& google_update_metrics) {
    698   SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
    699 
    700   std::string brand_code;
    701   if (google_util::GetBrand(&brand_code))
    702     system_profile->set_brand_code(brand_code);
    703 
    704   int enabled_date;
    705   bool success = base::StringToInt(GetMetricsEnabledDate(GetPrefService()),
    706                                    &enabled_date);
    707   DCHECK(success);
    708 
    709   // Reduce granularity of the enabled_date field to nearest hour.
    710   system_profile->set_uma_enabled_date(RoundSecondsToHour(enabled_date));
    711 
    712   int64 install_date = GetPrefService()->GetInt64(prefs::kInstallDate);
    713 
    714   // Reduce granularity of the install_date field to nearest hour.
    715   system_profile->set_install_date(RoundSecondsToHour(install_date));
    716 
    717   system_profile->set_application_locale(
    718       g_browser_process->GetApplicationLocale());
    719 
    720   SystemProfileProto::Hardware* hardware = system_profile->mutable_hardware();
    721   hardware->set_cpu_architecture(base::SysInfo::OperatingSystemArchitecture());
    722   hardware->set_system_ram_mb(base::SysInfo::AmountOfPhysicalMemoryMB());
    723 #if defined(OS_WIN)
    724   hardware->set_dll_base(reinterpret_cast<uint64>(&__ImageBase));
    725 #endif
    726 
    727   SystemProfileProto::Network* network = system_profile->mutable_network();
    728   network->set_connection_type_is_ambiguous(
    729       network_observer_.connection_type_is_ambiguous());
    730   network->set_connection_type(network_observer_.connection_type());
    731   network->set_wifi_phy_layer_protocol_is_ambiguous(
    732       network_observer_.wifi_phy_layer_protocol_is_ambiguous());
    733   network->set_wifi_phy_layer_protocol(
    734       network_observer_.wifi_phy_layer_protocol());
    735   network_observer_.Reset();
    736 
    737   SystemProfileProto::OS* os = system_profile->mutable_os();
    738   std::string os_name = base::SysInfo::OperatingSystemName();
    739 #if defined(OS_WIN)
    740   // TODO(mad): This only checks whether the main process is a Metro process at
    741   // upload time; not whether the collected metrics were all gathered from
    742   // Metro.  This is ok as an approximation for now, since users will rarely be
    743   // switching from Metro to Desktop mode; but we should re-evaluate whether we
    744   // can distinguish metrics more cleanly in the future: http://crbug.com/140568
    745   if (base::win::IsMetroProcess())
    746     os_name += " (Metro)";
    747 #endif
    748   os->set_name(os_name);
    749   os->set_version(base::SysInfo::OperatingSystemVersion());
    750 #if defined(OS_ANDROID)
    751   os->set_fingerprint(
    752       base::android::BuildInfo::GetInstance()->android_build_fp());
    753 #endif
    754 
    755   base::CPU cpu_info;
    756   SystemProfileProto::Hardware::CPU* cpu = hardware->mutable_cpu();
    757   cpu->set_vendor_name(cpu_info.vendor_name());
    758   cpu->set_signature(cpu_info.signature());
    759 
    760   const gpu::GPUInfo& gpu_info =
    761       GpuDataManager::GetInstance()->GetGPUInfo();
    762   SystemProfileProto::Hardware::Graphics* gpu = hardware->mutable_gpu();
    763   gpu->set_vendor_id(gpu_info.gpu.vendor_id);
    764   gpu->set_device_id(gpu_info.gpu.device_id);
    765   gpu->set_driver_version(gpu_info.driver_version);
    766   gpu->set_driver_date(gpu_info.driver_date);
    767   SystemProfileProto::Hardware::Graphics::PerformanceStatistics*
    768       gpu_performance = gpu->mutable_performance_statistics();
    769   gpu_performance->set_graphics_score(gpu_info.performance_stats.graphics);
    770   gpu_performance->set_gaming_score(gpu_info.performance_stats.gaming);
    771   gpu_performance->set_overall_score(gpu_info.performance_stats.overall);
    772   gpu->set_gl_vendor(gpu_info.gl_vendor);
    773   gpu->set_gl_renderer(gpu_info.gl_renderer);
    774 
    775   const gfx::Size display_size = GetScreenSize();
    776   hardware->set_primary_screen_width(display_size.width());
    777   hardware->set_primary_screen_height(display_size.height());
    778   hardware->set_primary_screen_scale_factor(GetScreenDeviceScaleFactor());
    779   hardware->set_screen_count(GetScreenCount());
    780 
    781 #if defined(OS_WIN)
    782   WriteScreenDPIInformationProto(hardware);
    783 #endif
    784 
    785   WriteGoogleUpdateProto(google_update_metrics);
    786 
    787   WritePluginList(plugin_list);
    788 
    789   std::vector<ActiveGroupId> field_trial_ids;
    790   GetFieldTrialIds(&field_trial_ids);
    791   WriteFieldTrials(field_trial_ids, system_profile);
    792 
    793 #if defined(OS_CHROMEOS)
    794   PerfDataProto perf_data_proto;
    795   if (perf_provider_.GetPerfData(&perf_data_proto))
    796     uma_proto()->add_perf_data()->Swap(&perf_data_proto);
    797 
    798   // BluetoothAdapterFactory::GetAdapter is synchronous on Chrome OS; if that
    799   // changes this will fail at the DCHECK().
    800   device::BluetoothAdapterFactory::GetAdapter(
    801       base::Bind(&MetricsLog::SetBluetoothAdapter,
    802                  base::Unretained(this)));
    803   DCHECK(adapter_.get());
    804   WriteBluetoothProto(hardware);
    805 #endif
    806 }
    807 
    808 void MetricsLog::RecordProfilerData(
    809     const tracked_objects::ProcessDataSnapshot& process_data,
    810     int process_type) {
    811   DCHECK(!locked());
    812 
    813   if (tracked_objects::GetTimeSourceType() !=
    814           tracked_objects::TIME_SOURCE_TYPE_WALL_TIME) {
    815     // We currently only support the default time source, wall clock time.
    816     return;
    817   }
    818 
    819   ProfilerEventProto* profile;
    820   if (!uma_proto()->profiler_event_size()) {
    821     // For the first process's data, add a new field to the protocol buffer.
    822     profile = uma_proto()->add_profiler_event();
    823     profile->set_profile_type(ProfilerEventProto::STARTUP_PROFILE);
    824     profile->set_time_source(ProfilerEventProto::WALL_CLOCK_TIME);
    825   } else {
    826     // For the remaining calls, re-use the existing field.
    827     profile = uma_proto()->mutable_profiler_event(0);
    828   }
    829 
    830   WriteProfilerData(process_data, process_type, profile);
    831 }
    832 
    833 void MetricsLog::RecordOmniboxOpenedURL(const OmniboxLog& log) {
    834   DCHECK(!locked());
    835 
    836   std::vector<string16> terms;
    837   const int num_terms =
    838       static_cast<int>(Tokenize(log.text, kWhitespaceUTF16, &terms));
    839 
    840   OmniboxEventProto* omnibox_event = uma_proto()->add_omnibox_event();
    841   omnibox_event->set_time(MetricsLogBase::GetCurrentTime());
    842   if (log.tab_id != -1) {
    843     // If we know what tab the autocomplete URL was opened in, log it.
    844     omnibox_event->set_tab_id(log.tab_id);
    845   }
    846   omnibox_event->set_typed_length(log.text.length());
    847   omnibox_event->set_just_deleted_text(log.just_deleted_text);
    848   omnibox_event->set_num_typed_terms(num_terms);
    849   omnibox_event->set_selected_index(log.selected_index);
    850   if (log.completed_length != string16::npos)
    851     omnibox_event->set_completed_length(log.completed_length);
    852   if (log.elapsed_time_since_user_first_modified_omnibox !=
    853       base::TimeDelta::FromMilliseconds(-1)) {
    854     // Only upload the typing duration if it is set/valid.
    855     omnibox_event->set_typing_duration_ms(
    856         log.elapsed_time_since_user_first_modified_omnibox.InMilliseconds());
    857   }
    858   omnibox_event->set_duration_since_last_default_match_update_ms(
    859       log.elapsed_time_since_last_change_to_default_match.InMilliseconds());
    860   omnibox_event->set_current_page_classification(
    861       AsOmniboxEventPageClassification(log.current_page_classification));
    862   omnibox_event->set_input_type(AsOmniboxEventInputType(log.input_type));
    863 
    864   // The view code to hide the top result is currently only implemented on the
    865   // Mac and for views.
    866 #if defined(OS_MACOSX) || defined(TOOLKIT_VIEWS)
    867   omnibox_event->set_is_top_result_hidden_in_dropdown(
    868       log.result.ShouldHideTopMatch());
    869 #endif  // defined(OS_MACOSX) || defined(TOOLKIT_VIEWS)
    870 
    871   for (AutocompleteResult::const_iterator i(log.result.begin());
    872        i != log.result.end(); ++i) {
    873     OmniboxEventProto::Suggestion* suggestion = omnibox_event->add_suggestion();
    874     suggestion->set_provider(i->provider->AsOmniboxEventProviderType());
    875     suggestion->set_result_type(AsOmniboxEventResultType(i->type));
    876     suggestion->set_relevance(i->relevance);
    877     if (i->typed_count != -1)
    878       suggestion->set_typed_count(i->typed_count);
    879     suggestion->set_is_starred(i->starred);
    880   }
    881   for (ProvidersInfo::const_iterator i(log.providers_info.begin());
    882        i != log.providers_info.end(); ++i) {
    883     OmniboxEventProto::ProviderInfo* provider_info =
    884         omnibox_event->add_provider_info();
    885     provider_info->CopyFrom(*i);
    886   }
    887 
    888   ++num_events_;
    889 }
    890 
    891 void MetricsLog::WriteGoogleUpdateProto(
    892     const GoogleUpdateMetrics& google_update_metrics) {
    893 #if defined(GOOGLE_CHROME_BUILD) && defined(OS_WIN)
    894   SystemProfileProto::GoogleUpdate* google_update =
    895       uma_proto()->mutable_system_profile()->mutable_google_update();
    896 
    897   google_update->set_is_system_install(google_update_metrics.is_system_install);
    898 
    899   if (!google_update_metrics.last_started_au.is_null()) {
    900     google_update->set_last_automatic_start_timestamp(
    901         google_update_metrics.last_started_au.ToTimeT());
    902   }
    903 
    904   if (!google_update_metrics.last_checked.is_null()) {
    905     google_update->set_last_update_check_timestamp(
    906       google_update_metrics.last_checked.ToTimeT());
    907   }
    908 
    909   if (!google_update_metrics.google_update_data.version.empty()) {
    910     ProductDataToProto(google_update_metrics.google_update_data,
    911                        google_update->mutable_google_update_status());
    912   }
    913 
    914   if (!google_update_metrics.product_data.version.empty()) {
    915     ProductDataToProto(google_update_metrics.product_data,
    916                        google_update->mutable_client_status());
    917   }
    918 #endif  // defined(GOOGLE_CHROME_BUILD) && defined(OS_WIN)
    919 }
    920 
    921 void MetricsLog::SetBluetoothAdapter(
    922     scoped_refptr<device::BluetoothAdapter> adapter) {
    923   adapter_ = adapter;
    924 }
    925 
    926 void MetricsLog::WriteBluetoothProto(
    927     SystemProfileProto::Hardware* hardware) {
    928 #if defined(OS_CHROMEOS)
    929   SystemProfileProto::Hardware::Bluetooth* bluetooth =
    930       hardware->mutable_bluetooth();
    931 
    932   bluetooth->set_is_present(adapter_->IsPresent());
    933   bluetooth->set_is_enabled(adapter_->IsPowered());
    934 
    935   device::BluetoothAdapter::DeviceList devices = adapter_->GetDevices();
    936   for (device::BluetoothAdapter::DeviceList::iterator iter =
    937            devices.begin(); iter != devices.end(); ++iter) {
    938     PairedDevice* paired_device = bluetooth->add_paired_device();
    939 
    940     device::BluetoothDevice* device = *iter;
    941     paired_device->set_bluetooth_class(device->GetBluetoothClass());
    942     paired_device->set_type(AsBluetoothDeviceType(device->GetDeviceType()));
    943 
    944     // address is xx:xx:xx:xx:xx:xx, extract the first three components and
    945     // pack into a uint32
    946     std::string address = device->GetAddress();
    947     if (address.size() > 9 &&
    948         address[2] == ':' && address[5] == ':' && address[8] == ':') {
    949       std::string vendor_prefix_str;
    950       uint64 vendor_prefix;
    951 
    952       RemoveChars(address.substr(0, 9), ":", &vendor_prefix_str);
    953       DCHECK_EQ(6U, vendor_prefix_str.size());
    954       base::HexStringToUInt64(vendor_prefix_str, &vendor_prefix);
    955 
    956       paired_device->set_vendor_prefix(vendor_prefix);
    957     }
    958 
    959     paired_device->set_vendor_id(device->GetVendorID());
    960     paired_device->set_product_id(device->GetProductID());
    961     paired_device->set_device_id(device->GetDeviceID());
    962   }
    963 #endif  // defined(OS_CHROMEOS)
    964 }
    965