blob: d72e1ae03652554383c8fde4c17abc8b02e6c4af [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// Copyright (c) 2006-2008 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.
initial.commit09911bf2008-07-26 23:55:294
5#include "chrome/browser/metrics_log.h"
6
7#include "base/file_util.h"
8#include "base/file_version_info.h"
9#include "base/md5.h"
10#include "base/scoped_ptr.h"
11#include "base/string_util.h"
12#include "chrome/browser/autocomplete/autocomplete.h"
13#include "chrome/browser/browser_process.h"
14#include "chrome/common/env_util.h"
15#include "chrome/common/logging_chrome.h"
16#include "chrome/common/pref_names.h"
17#include "chrome/common/pref_service.h"
[email protected]46072d42008-07-28 14:49:3518#include "googleurl/src/gurl.h"
initial.commit09911bf2008-07-26 23:55:2919#include "net/base/base64.h"
20
21#define OPEN_ELEMENT_FOR_SCOPE(name) ScopedElement scoped_element(this, name)
22
23// libxml take xmlChar*, which is unsigned char*
24inline const unsigned char* UnsignedChar(const char* input) {
25 return reinterpret_cast<const unsigned char*>(input);
26}
27
28// static
29void MetricsLog::RegisterPrefs(PrefService* local_state) {
30 local_state->RegisterListPref(prefs::kStabilityPluginStats);
31 local_state->RegisterBooleanPref(prefs::kMetricsIsRecording, true);
32}
33
34MetricsLog::MetricsLog(const std::string& client_id, int session_id)
35 : start_time_(Time::Now()),
36 num_events_(0),
37 locked_(false),
38 buffer_(NULL),
39 writer_(NULL),
40 client_id_(client_id),
41 session_id_(IntToString(session_id)) {
42
43 buffer_ = xmlBufferCreate();
44 DCHECK(buffer_);
45
46 writer_ = xmlNewTextWriterMemory(buffer_, 0);
47 DCHECK(writer_);
48
49 int result = xmlTextWriterSetIndent(writer_, 2);
50 DCHECK_EQ(0, result);
51
52 StartElement("log");
53 WriteAttribute("clientid", client_id_);
54
55 DCHECK_GE(result, 0);
56}
57
58MetricsLog::~MetricsLog() {
59 if (writer_)
60 xmlFreeTextWriter(writer_);
61
62 if (buffer_)
63 xmlBufferFree(buffer_);
64}
65
66void MetricsLog::CloseLog() {
67 DCHECK(!locked_);
68 locked_ = true;
69
70 int result = xmlTextWriterEndDocument(writer_);
71 DCHECK(result >= 0);
72
73 result = xmlTextWriterFlush(writer_);
74 DCHECK(result >= 0);
75}
76
77int MetricsLog::GetEncodedLogSize() {
78 DCHECK(locked_);
79 return buffer_->use;
80}
81
82bool MetricsLog::GetEncodedLog(char* buffer, int buffer_size) {
83 DCHECK(locked_);
84 if (buffer_size < GetEncodedLogSize())
85 return false;
86
87 memcpy(buffer, buffer_->content, GetEncodedLogSize());
88 return true;
89}
90
91int MetricsLog::GetElapsedSeconds() {
92 return static_cast<int>((Time::Now() - start_time_).InSeconds());
93}
94
95std::string MetricsLog::CreateHash(const std::string& value) {
96 MD5Context ctx;
97 MD5Init(&ctx);
98 MD5Update(&ctx, value.data(), value.length());
99
100 MD5Digest digest;
101 MD5Final(&digest, &ctx);
102
103 unsigned char reverse[8]; // UMA only uses first 8 chars of hash.
104 DCHECK(arraysize(digest.a) >= arraysize(reverse));
105 for (int i = 0; i < arraysize(reverse); ++i)
106 reverse[i] = digest.a[arraysize(reverse) - i - 1];
107 LOG(INFO) << "Metrics: Hash numeric [" << value << "]=["
108 << *reinterpret_cast<const uint64*>(&reverse[0]) << "]";
109 return std::string(reinterpret_cast<char*>(digest.a), arraysize(digest.a));
110}
111
112std::string MetricsLog::CreateBase64Hash(const std::string& string) {
113 std::string encoded_digest;
[email protected]a9bb6f692008-07-30 16:40:10114 if (net::Base64Encode(CreateHash(string), &encoded_digest)) {
initial.commit09911bf2008-07-26 23:55:29115 DLOG(INFO) << "Metrics: Hash [" << encoded_digest << "]=[" << string << "]";
116 return encoded_digest;
initial.commit09911bf2008-07-26 23:55:29117 }
[email protected]a9bb6f692008-07-30 16:40:10118 return std::string();
initial.commit09911bf2008-07-26 23:55:29119}
120
121void MetricsLog::RecordUserAction(const wchar_t* key) {
122 DCHECK(!locked_);
123
124 std::string command_hash = CreateBase64Hash(WideToUTF8(key));
125 if (command_hash.empty()) {
126 NOTREACHED() << "Unable generate encoded hash of command: " << key;
127 return;
128 }
129
130 StartElement("uielement");
131 WriteAttribute("action", "command");
132 WriteAttribute("targetidhash", command_hash);
133
134 // TODO(jhughes): Properly track windows.
135 WriteIntAttribute("window", 0);
136 WriteCommonEventAttributes();
137 EndElement();
138
139 ++num_events_;
140}
141
142void MetricsLog::RecordLoadEvent(int window_id,
143 const GURL& url,
144 PageTransition::Type origin,
145 int session_index,
146 TimeDelta load_time) {
147 DCHECK(!locked_);
148
149 StartElement("document");
150 WriteAttribute("action", "load");
151 WriteIntAttribute("docid", session_index);
152 WriteIntAttribute("window", window_id);
153 WriteAttribute("loadtime", Int64ToString(load_time.InMilliseconds()));
154
155 std::string origin_string;
156
157 switch (PageTransition::StripQualifier(origin)) {
158 // TODO(jhughes): Some of these mappings aren't right... we need to add
159 // some values to the server's enum.
160 case PageTransition::LINK:
161 case PageTransition::MANUAL_SUBFRAME:
162 origin_string = "link";
163 break;
164
165 case PageTransition::TYPED:
166 origin_string = "typed";
167 break;
168
169 case PageTransition::AUTO_BOOKMARK:
170 origin_string = "bookmark";
171 break;
172
173 case PageTransition::AUTO_SUBFRAME:
174 case PageTransition::RELOAD:
175 origin_string = "refresh";
176 break;
177
178 case PageTransition::GENERATED:
179 origin_string = "global-history";
180 break;
181
182 case PageTransition::START_PAGE:
183 origin_string = "start-page";
184 break;
185
186 case PageTransition::FORM_SUBMIT:
187 origin_string = "form-submit";
188 break;
189
190 default:
191 NOTREACHED() << "Received an unknown page transition type: " <<
192 PageTransition::StripQualifier(origin);
193 }
194 if (!origin_string.empty())
195 WriteAttribute("origin", origin_string);
196
197 WriteCommonEventAttributes();
198 EndElement();
199
200 ++num_events_;
201}
202
203// static
204const char* MetricsLog::WindowEventTypeToString(WindowEventType type) {
205 switch (type) {
206 case WINDOW_CREATE:
207 return "create";
208
209 case WINDOW_OPEN:
210 return "open";
211
212 case WINDOW_CLOSE:
213 return "close";
214
215 case WINDOW_DESTROY:
216 return "destroy";
217
218 default:
219 NOTREACHED();
220 return "unknown";
221 }
222}
223
224void MetricsLog::RecordWindowEvent(WindowEventType type,
225 int window_id,
226 int parent_id) {
227 DCHECK(!locked_);
228
229 StartElement("window");
230 WriteAttribute("action", WindowEventTypeToString(type));
231 WriteAttribute("windowid", IntToString(window_id));
232 if (parent_id >= 0)
233 WriteAttribute("parent", IntToString(parent_id));
234 WriteCommonEventAttributes();
235 EndElement();
236
237 ++num_events_;
238}
239
240std::string MetricsLog::GetCurrentTimeString() {
241 return Uint64ToString(Time::Now().ToTimeT());
242}
243
244// These are the attributes that are common to every event.
245void MetricsLog::WriteCommonEventAttributes() {
246 WriteAttribute("session", session_id_);
247 WriteAttribute("time", GetCurrentTimeString());
248}
249
250void MetricsLog::WriteAttribute(const std::string& name,
251 const std::string& value) {
252 DCHECK(!locked_);
253 DCHECK(!name.empty());
254
255 int result = xmlTextWriterWriteAttribute(writer_,
256 UnsignedChar(name.c_str()),
257 UnsignedChar(value.c_str()));
258 DCHECK_GE(result, 0);
259}
260
261void MetricsLog::WriteIntAttribute(const std::string& name, int value) {
262 WriteAttribute(name, IntToString(value));
263}
264
265void MetricsLog::WriteInt64Attribute(const std::string& name, int64 value) {
266 WriteAttribute(name, Int64ToString(value));
267}
268
269void MetricsLog::StartElement(const char* name) {
270 DCHECK(!locked_);
271 DCHECK(name);
272
273 int result = xmlTextWriterStartElement(writer_, UnsignedChar(name));
274 DCHECK_GE(result, 0);
275}
276
277void MetricsLog::EndElement() {
278 DCHECK(!locked_);
279
280 int result = xmlTextWriterEndElement(writer_);
281 DCHECK_GE(result, 0);
282}
283
284std::string MetricsLog::GetVersionString() const {
285 scoped_ptr<FileVersionInfo> version_info(
286 FileVersionInfo::CreateFileVersionInfoForCurrentModule());
287 if (version_info.get()) {
288 std::string version = WideToUTF8(version_info->product_version());
289 if (!version_info->is_official_build())
290 version.append("-devel");
291 return version;
292 } else {
293 NOTREACHED() << "Unable to retrieve version string.";
294 }
295
296 return std::string();
297}
298
299std::string MetricsLog::GetInstallDate() const {
300 PrefService* pref = g_browser_process->local_state();
301 if (pref) {
302 return WideToUTF8(pref->GetString(prefs::kMetricsClientIDTimestamp));
303 } else {
304 NOTREACHED();
305 return "0";
306 }
307}
308
309void MetricsLog::WriteStabilityElement() {
310 DCHECK(!locked_);
311
312 PrefService* pref = g_browser_process->local_state();
313 DCHECK(pref);
314
315 // Get stability attributes out of Local State, zeroing out stored values.
316 // NOTE: This could lead to some data loss if this report isn't successfully
317 // sent, but that's true for all the metrics.
318
319 StartElement("stability");
320
321 WriteIntAttribute("launchcount",
322 pref->GetInteger(prefs::kStabilityLaunchCount));
323 pref->SetInteger(prefs::kStabilityLaunchCount, 0);
324 WriteIntAttribute("crashcount",
325 pref->GetInteger(prefs::kStabilityCrashCount));
326 pref->SetInteger(prefs::kStabilityCrashCount, 0);
[email protected]8e674e42008-07-30 16:05:48327 WriteIntAttribute("incompleteshutdowncount",
328 pref->GetInteger(
329 prefs::kStabilityIncompleteSessionEndCount));
330 pref->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
initial.commit09911bf2008-07-26 23:55:29331 WriteIntAttribute("pageloadcount",
332 pref->GetInteger(prefs::kStabilityPageLoadCount));
333 pref->SetInteger(prefs::kStabilityPageLoadCount, 0);
334 WriteIntAttribute("renderercrashcount",
335 pref->GetInteger(prefs::kStabilityRendererCrashCount));
336 pref->SetInteger(prefs::kStabilityRendererCrashCount, 0);
337 WriteIntAttribute("rendererhangcount",
338 pref->GetInteger(prefs::kStabilityRendererHangCount));
339 pref->SetInteger(prefs::kStabilityRendererHangCount, 0);
[email protected]e73c01972008-08-13 00:18:24340 WriteIntAttribute("breakpadregistrationok",
341 pref->GetInteger(prefs::kStabilityBreakpadRegistrationSuccess));
342 pref->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
343 WriteIntAttribute("breakpadregistrationfail",
344 pref->GetInteger(prefs::kStabilityBreakpadRegistrationFail));
345 pref->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
346 WriteIntAttribute("debuggerpresent",
347 pref->GetInteger(prefs::kStabilityDebuggerPresent));
348 pref->SetInteger(prefs::kStabilityDebuggerPresent, 0);
349 WriteIntAttribute("debuggernotpresent",
350 pref->GetInteger(prefs::kStabilityDebuggerNotPresent));
351 pref->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
initial.commit09911bf2008-07-26 23:55:29352
353 // Uptime is stored as a string, since there's no int64 in Value/JSON.
354 WriteAttribute("uptimesec",
355 WideToUTF8(pref->GetString(prefs::kStabilityUptimeSec)));
356 pref->SetString(prefs::kStabilityUptimeSec, L"0");
357
358 // Now log plugin stability info
359 const ListValue* plugin_stats_list = pref->GetList(
360 prefs::kStabilityPluginStats);
361 if (plugin_stats_list) {
362 StartElement("plugins");
363 for (ListValue::const_iterator iter = plugin_stats_list->begin();
364 iter != plugin_stats_list->end(); ++iter) {
365 if (!(*iter)->IsType(Value::TYPE_DICTIONARY)) {
366 NOTREACHED();
367 continue;
368 }
369 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*iter);
370
371 std::wstring plugin_path;
372 plugin_dict->GetString(prefs::kStabilityPluginPath, &plugin_path);
373 plugin_path = file_util::GetFilenameFromPath(plugin_path);
374 if (plugin_path.empty()) {
375 NOTREACHED();
376 continue;
377 }
378
379 StartElement("pluginstability");
380 WriteAttribute("filename", CreateBase64Hash(WideToUTF8(plugin_path)));
381
382 int launches = 0;
383 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
384 WriteIntAttribute("launchcount", launches);
385
386 int instances = 0;
387 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
388 WriteIntAttribute("instancecount", instances);
389
390 int crashes = 0;
391 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
392 WriteIntAttribute("crashcount", crashes);
393 EndElement();
394 }
395
396 pref->ClearPref(prefs::kStabilityPluginStats);
397 EndElement();
398 }
399
400 EndElement();
401}
402
403void MetricsLog::WritePluginList(
404 const std::vector<WebPluginInfo>& plugin_list) {
405 DCHECK(!locked_);
406
407 StartElement("plugins");
408
409 for (std::vector<WebPluginInfo>::const_iterator iter = plugin_list.begin();
410 iter != plugin_list.end(); ++iter) {
411 StartElement("plugin");
412
413 // Plugin name and filename are hashed for the privacy of those
414 // testing unreleased new extensions.
415 WriteAttribute("name", CreateBase64Hash(WideToUTF8((*iter).name)));
416 std::wstring filename = file_util::GetFilenameFromPath((*iter).file);
417 WriteAttribute("filename", CreateBase64Hash(WideToUTF8(filename)));
418
419 WriteAttribute("version", WideToUTF8((*iter).version));
420
421 EndElement();
422 }
423
424 EndElement();
425}
426
427void MetricsLog::RecordEnvironment(
428 const std::vector<WebPluginInfo>& plugin_list,
429 const DictionaryValue* profile_metrics) {
430 DCHECK(!locked_);
431
432 PrefService* pref = g_browser_process->local_state();
433
434 StartElement("profile");
435 WriteCommonEventAttributes();
436
437 StartElement("install");
438 WriteAttribute("installdate", GetInstallDate());
439 WriteIntAttribute("buildid", 0); // means that we're using appversion instead
440 WriteAttribute("appversion", GetVersionString());
441 EndElement();
442
443 WritePluginList(plugin_list);
444
445 WriteStabilityElement();
446
447 {
448 OPEN_ELEMENT_FOR_SCOPE("cpu");
449 WriteAttribute("arch", env_util::GetCPUArchitecture());
450 }
451
452 {
453 OPEN_ELEMENT_FOR_SCOPE("security");
454 WriteIntAttribute("rendereronsboxdesktop",
455 pref->GetInteger(prefs::kSecurityRendererOnSboxDesktop));
456 pref->SetInteger(prefs::kSecurityRendererOnSboxDesktop, 0);
457
458 WriteIntAttribute("rendererondefaultdesktop",
459 pref->GetInteger(prefs::kSecurityRendererOnDefaultDesktop));
460 pref->SetInteger(prefs::kSecurityRendererOnDefaultDesktop, 0);
461 }
462
463 {
464 OPEN_ELEMENT_FOR_SCOPE("memory");
465 WriteIntAttribute("mb", env_util::GetPhysicalMemoryMB());
466 }
467
468 {
469 OPEN_ELEMENT_FOR_SCOPE("os");
470 WriteAttribute("name",
471 env_util::GetOperatingSystemName());
472 WriteAttribute("version",
473 env_util::GetOperatingSystemVersion());
474 }
475
476 {
477 OPEN_ELEMENT_FOR_SCOPE("display");
478 int width = 0;
479 int height = 0;
480 env_util::GetPrimaryDisplayDimensions(&width, &height);
481 WriteIntAttribute("xsize", width);
482 WriteIntAttribute("ysize", height);
483 WriteIntAttribute("screens", env_util::GetDisplayCount());
484 }
485
486 {
487 OPEN_ELEMENT_FOR_SCOPE("bookmarks");
488 int num_bookmarks_on_bookmark_bar =
489 pref->GetInteger(prefs::kNumBookmarksOnBookmarkBar);
490 int num_folders_on_bookmark_bar =
491 pref->GetInteger(prefs::kNumFoldersOnBookmarkBar);
492 int num_bookmarks_in_other_bookmarks_folder =
493 pref->GetInteger(prefs::kNumBookmarksInOtherBookmarkFolder);
494 int num_folders_in_other_bookmarks_folder =
495 pref->GetInteger(prefs::kNumFoldersInOtherBookmarkFolder);
496 {
497 OPEN_ELEMENT_FOR_SCOPE("bookmarklocation");
498 WriteAttribute("name", "full-tree");
499 WriteIntAttribute("foldercount",
500 num_folders_on_bookmark_bar + num_folders_in_other_bookmarks_folder);
501 WriteIntAttribute("itemcount",
502 num_bookmarks_on_bookmark_bar +
503 num_bookmarks_in_other_bookmarks_folder);
504 }
505 {
506 OPEN_ELEMENT_FOR_SCOPE("bookmarklocation");
507 WriteAttribute("name", "toolbar");
508 WriteIntAttribute("foldercount", num_folders_on_bookmark_bar);
509 WriteIntAttribute("itemcount", num_bookmarks_on_bookmark_bar);
510 }
511 }
512
513 {
514 OPEN_ELEMENT_FOR_SCOPE("keywords");
515 WriteIntAttribute("count", pref->GetInteger(prefs::kNumKeywords));
516 }
517
518 if (profile_metrics)
519 WriteAllProfilesMetrics(*profile_metrics);
520
521 EndElement(); // profile
522}
523
524void MetricsLog::WriteAllProfilesMetrics(
525 const DictionaryValue& all_profiles_metrics) {
526 const std::wstring profile_prefix(prefs::kProfilePrefix);
527 for (DictionaryValue::key_iterator i = all_profiles_metrics.begin_keys();
528 i != all_profiles_metrics.end_keys(); ++i) {
529 const std::wstring& key_name = *i;
530 if (key_name.compare(0, profile_prefix.size(), profile_prefix) == 0) {
531 DictionaryValue* profile;
532 if (all_profiles_metrics.GetDictionary(key_name, &profile))
533 WriteProfileMetrics(key_name.substr(profile_prefix.size()), *profile);
534 }
535 }
536}
537
538void MetricsLog::WriteProfileMetrics(const std::wstring& profileidhash,
539 const DictionaryValue& profile_metrics) {
540 OPEN_ELEMENT_FOR_SCOPE("userprofile");
541 WriteAttribute("profileidhash", WideToUTF8(profileidhash));
542 for (DictionaryValue::key_iterator i = profile_metrics.begin_keys();
543 i != profile_metrics.end_keys(); ++i) {
544 Value* value;
545 if (profile_metrics.Get(*i, &value)) {
546 DCHECK(*i != L"id");
547 switch (value->GetType()) {
548 case Value::TYPE_STRING: {
549 std::wstring string_value;
550 if (value->GetAsString(&string_value)) {
551 OPEN_ELEMENT_FOR_SCOPE("profileparam");
552 WriteAttribute("name", WideToUTF8(*i));
553 WriteAttribute("value", WideToUTF8(string_value));
554 }
555 break;
556 }
557
558 case Value::TYPE_BOOLEAN: {
559 bool bool_value;
560 if (value->GetAsBoolean(&bool_value)) {
561 OPEN_ELEMENT_FOR_SCOPE("profileparam");
562 WriteAttribute("name", WideToUTF8(*i));
563 WriteIntAttribute("value", bool_value ? 1 : 0);
564 }
565 break;
566 }
567
568 case Value::TYPE_INTEGER: {
569 int int_value;
570 if (value->GetAsInteger(&int_value)) {
571 OPEN_ELEMENT_FOR_SCOPE("profileparam");
572 WriteAttribute("name", WideToUTF8(*i));
573 WriteIntAttribute("value", int_value);
574 }
575 break;
576 }
577
578 default:
579 NOTREACHED();
580 break;
581 }
582 }
583 }
584}
585
586void MetricsLog::RecordOmniboxOpenedURL(const AutocompleteLog& log) {
587 DCHECK(!locked_);
588
589 StartElement("uielement");
590 WriteAttribute("action", "autocomplete");
591 WriteAttribute("targetidhash", "");
592 // TODO(kochi): Properly track windows.
593 WriteIntAttribute("window", 0);
594 WriteCommonEventAttributes();
595
596 StartElement("autocomplete");
597
598 WriteIntAttribute("typedlength", static_cast<int>(log.text.length()));
599 WriteIntAttribute("completedlength",
600 static_cast<int>(log.inline_autocompleted_length));
601 WriteIntAttribute("selectedindex", static_cast<int>(log.selected_index));
602
603 for (AutocompleteResult::const_iterator i(log.result.begin());
604 i != log.result.end(); ++i) {
605 StartElement("autocompleteitem");
606 if (i->provider)
607 WriteAttribute("provider", i->provider->name());
608 WriteIntAttribute("relevance", i->relevance);
609 WriteIntAttribute("isstarred", i->starred ? 1 : 0);
610 EndElement(); // autocompleteitem
611 }
612 EndElement(); // autocomplete
613 EndElement(); // uielement
614
615 ++num_events_;
616}
617
618// TODO(JAR): A The following should really be part of the histogram class.
619// Internal state is being needlessly exposed, and it would be hard to reuse
620// this code. If we moved this into the Histogram class, then we could use
621// the same infrastructure for logging StatsCounters, RatesCounters, etc.
622void MetricsLog::RecordHistogramDelta(const Histogram& histogram,
623 const Histogram::SampleSet& snapshot) {
624 DCHECK(!locked_);
625 DCHECK(0 != snapshot.TotalCount());
626 snapshot.CheckSize(histogram);
627
628 // We will ignore the MAX_INT/infinite value in the last element of range[].
629
630 OPEN_ELEMENT_FOR_SCOPE("histogram");
631
632 WriteAttribute("name", CreateBase64Hash(histogram.histogram_name()));
633
634 WriteInt64Attribute("sum", snapshot.sum());
635 WriteInt64Attribute("sumsquares", snapshot.square_sum());
636
637 for (size_t i = 0; i < histogram.bucket_count(); i++) {
638 if (snapshot.counts(i)) {
639 OPEN_ELEMENT_FOR_SCOPE("histogrambucket");
640 WriteIntAttribute("min", histogram.ranges(i));
641 WriteIntAttribute("max", histogram.ranges(i + 1));
642 WriteIntAttribute("count", snapshot.counts(i));
643 }
644 }
645}
license.botbf09a502008-08-24 00:55:55646