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