blob: 28ab192e123365c8cffd24130882a93ad4646f12 [file] [log] [blame]
isherman@chromium.org2e4cd1a2012-01-12 08:51:031// Copyright (c) 2012 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
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:1052// is closed (including snapshotting histograms), and persisted, for
initial.commit09911bf2008-07-26 23:55:2953// potential transmission during a future run of the product.
54//
55// There are two slightly abnormal shutdown conditions. There is a
56// "disconnected scenario," and a "really fast startup and shutdown" scenario.
57// In the "never connected" situation, the user has (during the running of the
58// process) never established an internet connection. As a result, attempts to
59// transmit the initial log have failed, and a lot(?) of data has accumulated in
60// the ongoing log (which didn't yet get closed, because there was never even a
61// contemplation of sending it). There is also a kindred "lost connection"
62// situation, where a loss of connection prevented an ongoing log from being
63// transmitted, and a (still open) log was stuck accumulating a lot(?) of data,
64// while the earlier log retried its transmission. In both of these
65// disconnected situations, two logs need to be, and are, persistently stored
66// for future transmission.
67//
68// The other unusual shutdown condition, termed "really fast startup and
69// shutdown," involves the deliberate user termination of the process before
70// the initial log is even formed or transmitted. In that situation, no logging
71// is done, but the historical crash statistics remain (unlogged) for inclusion
72// in a future run's initial log. (i.e., we don't lose crash stats).
73//
74// With the above overview, we can now describe the state machine's various
75// stats, based on the State enum specified in the state_ member. Those states
76// are:
77//
78// INITIALIZED, // Constructor was called.
zelidrag@chromium.org85ed9d42010-06-08 22:37:4479// INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to complete.
80// INIT_TASK_DONE, // Waiting for timer to send initial log.
initial.commit09911bf2008-07-26 23:55:2981// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
initial.commit09911bf2008-07-26 23:55:2982// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
83// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
84//
85// In more detail, we have:
86//
87// INITIALIZED, // Constructor was called.
88// The MS has been constructed, but has taken no actions to compose the
89// initial log.
90//
zelidrag@chromium.org85ed9d42010-06-08 22:37:4491// INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to complete.
initial.commit09911bf2008-07-26 23:55:2992// Typically about 30 seconds after startup, a task is sent to a second thread
zelidrag@chromium.org85ed9d42010-06-08 22:37:4493// (the file thread) to perform deferred (lower priority and slower)
94// initialization steps such as getting the list of plugins. That task will
95// (when complete) make an async callback (via a Task) to indicate the
96// completion.
initial.commit09911bf2008-07-26 23:55:2997//
zelidrag@chromium.org85ed9d42010-06-08 22:37:4498// INIT_TASK_DONE, // Waiting for timer to send initial log.
initial.commit09911bf2008-07-26 23:55:2999// The callback has arrived, and it is now possible for an initial log to be
100// created. This callback typically arrives back less than one second after
zelidrag@chromium.org85ed9d42010-06-08 22:37:44101// the deferred init task is dispatched.
initial.commit09911bf2008-07-26 23:55:29102//
103// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
104// This state is entered only after an initial log has been composed, and
105// prepared for transmission. It is also the case that any previously unsent
106// logs have been loaded into instance variables for possible transmission.
107//
initial.commit09911bf2008-07-26 23:55:29108// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10109// This state indicates that the initial log for this session has been
110// successfully sent and it is now time to send any logs that were
111// saved from previous sessions. All such logs will be transmitted before
112// exiting this state, and proceeding with ongoing logs from the current session
113// (see next state).
initial.commit09911bf2008-07-26 23:55:29114//
115// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
jar@google.com0b33f80b2008-12-17 21:34:36116// Current logs are being accumulated. Typically every 20 minutes a log is
initial.commit09911bf2008-07-26 23:55:29117// closed and finalized for transmission, at the same time as a new log is
118// started.
119//
120// The progression through the above states is simple, and sequential, in the
121// most common use cases. States proceed from INITIAL to SENDING_CURRENT_LOGS,
122// and remain in the latter until shutdown.
123//
124// The one unusual case is when the user asks that we stop logging. When that
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10125// happens, any staged (transmission in progress) log is persisted, and any log
126// log that is currently accumulating is also finalized and persisted. We then
127// regress back to the SEND_OLD_LOGS state in case the user enables log
128// recording again during this session. This way anything we have persisted
129// will be sent automatically if/when we progress back to SENDING_CURRENT_LOG
130// state.
initial.commit09911bf2008-07-26 23:55:29131//
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10132// Also note that whenever we successfully send an old log, we mirror the list
133// of logs into the PrefService. This ensures that IF we crash, we won't start
134// up and retransmit our old logs again.
initial.commit09911bf2008-07-26 23:55:29135//
136// Due to race conditions, it is always possible that a log file could be sent
137// twice. For example, if a log file is sent, but not yet acknowledged by
138// the external server, and the user shuts down, then a copy of the log may be
139// saved for re-transmission. These duplicates could be filtered out server
jar@chromium.org281d2882009-01-20 20:32:42140// side, but are not expected to be a significant problem.
initial.commit09911bf2008-07-26 23:55:29141//
142//
143//------------------------------------------------------------------------------
144
maruel@chromium.org40bcc302009-03-02 20:50:39145#include "chrome/browser/metrics/metrics_service.h"
146
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16147#include "base/bind.h"
148#include "base/callback.h"
erg@google.com5d91c9e2010-07-28 17:25:28149#include "base/command_line.h"
ziadh@chromium.org46f89e142010-07-19 08:00:42150#include "base/md5.h"
brettw@chromium.org835d7c82010-10-14 04:38:38151#include "base/metrics/histogram.h"
brettw@chromium.org528c56d2010-07-30 19:28:44152#include "base/string_number_conversions.h"
brettw@chromium.orgce072a72010-12-31 20:02:16153#include "base/threading/platform_thread.h"
tfarina@chromium.orgb3841c502011-03-09 01:21:31154#include "base/threading/thread.h"
viettrungluu@chromium.org440b37b22010-08-30 05:31:40155#include "base/utf_string_conversions.h"
erg@google.com679082052010-07-21 21:30:13156#include "base/values.h"
sky@google.comd8e41ed2008-09-11 15:22:32157#include "chrome/browser/bookmarks/bookmark_model.h"
initial.commit09911bf2008-07-26 23:55:29158#include "chrome/browser/browser_process.h"
aa@chromium.org6f371442011-11-09 06:45:46159#include "chrome/browser/extensions/extension_service.h"
160#include "chrome/browser/extensions/process_map.h"
sail@chromium.org84c988a2011-04-19 17:56:33161#include "chrome/browser/memory_details.h"
phajdan.jr@chromium.org7c927b62010-02-24 09:54:13162#include "chrome/browser/metrics/histogram_synchronizer.h"
erg@google.com679082052010-07-21 21:30:13163#include "chrome/browser/metrics/metrics_log.h"
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10164#include "chrome/browser/metrics/metrics_log_serializer.h"
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16165#include "chrome/browser/metrics/metrics_reporting_scheduler.h"
rtenneti@chromium.orgd67d1052011-06-09 05:11:41166#include "chrome/browser/net/network_stats.h"
evan@chromium.org37858e52010-08-26 00:22:02167#include "chrome/browser/prefs/pref_service.h"
battre@chromium.orgf8628c22011-04-05 12:10:18168#include "chrome/browser/prefs/scoped_user_pref_update.h"
ben@chromium.org8ecad5e2010-12-02 21:18:33169#include "chrome/browser/profiles/profile.h"
erg@google.com8e5c89a2011-06-07 18:13:33170#include "chrome/browser/search_engines/template_url_service.h"
tfarina@chromium.org71b73f02011-04-06 15:57:29171#include "chrome/browser/ui/browser_list.h"
kuchhal@chromium.org157d5472009-11-05 22:31:03172#include "chrome/common/child_process_logging.h"
ananta@chromium.org432115822011-07-10 15:52:27173#include "chrome/common/chrome_notification_types.h"
jar@chromium.org92745242009-06-12 16:52:21174#include "chrome/common/chrome_switches.h"
sergeyu@chromium.org3eb0d8f72010-12-15 23:38:25175#include "chrome/common/guid.h"
isherman@chromium.org2e4cd1a2012-01-12 08:51:03176#include "chrome/common/metrics/metrics_log_manager.h"
initial.commit09911bf2008-07-26 23:55:29177#include "chrome/common/pref_names.h"
jam@chromium.orge09ba552009-02-05 03:26:29178#include "chrome/common/render_messages.h"
avi@chromium.org35e251d2011-05-24 21:01:04179#include "content/browser/load_notification_details.h"
jam@chromium.org4967f792012-01-20 22:14:40180#include "content/public/browser/child_process_data.h"
jam@chromium.orgad50def52011-10-19 23:17:07181#include "content/public/browser/notification_service.h"
jam@chromium.org3a5180ae2011-12-21 02:39:38182#include "content/public/browser/plugin_service.h"
ananta@chromium.orgf3b1a082011-11-18 00:34:30183#include "content/public/browser/render_process_host.h"
jam@chromium.org36aea2702011-10-26 01:12:22184#include "content/public/common/url_fetcher.h"
isherman@chromium.orgfe58acc22012-02-29 01:29:58185#include "net/base/load_flags.h"
cpu@chromium.org91d9f3d2011-08-14 05:24:44186#include "webkit/plugins/webplugininfo.h"
initial.commit09911bf2008-07-26 23:55:29187
phajdan.jr@chromium.orge06131d2010-02-10 18:40:33188// TODO(port): port browser_distribution.h.
189#if !defined(OS_POSIX)
kuchhal@chromium.org79bf0b72009-04-27 21:30:55190#include "chrome/installer/util/browser_distribution.h"
paul@chromium.orgdc6f4962009-02-13 01:25:50191#endif
192
rvargas@google.com5ccaa412009-11-13 22:00:16193#if defined(OS_CHROMEOS)
stevenjb@chromium.orgdb342d52010-08-09 21:19:37194#include "chrome/browser/chromeos/cros/cros_library.h"
rvargas@google.com5ccaa412009-11-13 22:00:16195#include "chrome/browser/chromeos/external_metrics.h"
satorux@chromium.orgd43970a72011-07-10 06:24:52196#include "chrome/browser/chromeos/system/statistics_provider.h"
rvargas@google.com5ccaa412009-11-13 22:00:16197#endif
198
dsh@google.come1acf6f2008-10-27 20:43:33199using base::Time;
joi@chromium.org631bb742011-11-02 11:29:39200using content::BrowserThread;
jam@chromium.org4967f792012-01-20 22:14:40201using content::ChildProcessData;
jam@chromium.org3a5180ae2011-12-21 02:39:38202using content::PluginService;
dsh@google.come1acf6f2008-10-27 20:43:33203
isherman@chromium.orgfe58acc22012-02-29 01:29:58204namespace {
isherman@chromium.orgb2a4812d2012-02-28 05:31:31205
isherman@chromium.orgfe58acc22012-02-29 01:29:58206// Check to see that we're being called on only one thread.
207bool IsSingleThreaded() {
208 static base::PlatformThreadId thread_id = 0;
209 if (!thread_id)
210 thread_id = base::PlatformThread::CurrentId();
211 return base::PlatformThread::CurrentId() == thread_id;
212}
213
214const char kMetricsTypeXml[] = "application/vnd.mozilla.metrics.bz2";
215const char kMetricsTypeProto[] = "application/vnd.chrome.uma";
216
217const char kServerUrlXml[] =
218 "https://clients4.google.com/firefox/metrics/collect";
219const char kServerUrlProto[] = "https://clients4.google.com/uma/v2";
initial.commit09911bf2008-07-26 23:55:29220
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16221// The delay, in seconds, after starting recording before doing expensive
222// initialization work.
isherman@chromium.orgfe58acc22012-02-29 01:29:58223const int kInitializationDelaySeconds = 30;
petersont@google.com252873ef2008-08-04 21:59:45224
jar@chromium.orgc9a3ef82009-05-28 22:02:46225// This specifies the amount of time to wait for all renderers to send their
226// data.
isherman@chromium.orgfe58acc22012-02-29 01:29:58227const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
jar@chromium.orgc9a3ef82009-05-28 22:02:46228
stuartmorgan@chromium.org54702c92011-04-15 15:06:43229// The maximum number of events in a log uploaded to the UMA server.
isherman@chromium.orgfe58acc22012-02-29 01:29:58230const int kEventLimit = 2400;
jar@google.com68475e602008-08-22 03:21:15231
232// If an upload fails, and the transmission was over this byte count, then we
233// will discard the log, and not try to retransmit it. We also don't persist
234// the log to the prefs for transmission during the next chrome session if this
235// limit is exceeded.
isherman@chromium.orgfe58acc22012-02-29 01:29:58236const size_t kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29237
tedvessenes@gmail.comfc4252a72012-01-12 21:58:47238// Interval, in minutes, between state saves.
isherman@chromium.orgfe58acc22012-02-29 01:29:58239const int kSaveStateIntervalMinutes = 5;
240
241}
initial.commit09911bf2008-07-26 23:55:29242
jar@chromium.orgc0c55e92011-09-10 18:47:30243// static
244MetricsService::ShutdownCleanliness MetricsService::clean_shutdown_status_ =
245 MetricsService::CLEANLY_SHUTDOWN;
246
erg@google.com679082052010-07-21 21:30:13247// This is used to quickly log stats from child process related notifications in
248// MetricsService::child_stats_buffer_. The buffer's contents are transferred
249// out when Local State is periodically saved. The information is then
250// reported to the UMA server on next launch.
251struct MetricsService::ChildProcessStats {
252 public:
jam@chromium.orgbd5d6cf2011-12-01 00:39:12253 explicit ChildProcessStats(content::ProcessType type)
erg@google.com679082052010-07-21 21:30:13254 : process_launches(0),
255 process_crashes(0),
256 instances(0),
257 process_type(type) {}
258
259 // This constructor is only used by the map to return some default value for
260 // an index for which no value has been assigned.
261 ChildProcessStats()
262 : process_launches(0),
pkasting@chromium.orgd88bf0a2011-08-30 23:55:57263 process_crashes(0),
264 instances(0),
jam@chromium.orgbd5d6cf2011-12-01 00:39:12265 process_type(content::PROCESS_TYPE_UNKNOWN) {}
erg@google.com679082052010-07-21 21:30:13266
267 // The number of times that the given child process has been launched
268 int process_launches;
269
270 // The number of times that the given child process has crashed
271 int process_crashes;
272
273 // The number of instances of this child process that have been created.
274 // An instance is a DOM object rendered by this child process during a page
275 // load.
276 int instances;
277
jam@chromium.orgbd5d6cf2011-12-01 00:39:12278 content::ProcessType process_type;
erg@google.com679082052010-07-21 21:30:13279};
initial.commit09911bf2008-07-26 23:55:29280
sail@chromium.org84c988a2011-04-19 17:56:33281// Handles asynchronous fetching of memory details.
282// Will run the provided task after finished.
283class MetricsMemoryDetails : public MemoryDetails {
284 public:
dcheng@chromium.org2226c222011-11-22 00:08:40285 explicit MetricsMemoryDetails(const base::Closure& callback)
286 : callback_(callback) {}
sail@chromium.org84c988a2011-04-19 17:56:33287
288 virtual void OnDetailsAvailable() {
dcheng@chromium.org2226c222011-11-22 00:08:40289 MessageLoop::current()->PostTask(FROM_HERE, callback_);
sail@chromium.org84c988a2011-04-19 17:56:33290 }
291
292 private:
293 ~MetricsMemoryDetails() {}
294
dcheng@chromium.org2226c222011-11-22 00:08:40295 base::Closure callback_;
sail@chromium.org84c988a2011-04-19 17:56:33296 DISALLOW_COPY_AND_ASSIGN(MetricsMemoryDetails);
297};
298
initial.commit09911bf2008-07-26 23:55:29299// static
300void MetricsService::RegisterPrefs(PrefService* local_state) {
301 DCHECK(IsSingleThreaded());
estade@chromium.org20ce516d2010-06-18 02:20:04302 local_state->RegisterStringPref(prefs::kMetricsClientID, "");
robertshield@google.com0bb1a622009-03-04 03:22:32303 local_state->RegisterInt64Pref(prefs::kMetricsClientIDTimestamp, 0);
304 local_state->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
305 local_state->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
estade@chromium.org20ce516d2010-06-18 02:20:04306 local_state->RegisterStringPref(prefs::kStabilityStatsVersion, "");
jar@chromium.org225c50842010-01-19 21:19:13307 local_state->RegisterInt64Pref(prefs::kStabilityStatsBuildTime, 0);
initial.commit09911bf2008-07-26 23:55:29308 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
309 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
310 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
311 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
312 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
313 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
314 0);
315 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
initial.commit09911bf2008-07-26 23:55:29316 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
asargent@chromium.org1f085622009-12-04 05:33:45317 local_state->RegisterIntegerPref(prefs::kStabilityExtensionRendererCrashCount,
318 0);
initial.commit09911bf2008-07-26 23:55:29319 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
asargent@chromium.org1f085622009-12-04 05:33:45320 local_state->RegisterIntegerPref(prefs::kStabilityChildProcessCrashCount, 0);
cpu@google.come73c01972008-08-13 00:18:24321 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
322 0);
323 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
324 0);
325 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
326 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
petkov@chromium.orgc1834a92011-01-21 18:21:03327#if defined(OS_CHROMEOS)
328 local_state->RegisterIntegerPref(prefs::kStabilityOtherUserCrashCount, 0);
329 local_state->RegisterIntegerPref(prefs::kStabilityKernelCrashCount, 0);
330 local_state->RegisterIntegerPref(prefs::kStabilitySystemUncleanShutdownCount,
331 0);
332#endif // OS_CHROMEOS
cpu@google.come73c01972008-08-13 00:18:24333
initial.commit09911bf2008-07-26 23:55:29334 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
335 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
336 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
337 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
338 0);
339 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
340 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
isherman@chromium.orgfe58acc22012-02-29 01:29:58341 local_state->RegisterListPref(prefs::kMetricsInitialLogsXml);
342 local_state->RegisterListPref(prefs::kMetricsOngoingLogsXml);
343 local_state->RegisterListPref(prefs::kMetricsInitialLogsProto);
344 local_state->RegisterListPref(prefs::kMetricsOngoingLogsProto);
robertshield@google.com0bb1a622009-03-04 03:22:32345
346 local_state->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
347 local_state->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
robertshield@google.com6b5f21d2009-04-13 17:01:35348 local_state->RegisterInt64Pref(prefs::kUninstallMetricsInstallDate, 0);
robertshield@google.com0bb1a622009-03-04 03:22:32349 local_state->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
350 local_state->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
351 local_state->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
initial.commit09911bf2008-07-26 23:55:29352}
353
jar@chromium.org541f77922009-02-23 21:14:38354// static
355void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
356 local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
jar@chromium.orgc9abf242009-07-18 06:00:38357 local_state->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
jar@chromium.org541f77922009-02-23 21:14:38358
359 local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
360 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
361 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
362 local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
363 local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
364
365 local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
366 local_state->SetInteger(prefs::kStabilityCrashCount, 0);
367
368 local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
369 local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
370 local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
371
jar@chromium.org9165f742010-03-10 22:55:01372 local_state->SetInt64(prefs::kStabilityLaunchTimeSec, 0);
373 local_state->SetInt64(prefs::kStabilityLastTimestampSec, 0);
jar@chromium.org541f77922009-02-23 21:14:38374
375 local_state->ClearPref(prefs::kStabilityPluginStats);
jar@chromium.orgae155cb92009-06-19 06:10:37376
isherman@chromium.orgfe58acc22012-02-29 01:29:58377 local_state->ClearPref(prefs::kMetricsInitialLogsXml);
378 local_state->ClearPref(prefs::kMetricsOngoingLogsXml);
379 local_state->ClearPref(prefs::kMetricsInitialLogsProto);
380 local_state->ClearPref(prefs::kMetricsOngoingLogsProto);
jar@chromium.org541f77922009-02-23 21:14:38381}
382
initial.commit09911bf2008-07-26 23:55:29383MetricsService::MetricsService()
petersont@google.comd01b8732008-10-16 02:18:07384 : recording_active_(false),
385 reporting_active_(false),
petersont@google.comd01b8732008-10-16 02:18:07386 state_(INITIALIZED),
rtenneti@chromium.orgd67d1052011-06-09 05:11:41387 io_thread_(NULL),
petersont@google.comd01b8732008-10-16 02:18:07388 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29389 next_window_id_(0),
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40390 ALLOW_THIS_IN_INITIALIZER_LIST(self_ptr_factory_(this)),
maruel@chromium.org40bcc302009-03-02 20:50:39391 ALLOW_THIS_IN_INITIALIZER_LIST(state_saver_factory_(this)),
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16392 waiting_for_asynchronus_reporting_step_(false) {
initial.commit09911bf2008-07-26 23:55:29393 DCHECK(IsSingleThreaded());
394 InitializeMetricsState();
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16395
396 base::Closure callback = base::Bind(&MetricsService::StartScheduledUpload,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40397 self_ptr_factory_.GetWeakPtr());
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16398 scheduler_.reset(new MetricsReportingScheduler(callback));
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10399 log_manager_.set_log_serializer(new MetricsLogSerializer());
400 log_manager_.set_max_ongoing_log_store_size(kUploadLogAvoidRetransmitSize);
initial.commit09911bf2008-07-26 23:55:29401}
402
403MetricsService::~MetricsService() {
404 SetRecording(false);
405}
406
petersont@google.comd01b8732008-10-16 02:18:07407void MetricsService::Start() {
stuartmorgan@chromium.orgb1c8dc02011-04-13 18:32:04408 HandleIdleSinceLastTransmission(false);
petersont@google.comd01b8732008-10-16 02:18:07409 SetRecording(true);
410 SetReporting(true);
411}
412
413void MetricsService::StartRecordingOnly() {
414 SetRecording(true);
415 SetReporting(false);
416}
417
418void MetricsService::Stop() {
stuartmorgan@chromium.orgb1c8dc02011-04-13 18:32:04419 HandleIdleSinceLastTransmission(false);
petersont@google.comd01b8732008-10-16 02:18:07420 SetReporting(false);
421 SetRecording(false);
422}
423
joi@chromium.orgedafd4c2011-05-10 17:18:53424std::string MetricsService::GetClientId() {
425 return client_id_;
426}
427
jam@chromium.org5cbeeef72012-02-08 02:05:18428void MetricsService::ForceClientIdCreation() {
429 if (!client_id_.empty())
430 return;
431 PrefService* pref = g_browser_process->local_state();
432 client_id_ = pref->GetString(prefs::kMetricsClientID);
433 if (!client_id_.empty())
434 return;
435
436 client_id_ = GenerateClientID();
437 pref->SetString(prefs::kMetricsClientID, client_id_);
438
439 // Might as well make a note of how long this ID has existed
440 pref->SetString(prefs::kMetricsClientIDTimestamp,
441 base::Int64ToString(Time::Now().ToTimeT()));
442}
443
initial.commit09911bf2008-07-26 23:55:29444void MetricsService::SetRecording(bool enabled) {
445 DCHECK(IsSingleThreaded());
446
petersont@google.comd01b8732008-10-16 02:18:07447 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29448 return;
449
450 if (enabled) {
jam@chromium.org5cbeeef72012-02-08 02:05:18451 ForceClientIdCreation();
kuchhal@chromium.org157d5472009-11-05 22:31:03452 child_process_logging::SetClientId(client_id_);
initial.commit09911bf2008-07-26 23:55:29453 StartRecording();
pkasting@chromium.org005ef3e2009-05-22 20:55:46454
stuartmorgan@chromium.org3ffd3ae2011-03-17 22:17:52455 SetUpNotifications(&registrar_, this);
initial.commit09911bf2008-07-26 23:55:29456 } else {
pkasting@chromium.org005ef3e2009-05-22 20:55:46457 registrar_.RemoveAll();
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10458 PushPendingLogsToPersistentStorage();
459 DCHECK(!log_manager_.has_staged_log());
460 if (state_ > INITIAL_LOG_READY && log_manager_.has_unsent_logs())
461 state_ = SENDING_OLD_LOGS;
initial.commit09911bf2008-07-26 23:55:29462 }
petersont@google.comd01b8732008-10-16 02:18:07463 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29464}
465
petersont@google.comd01b8732008-10-16 02:18:07466bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29467 DCHECK(IsSingleThreaded());
petersont@google.comd01b8732008-10-16 02:18:07468 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29469}
470
petersont@google.comd01b8732008-10-16 02:18:07471void MetricsService::SetReporting(bool enable) {
472 if (reporting_active_ != enable) {
473 reporting_active_ = enable;
474 if (reporting_active_)
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16475 StartSchedulerIfNecessary();
initial.commit09911bf2008-07-26 23:55:29476 }
petersont@google.comd01b8732008-10-16 02:18:07477}
478
479bool MetricsService::reporting_active() const {
480 DCHECK(IsSingleThreaded());
481 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29482}
483
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15484// static
jam@chromium.org6c2381d2011-10-19 02:52:53485void MetricsService::SetUpNotifications(
486 content::NotificationRegistrar* registrar,
487 content::NotificationObserver* observer) {
488 registrar->Add(observer, chrome::NOTIFICATION_BROWSER_OPENED,
jam@chromium.orgad50def52011-10-19 23:17:07489 content::NotificationService::AllBrowserContextsAndSources());
jam@chromium.org6c2381d2011-10-19 02:52:53490 registrar->Add(observer, chrome::NOTIFICATION_BROWSER_CLOSED,
jam@chromium.orgad50def52011-10-19 23:17:07491 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53492 registrar->Add(observer, content::NOTIFICATION_USER_ACTION,
jam@chromium.orgad50def52011-10-19 23:17:07493 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53494 registrar->Add(observer, content::NOTIFICATION_TAB_PARENTED,
jam@chromium.orgad50def52011-10-19 23:17:07495 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53496 registrar->Add(observer, content::NOTIFICATION_TAB_CLOSING,
jam@chromium.orgad50def52011-10-19 23:17:07497 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53498 registrar->Add(observer, content::NOTIFICATION_LOAD_START,
jam@chromium.orgad50def52011-10-19 23:17:07499 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53500 registrar->Add(observer, content::NOTIFICATION_LOAD_STOP,
jam@chromium.orgad50def52011-10-19 23:17:07501 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53502 registrar->Add(observer, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
jam@chromium.orgad50def52011-10-19 23:17:07503 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53504 registrar->Add(observer, content::NOTIFICATION_RENDERER_PROCESS_HANG,
jam@chromium.orgad50def52011-10-19 23:17:07505 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53506 registrar->Add(observer, content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED,
jam@chromium.orgad50def52011-10-19 23:17:07507 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53508 registrar->Add(observer, content::NOTIFICATION_CHILD_INSTANCE_CREATED,
jam@chromium.orgad50def52011-10-19 23:17:07509 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53510 registrar->Add(observer, content::NOTIFICATION_CHILD_PROCESS_CRASHED,
jam@chromium.orgad50def52011-10-19 23:17:07511 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53512 registrar->Add(observer, chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED,
jam@chromium.orgad50def52011-10-19 23:17:07513 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53514 registrar->Add(observer, chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
jam@chromium.orgad50def52011-10-19 23:17:07515 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53516 registrar->Add(observer, chrome::NOTIFICATION_BOOKMARK_MODEL_LOADED,
jam@chromium.orgad50def52011-10-19 23:17:07517 content::NotificationService::AllBrowserContextsAndSources());
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15518}
519
ananta@chromium.org432115822011-07-10 15:52:27520void MetricsService::Observe(int type,
jam@chromium.org6c2381d2011-10-19 02:52:53521 const content::NotificationSource& source,
522 const content::NotificationDetails& details) {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10523 DCHECK(log_manager_.current_log());
initial.commit09911bf2008-07-26 23:55:29524 DCHECK(IsSingleThreaded());
525
526 if (!CanLogNotification(type, source, details))
527 return;
528
ananta@chromium.org432115822011-07-10 15:52:27529 switch (type) {
530 case content::NOTIFICATION_USER_ACTION:
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10531 log_manager_.current_log()->RecordUserAction(
jam@chromium.org6c2381d2011-10-19 02:52:53532 *content::Details<const char*>(details).ptr());
initial.commit09911bf2008-07-26 23:55:29533 break;
534
ananta@chromium.org432115822011-07-10 15:52:27535 case chrome::NOTIFICATION_BROWSER_OPENED:
536 case chrome::NOTIFICATION_BROWSER_CLOSED:
initial.commit09911bf2008-07-26 23:55:29537 LogWindowChange(type, source, details);
538 break;
539
ananta@chromium.org432115822011-07-10 15:52:27540 case content::NOTIFICATION_TAB_PARENTED:
541 case content::NOTIFICATION_TAB_CLOSING:
initial.commit09911bf2008-07-26 23:55:29542 LogWindowChange(type, source, details);
543 break;
544
ananta@chromium.org432115822011-07-10 15:52:27545 case content::NOTIFICATION_LOAD_STOP:
initial.commit09911bf2008-07-26 23:55:29546 LogLoadComplete(type, source, details);
547 break;
548
ananta@chromium.org432115822011-07-10 15:52:27549 case content::NOTIFICATION_LOAD_START:
initial.commit09911bf2008-07-26 23:55:29550 LogLoadStarted();
551 break;
552
ananta@chromium.org432115822011-07-10 15:52:27553 case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: {
ananta@chromium.orgf3b1a082011-11-18 00:34:30554 content::RenderProcessHost::RendererClosedDetails* process_details =
555 content::Details<
556 content::RenderProcessHost::RendererClosedDetails>(
557 details).ptr();
558 content::RenderProcessHost* host =
559 content::Source<content::RenderProcessHost>(source).ptr();
jochen@chromium.org718eab62011-10-05 21:16:52560 LogRendererCrash(
561 host, process_details->status, process_details->was_alive);
asargent@chromium.org1f085622009-12-04 05:33:45562 }
initial.commit09911bf2008-07-26 23:55:29563 break;
564
ananta@chromium.org432115822011-07-10 15:52:27565 case content::NOTIFICATION_RENDERER_PROCESS_HANG:
initial.commit09911bf2008-07-26 23:55:29566 LogRendererHang();
567 break;
568
ananta@chromium.org432115822011-07-10 15:52:27569 case content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED:
570 case content::NOTIFICATION_CHILD_PROCESS_CRASHED:
571 case content::NOTIFICATION_CHILD_INSTANCE_CREATED:
jam@chromium.orga27a9382009-02-11 23:55:10572 LogChildProcessChange(type, source, details);
initial.commit09911bf2008-07-26 23:55:29573 break;
574
ananta@chromium.org432115822011-07-10 15:52:27575 case chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED:
jam@chromium.org6c2381d2011-10-19 02:52:53576 LogKeywords(content::Source<TemplateURLService>(source).ptr());
initial.commit09911bf2008-07-26 23:55:29577 break;
578
ananta@chromium.org432115822011-07-10 15:52:27579 case chrome::NOTIFICATION_OMNIBOX_OPENED_URL: {
isherman@chromium.org279703f2012-01-20 22:23:26580 MetricsLog* current_log =
581 static_cast<MetricsLog*>(log_manager_.current_log());
ananta@chromium.org1226abb2010-06-10 18:01:28582 DCHECK(current_log);
583 current_log->RecordOmniboxOpenedURL(
jam@chromium.org6c2381d2011-10-19 02:52:53584 *content::Details<AutocompleteLog>(details).ptr());
initial.commit09911bf2008-07-26 23:55:29585 break;
ananta@chromium.org1226abb2010-06-10 18:01:28586 }
initial.commit09911bf2008-07-26 23:55:29587
ananta@chromium.org432115822011-07-10 15:52:27588 case chrome::NOTIFICATION_BOOKMARK_MODEL_LOADED: {
jam@chromium.org6c2381d2011-10-19 02:52:53589 Profile* p = content::Source<Profile>(source).ptr();
tim@chromium.orgb61236c62009-04-09 22:43:55590 if (p)
591 LogBookmarks(p->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29592 break;
tim@chromium.orgb61236c62009-04-09 22:43:55593 }
initial.commit09911bf2008-07-26 23:55:29594 default:
jar@chromium.orga063c102010-07-22 22:20:19595 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:29596 break;
597 }
petersont@google.comd01b8732008-10-16 02:18:07598
599 HandleIdleSinceLastTransmission(false);
600
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10601 if (log_manager_.current_log())
602 DVLOG(1) << "METRICS: NUMBER OF EVENTS = "
603 << log_manager_.current_log()->num_events();
petersont@google.comd01b8732008-10-16 02:18:07604}
605
606void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
607 // If there wasn't a lot of action, maybe the computer was asleep, in which
608 // case, the log transmissions should have stopped. Here we start them up
609 // again.
pkasting@chromium.orgcac78842008-11-27 01:02:20610 if (!in_idle && idle_since_last_transmission_)
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16611 StartSchedulerIfNecessary();
pkasting@chromium.orgcac78842008-11-27 01:02:20612 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29613}
614
initial.commit09911bf2008-07-26 23:55:29615void MetricsService::RecordStartOfSessionEnd() {
stuartmorgan@chromium.org466f3c12011-03-23 21:20:38616 LogCleanShutdown();
initial.commit09911bf2008-07-26 23:55:29617 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
618}
619
620void MetricsService::RecordCompletedSessionEnd() {
stuartmorgan@chromium.org466f3c12011-03-23 21:20:38621 LogCleanShutdown();
initial.commit09911bf2008-07-26 23:55:29622 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
623}
624
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16625void MetricsService::RecordBreakpadRegistration(bool success) {
jar@google.com68475e602008-08-22 03:21:15626 if (!success)
cpu@google.come73c01972008-08-13 00:18:24627 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
628 else
629 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
630}
631
632void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
633 if (!has_debugger)
634 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
635 else
jar@google.com68475e602008-08-22 03:21:15636 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
cpu@google.come73c01972008-08-13 00:18:24637}
638
initial.commit09911bf2008-07-26 23:55:29639//------------------------------------------------------------------------------
640// private methods
641//------------------------------------------------------------------------------
642
643
644//------------------------------------------------------------------------------
645// Initialization methods
646
647void MetricsService::InitializeMetricsState() {
kuchhal@chromium.org79bf0b72009-04-27 21:30:55648#if defined(OS_POSIX)
isherman@chromium.orgfe58acc22012-02-29 01:29:58649 server_url_xml_ = ASCIIToUTF16(kServerUrlXml);
650 server_url_proto_ = ASCIIToUTF16(kServerUrlProto);
rtenneti@chromium.org04d2728b2011-12-20 03:25:09651 network_stats_server_ = "chrome.googleechotest.com";
kuchhal@chromium.org79bf0b72009-04-27 21:30:55652#else
653 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
isherman@chromium.orgfe58acc22012-02-29 01:29:58654 server_url_xml_ = dist->GetStatsServerURL();
655 server_url_proto_ = ASCIIToUTF16(kServerUrlProto);
rtenneti@chromium.orgd67d1052011-06-09 05:11:41656 network_stats_server_ = dist->GetNetworkStatsServer();
kuchhal@chromium.org79bf0b72009-04-27 21:30:55657#endif
658
initial.commit09911bf2008-07-26 23:55:29659 PrefService* pref = g_browser_process->local_state();
660 DCHECK(pref);
661
jar@chromium.org225c50842010-01-19 21:19:13662 if ((pref->GetInt64(prefs::kStabilityStatsBuildTime)
663 != MetricsLog::GetBuildTime()) ||
estade@chromium.orgddd231e2010-06-29 20:35:19664 (pref->GetString(prefs::kStabilityStatsVersion)
jar@chromium.org225c50842010-01-19 21:19:13665 != MetricsLog::GetVersionString())) {
jar@chromium.org541f77922009-02-23 21:14:38666 // This is a new version, so we don't want to confuse the stats about the
667 // old version with info that we upload.
668 DiscardOldStabilityStats(pref);
669 pref->SetString(prefs::kStabilityStatsVersion,
estade@chromium.orgddd231e2010-06-29 20:35:19670 MetricsLog::GetVersionString());
jar@chromium.org225c50842010-01-19 21:19:13671 pref->SetInt64(prefs::kStabilityStatsBuildTime,
672 MetricsLog::GetBuildTime());
jar@chromium.org541f77922009-02-23 21:14:38673 }
674
initial.commit09911bf2008-07-26 23:55:29675 // Update session ID
676 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
677 ++session_id_;
678 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
679
initial.commit09911bf2008-07-26 23:55:29680 // Stability bookkeeping
cpu@google.come73c01972008-08-13 00:18:24681 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29682
cpu@google.come73c01972008-08-13 00:18:24683 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
684 IncrementPrefValue(prefs::kStabilityCrashCount);
jar@chromium.orgc0c55e92011-09-10 18:47:30685 // Reset flag, and wait until we call LogNeedForCleanShutdown() before
686 // monitoring.
687 pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
initial.commit09911bf2008-07-26 23:55:29688 }
cpu@google.come73c01972008-08-13 00:18:24689
cpu@google.come73c01972008-08-13 00:18:24690 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
691 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
jar@chromium.orgc9abf242009-07-18 06:00:38692 // This is marked false when we get a WM_ENDSESSION.
693 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
initial.commit09911bf2008-07-26 23:55:29694 }
initial.commit09911bf2008-07-26 23:55:29695
jar@chromium.org9165f742010-03-10 22:55:01696 // Initialize uptime counters.
697 int64 startup_uptime = MetricsLog::GetIncrementalUptime(pref);
mad@google.comae393ec702010-06-27 16:23:14698 DCHECK_EQ(0, startup_uptime);
jar@chromium.org9165f742010-03-10 22:55:01699 // For backwards compatibility, leave this intact in case Omaha is checking
700 // them. prefs::kStabilityLastTimestampSec may also be useless now.
701 // TODO(jar): Delete these if they have no uses.
robertshield@google.com0bb1a622009-03-04 03:22:32702 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
703
704 // Bookkeeping for the uninstall metrics.
705 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29706
707 // Save profile metrics.
708 PrefService* prefs = g_browser_process->local_state();
709 if (prefs) {
710 // Remove the current dictionary and store it for use when sending data to
711 // server. By removing the value we prune potentially dead profiles
712 // (and keys). All valid values are added back once services startup.
713 const DictionaryValue* profile_dictionary =
714 prefs->GetDictionary(prefs::kProfileMetrics);
715 if (profile_dictionary) {
716 // Do a deep copy of profile_dictionary since ClearPref will delete it.
717 profile_dictionary_.reset(static_cast<DictionaryValue*>(
718 profile_dictionary->DeepCopy()));
719 prefs->ClearPref(prefs::kProfileMetrics);
720 }
721 }
722
jar@chromium.org92745242009-06-12 16:52:21723 // Get stats on use of command line.
724 const CommandLine* command_line(CommandLine::ForCurrentProcess());
725 size_t common_commands = 0;
726 if (command_line->HasSwitch(switches::kUserDataDir)) {
727 ++common_commands;
728 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
729 }
730
731 if (command_line->HasSwitch(switches::kApp)) {
732 ++common_commands;
733 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
734 }
735
msw@chromium.org62b4e522011-07-13 21:46:32736 size_t switch_count = command_line->GetSwitches().size();
737 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount", switch_count);
jar@chromium.org92745242009-06-12 16:52:21738 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
msw@chromium.org62b4e522011-07-13 21:46:32739 switch_count - common_commands);
jar@chromium.org92745242009-06-12 16:52:21740
initial.commit09911bf2008-07-26 23:55:29741 // Kick off the process of saving the state (so the uptime numbers keep
742 // getting updated) every n minutes.
743 ScheduleNextStateSave();
744}
745
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40746// static
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56747void MetricsService::InitTaskGetHardwareClass(
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40748 base::WeakPtr<MetricsService> self,
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56749 base::MessageLoopProxy* target_loop) {
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56750 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
751
752 std::string hardware_class;
753#if defined(OS_CHROMEOS)
754 chromeos::system::StatisticsProvider::GetInstance()->GetMachineStatistic(
755 "hardware_class", &hardware_class);
756#endif // OS_CHROMEOS
757
758 target_loop->PostTask(FROM_HERE,
759 base::Bind(&MetricsService::OnInitTaskGotHardwareClass,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40760 self, hardware_class));
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56761}
762
763void MetricsService::OnInitTaskGotHardwareClass(
764 const std::string& hardware_class) {
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40765 DCHECK_EQ(state_, INIT_TASK_SCHEDULED);
zelidrag@chromium.org85ed9d42010-06-08 22:37:44766 hardware_class_ = hardware_class;
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56767
768 // Start the next part of the init task: loading plugin information.
769 PluginService::GetInstance()->GetPlugins(
770 base::Bind(&MetricsService::OnInitTaskGotPluginInfo,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40771 self_ptr_factory_.GetWeakPtr()));
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56772}
773
774void MetricsService::OnInitTaskGotPluginInfo(
775 const std::vector<webkit::WebPluginInfo>& plugins) {
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40776 DCHECK_EQ(state_, INIT_TASK_SCHEDULED);
jam@chromium.org35fa6a22009-08-15 00:04:01777 plugins_ = plugins;
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56778
rtenneti@chromium.orgd67d1052011-06-09 05:11:41779 io_thread_ = g_browser_process->io_thread();
zelidrag@chromium.org85ed9d42010-06-08 22:37:44780 if (state_ == INIT_TASK_SCHEDULED)
781 state_ = INIT_TASK_DONE;
initial.commit09911bf2008-07-26 23:55:29782}
783
784std::string MetricsService::GenerateClientID() {
dhollowa@chromium.org3469e7e2010-10-14 20:34:59785 return guid::GenerateGUID();
initial.commit09911bf2008-07-26 23:55:29786}
787
initial.commit09911bf2008-07-26 23:55:29788//------------------------------------------------------------------------------
789// State save methods
790
791void MetricsService::ScheduleNextStateSave() {
isherman@chromium.org8454aeb2011-11-19 23:38:20792 state_saver_factory_.InvalidateWeakPtrs();
initial.commit09911bf2008-07-26 23:55:29793
794 MessageLoop::current()->PostDelayedTask(FROM_HERE,
isherman@chromium.org8454aeb2011-11-19 23:38:20795 base::Bind(&MetricsService::SaveLocalState,
796 state_saver_factory_.GetWeakPtr()),
tedvessenes@gmail.comfc4252a72012-01-12 21:58:47797 base::TimeDelta::FromMinutes(kSaveStateIntervalMinutes));
initial.commit09911bf2008-07-26 23:55:29798}
799
800void MetricsService::SaveLocalState() {
801 PrefService* pref = g_browser_process->local_state();
802 if (!pref) {
jar@chromium.orga063c102010-07-22 22:20:19803 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:29804 return;
805 }
806
807 RecordCurrentState(pref);
initial.commit09911bf2008-07-26 23:55:29808
tedvessenes@gmail.comfc4252a72012-01-12 21:58:47809 // TODO(jar):110021 Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29810 ScheduleNextStateSave();
811}
812
813
814//------------------------------------------------------------------------------
815// Recording control methods
816
817void MetricsService::StartRecording() {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10818 if (log_manager_.current_log())
initial.commit09911bf2008-07-26 23:55:29819 return;
820
stuartmorgan@chromium.org29948262012-03-01 12:15:08821 log_manager_.BeginLoggingWithLog(new MetricsLog(client_id_, session_id_),
822 MetricsLogManager::ONGOING_LOG);
initial.commit09911bf2008-07-26 23:55:29823 if (state_ == INITIALIZED) {
824 // We only need to schedule that run once.
zelidrag@chromium.org85ed9d42010-06-08 22:37:44825 state_ = INIT_TASK_SCHEDULED;
initial.commit09911bf2008-07-26 23:55:29826
zelidrag@chromium.org85ed9d42010-06-08 22:37:44827 // Schedules a task on the file thread for execution of slower
828 // initialization steps (such as plugin list generation) necessary
829 // for sending the initial log. This avoids blocking the main UI
830 // thread.
joi@chromium.orged10dd12011-12-07 12:03:42831 BrowserThread::PostDelayedTask(
832 BrowserThread::FILE,
833 FROM_HERE,
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56834 base::Bind(&MetricsService::InitTaskGetHardwareClass,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40835 self_ptr_factory_.GetWeakPtr(),
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56836 MessageLoop::current()->message_loop_proxy()),
tedvessenes@gmail.comfc4252a72012-01-12 21:58:47837 kInitializationDelaySeconds);
initial.commit09911bf2008-07-26 23:55:29838 }
839}
840
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:38841void MetricsService::StopRecording() {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10842 if (!log_manager_.current_log())
initial.commit09911bf2008-07-26 23:55:29843 return;
844
jar@google.com68475e602008-08-22 03:21:15845 // TODO(jar): Integrate bounds on log recording more consistently, so that we
846 // can stop recording logs that are too big much sooner.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10847 if (log_manager_.current_log()->num_events() > kEventLimit) {
dsh@google.com553dba62009-02-24 19:08:23848 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10849 log_manager_.current_log()->num_events());
850 log_manager_.DiscardCurrentLog();
jar@google.com68475e602008-08-22 03:21:15851 StartRecording(); // Start trivial log to hold our histograms.
852 }
853
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10854 // Adds to ongoing logs.
855 log_manager_.current_log()->set_hardware_class(hardware_class_);
jar@chromium.orgaccdfa62011-09-20 01:56:52856
jar@google.com0b33f80b2008-12-17 21:34:36857 // Put incremental data (histogram deltas, and realtime stats deltas) at the
jar@google.com147bbc0b2009-01-06 19:37:40858 // end of all log transmissions (initial log handles this separately).
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:38859 // RecordIncrementalStabilityElements only exists on the derived
860 // MetricsLog class.
isherman@chromium.org279703f2012-01-20 22:23:26861 MetricsLog* current_log =
862 static_cast<MetricsLog*>(log_manager_.current_log());
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:38863 DCHECK(current_log);
isherman@chromium.orgfe58acc22012-02-29 01:29:58864 current_log->RecordIncrementalStabilityElements(plugins_);
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:38865 RecordCurrentHistograms();
initial.commit09911bf2008-07-26 23:55:29866
stuartmorgan@chromium.org29948262012-03-01 12:15:08867 log_manager_.FinishCurrentLog();
initial.commit09911bf2008-07-26 23:55:29868}
869
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10870void MetricsService::PushPendingLogsToPersistentStorage() {
initial.commit09911bf2008-07-26 23:55:29871 if (state_ < INITIAL_LOG_READY)
avi@google.com28ab7f92009-01-06 21:39:04872 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29873
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10874 if (log_manager_.has_staged_log()) {
stuartmorgan@chromium.org29948262012-03-01 12:15:08875 // We may race here, and send second copy of initial log later.
876 if (state_ == INITIAL_LOG_READY)
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10877 state_ = SENDING_OLD_LOGS;
stuartmorgan@chromium.org29948262012-03-01 12:15:08878 log_manager_.StoreStagedLogAsUnsent();
initial.commit09911bf2008-07-26 23:55:29879 }
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10880 DCHECK(!log_manager_.has_staged_log());
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:38881 StopRecording();
initial.commit09911bf2008-07-26 23:55:29882 StoreUnsentLogs();
883}
884
885//------------------------------------------------------------------------------
886// Transmission of logs methods
887
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16888void MetricsService::StartSchedulerIfNecessary() {
889 if (reporting_active() && recording_active())
890 scheduler_->Start();
initial.commit09911bf2008-07-26 23:55:29891}
892
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16893void MetricsService::StartScheduledUpload() {
894 // If reporting has been turned off, the scheduler doesn't need to run.
895 if (!reporting_active() || !recording_active()) {
896 scheduler_->Stop();
897 scheduler_->UploadCancelled();
898 return;
899 }
900
stuartmorgan@chromium.org29948262012-03-01 12:15:08901 StartFinalLogInfoCollection();
902}
903
904void MetricsService::StartFinalLogInfoCollection() {
905 // Begin the multi-step process of collecting memory usage histograms:
906 // First spawn a task to collect the memory details; when that task is
907 // finished, it will call OnMemoryDetailCollectionDone. That will in turn
908 // call HistogramSynchronization to collect histograms from all renderers and
909 // then call OnHistogramSynchronizationDone to continue processing.
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16910 DCHECK(!waiting_for_asynchronus_reporting_step_);
911 waiting_for_asynchronus_reporting_step_ = true;
912
dcheng@chromium.org2226c222011-11-22 00:08:40913 base::Closure callback =
914 base::Bind(&MetricsService::OnMemoryDetailCollectionDone,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40915 self_ptr_factory_.GetWeakPtr());
sail@chromium.org84c988a2011-04-19 17:56:33916
dcheng@chromium.org2226c222011-11-22 00:08:40917 scoped_refptr<MetricsMemoryDetails> details(
918 new MetricsMemoryDetails(callback));
sail@chromium.org84c988a2011-04-19 17:56:33919 details->StartFetch();
920
921 // Collect WebCore cache information to put into a histogram.
ananta@chromium.orgf3b1a082011-11-18 00:34:30922 for (content::RenderProcessHost::iterator i(
923 content::RenderProcessHost::AllHostsIterator());
sail@chromium.org84c988a2011-04-19 17:56:33924 !i.IsAtEnd(); i.Advance())
ananta@chromium.org2ccf45c2011-08-19 23:35:50925 i.GetCurrentValue()->Send(new ChromeViewMsg_GetCacheResourceStats());
sail@chromium.org84c988a2011-04-19 17:56:33926}
927
928void MetricsService::OnMemoryDetailCollectionDone() {
jar@chromium.orgc9a3ef82009-05-28 22:02:46929 DCHECK(IsSingleThreaded());
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16930 // This function should only be called as the callback from an ansynchronous
931 // step.
932 DCHECK(waiting_for_asynchronus_reporting_step_);
jar@chromium.orgc9a3ef82009-05-28 22:02:46933
jar@chromium.orgc9a3ef82009-05-28 22:02:46934 // Create a callback_task for OnHistogramSynchronizationDone.
dcheng@chromium.org2226c222011-11-22 00:08:40935 base::Closure callback = base::Bind(
936 &MetricsService::OnHistogramSynchronizationDone,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40937 self_ptr_factory_.GetWeakPtr());
jar@chromium.orgc9a3ef82009-05-28 22:02:46938
rtenneti@chromium.org908de522011-10-20 00:55:00939 base::StatisticsRecorder::CollectHistogramStats("Browser");
940
jar@chromium.orgc9a3ef82009-05-28 22:02:46941 // Set up the callback to task to call after we receive histograms from all
942 // renderer processes. Wait time specifies how long to wait before absolutely
943 // calling us back on the task.
944 HistogramSynchronizer::FetchRendererHistogramsAsynchronously(
dcheng@chromium.org2226c222011-11-22 00:08:40945 MessageLoop::current(), callback,
jar@chromium.orgc9a3ef82009-05-28 22:02:46946 kMaxHistogramGatheringWaitDuration);
947}
948
949void MetricsService::OnHistogramSynchronizationDone() {
initial.commit09911bf2008-07-26 23:55:29950 DCHECK(IsSingleThreaded());
stuartmorgan@chromium.org29948262012-03-01 12:15:08951 // This function should only be called as the callback from an ansynchronous
952 // step.
953 DCHECK(waiting_for_asynchronus_reporting_step_);
initial.commit09911bf2008-07-26 23:55:29954
stuartmorgan@chromium.org29948262012-03-01 12:15:08955 waiting_for_asynchronus_reporting_step_ = false;
956 OnFinalLogInfoCollectionDone();
957}
958
959void MetricsService::OnFinalLogInfoCollectionDone() {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16960 // If somehow there is a fetch in progress, we return and hope things work
961 // out. The scheduler isn't informed since if this happens, the scheduler
962 // will get a response from the upload.
isherman@chromium.orgfe58acc22012-02-29 01:29:58963 DCHECK(!current_fetch_xml_.get());
964 DCHECK(!current_fetch_proto_.get());
965 if (current_fetch_xml_.get() || current_fetch_proto_.get())
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16966 return;
967
petersont@google.comd01b8732008-10-16 02:18:07968 // If we're getting no notifications, then the log won't have much in it, and
969 // it's possible the computer is about to go to sleep, so don't upload and
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16970 // stop the scheduler.
971 // Similarly, if logs should no longer be uploaded, stop here.
972 if (idle_since_last_transmission_ ||
973 !recording_active() || !reporting_active()) {
974 scheduler_->Stop();
975 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:07976 return;
977 }
978
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10979 MakeStagedLog();
initial.commit09911bf2008-07-26 23:55:29980
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10981 // MakeStagedLog should have prepared log text; if it didn't, skip this
982 // upload and hope things work out next time.
983 if (log_manager_.staged_log_text().empty()) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16984 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:07985 return;
986 }
initial.commit09911bf2008-07-26 23:55:29987
stuartmorgan@chromium.org29948262012-03-01 12:15:08988 SendStagedLog();
989}
990
991void MetricsService::MakeStagedLog() {
992 if (log_manager_.has_staged_log())
993 return;
994
995 switch (state_) {
996 case INITIALIZED:
997 case INIT_TASK_SCHEDULED: // We should be further along by now.
998 DCHECK(false);
999 return;
1000
1001 case INIT_TASK_DONE:
1002 // We need to wait for the initial log to be ready before sending
1003 // anything, because the server will tell us whether it wants to hear
1004 // from us.
1005 PrepareInitialLog();
1006 DCHECK(state_ == INIT_TASK_DONE);
1007 log_manager_.LoadPersistedUnsentLogs();
1008 state_ = INITIAL_LOG_READY;
1009 break;
1010
1011 case SENDING_OLD_LOGS:
1012 if (log_manager_.has_unsent_logs()) {
1013 log_manager_.StageNextLogForUpload();
1014 break;
1015 }
1016 state_ = SENDING_CURRENT_LOGS;
1017 // Fall through.
1018
1019 case SENDING_CURRENT_LOGS:
1020 StopRecording();
1021 StartRecording();
1022 log_manager_.StageNextLogForUpload();
1023 break;
1024
1025 default:
1026 NOTREACHED();
1027 return;
1028 }
1029
1030 DCHECK(log_manager_.has_staged_log());
1031}
1032
1033void MetricsService::PrepareInitialLog() {
1034 DCHECK(state_ == INIT_TASK_DONE);
1035
1036 MetricsLog* log = new MetricsLog(client_id_, session_id_);
1037 log->set_hardware_class(hardware_class_); // Adds to initial log.
1038 log->RecordEnvironment(plugins_, profile_dictionary_.get());
1039
1040 // Histograms only get written to the current log, so make the new log current
1041 // before writing them.
1042 log_manager_.PauseCurrentLog();
1043 log_manager_.BeginLoggingWithLog(log, MetricsLogManager::INITIAL_LOG);
1044 RecordCurrentHistograms();
1045 log_manager_.FinishCurrentLog();
1046 log_manager_.ResumePausedLog();
1047
1048 DCHECK(!log_manager_.has_staged_log());
1049 log_manager_.StageNextLogForUpload();
1050}
1051
1052void MetricsService::StoreUnsentLogs() {
1053 if (state_ < INITIAL_LOG_READY)
1054 return; // We never Recalled the prior unsent logs.
1055
1056 log_manager_.PersistUnsentLogs();
1057}
1058
1059void MetricsService::SendStagedLog() {
1060 DCHECK(log_manager_.has_staged_log());
1061
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101062 PrepareFetchWithStagedLog();
petersont@google.comd01b8732008-10-16 02:18:071063
isherman@chromium.orgfe58acc22012-02-29 01:29:581064 if (!current_fetch_xml_.get()) {
1065 DCHECK(!current_fetch_proto_.get());
petersont@google.comd01b8732008-10-16 02:18:071066 // Compression failed, and log discarded :-/.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101067 log_manager_.DiscardStagedLog();
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161068 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:071069 // TODO(jar): If compression failed, we should have created a tiny log and
1070 // compressed that, so that we can signal that we're losing logs.
1071 return;
1072 }
isherman@chromium.orgfe58acc22012-02-29 01:29:581073 // Currently, the staged log for the protobuf version of the data is discarded
1074 // after we create the URL request, so that there is no chance for
1075 // re-transmission in case the corresponding XML request fails. We will
1076 // handle protobuf failures more carefully once that becomes the main
1077 // pipeline, i.e. once we switch away from the XML pipeline.
1078 DCHECK(current_fetch_proto_.get() || !log_manager_.has_staged_log_proto());
petersont@google.comd01b8732008-10-16 02:18:071079
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161080 DCHECK(!waiting_for_asynchronus_reporting_step_);
petersont@google.comd01b8732008-10-16 02:18:071081
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161082 waiting_for_asynchronus_reporting_step_ = true;
isherman@chromium.orgfe58acc22012-02-29 01:29:581083 current_fetch_xml_->Start();
1084 if (current_fetch_proto_.get())
1085 current_fetch_proto_->Start();
petersont@google.comd01b8732008-10-16 02:18:071086
1087 HandleIdleSinceLastTransmission(true);
1088}
1089
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101090void MetricsService::PrepareFetchWithStagedLog() {
1091 DCHECK(!log_manager_.staged_log_text().empty());
pkasting@chromium.orgcac78842008-11-27 01:02:201092
isherman@chromium.orgfe58acc22012-02-29 01:29:581093 // Prepare the XML version.
1094 DCHECK(!current_fetch_xml_.get());
1095 current_fetch_xml_.reset(content::URLFetcher::Create(
1096 GURL(server_url_xml_), content::URLFetcher::POST, this));
1097 current_fetch_xml_->SetRequestContext(
nkostylev@chromium.org8ef3d8052011-07-22 09:03:001098 g_browser_process->system_request_context());
isherman@chromium.orgfe58acc22012-02-29 01:29:581099 current_fetch_xml_->SetUploadData(kMetricsTypeXml,
1100 log_manager_.staged_log_text().xml);
1101 // We already drop cookies server-side, but we might as well strip them out
1102 // client-side as well.
1103 current_fetch_xml_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES |
1104 net::LOAD_DO_NOT_SEND_COOKIES);
1105
1106 // Prepare the protobuf version.
1107 DCHECK(!current_fetch_proto_.get());
1108 if (log_manager_.has_staged_log_proto()) {
1109 current_fetch_proto_.reset(content::URLFetcher::Create(
1110 GURL(server_url_proto_), content::URLFetcher::POST, this));
1111 current_fetch_proto_->SetRequestContext(
1112 g_browser_process->system_request_context());
1113 current_fetch_proto_->SetUploadData(kMetricsTypeProto,
1114 log_manager_.staged_log_text().proto);
1115 // We already drop cookies server-side, but we might as well strip them out
1116 // client-side as well.
1117 current_fetch_proto_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES |
1118 net::LOAD_DO_NOT_SEND_COOKIES);
1119
1120 // Discard the protobuf version of the staged log, so that we will avoid
1121 // re-uploading it even if we need to re-upload the XML version.
1122 // TODO(isherman): Handle protobuf upload failures more gracefully once we
1123 // transition away from the XML-based pipeline.
1124 log_manager_.DiscardStagedLogProto();
1125 }
initial.commit09911bf2008-07-26 23:55:291126}
1127
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441128static const char* StatusToString(const net::URLRequestStatus& status) {
initial.commit09911bf2008-07-26 23:55:291129 switch (status.status()) {
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441130 case net::URLRequestStatus::SUCCESS:
initial.commit09911bf2008-07-26 23:55:291131 return "SUCCESS";
1132
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441133 case net::URLRequestStatus::IO_PENDING:
initial.commit09911bf2008-07-26 23:55:291134 return "IO_PENDING";
1135
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441136 case net::URLRequestStatus::HANDLED_EXTERNALLY:
initial.commit09911bf2008-07-26 23:55:291137 return "HANDLED_EXTERNALLY";
1138
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441139 case net::URLRequestStatus::CANCELED:
initial.commit09911bf2008-07-26 23:55:291140 return "CANCELED";
1141
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441142 case net::URLRequestStatus::FAILED:
initial.commit09911bf2008-07-26 23:55:291143 return "FAILED";
1144
1145 default:
jar@chromium.orga063c102010-07-22 22:20:191146 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291147 return "Unknown";
1148 }
1149}
1150
isherman@chromium.orgfe58acc22012-02-29 01:29:581151// We need to wait for two responses: the response to the XML upload, and the
1152// response to the protobuf upload. For now, only the XML upload's response
1153// affects decisions like whether to retry the upload, whether to abandon the
1154// upload because it is too large, etc. However, we still need to wait for the
1155// protobuf upload, as we cannot reset |current_fetch_proto_| until we have
1156// confirmation that the network request was sent; and the easiest way to do
1157// that is to wait for the response. In case the XML upload's response arrives
1158// first, we cache that response until the protobuf upload's response also
1159// arrives.
1160//
1161// Note that if the XML upload succeeds but the protobuf upload fails, we will
1162// not retry the protobuf upload. If the XML upload fails while the protobuf
1163// upload succeeds, we will still avoid re-uploading the protobuf data because
1164// we "zap" the data after the first upload attempt. This means that we might
1165// lose protobuf uploads when XML ones succeed; but we will never duplicate any
1166// protobuf uploads. Protobuf failures should be rare enough to where this
1167// should be ok while we have the two pipelines running in parallel.
jam@chromium.org7cc6e5632011-10-25 17:56:121168void MetricsService::OnURLFetchComplete(const content::URLFetcher* source) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161169 DCHECK(waiting_for_asynchronus_reporting_step_);
isherman@chromium.orgfe58acc22012-02-29 01:29:581170
1171 // We're not allowed to re-use the existing |URLFetcher|s, so free them here.
1172 scoped_ptr<content::URLFetcher> s;
1173 if (source == current_fetch_xml_.get()) {
1174 s.reset(current_fetch_xml_.release());
1175
1176 // Cache the XML responses, in case we still need to wait for the protobuf
1177 // response.
1178 response_code_ = source->GetResponseCode();
1179 response_status_ = StatusToString(source->GetStatus());
1180 source->GetResponseAsString(&response_data_);
1181 } else if (source == current_fetch_proto_.get()) {
1182 s.reset(current_fetch_proto_.release());
1183 } else {
1184 NOTREACHED();
1185 return;
1186 }
1187
1188 // If we're still waiting for one of the responses, keep waiting...
1189 if (current_fetch_xml_.get() || current_fetch_proto_.get())
1190 return;
1191
1192 // We should only be able to reach here once we've received responses to both
1193 // the XML and the protobuf requests. We should always have the response code
1194 // available.
1195 DCHECK_NE(response_code_, content::URLFetcher::RESPONSE_CODE_INVALID);
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161196 waiting_for_asynchronus_reporting_step_ = false;
isherman@chromium.orgfe58acc22012-02-29 01:29:581197
initial.commit09911bf2008-07-26 23:55:291198
1199 // Confirm send so that we can move on.
isherman@chromium.orgfe58acc22012-02-29 01:29:581200 VLOG(1) << "METRICS RESPONSE CODE: " << response_code_
1201 << " status=" << response_status_;
petersont@google.com252873ef2008-08-04 21:59:451202
isherman@chromium.orgfe58acc22012-02-29 01:29:581203 bool upload_succeeded = response_code_ == 200;
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161204
jar@chromium.org0eb34fee2009-01-21 08:04:381205 // Provide boolean for error recovery (allow us to ignore response_code).
paul@chromium.orgdc6f4962009-02-13 01:25:501206 bool discard_log = false;
jar@chromium.org0eb34fee2009-01-21 08:04:381207
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161208 if (!upload_succeeded &&
isherman@chromium.orgfe58acc22012-02-29 01:29:581209 log_manager_.staged_log_text().xml.length() >
1210 kUploadLogAvoidRetransmitSize) {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101211 UMA_HISTOGRAM_COUNTS(
1212 "UMA.Large Rejected Log was Discarded",
isherman@chromium.orgfe58acc22012-02-29 01:29:581213 static_cast<int>(log_manager_.staged_log_text().xml.length()));
jar@chromium.org0eb34fee2009-01-21 08:04:381214 discard_log = true;
isherman@chromium.orgfe58acc22012-02-29 01:29:581215 } else if (response_code_ == 400) {
jar@chromium.org0eb34fee2009-01-21 08:04:381216 // Bad syntax. Retransmission won't work.
dsh@google.com553dba62009-02-24 19:08:231217 UMA_HISTOGRAM_COUNTS("UMA.Unacceptable_Log_Discarded", state_);
jar@chromium.org0eb34fee2009-01-21 08:04:381218 discard_log = true;
jar@google.com68475e602008-08-22 03:21:151219 }
1220
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161221 if (!upload_succeeded && !discard_log) {
pkasting@chromium.org666205032010-10-21 20:56:581222 VLOG(1) << "METRICS: transmission attempt returned a failure code: "
isherman@chromium.orgfe58acc22012-02-29 01:29:581223 << response_code_ << ". Verify network connectivity";
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161224 LogBadResponseCode();
jar@chromium.org0eb34fee2009-01-21 08:04:381225 } else { // Successful receipt (or we are discarding log).
isherman@chromium.orgfe58acc22012-02-29 01:29:581226 VLOG(1) << "METRICS RESPONSE DATA: " << response_data_;
initial.commit09911bf2008-07-26 23:55:291227 switch (state_) {
1228 case INITIAL_LOG_READY:
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101229 state_ = SENDING_OLD_LOGS;
initial.commit09911bf2008-07-26 23:55:291230 break;
1231
initial.commit09911bf2008-07-26 23:55:291232 case SENDING_OLD_LOGS:
stuartmorgan@chromium.orgd53e2232011-06-30 15:54:571233 // Store the updated list to disk now that the removed log is uploaded.
initial.commit09911bf2008-07-26 23:55:291234 StoreUnsentLogs();
1235 break;
1236
1237 case SENDING_CURRENT_LOGS:
1238 break;
1239
1240 default:
jar@chromium.orga063c102010-07-22 22:20:191241 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291242 break;
1243 }
petersont@google.comd01b8732008-10-16 02:18:071244
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101245 log_manager_.DiscardStagedLog();
petersont@google.com252873ef2008-08-04 21:59:451246
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101247 if (log_manager_.has_unsent_logs())
initial.commit09911bf2008-07-26 23:55:291248 DCHECK(state_ < SENDING_CURRENT_LOGS);
initial.commit09911bf2008-07-26 23:55:291249 }
petersont@google.com252873ef2008-08-04 21:59:451250
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161251 // Error 400 indicates a problem with the log, not with the server, so
1252 // don't consider that a sign that the server is in trouble.
isherman@chromium.orgfe58acc22012-02-29 01:29:581253 bool server_is_healthy = upload_succeeded || response_code_ == 400;
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161254
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101255 scheduler_->UploadFinished(server_is_healthy,
1256 log_manager_.has_unsent_logs());
rtenneti@chromium.orgd67d1052011-06-09 05:11:411257
1258 // Collect network stats if UMA upload succeeded.
1259 if (server_is_healthy && io_thread_)
1260 chrome_browser_net::CollectNetworkStats(network_stats_server_, io_thread_);
isherman@chromium.orgfe58acc22012-02-29 01:29:581261
1262 // Reset the cached response data.
1263 response_code_ = content::URLFetcher::RESPONSE_CODE_INVALID;
1264 response_data_ = std::string();
1265 response_status_ = std::string();
initial.commit09911bf2008-07-26 23:55:291266}
1267
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161268void MetricsService::LogBadResponseCode() {
pkasting@chromium.org666205032010-10-21 20:56:581269 VLOG(1) << "Verify your metrics logs are formatted correctly. Verify server "
isherman@chromium.orgfe58acc22012-02-29 01:29:581270 "is active at " << server_url_xml_;
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101271 if (!log_manager_.has_staged_log()) {
pkasting@chromium.org666205032010-10-21 20:56:581272 VLOG(1) << "METRICS: Recorder shutdown during log transmission.";
petersont@google.com252873ef2008-08-04 21:59:451273 } else {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161274 VLOG(1) << "METRICS: transmission retry being scheduled for "
isherman@chromium.orgfe58acc22012-02-29 01:29:581275 << log_manager_.staged_log_text().xml;
initial.commit09911bf2008-07-26 23:55:291276 }
initial.commit09911bf2008-07-26 23:55:291277}
1278
jam@chromium.org6c2381d2011-10-19 02:52:531279void MetricsService::LogWindowChange(
1280 int type,
1281 const content::NotificationSource& source,
1282 const content::NotificationDetails& details) {
brettw@google.com534e54b2008-08-13 15:40:091283 int controller_id = -1;
1284 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291285 MetricsLog::WindowEventType window_type;
1286
1287 // Note: since we stop all logging when a single OTR session is active, it is
1288 // possible that we start getting notifications about a window that we don't
1289 // know about.
brettw@google.com534e54b2008-08-13 15:40:091290 if (window_map_.find(window_or_tab) == window_map_.end()) {
1291 controller_id = next_window_id_++;
1292 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291293 } else {
brettw@google.com534e54b2008-08-13 15:40:091294 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291295 }
jar@chromium.org92745242009-06-12 16:52:211296 DCHECK_NE(controller_id, -1);
initial.commit09911bf2008-07-26 23:55:291297
ananta@chromium.org432115822011-07-10 15:52:271298 switch (type) {
1299 case content::NOTIFICATION_TAB_PARENTED:
1300 case chrome::NOTIFICATION_BROWSER_OPENED:
initial.commit09911bf2008-07-26 23:55:291301 window_type = MetricsLog::WINDOW_CREATE;
1302 break;
1303
ananta@chromium.org432115822011-07-10 15:52:271304 case content::NOTIFICATION_TAB_CLOSING:
1305 case chrome::NOTIFICATION_BROWSER_CLOSED:
brettw@google.com534e54b2008-08-13 15:40:091306 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291307 window_type = MetricsLog::WINDOW_DESTROY;
1308 break;
1309
1310 default:
jar@chromium.orga063c102010-07-22 22:20:191311 NOTREACHED();
paul@chromium.org68d74f02009-02-13 01:36:501312 return;
initial.commit09911bf2008-07-26 23:55:291313 }
1314
brettw@google.com534e54b2008-08-13 15:40:091315 // TODO(brettw) we should have some kind of ID for the parent.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101316 log_manager_.current_log()->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291317}
1318
jam@chromium.org6c2381d2011-10-19 02:52:531319void MetricsService::LogLoadComplete(
1320 int type,
1321 const content::NotificationSource& source,
1322 const content::NotificationDetails& details) {
jam@chromium.orgad50def52011-10-19 23:17:071323 if (details == content::NotificationService::NoDetails())
initial.commit09911bf2008-07-26 23:55:291324 return;
1325
jar@google.com68475e602008-08-22 03:21:151326 // TODO(jar): There is a bug causing this to be called too many times, and
1327 // the log overflows. For now, we won't record these events.
dsh@google.com553dba62009-02-24 19:08:231328 UMA_HISTOGRAM_COUNTS("UMA.LogLoadComplete called", 1);
jar@google.com68475e602008-08-22 03:21:151329 return;
1330
jam@chromium.org6c2381d2011-10-19 02:52:531331 const content::Details<LoadNotificationDetails> load_details(details);
brettw@google.com534e54b2008-08-13 15:40:091332 int controller_id = window_map_[details.map_key()];
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101333 log_manager_.current_log()->RecordLoadEvent(controller_id,
1334 load_details->url(),
1335 load_details->origin(),
1336 load_details->session_index(),
1337 load_details->load_time());
initial.commit09911bf2008-07-26 23:55:291338}
1339
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511340void MetricsService::IncrementPrefValue(const char* path) {
cpu@google.come73c01972008-08-13 00:18:241341 PrefService* pref = g_browser_process->local_state();
1342 DCHECK(pref);
1343 int value = pref->GetInteger(path);
1344 pref->SetInteger(path, value + 1);
1345}
1346
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511347void MetricsService::IncrementLongPrefsValue(const char* path) {
robertshield@google.com0bb1a622009-03-04 03:22:321348 PrefService* pref = g_browser_process->local_state();
1349 DCHECK(pref);
1350 int64 value = pref->GetInt64(path);
jar@chromium.orgb42c5e42010-06-03 20:43:251351 pref->SetInt64(path, value + 1);
robertshield@google.com0bb1a622009-03-04 03:22:321352}
1353
initial.commit09911bf2008-07-26 23:55:291354void MetricsService::LogLoadStarted() {
jar@chromium.orgdd8d12a2011-09-02 02:10:151355 HISTOGRAM_ENUMERATION("Chrome.UmaPageloadCounter", 1, 2);
cpu@google.come73c01972008-08-13 00:18:241356 IncrementPrefValue(prefs::kStabilityPageLoadCount);
robertshield@google.com0bb1a622009-03-04 03:22:321357 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
jar@google.com0b33f80b2008-12-17 21:34:361358 // We need to save the prefs, as page load count is a critical stat, and it
1359 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291360}
1361
ananta@chromium.orgf3b1a082011-11-18 00:34:301362void MetricsService::LogRendererCrash(content::RenderProcessHost* host,
jochen@chromium.org718eab62011-10-05 21:16:521363 base::TerminationStatus status,
1364 bool was_alive) {
ananta@chromium.orgf3b1a082011-11-18 00:34:301365 Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
aa@chromium.org6f371442011-11-09 06:45:461366 ExtensionService* service = profile->GetExtensionService();
1367 bool was_extension_process =
ananta@chromium.orgf3b1a082011-11-18 00:34:301368 service && service->process_map()->Contains(host->GetID());
jochen@chromium.org718eab62011-10-05 21:16:521369 if (status == base::TERMINATION_STATUS_PROCESS_CRASHED ||
1370 status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
1371 if (was_extension_process)
1372 IncrementPrefValue(prefs::kStabilityExtensionRendererCrashCount);
1373 else
1374 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291375
jochen@chromium.org718eab62011-10-05 21:16:521376 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildCrashes",
1377 was_extension_process ? 2 : 1);
1378 if (was_alive) {
1379 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildCrashesWasAlive",
1380 was_extension_process ? 2 : 1);
1381 }
1382 } else if (status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED) {
1383 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildKills",
1384 was_extension_process ? 2 : 1);
1385 if (was_alive) {
1386 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildKillsWasAlive",
1387 was_extension_process ? 2 : 1);
1388 }
1389 }
asargent@chromium.org1f085622009-12-04 05:33:451390}
1391
initial.commit09911bf2008-07-26 23:55:291392void MetricsService::LogRendererHang() {
cpu@google.come73c01972008-08-13 00:18:241393 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291394}
1395
jar@chromium.orgc0c55e92011-09-10 18:47:301396void MetricsService::LogNeedForCleanShutdown() {
1397 PrefService* pref = g_browser_process->local_state();
1398 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
1399 // Redundant setting to be sure we call for a clean shutdown.
1400 clean_shutdown_status_ = NEED_TO_SHUTDOWN;
1401}
1402
1403bool MetricsService::UmaMetricsProperlyShutdown() {
1404 CHECK(clean_shutdown_status_ == CLEANLY_SHUTDOWN ||
1405 clean_shutdown_status_ == NEED_TO_SHUTDOWN);
1406 return clean_shutdown_status_ == CLEANLY_SHUTDOWN;
1407}
1408
jar@chromium.org67c4e952011-09-17 00:44:271409// For use in hack in LogCleanShutdown.
1410static void Signal(base::WaitableEvent* event) {
1411 event->Signal();
1412}
1413
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381414void MetricsService::LogCleanShutdown() {
jar@chromium.orgacd55b32011-09-05 17:35:311415 // Redundant hack to write pref ASAP.
1416 PrefService* pref = g_browser_process->local_state();
1417 pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
bauerb@chromium.orgfbe17c8a2011-12-27 16:41:481418 pref->CommitPendingWrite();
jar@chromium.org67c4e952011-09-17 00:44:271419 // Hack: TBD: Remove this wait.
1420 // We are so concerned that the pref gets written, we are now willing to stall
1421 // the UI thread until we get assurance that a pref-writing task has
1422 // completed.
1423 base::WaitableEvent done_writing(false, false);
1424 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
isherman@chromium.org8454aeb2011-11-19 23:38:201425 base::Bind(Signal, &done_writing));
jar@chromium.org67c4e952011-09-17 00:44:271426 done_writing.TimedWait(base::TimeDelta::FromHours(1));
1427
jar@chromium.orgc0c55e92011-09-10 18:47:301428 // Redundant setting to assure that we always reset this value at shutdown
1429 // (and that we don't use some alternate path, and not call LogCleanShutdown).
1430 clean_shutdown_status_ = CLEANLY_SHUTDOWN;
jar@chromium.orgacd55b32011-09-05 17:35:311431
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381432 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
1433}
1434
petkov@chromium.orgc1834a92011-01-21 18:21:031435#if defined(OS_CHROMEOS)
1436void MetricsService::LogChromeOSCrash(const std::string &crash_type) {
1437 if (crash_type == "user")
1438 IncrementPrefValue(prefs::kStabilityOtherUserCrashCount);
1439 else if (crash_type == "kernel")
1440 IncrementPrefValue(prefs::kStabilityKernelCrashCount);
1441 else if (crash_type == "uncleanshutdown")
1442 IncrementPrefValue(prefs::kStabilitySystemUncleanShutdownCount);
1443 else
1444 NOTREACHED() << "Unexpected Chrome OS crash type " << crash_type;
1445 // Wake up metrics logs sending if necessary now that new
1446 // log data is available.
1447 HandleIdleSinceLastTransmission(false);
1448}
1449#endif // OS_CHROMEOS
1450
jam@chromium.orga27a9382009-02-11 23:55:101451void MetricsService::LogChildProcessChange(
ananta@chromium.org432115822011-07-10 15:52:271452 int type,
jam@chromium.org6c2381d2011-10-19 02:52:531453 const content::NotificationSource& source,
1454 const content::NotificationDetails& details) {
jam@chromium.org4967f792012-01-20 22:14:401455 content::Details<ChildProcessData> child_details(details);
jam@chromium.org4306c3792011-12-02 01:57:531456 const string16& child_name = child_details->name;
gregoryd@google.com0d84c5d2009-10-09 01:10:421457
jam@chromium.orga27a9382009-02-11 23:55:101458 if (child_process_stats_buffer_.find(child_name) ==
1459 child_process_stats_buffer_.end()) {
gregoryd@google.com0d84c5d2009-10-09 01:10:421460 child_process_stats_buffer_[child_name] =
jam@chromium.org4306c3792011-12-02 01:57:531461 ChildProcessStats(child_details->type);
initial.commit09911bf2008-07-26 23:55:291462 }
1463
jam@chromium.orga27a9382009-02-11 23:55:101464 ChildProcessStats& stats = child_process_stats_buffer_[child_name];
ananta@chromium.org432115822011-07-10 15:52:271465 switch (type) {
1466 case content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED:
initial.commit09911bf2008-07-26 23:55:291467 stats.process_launches++;
1468 break;
1469
ananta@chromium.org432115822011-07-10 15:52:271470 case content::NOTIFICATION_CHILD_INSTANCE_CREATED:
initial.commit09911bf2008-07-26 23:55:291471 stats.instances++;
1472 break;
1473
ananta@chromium.org432115822011-07-10 15:52:271474 case content::NOTIFICATION_CHILD_PROCESS_CRASHED:
initial.commit09911bf2008-07-26 23:55:291475 stats.process_crashes++;
asargent@chromium.org1f085622009-12-04 05:33:451476 // Exclude plugin crashes from the count below because we report them via
1477 // a separate UMA metric.
jam@chromium.org4306c3792011-12-02 01:57:531478 if (!IsPluginProcess(child_details->type)) {
asargent@chromium.org1f085622009-12-04 05:33:451479 IncrementPrefValue(prefs::kStabilityChildProcessCrashCount);
1480 }
initial.commit09911bf2008-07-26 23:55:291481 break;
1482
1483 default:
ananta@chromium.org432115822011-07-10 15:52:271484 NOTREACHED() << "Unexpected notification type " << type;
initial.commit09911bf2008-07-26 23:55:291485 return;
1486 }
1487}
1488
1489// Recursively counts the number of bookmarks and folders in node.
munjal@chromium.orgb3c33d462009-06-26 22:29:201490static void CountBookmarks(const BookmarkNode* node,
1491 int* bookmarks,
1492 int* folders) {
tfarina@chromium.org0890e60e2011-06-27 14:55:211493 if (node->is_url())
initial.commit09911bf2008-07-26 23:55:291494 (*bookmarks)++;
1495 else
1496 (*folders)++;
tfarina@chromium.org9c1a75a2011-03-10 02:38:121497 for (int i = 0; i < node->child_count(); ++i)
initial.commit09911bf2008-07-26 23:55:291498 CountBookmarks(node->GetChild(i), bookmarks, folders);
1499}
1500
munjal@chromium.orgb3c33d462009-06-26 22:29:201501void MetricsService::LogBookmarks(const BookmarkNode* node,
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511502 const char* num_bookmarks_key,
1503 const char* num_folders_key) {
initial.commit09911bf2008-07-26 23:55:291504 DCHECK(node);
1505 int num_bookmarks = 0;
1506 int num_folders = 0;
1507 CountBookmarks(node, &num_bookmarks, &num_folders);
1508 num_folders--; // Don't include the root folder in the count.
1509
1510 PrefService* pref = g_browser_process->local_state();
1511 DCHECK(pref);
1512 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1513 pref->SetInteger(num_folders_key, num_folders);
1514}
1515
sky@google.comd8e41ed2008-09-11 15:22:321516void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291517 DCHECK(model);
tfarina@chromium.org72bdcfe2011-07-22 17:21:581518 LogBookmarks(model->bookmark_bar_node(),
initial.commit09911bf2008-07-26 23:55:291519 prefs::kNumBookmarksOnBookmarkBar,
1520 prefs::kNumFoldersOnBookmarkBar);
1521 LogBookmarks(model->other_node(),
1522 prefs::kNumBookmarksInOtherBookmarkFolder,
1523 prefs::kNumFoldersInOtherBookmarkFolder);
1524 ScheduleNextStateSave();
1525}
1526
erg@google.com8e5c89a2011-06-07 18:13:331527void MetricsService::LogKeywords(const TemplateURLService* url_model) {
initial.commit09911bf2008-07-26 23:55:291528 DCHECK(url_model);
1529
1530 PrefService* pref = g_browser_process->local_state();
1531 DCHECK(pref);
1532 pref->SetInteger(prefs::kNumKeywords,
1533 static_cast<int>(url_model->GetTemplateURLs().size()));
1534 ScheduleNextStateSave();
1535}
1536
1537void MetricsService::RecordPluginChanges(PrefService* pref) {
battre@chromium.orgf8628c22011-04-05 12:10:181538 ListPrefUpdate update(pref, prefs::kStabilityPluginStats);
1539 ListValue* plugins = update.Get();
initial.commit09911bf2008-07-26 23:55:291540 DCHECK(plugins);
1541
1542 for (ListValue::iterator value_iter = plugins->begin();
1543 value_iter != plugins->end(); ++value_iter) {
1544 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
jar@chromium.orga063c102010-07-22 22:20:191545 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291546 continue;
1547 }
1548
1549 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511550 std::string plugin_name;
nsylvain@chromium.org8e50b602009-03-03 22:59:431551 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
nsylvain@chromium.org6470ee8f2009-03-03 20:46:401552 if (plugin_name.empty()) {
jar@chromium.orga063c102010-07-22 22:20:191553 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291554 continue;
1555 }
1556
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511557 // TODO(viettrungluu): remove conversions
evan@chromium.org68b9e72b2011-08-05 23:08:221558 string16 name16 = UTF8ToUTF16(plugin_name);
1559 if (child_process_stats_buffer_.find(name16) ==
1560 child_process_stats_buffer_.end()) {
initial.commit09911bf2008-07-26 23:55:291561 continue;
evan@chromium.org68b9e72b2011-08-05 23:08:221562 }
initial.commit09911bf2008-07-26 23:55:291563
evan@chromium.org68b9e72b2011-08-05 23:08:221564 ChildProcessStats stats = child_process_stats_buffer_[name16];
initial.commit09911bf2008-07-26 23:55:291565 if (stats.process_launches) {
1566 int launches = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431567 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291568 launches += stats.process_launches;
nsylvain@chromium.org8e50b602009-03-03 22:59:431569 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291570 }
1571 if (stats.process_crashes) {
1572 int crashes = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431573 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291574 crashes += stats.process_crashes;
nsylvain@chromium.org8e50b602009-03-03 22:59:431575 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291576 }
1577 if (stats.instances) {
1578 int instances = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431579 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291580 instances += stats.instances;
nsylvain@chromium.org8e50b602009-03-03 22:59:431581 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291582 }
1583
evan@chromium.org68b9e72b2011-08-05 23:08:221584 child_process_stats_buffer_.erase(name16);
initial.commit09911bf2008-07-26 23:55:291585 }
1586
1587 // Now go through and add dictionaries for plugins that didn't already have
1588 // reports in Local State.
evan@chromium.org68b9e72b2011-08-05 23:08:221589 for (std::map<string16, ChildProcessStats>::iterator cache_iter =
jam@chromium.orga27a9382009-02-11 23:55:101590 child_process_stats_buffer_.begin();
1591 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
jam@chromium.orga27a9382009-02-11 23:55:101592 ChildProcessStats stats = cache_iter->second;
gregoryd@google.com0d84c5d2009-10-09 01:10:421593
1594 // Insert only plugins information into the plugins list.
petkov@chromium.org8d5f1dae2011-11-11 14:30:411595 if (!IsPluginProcess(stats.process_type))
gregoryd@google.com0d84c5d2009-10-09 01:10:421596 continue;
1597
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511598 // TODO(viettrungluu): remove conversion
evan@chromium.org68b9e72b2011-08-05 23:08:221599 std::string plugin_name = UTF16ToUTF8(cache_iter->first);
gregoryd@google.com0d84c5d2009-10-09 01:10:421600
initial.commit09911bf2008-07-26 23:55:291601 DictionaryValue* plugin_dict = new DictionaryValue;
1602
nsylvain@chromium.org8e50b602009-03-03 22:59:431603 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
1604 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:291605 stats.process_launches);
nsylvain@chromium.org8e50b602009-03-03 22:59:431606 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:291607 stats.process_crashes);
nsylvain@chromium.org8e50b602009-03-03 22:59:431608 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:291609 stats.instances);
1610 plugins->Append(plugin_dict);
1611 }
jam@chromium.orga27a9382009-02-11 23:55:101612 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291613}
1614
jam@chromium.org6c2381d2011-10-19 02:52:531615bool MetricsService::CanLogNotification(
1616 int type,
1617 const content::NotificationSource& source,
1618 const content::NotificationDetails& details) {
akalin@chromium.org2c910b72011-03-08 21:16:321619 // We simply don't log anything to UMA if there is a single incognito
initial.commit09911bf2008-07-26 23:55:291620 // session visible. The problem is that we always notify using the orginal
1621 // profile in order to simplify notification processing.
1622 return !BrowserList::IsOffTheRecordSessionActive();
1623}
1624
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511625void MetricsService::RecordBooleanPrefValue(const char* path, bool value) {
initial.commit09911bf2008-07-26 23:55:291626 DCHECK(IsSingleThreaded());
1627
1628 PrefService* pref = g_browser_process->local_state();
1629 DCHECK(pref);
1630
1631 pref->SetBoolean(path, value);
1632 RecordCurrentState(pref);
1633}
1634
1635void MetricsService::RecordCurrentState(PrefService* pref) {
robertshield@google.com0bb1a622009-03-04 03:22:321636 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291637
1638 RecordPluginChanges(pref);
1639}
1640
petkov@chromium.org8d5f1dae2011-11-11 14:30:411641// static
jam@chromium.orgbd5d6cf2011-12-01 00:39:121642bool MetricsService::IsPluginProcess(content::ProcessType type) {
1643 return (type == content::PROCESS_TYPE_PLUGIN||
1644 type == content::PROCESS_TYPE_PPAPI_PLUGIN);
petkov@chromium.org8d5f1dae2011-11-11 14:30:411645}
1646
rvargas@google.com5ccaa412009-11-13 22:00:161647#if defined(OS_CHROMEOS)
sky@chromium.org29cf16772010-04-21 15:13:471648void MetricsService::StartExternalMetrics() {
rvargas@google.com5ccaa412009-11-13 22:00:161649 external_metrics_ = new chromeos::ExternalMetrics;
sky@chromium.org29cf16772010-04-21 15:13:471650 external_metrics_->Start();
rvargas@google.com5ccaa412009-11-13 22:00:161651}
1652#endif
sreeram@chromium.org3819f2ee2011-08-21 09:44:381653
1654// static
1655bool MetricsServiceHelper::IsMetricsReportingEnabled() {
1656 bool result = false;
1657 const PrefService* local_state = g_browser_process->local_state();
1658 if (local_state) {
1659 const PrefService::Preference* uma_pref =
1660 local_state->FindPreference(prefs::kMetricsReportingEnabled);
1661 if (uma_pref) {
1662 bool success = uma_pref->GetValue()->GetAsBoolean(&result);
1663 DCHECK(success);
1664 }
1665 }
1666 return result;
1667}