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