blob: 08446803cc2614a94f52f56cdf610523ef032d9c [file] [log] [blame]
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441// Copyright (c) 2011 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// 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
initial.commit09911bf2008-07-26 23:55:295//------------------------------------------------------------------------------
6// Description of the life cycle of a instance of MetricsService.
7//
8// OVERVIEW
9//
10// A MetricsService instance is typically created at application startup. It
11// is the central controller for the acquisition of log data, and the automatic
12// transmission of that log data to an external server. Its major job is to
13// manage logs, grouping them for transmission, and transmitting them. As part
14// of its grouping, MS finalizes logs by including some just-in-time gathered
15// memory statistics, snapshotting the current stats of numerous histograms,
16// closing the logs, translating to XML text, and compressing the results for
17// transmission. Transmission includes submitting a compressed log as data in a
jar@chromium.org281d2882009-01-20 20:32:4218// URL-post, and retransmitting (or retaining at process termination) if the
initial.commit09911bf2008-07-26 23:55:2919// attempted transmission failed. Retention across process terminations is done
ziadh@chromium.org46f89e142010-07-19 08:00:4220// using the the PrefServices facilities. The retained logs (the ones that never
21// got transmitted) are compressed and base64-encoded before being persisted.
initial.commit09911bf2008-07-26 23:55:2922//
jar@chromium.org281d2882009-01-20 20:32:4223// Logs fall into one of two categories: "initial logs," and "ongoing logs."
24// There is at most one initial log sent for each complete run of the chromium
initial.commit09911bf2008-07-26 23:55:2925// product (from startup, to browser shutdown). An initial log is generally
26// transmitted some short time (1 minute?) after startup, and includes stats
27// such as recent crash info, the number and types of plugins, etc. The
jar@chromium.org281d2882009-01-20 20:32:4228// external server's response to the initial log conceptually tells this MS if
29// it should continue transmitting logs (during this session). The server
30// response can actually be much more detailed, and always includes (at a
31// minimum) how often additional ongoing logs should be sent.
initial.commit09911bf2008-07-26 23:55:2932//
33// After the above initial log, a series of ongoing logs will be transmitted.
34// The first ongoing log actually begins to accumulate information stating when
35// the MS was first constructed. Note that even though the initial log is
36// commonly sent a full minute after startup, the initial log does not include
37// much in the way of user stats. The most common interlog period (delay)
jar@google.com0b33f80b2008-12-17 21:34:3638// is 20 minutes. That time period starts when the first user action causes a
initial.commit09911bf2008-07-26 23:55:2939// logging event. This means that if there is no user action, there may be long
jar@chromium.org281d2882009-01-20 20:32:4240// periods without any (ongoing) log transmissions. Ongoing logs typically
initial.commit09911bf2008-07-26 23:55:2941// contain very detailed records of user activities (ex: opened tab, closed
42// tab, fetched URL, maximized window, etc.) In addition, just before an
43// ongoing log is closed out, a call is made to gather memory statistics. Those
44// memory statistics are deposited into a histogram, and the log finalization
45// code is then called. In the finalization, a call to a Histogram server
46// acquires a list of all local histograms that have been flagged for upload
jar@chromium.org281d2882009-01-20 20:32:4247// to the UMA server. The finalization also acquires a the most recent number
48// of page loads, along with any counts of renderer or plugin crashes.
initial.commit09911bf2008-07-26 23:55:2949//
50// When the browser shuts down, there will typically be a fragment of an ongoing
51// log that has not yet been transmitted. At shutdown time, that fragment
52// is closed (including snapshotting histograms), and converted to text. Note
53// that memory stats are not gathered during shutdown, as gathering *might* be
54// too time consuming. The textual representation of the fragment of the
55// ongoing log is then stored persistently as a string in the PrefServices, for
56// potential transmission during a future run of the product.
57//
58// There are two slightly abnormal shutdown conditions. There is a
59// "disconnected scenario," and a "really fast startup and shutdown" scenario.
60// In the "never connected" situation, the user has (during the running of the
61// process) never established an internet connection. As a result, attempts to
62// transmit the initial log have failed, and a lot(?) of data has accumulated in
63// the ongoing log (which didn't yet get closed, because there was never even a
64// contemplation of sending it). There is also a kindred "lost connection"
65// situation, where a loss of connection prevented an ongoing log from being
66// transmitted, and a (still open) log was stuck accumulating a lot(?) of data,
67// while the earlier log retried its transmission. In both of these
68// disconnected situations, two logs need to be, and are, persistently stored
69// for future transmission.
70//
71// The other unusual shutdown condition, termed "really fast startup and
72// shutdown," involves the deliberate user termination of the process before
73// the initial log is even formed or transmitted. In that situation, no logging
74// is done, but the historical crash statistics remain (unlogged) for inclusion
75// in a future run's initial log. (i.e., we don't lose crash stats).
76//
77// With the above overview, we can now describe the state machine's various
78// stats, based on the State enum specified in the state_ member. Those states
79// are:
80//
81// INITIALIZED, // Constructor was called.
zelidrag@chromium.org85ed9d42010-06-08 22:37:4482// INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to complete.
83// INIT_TASK_DONE, // Waiting for timer to send initial log.
initial.commit09911bf2008-07-26 23:55:2984// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
85// SEND_OLD_INITIAL_LOGS, // Sending unsent logs from previous session.
86// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
87// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
88//
89// In more detail, we have:
90//
91// INITIALIZED, // Constructor was called.
92// The MS has been constructed, but has taken no actions to compose the
93// initial log.
94//
zelidrag@chromium.org85ed9d42010-06-08 22:37:4495// INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to complete.
initial.commit09911bf2008-07-26 23:55:2996// Typically about 30 seconds after startup, a task is sent to a second thread
zelidrag@chromium.org85ed9d42010-06-08 22:37:4497// (the file thread) to perform deferred (lower priority and slower)
98// initialization steps such as getting the list of plugins. That task will
99// (when complete) make an async callback (via a Task) to indicate the
100// completion.
initial.commit09911bf2008-07-26 23:55:29101//
zelidrag@chromium.org85ed9d42010-06-08 22:37:44102// INIT_TASK_DONE, // Waiting for timer to send initial log.
initial.commit09911bf2008-07-26 23:55:29103// The callback has arrived, and it is now possible for an initial log to be
104// created. This callback typically arrives back less than one second after
zelidrag@chromium.org85ed9d42010-06-08 22:37:44105// the deferred init task is dispatched.
initial.commit09911bf2008-07-26 23:55:29106//
107// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
108// This state is entered only after an initial log has been composed, and
109// prepared for transmission. It is also the case that any previously unsent
110// logs have been loaded into instance variables for possible transmission.
111//
112// SEND_OLD_INITIAL_LOGS, // Sending unsent logs from previous session.
113// This state indicates that the initial log for this session has been
114// successfully sent and it is now time to send any "initial logs" that were
115// saved from previous sessions. Most commonly, there are none, but all old
116// logs that were "initial logs" must be sent before this state is exited.
117//
118// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
119// This state indicates that there are no more unsent initial logs, and now any
120// ongoing logs from previous sessions should be transmitted. All such logs
121// will be transmitted before exiting this state, and proceeding with ongoing
122// logs from the current session (see next state).
123//
124// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
jar@google.com0b33f80b2008-12-17 21:34:36125// Current logs are being accumulated. Typically every 20 minutes a log is
initial.commit09911bf2008-07-26 23:55:29126// closed and finalized for transmission, at the same time as a new log is
127// started.
128//
129// The progression through the above states is simple, and sequential, in the
130// most common use cases. States proceed from INITIAL to SENDING_CURRENT_LOGS,
131// and remain in the latter until shutdown.
132//
133// The one unusual case is when the user asks that we stop logging. When that
134// happens, any pending (transmission in progress) log is pushed into the list
135// of old unsent logs (the appropriate list, depending on whether it is an
136// initial log, or an ongoing log). An addition, any log that is currently
137// accumulating is also finalized, and pushed into the unsent log list. With
jar@chromium.org281d2882009-01-20 20:32:42138// those pushes performed, we regress back to the SEND_OLD_INITIAL_LOGS state in
initial.commit09911bf2008-07-26 23:55:29139// case the user enables log recording again during this session. This way
140// anything we have "pushed back" will be sent automatically if/when we progress
141// back to SENDING_CURRENT_LOG state.
142//
143// Also note that whenever the member variables containing unsent logs are
144// modified (i.e., when we send an old log), we mirror the list of logs into
145// the PrefServices. This ensures that IF we crash, we won't start up and
146// retransmit our old logs again.
147//
148// Due to race conditions, it is always possible that a log file could be sent
149// twice. For example, if a log file is sent, but not yet acknowledged by
150// the external server, and the user shuts down, then a copy of the log may be
151// saved for re-transmission. These duplicates could be filtered out server
jar@chromium.org281d2882009-01-20 20:32:42152// side, but are not expected to be a significant problem.
initial.commit09911bf2008-07-26 23:55:29153//
154//
155//------------------------------------------------------------------------------
156
maruel@chromium.org40bcc302009-03-02 20:50:39157#include "chrome/browser/metrics/metrics_service.h"
158
ziadh@chromium.org46f89e142010-07-19 08:00:42159#include "base/base64.h"
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16160#include "base/bind.h"
161#include "base/callback.h"
erg@google.com5d91c9e2010-07-28 17:25:28162#include "base/command_line.h"
ziadh@chromium.org46f89e142010-07-19 08:00:42163#include "base/md5.h"
brettw@chromium.org835d7c82010-10-14 04:38:38164#include "base/metrics/histogram.h"
brettw@chromium.org528c56d2010-07-30 19:28:44165#include "base/string_number_conversions.h"
rohitrao@chromium.orge257d5b2011-05-25 14:10:16166#include "base/string_util.h" // For WriteInto().
brettw@chromium.orgce072a72010-12-31 20:02:16167#include "base/threading/platform_thread.h"
tfarina@chromium.orgb3841c502011-03-09 01:21:31168#include "base/threading/thread.h"
viettrungluu@chromium.org440b37b22010-08-30 05:31:40169#include "base/utf_string_conversions.h"
erg@google.com679082052010-07-21 21:30:13170#include "base/values.h"
sky@google.comd8e41ed2008-09-11 15:22:32171#include "chrome/browser/bookmarks/bookmark_model.h"
initial.commit09911bf2008-07-26 23:55:29172#include "chrome/browser/browser_process.h"
sail@chromium.org84c988a2011-04-19 17:56:33173#include "chrome/browser/memory_details.h"
phajdan.jr@chromium.org7c927b62010-02-24 09:54:13174#include "chrome/browser/metrics/histogram_synchronizer.h"
erg@google.com679082052010-07-21 21:30:13175#include "chrome/browser/metrics/metrics_log.h"
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16176#include "chrome/browser/metrics/metrics_reporting_scheduler.h"
rtenneti@chromium.orgd67d1052011-06-09 05:11:41177#include "chrome/browser/net/network_stats.h"
evan@chromium.org37858e52010-08-26 00:22:02178#include "chrome/browser/prefs/pref_service.h"
battre@chromium.orgf8628c22011-04-05 12:10:18179#include "chrome/browser/prefs/scoped_user_pref_update.h"
ben@chromium.org8ecad5e2010-12-02 21:18:33180#include "chrome/browser/profiles/profile.h"
erg@google.com8e5c89a2011-06-07 18:13:33181#include "chrome/browser/search_engines/template_url_service.h"
tfarina@chromium.org71b73f02011-04-06 15:57:29182#include "chrome/browser/ui/browser_list.h"
kuchhal@chromium.org157d5472009-11-05 22:31:03183#include "chrome/common/child_process_logging.h"
ananta@chromium.org432115822011-07-10 15:52:27184#include "chrome/common/chrome_notification_types.h"
jar@chromium.org92745242009-06-12 16:52:21185#include "chrome/common/chrome_switches.h"
sergeyu@chromium.org3eb0d8f72010-12-15 23:38:25186#include "chrome/common/guid.h"
initial.commit09911bf2008-07-26 23:55:29187#include "chrome/common/pref_names.h"
jam@chromium.orge09ba552009-02-05 03:26:29188#include "chrome/common/render_messages.h"
avi@chromium.org35e251d2011-05-24 21:01:04189#include "content/browser/load_notification_details.h"
jam@chromium.org5de634712011-03-02 00:20:19190#include "content/browser/renderer_host/render_process_host.h"
jam@chromium.org6faf7b12011-03-09 19:24:14191#include "content/common/child_process_info.h"
tfarina@chromium.orgb3841c502011-03-09 01:21:31192#include "content/common/notification_service.h"
brettw@chromium.org191eb3f72010-12-21 06:27:50193#include "webkit/plugins/npapi/plugin_list.h"
cpu@chromium.org91d9f3d2011-08-14 05:24:44194#include "webkit/plugins/webplugininfo.h"
initial.commit09911bf2008-07-26 23:55:29195
phajdan.jr@chromium.orge06131d2010-02-10 18:40:33196// TODO(port): port browser_distribution.h.
197#if !defined(OS_POSIX)
kuchhal@chromium.org79bf0b72009-04-27 21:30:55198#include "chrome/installer/util/browser_distribution.h"
paul@chromium.orgdc6f4962009-02-13 01:25:50199#endif
200
rvargas@google.com5ccaa412009-11-13 22:00:16201#if defined(OS_CHROMEOS)
stevenjb@chromium.orgdb342d52010-08-09 21:19:37202#include "chrome/browser/chromeos/cros/cros_library.h"
rvargas@google.com5ccaa412009-11-13 22:00:16203#include "chrome/browser/chromeos/external_metrics.h"
satorux@chromium.orgd43970a72011-07-10 06:24:52204#include "chrome/browser/chromeos/system/statistics_provider.h"
rvargas@google.com5ccaa412009-11-13 22:00:16205#endif
206
ziadh@chromium.org46f89e142010-07-19 08:00:42207namespace {
208MetricsService::LogRecallStatus MakeRecallStatusHistogram(
209 MetricsService::LogRecallStatus status) {
210 UMA_HISTOGRAM_ENUMERATION("PrefService.PersistentLogRecall", status,
211 MetricsService::END_RECALL_STATUS);
212 return status;
213}
214
215// TODO(ziadh): Remove this when done with experiment.
216void MakeStoreStatusHistogram(MetricsService::LogStoreStatus status) {
ziadh@chromium.org4e95d202010-07-24 01:47:56217 UMA_HISTOGRAM_ENUMERATION("PrefService.PersistentLogStore2", status,
ziadh@chromium.org46f89e142010-07-19 08:00:42218 MetricsService::END_STORE_STATUS);
219}
220} // namespace
221
dsh@google.come1acf6f2008-10-27 20:43:33222using base::Time;
dsh@google.come1acf6f2008-10-27 20:43:33223
initial.commit09911bf2008-07-26 23:55:29224// Check to see that we're being called on only one thread.
225static bool IsSingleThreaded();
226
initial.commit09911bf2008-07-26 23:55:29227static const char kMetricsType[] = "application/vnd.mozilla.metrics.bz2";
228
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16229// The delay, in seconds, after starting recording before doing expensive
230// initialization work.
231static const int kInitializationDelaySeconds = 30;
petersont@google.com252873ef2008-08-04 21:59:45232
jar@chromium.orgc9a3ef82009-05-28 22:02:46233// This specifies the amount of time to wait for all renderers to send their
234// data.
235static const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
236
stuartmorgan@chromium.org54702c92011-04-15 15:06:43237// The maximum number of events in a log uploaded to the UMA server.
238static const int kEventLimit = 2400;
jar@google.com68475e602008-08-22 03:21:15239
240// If an upload fails, and the transmission was over this byte count, then we
241// will discard the log, and not try to retransmit it. We also don't persist
242// the log to the prefs for transmission during the next chrome session if this
243// limit is exceeded.
244static const int kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29245
initial.commit09911bf2008-07-26 23:55:29246// Interval, in seconds, between state saves.
247static const int kSaveStateInterval = 5 * 60; // five minutes
248
249// The number of "initial" logs we're willing to save, and hope to send during
250// a future Chrome session. Initial logs contain crash stats, and are pretty
251// small.
252static const size_t kMaxInitialLogsPersisted = 20;
253
254// The number of ongoing logs we're willing to save persistently, and hope to
jar@chromium.org281d2882009-01-20 20:32:42255// send during a this or future sessions. Note that each log may be pretty
initial.commit09911bf2008-07-26 23:55:29256// large, as presumably the related "initial" log wasn't sent (probably nothing
257// was, as the user was probably off-line). As a result, the log probably kept
258// accumulating while the "initial" log was stalled (pending_), and couldn't be
259// sent. As a result, we don't want to save too many of these mega-logs.
260// A "standard shutdown" will create a small log, including just the data that
261// was not yet been transmitted, and that is normal (to have exactly one
262// ongoing_log_ at startup).
jar@chromium.org281d2882009-01-20 20:32:42263static const size_t kMaxOngoingLogsPersisted = 8;
initial.commit09911bf2008-07-26 23:55:29264
ziadh@chromium.org46f89e142010-07-19 08:00:42265// We append (2) more elements to persisted lists: the size of the list and a
266// checksum of the elements.
267static const size_t kChecksumEntryCount = 2;
268
jar@chromium.orgc0c55e92011-09-10 18:47:30269// static
270MetricsService::ShutdownCleanliness MetricsService::clean_shutdown_status_ =
271 MetricsService::CLEANLY_SHUTDOWN;
272
erg@google.com679082052010-07-21 21:30:13273// This is used to quickly log stats from child process related notifications in
274// MetricsService::child_stats_buffer_. The buffer's contents are transferred
275// out when Local State is periodically saved. The information is then
276// reported to the UMA server on next launch.
277struct MetricsService::ChildProcessStats {
278 public:
279 explicit ChildProcessStats(ChildProcessInfo::ProcessType type)
280 : process_launches(0),
281 process_crashes(0),
282 instances(0),
283 process_type(type) {}
284
285 // This constructor is only used by the map to return some default value for
286 // an index for which no value has been assigned.
287 ChildProcessStats()
288 : process_launches(0),
pkasting@chromium.orgd88bf0a2011-08-30 23:55:57289 process_crashes(0),
290 instances(0),
291 process_type(ChildProcessInfo::UNKNOWN_PROCESS) {}
erg@google.com679082052010-07-21 21:30:13292
293 // The number of times that the given child process has been launched
294 int process_launches;
295
296 // The number of times that the given child process has crashed
297 int process_crashes;
298
299 // The number of instances of this child process that have been created.
300 // An instance is a DOM object rendered by this child process during a page
301 // load.
302 int instances;
303
304 ChildProcessInfo::ProcessType process_type;
305};
initial.commit09911bf2008-07-26 23:55:29306
sail@chromium.org84c988a2011-04-19 17:56:33307// Handles asynchronous fetching of memory details.
308// Will run the provided task after finished.
309class MetricsMemoryDetails : public MemoryDetails {
310 public:
311 explicit MetricsMemoryDetails(Task* completion) : completion_(completion) {}
312
313 virtual void OnDetailsAvailable() {
314 MessageLoop::current()->PostTask(FROM_HERE, completion_);
315 }
316
317 private:
318 ~MetricsMemoryDetails() {}
319
320 Task* completion_;
321 DISALLOW_COPY_AND_ASSIGN(MetricsMemoryDetails);
322};
323
zelidrag@chromium.org85ed9d42010-06-08 22:37:44324class MetricsService::InitTaskComplete : public Task {
jam@chromium.org35fa6a22009-08-15 00:04:01325 public:
brettw@chromium.org191eb3f72010-12-21 06:27:50326 explicit InitTaskComplete(
327 const std::string& hardware_class,
cpu@chromium.org91d9f3d2011-08-14 05:24:44328 const std::vector<webkit::WebPluginInfo>& plugins)
zelidrag@chromium.org85ed9d42010-06-08 22:37:44329 : hardware_class_(hardware_class), plugins_(plugins) {}
330
jamesr@chromium.org7f2e792e2009-11-30 23:18:29331 virtual void Run() {
zelidrag@chromium.org85ed9d42010-06-08 22:37:44332 g_browser_process->metrics_service()->OnInitTaskComplete(
333 hardware_class_, plugins_);
initial.commit09911bf2008-07-26 23:55:29334 }
jam@chromium.org35fa6a22009-08-15 00:04:01335
jamesr@chromium.org7f2e792e2009-11-30 23:18:29336 private:
zelidrag@chromium.org85ed9d42010-06-08 22:37:44337 std::string hardware_class_;
cpu@chromium.org91d9f3d2011-08-14 05:24:44338 std::vector<webkit::WebPluginInfo> plugins_;
initial.commit09911bf2008-07-26 23:55:29339};
340
zelidrag@chromium.org85ed9d42010-06-08 22:37:44341class MetricsService::InitTask : public Task {
jamesr@chromium.org7f2e792e2009-11-30 23:18:29342 public:
zelidrag@chromium.org85ed9d42010-06-08 22:37:44343 explicit InitTask(MessageLoop* callback_loop)
jamesr@chromium.org7f2e792e2009-11-30 23:18:29344 : callback_loop_(callback_loop) {}
345
346 virtual void Run() {
cpu@chromium.org91d9f3d2011-08-14 05:24:44347 std::vector<webkit::WebPluginInfo> plugins;
bauerb@chromium.org68598072011-07-29 08:21:28348 webkit::npapi::PluginList::Singleton()->GetPlugins(&plugins);
zelidrag@chromium.org85ed9d42010-06-08 22:37:44349 std::string hardware_class; // Empty string by default.
350#if defined(OS_CHROMEOS)
satorux@chromium.orgd43970a72011-07-10 06:24:52351 chromeos::system::StatisticsProvider::GetInstance()->GetMachineStatistic(
satorux@chromium.org9b345162011-04-15 05:21:30352 "hardware_class", &hardware_class);
zelidrag@chromium.org85ed9d42010-06-08 22:37:44353#endif // OS_CHROMEOS
354 callback_loop_->PostTask(FROM_HERE, new InitTaskComplete(
355 hardware_class, plugins));
jamesr@chromium.org7f2e792e2009-11-30 23:18:29356 }
357
358 private:
359 MessageLoop* callback_loop_;
360};
evan@chromium.org90d41372009-11-30 21:52:32361
initial.commit09911bf2008-07-26 23:55:29362// static
363void MetricsService::RegisterPrefs(PrefService* local_state) {
364 DCHECK(IsSingleThreaded());
estade@chromium.org20ce516d2010-06-18 02:20:04365 local_state->RegisterStringPref(prefs::kMetricsClientID, "");
robertshield@google.com0bb1a622009-03-04 03:22:32366 local_state->RegisterInt64Pref(prefs::kMetricsClientIDTimestamp, 0);
367 local_state->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
368 local_state->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
estade@chromium.org20ce516d2010-06-18 02:20:04369 local_state->RegisterStringPref(prefs::kStabilityStatsVersion, "");
jar@chromium.org225c50842010-01-19 21:19:13370 local_state->RegisterInt64Pref(prefs::kStabilityStatsBuildTime, 0);
initial.commit09911bf2008-07-26 23:55:29371 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
372 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
373 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
374 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
375 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
376 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
377 0);
378 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
initial.commit09911bf2008-07-26 23:55:29379 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
asargent@chromium.org1f085622009-12-04 05:33:45380 local_state->RegisterIntegerPref(prefs::kStabilityExtensionRendererCrashCount,
381 0);
initial.commit09911bf2008-07-26 23:55:29382 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
asargent@chromium.org1f085622009-12-04 05:33:45383 local_state->RegisterIntegerPref(prefs::kStabilityChildProcessCrashCount, 0);
cpu@google.come73c01972008-08-13 00:18:24384 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
385 0);
386 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
387 0);
388 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
389 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
petkov@chromium.orgc1834a92011-01-21 18:21:03390#if defined(OS_CHROMEOS)
391 local_state->RegisterIntegerPref(prefs::kStabilityOtherUserCrashCount, 0);
392 local_state->RegisterIntegerPref(prefs::kStabilityKernelCrashCount, 0);
393 local_state->RegisterIntegerPref(prefs::kStabilitySystemUncleanShutdownCount,
394 0);
395#endif // OS_CHROMEOS
cpu@google.come73c01972008-08-13 00:18:24396
initial.commit09911bf2008-07-26 23:55:29397 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
398 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
399 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
400 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
401 0);
402 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
403 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
404 local_state->RegisterListPref(prefs::kMetricsInitialLogs);
405 local_state->RegisterListPref(prefs::kMetricsOngoingLogs);
robertshield@google.com0bb1a622009-03-04 03:22:32406
407 local_state->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
408 local_state->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
robertshield@google.com6b5f21d2009-04-13 17:01:35409 local_state->RegisterInt64Pref(prefs::kUninstallMetricsInstallDate, 0);
robertshield@google.com0bb1a622009-03-04 03:22:32410 local_state->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
411 local_state->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
412 local_state->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
initial.commit09911bf2008-07-26 23:55:29413}
414
jar@chromium.org541f77922009-02-23 21:14:38415// static
416void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
417 local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
jar@chromium.orgc9abf242009-07-18 06:00:38418 local_state->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
jar@chromium.org541f77922009-02-23 21:14:38419
420 local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
421 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
422 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
423 local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
424 local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
425
426 local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
427 local_state->SetInteger(prefs::kStabilityCrashCount, 0);
428
429 local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
430 local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
431 local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
432
jar@chromium.org9165f742010-03-10 22:55:01433 local_state->SetInt64(prefs::kStabilityLaunchTimeSec, 0);
434 local_state->SetInt64(prefs::kStabilityLastTimestampSec, 0);
jar@chromium.org541f77922009-02-23 21:14:38435
436 local_state->ClearPref(prefs::kStabilityPluginStats);
jar@chromium.orgae155cb92009-06-19 06:10:37437
battre@chromium.orgf8628c22011-04-05 12:10:18438 local_state->ClearPref(prefs::kMetricsInitialLogs);
439 local_state->ClearPref(prefs::kMetricsOngoingLogs);
jar@chromium.org541f77922009-02-23 21:14:38440}
441
initial.commit09911bf2008-07-26 23:55:29442MetricsService::MetricsService()
petersont@google.comd01b8732008-10-16 02:18:07443 : recording_active_(false),
444 reporting_active_(false),
petersont@google.comd01b8732008-10-16 02:18:07445 state_(INITIALIZED),
initial.commit09911bf2008-07-26 23:55:29446 current_fetch_(NULL),
rtenneti@chromium.orgd67d1052011-06-09 05:11:41447 io_thread_(NULL),
petersont@google.comd01b8732008-10-16 02:18:07448 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29449 next_window_id_(0),
maruel@chromium.org40bcc302009-03-02 20:50:39450 ALLOW_THIS_IN_INITIALIZER_LIST(log_sender_factory_(this)),
451 ALLOW_THIS_IN_INITIALIZER_LIST(state_saver_factory_(this)),
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16452 waiting_for_asynchronus_reporting_step_(false) {
initial.commit09911bf2008-07-26 23:55:29453 DCHECK(IsSingleThreaded());
454 InitializeMetricsState();
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16455
456 base::Closure callback = base::Bind(&MetricsService::StartScheduledUpload,
457 base::Unretained(this));
458 scheduler_.reset(new MetricsReportingScheduler(callback));
initial.commit09911bf2008-07-26 23:55:29459}
460
461MetricsService::~MetricsService() {
462 SetRecording(false);
463}
464
petersont@google.comd01b8732008-10-16 02:18:07465void MetricsService::Start() {
stuartmorgan@chromium.orgb1c8dc02011-04-13 18:32:04466 HandleIdleSinceLastTransmission(false);
petersont@google.comd01b8732008-10-16 02:18:07467 SetRecording(true);
468 SetReporting(true);
469}
470
471void MetricsService::StartRecordingOnly() {
472 SetRecording(true);
473 SetReporting(false);
474}
475
476void MetricsService::Stop() {
stuartmorgan@chromium.orgb1c8dc02011-04-13 18:32:04477 HandleIdleSinceLastTransmission(false);
petersont@google.comd01b8732008-10-16 02:18:07478 SetReporting(false);
479 SetRecording(false);
480}
481
joi@chromium.orgedafd4c2011-05-10 17:18:53482std::string MetricsService::GetClientId() {
483 return client_id_;
484}
485
initial.commit09911bf2008-07-26 23:55:29486void MetricsService::SetRecording(bool enabled) {
487 DCHECK(IsSingleThreaded());
488
petersont@google.comd01b8732008-10-16 02:18:07489 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29490 return;
491
492 if (enabled) {
jar@chromium.orgb0c819f2009-03-08 04:52:15493 if (client_id_.empty()) {
494 PrefService* pref = g_browser_process->local_state();
495 DCHECK(pref);
estade@chromium.orgddd231e2010-06-29 20:35:19496 client_id_ = pref->GetString(prefs::kMetricsClientID);
jar@chromium.orgb0c819f2009-03-08 04:52:15497 if (client_id_.empty()) {
498 client_id_ = GenerateClientID();
estade@chromium.orgddd231e2010-06-29 20:35:19499 pref->SetString(prefs::kMetricsClientID, client_id_);
jar@chromium.orgb0c819f2009-03-08 04:52:15500
501 // Might as well make a note of how long this ID has existed
502 pref->SetString(prefs::kMetricsClientIDTimestamp,
brettw@chromium.org528c56d2010-07-30 19:28:44503 base::Int64ToString(Time::Now().ToTimeT()));
jar@chromium.orgb0c819f2009-03-08 04:52:15504 }
505 }
kuchhal@chromium.org157d5472009-11-05 22:31:03506 child_process_logging::SetClientId(client_id_);
initial.commit09911bf2008-07-26 23:55:29507 StartRecording();
pkasting@chromium.org005ef3e2009-05-22 20:55:46508
stuartmorgan@chromium.org3ffd3ae2011-03-17 22:17:52509 SetUpNotifications(&registrar_, this);
initial.commit09911bf2008-07-26 23:55:29510 } else {
pkasting@chromium.org005ef3e2009-05-22 20:55:46511 registrar_.RemoveAll();
initial.commit09911bf2008-07-26 23:55:29512 PushPendingLogsToUnsentLists();
513 DCHECK(!pending_log());
514 if (state_ > INITIAL_LOG_READY && unsent_logs())
515 state_ = SEND_OLD_INITIAL_LOGS;
516 }
petersont@google.comd01b8732008-10-16 02:18:07517 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29518}
519
petersont@google.comd01b8732008-10-16 02:18:07520bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29521 DCHECK(IsSingleThreaded());
petersont@google.comd01b8732008-10-16 02:18:07522 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29523}
524
petersont@google.comd01b8732008-10-16 02:18:07525void MetricsService::SetReporting(bool enable) {
526 if (reporting_active_ != enable) {
527 reporting_active_ = enable;
528 if (reporting_active_)
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16529 StartSchedulerIfNecessary();
initial.commit09911bf2008-07-26 23:55:29530 }
petersont@google.comd01b8732008-10-16 02:18:07531}
532
533bool MetricsService::reporting_active() const {
534 DCHECK(IsSingleThreaded());
535 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29536}
537
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15538// static
stuartmorgan@chromium.org3ffd3ae2011-03-17 22:17:52539void MetricsService::SetUpNotifications(NotificationRegistrar* registrar,
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15540 NotificationObserver* observer) {
ananta@chromium.org432115822011-07-10 15:52:27541 registrar->Add(observer, chrome::NOTIFICATION_BROWSER_OPENED,
erg@google.com04024e2c2011-08-12 19:32:10542 NotificationService::AllBrowserContextsAndSources());
ananta@chromium.org432115822011-07-10 15:52:27543 registrar->Add(observer, chrome::NOTIFICATION_BROWSER_CLOSED,
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15544 NotificationService::AllSources());
ananta@chromium.org432115822011-07-10 15:52:27545 registrar->Add(observer, content::NOTIFICATION_USER_ACTION,
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15546 NotificationService::AllSources());
ananta@chromium.org432115822011-07-10 15:52:27547 registrar->Add(observer, content::NOTIFICATION_TAB_PARENTED,
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15548 NotificationService::AllSources());
ananta@chromium.org432115822011-07-10 15:52:27549 registrar->Add(observer, content::NOTIFICATION_TAB_CLOSING,
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15550 NotificationService::AllSources());
ananta@chromium.org432115822011-07-10 15:52:27551 registrar->Add(observer, content::NOTIFICATION_LOAD_START,
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15552 NotificationService::AllSources());
ananta@chromium.org432115822011-07-10 15:52:27553 registrar->Add(observer, content::NOTIFICATION_LOAD_STOP,
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15554 NotificationService::AllSources());
ananta@chromium.org432115822011-07-10 15:52:27555 registrar->Add(observer, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15556 NotificationService::AllSources());
ananta@chromium.org432115822011-07-10 15:52:27557 registrar->Add(observer, content::NOTIFICATION_RENDERER_PROCESS_HANG,
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15558 NotificationService::AllSources());
ananta@chromium.org432115822011-07-10 15:52:27559 registrar->Add(observer, content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED,
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15560 NotificationService::AllSources());
ananta@chromium.org432115822011-07-10 15:52:27561 registrar->Add(observer, content::NOTIFICATION_CHILD_INSTANCE_CREATED,
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15562 NotificationService::AllSources());
ananta@chromium.org432115822011-07-10 15:52:27563 registrar->Add(observer, content::NOTIFICATION_CHILD_PROCESS_CRASHED,
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15564 NotificationService::AllSources());
ananta@chromium.org432115822011-07-10 15:52:27565 registrar->Add(observer, chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED,
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15566 NotificationService::AllSources());
ananta@chromium.org432115822011-07-10 15:52:27567 registrar->Add(observer, chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15568 NotificationService::AllSources());
ananta@chromium.org432115822011-07-10 15:52:27569 registrar->Add(observer, chrome::NOTIFICATION_BOOKMARK_MODEL_LOADED,
erg@chromium.org2f35a312011-08-09 20:21:29570 NotificationService::AllBrowserContextsAndSources());
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15571}
572
ananta@chromium.org432115822011-07-10 15:52:27573void MetricsService::Observe(int type,
initial.commit09911bf2008-07-26 23:55:29574 const NotificationSource& source,
575 const NotificationDetails& details) {
576 DCHECK(current_log_);
577 DCHECK(IsSingleThreaded());
578
579 if (!CanLogNotification(type, source, details))
580 return;
581
ananta@chromium.org432115822011-07-10 15:52:27582 switch (type) {
583 case content::NOTIFICATION_USER_ACTION:
evan@chromium.orgafe3a1672009-11-17 19:04:12584 current_log_->RecordUserAction(*Details<const char*>(details).ptr());
initial.commit09911bf2008-07-26 23:55:29585 break;
586
ananta@chromium.org432115822011-07-10 15:52:27587 case chrome::NOTIFICATION_BROWSER_OPENED:
588 case chrome::NOTIFICATION_BROWSER_CLOSED:
initial.commit09911bf2008-07-26 23:55:29589 LogWindowChange(type, source, details);
590 break;
591
ananta@chromium.org432115822011-07-10 15:52:27592 case content::NOTIFICATION_TAB_PARENTED:
593 case content::NOTIFICATION_TAB_CLOSING:
initial.commit09911bf2008-07-26 23:55:29594 LogWindowChange(type, source, details);
595 break;
596
ananta@chromium.org432115822011-07-10 15:52:27597 case content::NOTIFICATION_LOAD_STOP:
initial.commit09911bf2008-07-26 23:55:29598 LogLoadComplete(type, source, details);
599 break;
600
ananta@chromium.org432115822011-07-10 15:52:27601 case content::NOTIFICATION_LOAD_START:
initial.commit09911bf2008-07-26 23:55:29602 LogLoadStarted();
603 break;
604
ananta@chromium.org432115822011-07-10 15:52:27605 case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: {
kkania@chromium.orgcd69619b2010-05-05 02:41:38606 RenderProcessHost::RendererClosedDetails* process_details =
607 Details<RenderProcessHost::RendererClosedDetails>(details).ptr();
gspencer@chromium.org443b80e2010-12-14 00:42:23608 if (process_details->status ==
609 base::TERMINATION_STATUS_PROCESS_CRASHED ||
610 process_details->status ==
611 base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
kkania@chromium.orgcd69619b2010-05-05 02:41:38612 if (process_details->was_extension_renderer) {
613 LogExtensionRendererCrash();
614 } else {
615 LogRendererCrash();
616 }
617 }
asargent@chromium.org1f085622009-12-04 05:33:45618 }
initial.commit09911bf2008-07-26 23:55:29619 break;
620
ananta@chromium.org432115822011-07-10 15:52:27621 case content::NOTIFICATION_RENDERER_PROCESS_HANG:
initial.commit09911bf2008-07-26 23:55:29622 LogRendererHang();
623 break;
624
ananta@chromium.org432115822011-07-10 15:52:27625 case content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED:
626 case content::NOTIFICATION_CHILD_PROCESS_CRASHED:
627 case content::NOTIFICATION_CHILD_INSTANCE_CREATED:
jam@chromium.orga27a9382009-02-11 23:55:10628 LogChildProcessChange(type, source, details);
initial.commit09911bf2008-07-26 23:55:29629 break;
630
ananta@chromium.org432115822011-07-10 15:52:27631 case chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED:
erg@google.com8e5c89a2011-06-07 18:13:33632 LogKeywords(Source<TemplateURLService>(source).ptr());
initial.commit09911bf2008-07-26 23:55:29633 break;
634
ananta@chromium.org432115822011-07-10 15:52:27635 case chrome::NOTIFICATION_OMNIBOX_OPENED_URL: {
ananta@chromium.org1226abb2010-06-10 18:01:28636 MetricsLog* current_log = current_log_->AsMetricsLog();
637 DCHECK(current_log);
638 current_log->RecordOmniboxOpenedURL(
initial.commit09911bf2008-07-26 23:55:29639 *Details<AutocompleteLog>(details).ptr());
640 break;
ananta@chromium.org1226abb2010-06-10 18:01:28641 }
initial.commit09911bf2008-07-26 23:55:29642
ananta@chromium.org432115822011-07-10 15:52:27643 case chrome::NOTIFICATION_BOOKMARK_MODEL_LOADED: {
tim@chromium.orgb61236c62009-04-09 22:43:55644 Profile* p = Source<Profile>(source).ptr();
645 if (p)
646 LogBookmarks(p->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29647 break;
tim@chromium.orgb61236c62009-04-09 22:43:55648 }
initial.commit09911bf2008-07-26 23:55:29649 default:
jar@chromium.orga063c102010-07-22 22:20:19650 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:29651 break;
652 }
petersont@google.comd01b8732008-10-16 02:18:07653
654 HandleIdleSinceLastTransmission(false);
655
656 if (current_log_)
pkasting@chromium.org666205032010-10-21 20:56:58657 DVLOG(1) << "METRICS: NUMBER OF EVENTS = " << current_log_->num_events();
petersont@google.comd01b8732008-10-16 02:18:07658}
659
660void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
661 // If there wasn't a lot of action, maybe the computer was asleep, in which
662 // case, the log transmissions should have stopped. Here we start them up
663 // again.
pkasting@chromium.orgcac78842008-11-27 01:02:20664 if (!in_idle && idle_since_last_transmission_)
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16665 StartSchedulerIfNecessary();
pkasting@chromium.orgcac78842008-11-27 01:02:20666 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29667}
668
initial.commit09911bf2008-07-26 23:55:29669void MetricsService::RecordStartOfSessionEnd() {
stuartmorgan@chromium.org466f3c12011-03-23 21:20:38670 LogCleanShutdown();
initial.commit09911bf2008-07-26 23:55:29671 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
672}
673
674void MetricsService::RecordCompletedSessionEnd() {
stuartmorgan@chromium.org466f3c12011-03-23 21:20:38675 LogCleanShutdown();
initial.commit09911bf2008-07-26 23:55:29676 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
677}
678
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16679void MetricsService::RecordBreakpadRegistration(bool success) {
jar@google.com68475e602008-08-22 03:21:15680 if (!success)
cpu@google.come73c01972008-08-13 00:18:24681 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
682 else
683 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
684}
685
686void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
687 if (!has_debugger)
688 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
689 else
jar@google.com68475e602008-08-22 03:21:15690 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
cpu@google.come73c01972008-08-13 00:18:24691}
692
initial.commit09911bf2008-07-26 23:55:29693//------------------------------------------------------------------------------
694// private methods
695//------------------------------------------------------------------------------
696
697
698//------------------------------------------------------------------------------
699// Initialization methods
700
701void MetricsService::InitializeMetricsState() {
kuchhal@chromium.org79bf0b72009-04-27 21:30:55702#if defined(OS_POSIX)
703 server_url_ = L"https://clients4.google.com/firefox/metrics/collect";
rtenneti@chromium.orgd67d1052011-06-09 05:11:41704 // TODO(rtenneti): Return the network stats server name.
705 network_stats_server_ = "";
kuchhal@chromium.org79bf0b72009-04-27 21:30:55706#else
707 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
708 server_url_ = dist->GetStatsServerURL();
rtenneti@chromium.orgd67d1052011-06-09 05:11:41709 network_stats_server_ = dist->GetNetworkStatsServer();
kuchhal@chromium.org79bf0b72009-04-27 21:30:55710#endif
711
initial.commit09911bf2008-07-26 23:55:29712 PrefService* pref = g_browser_process->local_state();
713 DCHECK(pref);
714
jar@chromium.org225c50842010-01-19 21:19:13715 if ((pref->GetInt64(prefs::kStabilityStatsBuildTime)
716 != MetricsLog::GetBuildTime()) ||
estade@chromium.orgddd231e2010-06-29 20:35:19717 (pref->GetString(prefs::kStabilityStatsVersion)
jar@chromium.org225c50842010-01-19 21:19:13718 != MetricsLog::GetVersionString())) {
jar@chromium.org541f77922009-02-23 21:14:38719 // This is a new version, so we don't want to confuse the stats about the
720 // old version with info that we upload.
721 DiscardOldStabilityStats(pref);
722 pref->SetString(prefs::kStabilityStatsVersion,
estade@chromium.orgddd231e2010-06-29 20:35:19723 MetricsLog::GetVersionString());
jar@chromium.org225c50842010-01-19 21:19:13724 pref->SetInt64(prefs::kStabilityStatsBuildTime,
725 MetricsLog::GetBuildTime());
jar@chromium.org541f77922009-02-23 21:14:38726 }
727
initial.commit09911bf2008-07-26 23:55:29728 // Update session ID
729 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
730 ++session_id_;
731 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
732
initial.commit09911bf2008-07-26 23:55:29733 // Stability bookkeeping
cpu@google.come73c01972008-08-13 00:18:24734 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29735
cpu@google.come73c01972008-08-13 00:18:24736 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
737 IncrementPrefValue(prefs::kStabilityCrashCount);
jar@chromium.orgc0c55e92011-09-10 18:47:30738 // Reset flag, and wait until we call LogNeedForCleanShutdown() before
739 // monitoring.
740 pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
initial.commit09911bf2008-07-26 23:55:29741 }
cpu@google.come73c01972008-08-13 00:18:24742
cpu@google.come73c01972008-08-13 00:18:24743 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
744 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
jar@chromium.orgc9abf242009-07-18 06:00:38745 // This is marked false when we get a WM_ENDSESSION.
746 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
initial.commit09911bf2008-07-26 23:55:29747 }
initial.commit09911bf2008-07-26 23:55:29748
jar@chromium.org9165f742010-03-10 22:55:01749 // Initialize uptime counters.
750 int64 startup_uptime = MetricsLog::GetIncrementalUptime(pref);
mad@google.comae393ec702010-06-27 16:23:14751 DCHECK_EQ(0, startup_uptime);
jar@chromium.org9165f742010-03-10 22:55:01752 // For backwards compatibility, leave this intact in case Omaha is checking
753 // them. prefs::kStabilityLastTimestampSec may also be useless now.
754 // TODO(jar): Delete these if they have no uses.
robertshield@google.com0bb1a622009-03-04 03:22:32755 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
756
757 // Bookkeeping for the uninstall metrics.
758 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29759
760 // Save profile metrics.
761 PrefService* prefs = g_browser_process->local_state();
762 if (prefs) {
763 // Remove the current dictionary and store it for use when sending data to
764 // server. By removing the value we prune potentially dead profiles
765 // (and keys). All valid values are added back once services startup.
766 const DictionaryValue* profile_dictionary =
767 prefs->GetDictionary(prefs::kProfileMetrics);
768 if (profile_dictionary) {
769 // Do a deep copy of profile_dictionary since ClearPref will delete it.
770 profile_dictionary_.reset(static_cast<DictionaryValue*>(
771 profile_dictionary->DeepCopy()));
772 prefs->ClearPref(prefs::kProfileMetrics);
773 }
774 }
775
jar@chromium.org92745242009-06-12 16:52:21776 // Get stats on use of command line.
777 const CommandLine* command_line(CommandLine::ForCurrentProcess());
778 size_t common_commands = 0;
779 if (command_line->HasSwitch(switches::kUserDataDir)) {
780 ++common_commands;
781 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
782 }
783
784 if (command_line->HasSwitch(switches::kApp)) {
785 ++common_commands;
786 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
787 }
788
msw@chromium.org62b4e522011-07-13 21:46:32789 size_t switch_count = command_line->GetSwitches().size();
790 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount", switch_count);
jar@chromium.org92745242009-06-12 16:52:21791 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
msw@chromium.org62b4e522011-07-13 21:46:32792 switch_count - common_commands);
jar@chromium.org92745242009-06-12 16:52:21793
initial.commit09911bf2008-07-26 23:55:29794 // Kick off the process of saving the state (so the uptime numbers keep
795 // getting updated) every n minutes.
796 ScheduleNextStateSave();
797}
798
zelidrag@chromium.org85ed9d42010-06-08 22:37:44799void MetricsService::OnInitTaskComplete(
800 const std::string& hardware_class,
cpu@chromium.org91d9f3d2011-08-14 05:24:44801 const std::vector<webkit::WebPluginInfo>& plugins) {
zelidrag@chromium.org85ed9d42010-06-08 22:37:44802 DCHECK(state_ == INIT_TASK_SCHEDULED);
803 hardware_class_ = hardware_class;
jam@chromium.org35fa6a22009-08-15 00:04:01804 plugins_ = plugins;
rtenneti@chromium.orgd67d1052011-06-09 05:11:41805 io_thread_ = g_browser_process->io_thread();
zelidrag@chromium.org85ed9d42010-06-08 22:37:44806 if (state_ == INIT_TASK_SCHEDULED)
807 state_ = INIT_TASK_DONE;
initial.commit09911bf2008-07-26 23:55:29808}
809
810std::string MetricsService::GenerateClientID() {
dhollowa@chromium.org3469e7e2010-10-14 20:34:59811 return guid::GenerateGUID();
initial.commit09911bf2008-07-26 23:55:29812}
813
initial.commit09911bf2008-07-26 23:55:29814//------------------------------------------------------------------------------
815// State save methods
816
817void MetricsService::ScheduleNextStateSave() {
818 state_saver_factory_.RevokeAll();
819
820 MessageLoop::current()->PostDelayedTask(FROM_HERE,
821 state_saver_factory_.NewRunnableMethod(&MetricsService::SaveLocalState),
822 kSaveStateInterval * 1000);
823}
824
825void MetricsService::SaveLocalState() {
826 PrefService* pref = g_browser_process->local_state();
827 if (!pref) {
jar@chromium.orga063c102010-07-22 22:20:19828 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:29829 return;
830 }
831
832 RecordCurrentState(pref);
phajdan.jr@chromium.org6faa0e0d2009-04-28 06:50:36833 pref->ScheduleSavePersistentPrefs();
initial.commit09911bf2008-07-26 23:55:29834
jar@chromium.org281d2882009-01-20 20:32:42835 // TODO(jar): Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29836 ScheduleNextStateSave();
837}
838
839
840//------------------------------------------------------------------------------
841// Recording control methods
842
843void MetricsService::StartRecording() {
844 if (current_log_)
845 return;
846
847 current_log_ = new MetricsLog(client_id_, session_id_);
848 if (state_ == INITIALIZED) {
849 // We only need to schedule that run once.
zelidrag@chromium.org85ed9d42010-06-08 22:37:44850 state_ = INIT_TASK_SCHEDULED;
initial.commit09911bf2008-07-26 23:55:29851
zelidrag@chromium.org85ed9d42010-06-08 22:37:44852 // Schedules a task on the file thread for execution of slower
853 // initialization steps (such as plugin list generation) necessary
854 // for sending the initial log. This avoids blocking the main UI
855 // thread.
jamesr@chromium.org7f2e792e2009-11-30 23:18:29856 g_browser_process->file_thread()->message_loop()->PostDelayedTask(FROM_HERE,
zelidrag@chromium.org85ed9d42010-06-08 22:37:44857 new InitTask(MessageLoop::current()),
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16858 kInitializationDelaySeconds * 1000);
initial.commit09911bf2008-07-26 23:55:29859 }
860}
861
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:38862void MetricsService::StopRecording() {
initial.commit09911bf2008-07-26 23:55:29863 if (!current_log_)
864 return;
865
bryner@chromium.org49cd7e882011-02-01 03:54:36866 current_log_->set_hardware_class(hardware_class_); // Adds to ongoing logs.
zelidrag@chromium.org85ed9d42010-06-08 22:37:44867
jar@google.com68475e602008-08-22 03:21:15868 // TODO(jar): Integrate bounds on log recording more consistently, so that we
869 // can stop recording logs that are too big much sooner.
stuartmorgan@chromium.org54702c92011-04-15 15:06:43870 if (current_log_->num_events() > kEventLimit) {
dsh@google.com553dba62009-02-24 19:08:23871 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
jar@google.com68475e602008-08-22 03:21:15872 current_log_->num_events());
873 current_log_->CloseLog();
874 delete current_log_;
jar@google.com294638782008-09-24 00:22:41875 current_log_ = NULL;
jar@google.com68475e602008-08-22 03:21:15876 StartRecording(); // Start trivial log to hold our histograms.
877 }
878
jar@google.com0b33f80b2008-12-17 21:34:36879 // Put incremental data (histogram deltas, and realtime stats deltas) at the
jar@google.com147bbc0b2009-01-06 19:37:40880 // end of all log transmissions (initial log handles this separately).
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:38881 // RecordIncrementalStabilityElements only exists on the derived
882 // MetricsLog class.
883 MetricsLog* current_log = current_log_->AsMetricsLog();
884 DCHECK(current_log);
885 current_log->RecordIncrementalStabilityElements();
886 RecordCurrentHistograms();
initial.commit09911bf2008-07-26 23:55:29887
888 current_log_->CloseLog();
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:38889 pending_log_ = current_log_;
initial.commit09911bf2008-07-26 23:55:29890 current_log_ = NULL;
891}
892
initial.commit09911bf2008-07-26 23:55:29893void MetricsService::PushPendingLogsToUnsentLists() {
894 if (state_ < INITIAL_LOG_READY)
avi@google.com28ab7f92009-01-06 21:39:04895 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29896
897 if (pending_log()) {
898 PreparePendingLogText();
899 if (state_ == INITIAL_LOG_READY) {
900 // We may race here, and send second copy of initial log later.
ziadh@chromium.org46f89e142010-07-19 08:00:42901 unsent_initial_logs_.push_back(compressed_log_);
petersont@google.comd01b8732008-10-16 02:18:07902 state_ = SEND_OLD_INITIAL_LOGS;
initial.commit09911bf2008-07-26 23:55:29903 } else {
jar@chromium.org281d2882009-01-20 20:32:42904 // TODO(jar): Verify correctness in other states, including sending unsent
jar@chromium.org541f77922009-02-23 21:14:38905 // initial logs.
jar@google.com68475e602008-08-22 03:21:15906 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29907 }
908 DiscardPendingLog();
909 }
910 DCHECK(!pending_log());
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:38911 StopRecording();
initial.commit09911bf2008-07-26 23:55:29912 PreparePendingLogText();
jar@google.com68475e602008-08-22 03:21:15913 PushPendingLogTextToUnsentOngoingLogs();
initial.commit09911bf2008-07-26 23:55:29914 DiscardPendingLog();
915 StoreUnsentLogs();
916}
917
jar@google.com68475e602008-08-22 03:21:15918void MetricsService::PushPendingLogTextToUnsentOngoingLogs() {
ziadh@chromium.org46f89e142010-07-19 08:00:42919 if (compressed_log_.length() >
paul@chromium.orgdc6f4962009-02-13 01:25:50920 static_cast<size_t>(kUploadLogAvoidRetransmitSize)) {
dsh@google.com553dba62009-02-24 19:08:23921 UMA_HISTOGRAM_COUNTS("UMA.Large Accumulated Log Not Persisted",
ziadh@chromium.org46f89e142010-07-19 08:00:42922 static_cast<int>(compressed_log_.length()));
jar@google.com68475e602008-08-22 03:21:15923 return;
924 }
ziadh@chromium.org46f89e142010-07-19 08:00:42925 unsent_ongoing_logs_.push_back(compressed_log_);
jar@google.com68475e602008-08-22 03:21:15926}
927
initial.commit09911bf2008-07-26 23:55:29928//------------------------------------------------------------------------------
929// Transmission of logs methods
930
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16931void MetricsService::StartSchedulerIfNecessary() {
932 if (reporting_active() && recording_active())
933 scheduler_->Start();
initial.commit09911bf2008-07-26 23:55:29934}
935
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16936void MetricsService::StartScheduledUpload() {
937 // If reporting has been turned off, the scheduler doesn't need to run.
938 if (!reporting_active() || !recording_active()) {
939 scheduler_->Stop();
940 scheduler_->UploadCancelled();
941 return;
942 }
943
944 DCHECK(!waiting_for_asynchronus_reporting_step_);
945 waiting_for_asynchronus_reporting_step_ = true;
946
sail@chromium.org84c988a2011-04-19 17:56:33947 Task* task = log_sender_factory_.
948 NewRunnableMethod(&MetricsService::OnMemoryDetailCollectionDone);
949
950 scoped_refptr<MetricsMemoryDetails> details(new MetricsMemoryDetails(task));
951 details->StartFetch();
952
953 // Collect WebCore cache information to put into a histogram.
954 for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());
955 !i.IsAtEnd(); i.Advance())
ananta@chromium.org2ccf45c2011-08-19 23:35:50956 i.GetCurrentValue()->Send(new ChromeViewMsg_GetCacheResourceStats());
sail@chromium.org84c988a2011-04-19 17:56:33957}
958
959void MetricsService::OnMemoryDetailCollectionDone() {
jar@chromium.orgc9a3ef82009-05-28 22:02:46960 DCHECK(IsSingleThreaded());
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16961 // This function should only be called as the callback from an ansynchronous
962 // step.
963 DCHECK(waiting_for_asynchronus_reporting_step_);
jar@chromium.orgc9a3ef82009-05-28 22:02:46964
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16965 // Right before the UMA transmission gets started, there's one more thing we'd
966 // like to record: the histogram of memory usage, so we spawn a task to
967 // collect the memory details and when that task is finished, it will call
968 // OnMemoryDetailCollectionDone, which will call HistogramSynchronization to
969 // collect histograms from all renderers and then we will call
970 // OnHistogramSynchronizationDone to continue processing.
jar@chromium.orgc9a3ef82009-05-28 22:02:46971
972 // Create a callback_task for OnHistogramSynchronizationDone.
973 Task* callback_task = log_sender_factory_.NewRunnableMethod(
974 &MetricsService::OnHistogramSynchronizationDone);
975
976 // Set up the callback to task to call after we receive histograms from all
977 // renderer processes. Wait time specifies how long to wait before absolutely
978 // calling us back on the task.
979 HistogramSynchronizer::FetchRendererHistogramsAsynchronously(
980 MessageLoop::current(), callback_task,
981 kMaxHistogramGatheringWaitDuration);
982}
983
984void MetricsService::OnHistogramSynchronizationDone() {
initial.commit09911bf2008-07-26 23:55:29985 DCHECK(IsSingleThreaded());
986
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16987 // If somehow there is a fetch in progress, we return and hope things work
988 // out. The scheduler isn't informed since if this happens, the scheduler
989 // will get a response from the upload.
initial.commit09911bf2008-07-26 23:55:29990 DCHECK(!current_fetch_.get());
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16991 if (current_fetch_.get())
992 return;
993
994 // This function should only be called as the callback from an ansynchronous
995 // step.
996 DCHECK(waiting_for_asynchronus_reporting_step_);
997 waiting_for_asynchronus_reporting_step_ = false;
initial.commit09911bf2008-07-26 23:55:29998
petersont@google.comd01b8732008-10-16 02:18:07999 // If we're getting no notifications, then the log won't have much in it, and
1000 // it's possible the computer is about to go to sleep, so don't upload and
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161001 // stop the scheduler.
1002 // Similarly, if logs should no longer be uploaded, stop here.
1003 if (idle_since_last_transmission_ ||
1004 !recording_active() || !reporting_active()) {
1005 scheduler_->Stop();
1006 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:071007 return;
1008 }
1009
petersont@google.comd01b8732008-10-16 02:18:071010 MakePendingLog();
initial.commit09911bf2008-07-26 23:55:291011
petersont@google.comd01b8732008-10-16 02:18:071012 // MakePendingLog should have put something in the pending log, if it didn't,
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161013 // we skip this upload and hope things work out next time.
petersont@google.comd01b8732008-10-16 02:18:071014 if (!pending_log()) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161015 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:071016 return;
1017 }
initial.commit09911bf2008-07-26 23:55:291018
petersont@google.comd01b8732008-10-16 02:18:071019 PrepareFetchWithPendingLog();
1020
1021 if (!current_fetch_.get()) {
1022 // Compression failed, and log discarded :-/.
1023 DiscardPendingLog();
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161024 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:071025 // TODO(jar): If compression failed, we should have created a tiny log and
1026 // compressed that, so that we can signal that we're losing logs.
1027 return;
1028 }
1029
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161030 DCHECK(!waiting_for_asynchronus_reporting_step_);
petersont@google.comd01b8732008-10-16 02:18:071031
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161032 waiting_for_asynchronus_reporting_step_ = true;
petersont@google.comd01b8732008-10-16 02:18:071033 current_fetch_->Start();
1034
1035 HandleIdleSinceLastTransmission(true);
1036}
1037
1038
1039void MetricsService::MakePendingLog() {
1040 if (pending_log())
1041 return;
1042
1043 switch (state_) {
1044 case INITIALIZED:
zelidrag@chromium.org85ed9d42010-06-08 22:37:441045 case INIT_TASK_SCHEDULED: // We should be further along by now.
petersont@google.comd01b8732008-10-16 02:18:071046 DCHECK(false);
1047 return;
1048
zelidrag@chromium.org85ed9d42010-06-08 22:37:441049 case INIT_TASK_DONE:
petersont@google.comd01b8732008-10-16 02:18:071050 // We need to wait for the initial log to be ready before sending
1051 // anything, because the server will tell us whether it wants to hear
1052 // from us.
1053 PrepareInitialLog();
zelidrag@chromium.org85ed9d42010-06-08 22:37:441054 DCHECK(state_ == INIT_TASK_DONE);
petersont@google.comd01b8732008-10-16 02:18:071055 RecallUnsentLogs();
1056 state_ = INITIAL_LOG_READY;
1057 break;
1058
1059 case SEND_OLD_INITIAL_LOGS:
pkasting@chromium.orgcac78842008-11-27 01:02:201060 if (!unsent_initial_logs_.empty()) {
ziadh@chromium.org46f89e142010-07-19 08:00:421061 compressed_log_ = unsent_initial_logs_.back();
stuartmorgan@chromium.orgd53e2232011-06-30 15:54:571062 unsent_initial_logs_.pop_back();
pkasting@chromium.orgcac78842008-11-27 01:02:201063 break;
1064 }
petersont@google.comd01b8732008-10-16 02:18:071065 state_ = SENDING_OLD_LOGS;
1066 // Fall through.
initial.commit09911bf2008-07-26 23:55:291067
petersont@google.comd01b8732008-10-16 02:18:071068 case SENDING_OLD_LOGS:
1069 if (!unsent_ongoing_logs_.empty()) {
ziadh@chromium.org46f89e142010-07-19 08:00:421070 compressed_log_ = unsent_ongoing_logs_.back();
stuartmorgan@chromium.orgd53e2232011-06-30 15:54:571071 unsent_ongoing_logs_.pop_back();
petersont@google.comd01b8732008-10-16 02:18:071072 break;
1073 }
1074 state_ = SENDING_CURRENT_LOGS;
1075 // Fall through.
1076
1077 case SENDING_CURRENT_LOGS:
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:381078 StopRecording();
petersont@google.comd01b8732008-10-16 02:18:071079 StartRecording();
1080 break;
1081
1082 default:
jar@chromium.orga063c102010-07-22 22:20:191083 NOTREACHED();
petersont@google.comd01b8732008-10-16 02:18:071084 return;
1085 }
1086
1087 DCHECK(pending_log());
1088}
1089
initial.commit09911bf2008-07-26 23:55:291090void MetricsService::PrepareInitialLog() {
zelidrag@chromium.org85ed9d42010-06-08 22:37:441091 DCHECK(state_ == INIT_TASK_DONE);
initial.commit09911bf2008-07-26 23:55:291092
1093 MetricsLog* log = new MetricsLog(client_id_, session_id_);
zelidrag@chromium.org85ed9d42010-06-08 22:37:441094 log->set_hardware_class(hardware_class_); // Adds to initial log.
jam@chromium.org35fa6a22009-08-15 00:04:011095 log->RecordEnvironment(plugins_, profile_dictionary_.get());
initial.commit09911bf2008-07-26 23:55:291096
1097 // Histograms only get written to current_log_, so setup for the write.
ananta@chromium.org1226abb2010-06-10 18:01:281098 MetricsLogBase* save_log = current_log_;
initial.commit09911bf2008-07-26 23:55:291099 current_log_ = log;
1100 RecordCurrentHistograms(); // Into current_log_... which is really log.
1101 current_log_ = save_log;
1102
1103 log->CloseLog();
1104 DCHECK(!pending_log());
1105 pending_log_ = log;
1106}
1107
ziadh@chromium.org46f89e142010-07-19 08:00:421108// static
1109MetricsService::LogRecallStatus MetricsService::RecallUnsentLogsHelper(
1110 const ListValue& list,
1111 std::vector<std::string>* local_list) {
1112 DCHECK(local_list->empty());
1113 if (list.GetSize() == 0)
1114 return MakeRecallStatusHistogram(LIST_EMPTY);
1115 if (list.GetSize() < 3)
1116 return MakeRecallStatusHistogram(LIST_SIZE_TOO_SMALL);
initial.commit09911bf2008-07-26 23:55:291117
ziadh@chromium.org46f89e142010-07-19 08:00:421118 // The size is stored at the beginning of the list.
1119 int size;
1120 bool valid = (*list.begin())->GetAsInteger(&size);
1121 if (!valid)
1122 return MakeRecallStatusHistogram(LIST_SIZE_MISSING);
1123
1124 // Account for checksum and size included in the list.
1125 if (static_cast<unsigned int>(size) !=
1126 list.GetSize() - kChecksumEntryCount)
1127 return MakeRecallStatusHistogram(LIST_SIZE_CORRUPTION);
1128
tfarina@chromium.org0ad1d2d62011-07-18 16:54:581129 base::MD5Context ctx;
1130 base::MD5Init(&ctx);
ziadh@chromium.org46f89e142010-07-19 08:00:421131 std::string encoded_log;
1132 std::string decoded_log;
1133 for (ListValue::const_iterator it = list.begin() + 1;
1134 it != list.end() - 1; ++it) { // Last element is the checksum.
1135 valid = (*it)->GetAsString(&encoded_log);
1136 if (!valid) {
1137 local_list->clear();
1138 return MakeRecallStatusHistogram(LOG_STRING_CORRUPTION);
1139 }
1140
dominich@chromium.orga3bcff62011-07-26 23:39:501141 base::MD5Update(&ctx, encoded_log);
ziadh@chromium.org46f89e142010-07-19 08:00:421142
1143 if (!base::Base64Decode(encoded_log, &decoded_log)) {
1144 local_list->clear();
1145 return MakeRecallStatusHistogram(DECODE_FAIL);
1146 }
1147 local_list->push_back(decoded_log);
1148 }
1149
1150 // Verify checksum.
tfarina@chromium.org0ad1d2d62011-07-18 16:54:581151 base::MD5Digest digest;
1152 base::MD5Final(&digest, &ctx);
ziadh@chromium.org46f89e142010-07-19 08:00:421153 std::string recovered_md5;
1154 // We store the hash at the end of the list.
1155 valid = (*(list.end() - 1))->GetAsString(&recovered_md5);
1156 if (!valid) {
1157 local_list->clear();
1158 return MakeRecallStatusHistogram(CHECKSUM_STRING_CORRUPTION);
1159 }
tfarina@chromium.org0ad1d2d62011-07-18 16:54:581160 if (recovered_md5 != base::MD5DigestToBase16(digest)) {
ziadh@chromium.org46f89e142010-07-19 08:00:421161 local_list->clear();
1162 return MakeRecallStatusHistogram(CHECKSUM_CORRUPTION);
1163 }
1164 return MakeRecallStatusHistogram(RECALL_SUCCESS);
1165}
1166void MetricsService::RecallUnsentLogs() {
initial.commit09911bf2008-07-26 23:55:291167 PrefService* local_state = g_browser_process->local_state();
1168 DCHECK(local_state);
1169
battre@chromium.orgf8628c22011-04-05 12:10:181170 const ListValue* unsent_initial_logs = local_state->GetList(
initial.commit09911bf2008-07-26 23:55:291171 prefs::kMetricsInitialLogs);
ziadh@chromium.org46f89e142010-07-19 08:00:421172 RecallUnsentLogsHelper(*unsent_initial_logs, &unsent_initial_logs_);
initial.commit09911bf2008-07-26 23:55:291173
battre@chromium.orgf8628c22011-04-05 12:10:181174 const ListValue* unsent_ongoing_logs = local_state->GetList(
initial.commit09911bf2008-07-26 23:55:291175 prefs::kMetricsOngoingLogs);
ziadh@chromium.org46f89e142010-07-19 08:00:421176 RecallUnsentLogsHelper(*unsent_ongoing_logs, &unsent_ongoing_logs_);
1177}
1178
1179// static
1180void MetricsService::StoreUnsentLogsHelper(
1181 const std::vector<std::string>& local_list,
1182 const size_t kMaxLocalListSize,
1183 ListValue* list) {
1184 list->Clear();
1185 size_t start = 0;
1186 if (local_list.size() > kMaxLocalListSize)
1187 start = local_list.size() - kMaxLocalListSize;
1188 DCHECK(start <= local_list.size());
1189 if (local_list.size() == start)
1190 return;
1191
1192 // Store size at the beginning of the list.
1193 list->Append(Value::CreateIntegerValue(local_list.size() - start));
1194
tfarina@chromium.org0ad1d2d62011-07-18 16:54:581195 base::MD5Context ctx;
1196 base::MD5Init(&ctx);
ziadh@chromium.org46f89e142010-07-19 08:00:421197 std::string encoded_log;
1198 for (std::vector<std::string>::const_iterator it = local_list.begin() + start;
1199 it != local_list.end(); ++it) {
1200 // We encode the compressed log as Value::CreateStringValue() expects to
1201 // take a valid UTF8 string.
1202 if (!base::Base64Encode(*it, &encoded_log)) {
1203 MakeStoreStatusHistogram(ENCODE_FAIL);
1204 list->Clear();
1205 return;
1206 }
dominich@chromium.orga3bcff62011-07-26 23:39:501207 base::MD5Update(&ctx, encoded_log);
ziadh@chromium.org46f89e142010-07-19 08:00:421208 list->Append(Value::CreateStringValue(encoded_log));
initial.commit09911bf2008-07-26 23:55:291209 }
ziadh@chromium.org46f89e142010-07-19 08:00:421210
1211 // Append hash to the end of the list.
tfarina@chromium.org0ad1d2d62011-07-18 16:54:581212 base::MD5Digest digest;
1213 base::MD5Final(&digest, &ctx);
1214 list->Append(Value::CreateStringValue(base::MD5DigestToBase16(digest)));
ziadh@chromium.org46f89e142010-07-19 08:00:421215 DCHECK(list->GetSize() >= 3); // Minimum of 3 elements (size, data, hash).
ziadh@chromium.org4e95d202010-07-24 01:47:561216 MakeStoreStatusHistogram(STORE_SUCCESS);
initial.commit09911bf2008-07-26 23:55:291217}
1218
1219void MetricsService::StoreUnsentLogs() {
1220 if (state_ < INITIAL_LOG_READY)
1221 return; // We never Recalled the prior unsent logs.
1222
1223 PrefService* local_state = g_browser_process->local_state();
1224 DCHECK(local_state);
1225
battre@chromium.orgf8628c22011-04-05 12:10:181226 {
1227 ListPrefUpdate update(local_state, prefs::kMetricsInitialLogs);
1228 ListValue* unsent_initial_logs = update.Get();
1229 StoreUnsentLogsHelper(unsent_initial_logs_, kMaxInitialLogsPersisted,
1230 unsent_initial_logs);
1231 }
initial.commit09911bf2008-07-26 23:55:291232
battre@chromium.orgf8628c22011-04-05 12:10:181233 {
1234 ListPrefUpdate update(local_state, prefs::kMetricsOngoingLogs);
1235 ListValue* unsent_ongoing_logs = update.Get();
1236 StoreUnsentLogsHelper(unsent_ongoing_logs_, kMaxOngoingLogsPersisted,
1237 unsent_ongoing_logs);
1238 }
initial.commit09911bf2008-07-26 23:55:291239}
1240
1241void MetricsService::PreparePendingLogText() {
1242 DCHECK(pending_log());
ziadh@chromium.org46f89e142010-07-19 08:00:421243 if (!compressed_log_.empty())
initial.commit09911bf2008-07-26 23:55:291244 return;
mark@chromium.org9ffcccf42009-09-15 22:19:181245 int text_size = pending_log_->GetEncodedLogSize();
1246
ziadh@chromium.org46f89e142010-07-19 08:00:421247 std::string pending_log_text;
1248 // Leave room for the NULL terminator.
1249 pending_log_->GetEncodedLog(WriteInto(&pending_log_text, text_size + 1),
mark@chromium.org9ffcccf42009-09-15 22:19:181250 text_size);
ziadh@chromium.org46f89e142010-07-19 08:00:421251
1252 if (Bzip2Compress(pending_log_text, &compressed_log_)) {
1253 // Allow security conscious users to see all metrics logs that we send.
pkasting@chromium.org666205032010-10-21 20:56:581254 VLOG(1) << "COMPRESSED FOLLOWING METRICS LOG: " << pending_log_text;
ziadh@chromium.org46f89e142010-07-19 08:00:421255 } else {
1256 LOG(DFATAL) << "Failed to compress log for transmission.";
1257 // We can't discard the logs as other caller functions expect that
1258 // |compressed_log_| not be empty. We can detect this failure at the server
1259 // after we transmit.
1260 compressed_log_ = "Unable to compress!";
1261 MakeStoreStatusHistogram(COMPRESS_FAIL);
1262 return;
1263 }
initial.commit09911bf2008-07-26 23:55:291264}
1265
petersont@google.comd01b8732008-10-16 02:18:071266void MetricsService::PrepareFetchWithPendingLog() {
initial.commit09911bf2008-07-26 23:55:291267 DCHECK(pending_log());
1268 DCHECK(!current_fetch_.get());
1269 PreparePendingLogText();
ziadh@chromium.org46f89e142010-07-19 08:00:421270 DCHECK(!compressed_log_.empty());
pkasting@chromium.orgcac78842008-11-27 01:02:201271
kuchhal@chromium.org79bf0b72009-04-27 21:30:551272 current_fetch_.reset(new URLFetcher(GURL(WideToUTF16(server_url_)),
1273 URLFetcher::POST,
initial.commit09911bf2008-07-26 23:55:291274 this));
willchan@chromium.org9abfa192011-07-20 15:48:531275 current_fetch_->set_request_context(
nkostylev@chromium.org8ef3d8052011-07-22 09:03:001276 g_browser_process->system_request_context());
ziadh@chromium.org46f89e142010-07-19 08:00:421277 current_fetch_->set_upload_data(kMetricsType, compressed_log_);
initial.commit09911bf2008-07-26 23:55:291278}
1279
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441280static const char* StatusToString(const net::URLRequestStatus& status) {
initial.commit09911bf2008-07-26 23:55:291281 switch (status.status()) {
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441282 case net::URLRequestStatus::SUCCESS:
initial.commit09911bf2008-07-26 23:55:291283 return "SUCCESS";
1284
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441285 case net::URLRequestStatus::IO_PENDING:
initial.commit09911bf2008-07-26 23:55:291286 return "IO_PENDING";
1287
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441288 case net::URLRequestStatus::HANDLED_EXTERNALLY:
initial.commit09911bf2008-07-26 23:55:291289 return "HANDLED_EXTERNALLY";
1290
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441291 case net::URLRequestStatus::CANCELED:
initial.commit09911bf2008-07-26 23:55:291292 return "CANCELED";
1293
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441294 case net::URLRequestStatus::FAILED:
initial.commit09911bf2008-07-26 23:55:291295 return "FAILED";
1296
1297 default:
jar@chromium.orga063c102010-07-22 22:20:191298 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291299 return "Unknown";
1300 }
1301}
1302
1303void MetricsService::OnURLFetchComplete(const URLFetcher* source,
1304 const GURL& url,
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441305 const net::URLRequestStatus& status,
initial.commit09911bf2008-07-26 23:55:291306 int response_code,
tfarina@chromium.orgcb04f5e2011-05-06 01:10:001307 const net::ResponseCookies& cookies,
initial.commit09911bf2008-07-26 23:55:291308 const std::string& data) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161309 DCHECK(waiting_for_asynchronus_reporting_step_);
1310 waiting_for_asynchronus_reporting_step_ = false;
initial.commit09911bf2008-07-26 23:55:291311 DCHECK(current_fetch_.get());
1312 current_fetch_.reset(NULL); // We're not allowed to re-use it.
1313
1314 // Confirm send so that we can move on.
pkasting@chromium.org666205032010-10-21 20:56:581315 VLOG(1) << "METRICS RESPONSE CODE: " << response_code
1316 << " status=" << StatusToString(status);
petersont@google.com252873ef2008-08-04 21:59:451317
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161318 bool upload_succeeded = response_code == 200;
1319
jar@chromium.org0eb34fee2009-01-21 08:04:381320 // Provide boolean for error recovery (allow us to ignore response_code).
paul@chromium.orgdc6f4962009-02-13 01:25:501321 bool discard_log = false;
jar@chromium.org0eb34fee2009-01-21 08:04:381322
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161323 if (!upload_succeeded &&
ziadh@chromium.org46f89e142010-07-19 08:00:421324 (compressed_log_.length() >
1325 static_cast<size_t>(kUploadLogAvoidRetransmitSize))) {
dsh@google.com553dba62009-02-24 19:08:231326 UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
ziadh@chromium.org46f89e142010-07-19 08:00:421327 static_cast<int>(compressed_log_.length()));
jar@chromium.org0eb34fee2009-01-21 08:04:381328 discard_log = true;
1329 } else if (response_code == 400) {
1330 // Bad syntax. Retransmission won't work.
dsh@google.com553dba62009-02-24 19:08:231331 UMA_HISTOGRAM_COUNTS("UMA.Unacceptable_Log_Discarded", state_);
jar@chromium.org0eb34fee2009-01-21 08:04:381332 discard_log = true;
jar@google.com68475e602008-08-22 03:21:151333 }
1334
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161335 if (!upload_succeeded && !discard_log) {
pkasting@chromium.org666205032010-10-21 20:56:581336 VLOG(1) << "METRICS: transmission attempt returned a failure code: "
1337 << response_code << ". Verify network connectivity";
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161338 LogBadResponseCode();
jar@chromium.org0eb34fee2009-01-21 08:04:381339 } else { // Successful receipt (or we are discarding log).
pkasting@chromium.org666205032010-10-21 20:56:581340 VLOG(1) << "METRICS RESPONSE DATA: " << data;
initial.commit09911bf2008-07-26 23:55:291341 switch (state_) {
1342 case INITIAL_LOG_READY:
1343 state_ = SEND_OLD_INITIAL_LOGS;
1344 break;
1345
1346 case SEND_OLD_INITIAL_LOGS:
initial.commit09911bf2008-07-26 23:55:291347 case SENDING_OLD_LOGS:
stuartmorgan@chromium.orgd53e2232011-06-30 15:54:571348 // Store the updated list to disk now that the removed log is uploaded.
initial.commit09911bf2008-07-26 23:55:291349 StoreUnsentLogs();
1350 break;
1351
1352 case SENDING_CURRENT_LOGS:
1353 break;
1354
1355 default:
jar@chromium.orga063c102010-07-22 22:20:191356 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291357 break;
1358 }
petersont@google.comd01b8732008-10-16 02:18:071359
initial.commit09911bf2008-07-26 23:55:291360 DiscardPendingLog();
jar@google.com29be92552008-08-07 22:49:271361 // Since we sent a log, make sure our in-memory state is recorded to disk.
1362 PrefService* local_state = g_browser_process->local_state();
1363 DCHECK(local_state);
1364 if (local_state)
phajdan.jr@chromium.org6faa0e0d2009-04-28 06:50:361365 local_state->ScheduleSavePersistentPrefs();
petersont@google.com252873ef2008-08-04 21:59:451366
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161367 if (unsent_logs())
initial.commit09911bf2008-07-26 23:55:291368 DCHECK(state_ < SENDING_CURRENT_LOGS);
initial.commit09911bf2008-07-26 23:55:291369 }
petersont@google.com252873ef2008-08-04 21:59:451370
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161371 // Error 400 indicates a problem with the log, not with the server, so
1372 // don't consider that a sign that the server is in trouble.
1373 bool server_is_healthy = upload_succeeded || response_code == 400;
1374
1375 scheduler_->UploadFinished(server_is_healthy, unsent_logs());
rtenneti@chromium.orgd67d1052011-06-09 05:11:411376
1377 // Collect network stats if UMA upload succeeded.
1378 if (server_is_healthy && io_thread_)
1379 chrome_browser_net::CollectNetworkStats(network_stats_server_, io_thread_);
initial.commit09911bf2008-07-26 23:55:291380}
1381
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161382void MetricsService::LogBadResponseCode() {
pkasting@chromium.org666205032010-10-21 20:56:581383 VLOG(1) << "Verify your metrics logs are formatted correctly. Verify server "
1384 "is active at " << server_url_;
petersont@google.com252873ef2008-08-04 21:59:451385 if (!pending_log()) {
pkasting@chromium.org666205032010-10-21 20:56:581386 VLOG(1) << "METRICS: Recorder shutdown during log transmission.";
petersont@google.com252873ef2008-08-04 21:59:451387 } else {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161388 VLOG(1) << "METRICS: transmission retry being scheduled for "
pkasting@chromium.org666205032010-10-21 20:56:581389 << compressed_log_;
initial.commit09911bf2008-07-26 23:55:291390 }
initial.commit09911bf2008-07-26 23:55:291391}
1392
ananta@chromium.org432115822011-07-10 15:52:271393void MetricsService::LogWindowChange(int type,
initial.commit09911bf2008-07-26 23:55:291394 const NotificationSource& source,
1395 const NotificationDetails& details) {
brettw@google.com534e54b2008-08-13 15:40:091396 int controller_id = -1;
1397 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291398 MetricsLog::WindowEventType window_type;
1399
1400 // Note: since we stop all logging when a single OTR session is active, it is
1401 // possible that we start getting notifications about a window that we don't
1402 // know about.
brettw@google.com534e54b2008-08-13 15:40:091403 if (window_map_.find(window_or_tab) == window_map_.end()) {
1404 controller_id = next_window_id_++;
1405 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291406 } else {
brettw@google.com534e54b2008-08-13 15:40:091407 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291408 }
jar@chromium.org92745242009-06-12 16:52:211409 DCHECK_NE(controller_id, -1);
initial.commit09911bf2008-07-26 23:55:291410
ananta@chromium.org432115822011-07-10 15:52:271411 switch (type) {
1412 case content::NOTIFICATION_TAB_PARENTED:
1413 case chrome::NOTIFICATION_BROWSER_OPENED:
initial.commit09911bf2008-07-26 23:55:291414 window_type = MetricsLog::WINDOW_CREATE;
1415 break;
1416
ananta@chromium.org432115822011-07-10 15:52:271417 case content::NOTIFICATION_TAB_CLOSING:
1418 case chrome::NOTIFICATION_BROWSER_CLOSED:
brettw@google.com534e54b2008-08-13 15:40:091419 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291420 window_type = MetricsLog::WINDOW_DESTROY;
1421 break;
1422
1423 default:
jar@chromium.orga063c102010-07-22 22:20:191424 NOTREACHED();
paul@chromium.org68d74f02009-02-13 01:36:501425 return;
initial.commit09911bf2008-07-26 23:55:291426 }
1427
brettw@google.com534e54b2008-08-13 15:40:091428 // TODO(brettw) we should have some kind of ID for the parent.
1429 current_log_->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291430}
1431
ananta@chromium.org432115822011-07-10 15:52:271432void MetricsService::LogLoadComplete(int type,
initial.commit09911bf2008-07-26 23:55:291433 const NotificationSource& source,
1434 const NotificationDetails& details) {
1435 if (details == NotificationService::NoDetails())
1436 return;
1437
jar@google.com68475e602008-08-22 03:21:151438 // TODO(jar): There is a bug causing this to be called too many times, and
1439 // the log overflows. For now, we won't record these events.
dsh@google.com553dba62009-02-24 19:08:231440 UMA_HISTOGRAM_COUNTS("UMA.LogLoadComplete called", 1);
jar@google.com68475e602008-08-22 03:21:151441 return;
1442
initial.commit09911bf2008-07-26 23:55:291443 const Details<LoadNotificationDetails> load_details(details);
brettw@google.com534e54b2008-08-13 15:40:091444 int controller_id = window_map_[details.map_key()];
1445 current_log_->RecordLoadEvent(controller_id,
initial.commit09911bf2008-07-26 23:55:291446 load_details->url(),
1447 load_details->origin(),
1448 load_details->session_index(),
1449 load_details->load_time());
1450}
1451
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511452void MetricsService::IncrementPrefValue(const char* path) {
cpu@google.come73c01972008-08-13 00:18:241453 PrefService* pref = g_browser_process->local_state();
1454 DCHECK(pref);
1455 int value = pref->GetInteger(path);
1456 pref->SetInteger(path, value + 1);
1457}
1458
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511459void MetricsService::IncrementLongPrefsValue(const char* path) {
robertshield@google.com0bb1a622009-03-04 03:22:321460 PrefService* pref = g_browser_process->local_state();
1461 DCHECK(pref);
1462 int64 value = pref->GetInt64(path);
jar@chromium.orgb42c5e42010-06-03 20:43:251463 pref->SetInt64(path, value + 1);
robertshield@google.com0bb1a622009-03-04 03:22:321464}
1465
initial.commit09911bf2008-07-26 23:55:291466void MetricsService::LogLoadStarted() {
jar@chromium.orgdd8d12a2011-09-02 02:10:151467 HISTOGRAM_ENUMERATION("Chrome.UmaPageloadCounter", 1, 2);
cpu@google.come73c01972008-08-13 00:18:241468 IncrementPrefValue(prefs::kStabilityPageLoadCount);
robertshield@google.com0bb1a622009-03-04 03:22:321469 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
jar@google.com0b33f80b2008-12-17 21:34:361470 // We need to save the prefs, as page load count is a critical stat, and it
1471 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291472}
1473
initial.commit09911bf2008-07-26 23:55:291474void MetricsService::LogRendererCrash() {
cpu@google.come73c01972008-08-13 00:18:241475 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291476}
1477
asargent@chromium.org1f085622009-12-04 05:33:451478void MetricsService::LogExtensionRendererCrash() {
1479 IncrementPrefValue(prefs::kStabilityExtensionRendererCrashCount);
1480}
1481
initial.commit09911bf2008-07-26 23:55:291482void MetricsService::LogRendererHang() {
cpu@google.come73c01972008-08-13 00:18:241483 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291484}
1485
jar@chromium.orgc0c55e92011-09-10 18:47:301486void MetricsService::LogNeedForCleanShutdown() {
1487 PrefService* pref = g_browser_process->local_state();
1488 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
1489 // Redundant setting to be sure we call for a clean shutdown.
1490 clean_shutdown_status_ = NEED_TO_SHUTDOWN;
1491}
1492
1493bool MetricsService::UmaMetricsProperlyShutdown() {
1494 CHECK(clean_shutdown_status_ == CLEANLY_SHUTDOWN ||
1495 clean_shutdown_status_ == NEED_TO_SHUTDOWN);
1496 return clean_shutdown_status_ == CLEANLY_SHUTDOWN;
1497}
1498
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381499void MetricsService::LogCleanShutdown() {
jar@chromium.orgacd55b32011-09-05 17:35:311500 // Redundant hack to write pref ASAP.
1501 PrefService* pref = g_browser_process->local_state();
1502 pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
1503 pref->SavePersistentPrefs();
jar@chromium.orgc0c55e92011-09-10 18:47:301504 // Redundant setting to assure that we always reset this value at shutdown
1505 // (and that we don't use some alternate path, and not call LogCleanShutdown).
1506 clean_shutdown_status_ = CLEANLY_SHUTDOWN;
jar@chromium.orgacd55b32011-09-05 17:35:311507
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381508 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
1509}
1510
petkov@chromium.orgc1834a92011-01-21 18:21:031511#if defined(OS_CHROMEOS)
1512void MetricsService::LogChromeOSCrash(const std::string &crash_type) {
1513 if (crash_type == "user")
1514 IncrementPrefValue(prefs::kStabilityOtherUserCrashCount);
1515 else if (crash_type == "kernel")
1516 IncrementPrefValue(prefs::kStabilityKernelCrashCount);
1517 else if (crash_type == "uncleanshutdown")
1518 IncrementPrefValue(prefs::kStabilitySystemUncleanShutdownCount);
1519 else
1520 NOTREACHED() << "Unexpected Chrome OS crash type " << crash_type;
1521 // Wake up metrics logs sending if necessary now that new
1522 // log data is available.
1523 HandleIdleSinceLastTransmission(false);
1524}
1525#endif // OS_CHROMEOS
1526
jam@chromium.orga27a9382009-02-11 23:55:101527void MetricsService::LogChildProcessChange(
ananta@chromium.org432115822011-07-10 15:52:271528 int type,
jam@chromium.orga27a9382009-02-11 23:55:101529 const NotificationSource& source,
1530 const NotificationDetails& details) {
gregoryd@google.com0d84c5d2009-10-09 01:10:421531 Details<ChildProcessInfo> child_details(details);
evan@chromium.org68b9e72b2011-08-05 23:08:221532 const string16& child_name = child_details->name();
gregoryd@google.com0d84c5d2009-10-09 01:10:421533
jam@chromium.orga27a9382009-02-11 23:55:101534 if (child_process_stats_buffer_.find(child_name) ==
1535 child_process_stats_buffer_.end()) {
gregoryd@google.com0d84c5d2009-10-09 01:10:421536 child_process_stats_buffer_[child_name] =
1537 ChildProcessStats(child_details->type());
initial.commit09911bf2008-07-26 23:55:291538 }
1539
jam@chromium.orga27a9382009-02-11 23:55:101540 ChildProcessStats& stats = child_process_stats_buffer_[child_name];
ananta@chromium.org432115822011-07-10 15:52:271541 switch (type) {
1542 case content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED:
initial.commit09911bf2008-07-26 23:55:291543 stats.process_launches++;
1544 break;
1545
ananta@chromium.org432115822011-07-10 15:52:271546 case content::NOTIFICATION_CHILD_INSTANCE_CREATED:
initial.commit09911bf2008-07-26 23:55:291547 stats.instances++;
1548 break;
1549
ananta@chromium.org432115822011-07-10 15:52:271550 case content::NOTIFICATION_CHILD_PROCESS_CRASHED:
initial.commit09911bf2008-07-26 23:55:291551 stats.process_crashes++;
asargent@chromium.org1f085622009-12-04 05:33:451552 // Exclude plugin crashes from the count below because we report them via
1553 // a separate UMA metric.
1554 if (child_details->type() != ChildProcessInfo::PLUGIN_PROCESS) {
1555 IncrementPrefValue(prefs::kStabilityChildProcessCrashCount);
1556 }
initial.commit09911bf2008-07-26 23:55:291557 break;
1558
1559 default:
ananta@chromium.org432115822011-07-10 15:52:271560 NOTREACHED() << "Unexpected notification type " << type;
initial.commit09911bf2008-07-26 23:55:291561 return;
1562 }
1563}
1564
1565// Recursively counts the number of bookmarks and folders in node.
munjal@chromium.orgb3c33d462009-06-26 22:29:201566static void CountBookmarks(const BookmarkNode* node,
1567 int* bookmarks,
1568 int* folders) {
tfarina@chromium.org0890e60e2011-06-27 14:55:211569 if (node->is_url())
initial.commit09911bf2008-07-26 23:55:291570 (*bookmarks)++;
1571 else
1572 (*folders)++;
tfarina@chromium.org9c1a75a2011-03-10 02:38:121573 for (int i = 0; i < node->child_count(); ++i)
initial.commit09911bf2008-07-26 23:55:291574 CountBookmarks(node->GetChild(i), bookmarks, folders);
1575}
1576
munjal@chromium.orgb3c33d462009-06-26 22:29:201577void MetricsService::LogBookmarks(const BookmarkNode* node,
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511578 const char* num_bookmarks_key,
1579 const char* num_folders_key) {
initial.commit09911bf2008-07-26 23:55:291580 DCHECK(node);
1581 int num_bookmarks = 0;
1582 int num_folders = 0;
1583 CountBookmarks(node, &num_bookmarks, &num_folders);
1584 num_folders--; // Don't include the root folder in the count.
1585
1586 PrefService* pref = g_browser_process->local_state();
1587 DCHECK(pref);
1588 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1589 pref->SetInteger(num_folders_key, num_folders);
1590}
1591
sky@google.comd8e41ed2008-09-11 15:22:321592void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291593 DCHECK(model);
tfarina@chromium.org72bdcfe2011-07-22 17:21:581594 LogBookmarks(model->bookmark_bar_node(),
initial.commit09911bf2008-07-26 23:55:291595 prefs::kNumBookmarksOnBookmarkBar,
1596 prefs::kNumFoldersOnBookmarkBar);
1597 LogBookmarks(model->other_node(),
1598 prefs::kNumBookmarksInOtherBookmarkFolder,
1599 prefs::kNumFoldersInOtherBookmarkFolder);
1600 ScheduleNextStateSave();
1601}
1602
erg@google.com8e5c89a2011-06-07 18:13:331603void MetricsService::LogKeywords(const TemplateURLService* url_model) {
initial.commit09911bf2008-07-26 23:55:291604 DCHECK(url_model);
1605
1606 PrefService* pref = g_browser_process->local_state();
1607 DCHECK(pref);
1608 pref->SetInteger(prefs::kNumKeywords,
1609 static_cast<int>(url_model->GetTemplateURLs().size()));
1610 ScheduleNextStateSave();
1611}
1612
1613void MetricsService::RecordPluginChanges(PrefService* pref) {
battre@chromium.orgf8628c22011-04-05 12:10:181614 ListPrefUpdate update(pref, prefs::kStabilityPluginStats);
1615 ListValue* plugins = update.Get();
initial.commit09911bf2008-07-26 23:55:291616 DCHECK(plugins);
1617
1618 for (ListValue::iterator value_iter = plugins->begin();
1619 value_iter != plugins->end(); ++value_iter) {
1620 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
jar@chromium.orga063c102010-07-22 22:20:191621 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291622 continue;
1623 }
1624
1625 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511626 std::string plugin_name;
nsylvain@chromium.org8e50b602009-03-03 22:59:431627 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
nsylvain@chromium.org6470ee8f2009-03-03 20:46:401628 if (plugin_name.empty()) {
jar@chromium.orga063c102010-07-22 22:20:191629 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291630 continue;
1631 }
1632
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511633 // TODO(viettrungluu): remove conversions
evan@chromium.org68b9e72b2011-08-05 23:08:221634 string16 name16 = UTF8ToUTF16(plugin_name);
1635 if (child_process_stats_buffer_.find(name16) ==
1636 child_process_stats_buffer_.end()) {
initial.commit09911bf2008-07-26 23:55:291637 continue;
evan@chromium.org68b9e72b2011-08-05 23:08:221638 }
initial.commit09911bf2008-07-26 23:55:291639
evan@chromium.org68b9e72b2011-08-05 23:08:221640 ChildProcessStats stats = child_process_stats_buffer_[name16];
initial.commit09911bf2008-07-26 23:55:291641 if (stats.process_launches) {
1642 int launches = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431643 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291644 launches += stats.process_launches;
nsylvain@chromium.org8e50b602009-03-03 22:59:431645 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291646 }
1647 if (stats.process_crashes) {
1648 int crashes = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431649 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291650 crashes += stats.process_crashes;
nsylvain@chromium.org8e50b602009-03-03 22:59:431651 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291652 }
1653 if (stats.instances) {
1654 int instances = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431655 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291656 instances += stats.instances;
nsylvain@chromium.org8e50b602009-03-03 22:59:431657 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291658 }
1659
evan@chromium.org68b9e72b2011-08-05 23:08:221660 child_process_stats_buffer_.erase(name16);
initial.commit09911bf2008-07-26 23:55:291661 }
1662
1663 // Now go through and add dictionaries for plugins that didn't already have
1664 // reports in Local State.
evan@chromium.org68b9e72b2011-08-05 23:08:221665 for (std::map<string16, ChildProcessStats>::iterator cache_iter =
jam@chromium.orga27a9382009-02-11 23:55:101666 child_process_stats_buffer_.begin();
1667 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
jam@chromium.orga27a9382009-02-11 23:55:101668 ChildProcessStats stats = cache_iter->second;
gregoryd@google.com0d84c5d2009-10-09 01:10:421669
1670 // Insert only plugins information into the plugins list.
1671 if (ChildProcessInfo::PLUGIN_PROCESS != stats.process_type)
1672 continue;
1673
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511674 // TODO(viettrungluu): remove conversion
evan@chromium.org68b9e72b2011-08-05 23:08:221675 std::string plugin_name = UTF16ToUTF8(cache_iter->first);
gregoryd@google.com0d84c5d2009-10-09 01:10:421676
initial.commit09911bf2008-07-26 23:55:291677 DictionaryValue* plugin_dict = new DictionaryValue;
1678
nsylvain@chromium.org8e50b602009-03-03 22:59:431679 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
1680 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:291681 stats.process_launches);
nsylvain@chromium.org8e50b602009-03-03 22:59:431682 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:291683 stats.process_crashes);
nsylvain@chromium.org8e50b602009-03-03 22:59:431684 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:291685 stats.instances);
1686 plugins->Append(plugin_dict);
1687 }
jam@chromium.orga27a9382009-02-11 23:55:101688 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291689}
1690
ananta@chromium.org432115822011-07-10 15:52:271691bool MetricsService::CanLogNotification(int type,
initial.commit09911bf2008-07-26 23:55:291692 const NotificationSource& source,
1693 const NotificationDetails& details) {
akalin@chromium.org2c910b72011-03-08 21:16:321694 // We simply don't log anything to UMA if there is a single incognito
initial.commit09911bf2008-07-26 23:55:291695 // session visible. The problem is that we always notify using the orginal
1696 // profile in order to simplify notification processing.
1697 return !BrowserList::IsOffTheRecordSessionActive();
1698}
1699
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511700void MetricsService::RecordBooleanPrefValue(const char* path, bool value) {
initial.commit09911bf2008-07-26 23:55:291701 DCHECK(IsSingleThreaded());
1702
1703 PrefService* pref = g_browser_process->local_state();
1704 DCHECK(pref);
1705
1706 pref->SetBoolean(path, value);
1707 RecordCurrentState(pref);
1708}
1709
1710void MetricsService::RecordCurrentState(PrefService* pref) {
robertshield@google.com0bb1a622009-03-04 03:22:321711 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291712
1713 RecordPluginChanges(pref);
1714}
1715
initial.commit09911bf2008-07-26 23:55:291716static bool IsSingleThreaded() {
brettw@chromium.orgce072a72010-12-31 20:02:161717 static base::PlatformThreadId thread_id = 0;
initial.commit09911bf2008-07-26 23:55:291718 if (!thread_id)
brettw@chromium.orgce072a72010-12-31 20:02:161719 thread_id = base::PlatformThread::CurrentId();
1720 return base::PlatformThread::CurrentId() == thread_id;
initial.commit09911bf2008-07-26 23:55:291721}
rvargas@google.com5ccaa412009-11-13 22:00:161722
1723#if defined(OS_CHROMEOS)
sky@chromium.org29cf16772010-04-21 15:13:471724void MetricsService::StartExternalMetrics() {
rvargas@google.com5ccaa412009-11-13 22:00:161725 external_metrics_ = new chromeos::ExternalMetrics;
sky@chromium.org29cf16772010-04-21 15:13:471726 external_metrics_->Start();
rvargas@google.com5ccaa412009-11-13 22:00:161727}
1728#endif
sreeram@chromium.org3819f2ee2011-08-21 09:44:381729
1730// static
1731bool MetricsServiceHelper::IsMetricsReportingEnabled() {
1732 bool result = false;
1733 const PrefService* local_state = g_browser_process->local_state();
1734 if (local_state) {
1735 const PrefService::Preference* uma_pref =
1736 local_state->FindPreference(prefs::kMetricsReportingEnabled);
1737 if (uma_pref) {
1738 bool success = uma_pref->GetValue()->GetAsBoolean(&result);
1739 DCHECK(success);
1740 }
1741 }
1742 return result;
1743}