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