blob: c0ac0e04d7a3ed43d1b3994c6245b54d5e78986a [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"
jam@chromium.org3a7b66d2012-04-26 16:34:16155#include "base/threading/thread_restrictions.h"
isherman@chromium.orged0fd002012-04-25 23:10:34156#include "base/tracked_objects.h"
viettrungluu@chromium.org440b37b22010-08-30 05:31:40157#include "base/utf_string_conversions.h"
erg@google.com679082052010-07-21 21:30:13158#include "base/values.h"
sky@google.comd8e41ed2008-09-11 15:22:32159#include "chrome/browser/bookmarks/bookmark_model.h"
initial.commit09911bf2008-07-26 23:55:29160#include "chrome/browser/browser_process.h"
aa@chromium.org6f371442011-11-09 06:45:46161#include "chrome/browser/extensions/extension_service.h"
162#include "chrome/browser/extensions/process_map.h"
isherman@chromium.orgb8ddb052012-04-19 02:36:06163#include "chrome/browser/io_thread.h"
sail@chromium.org84c988a2011-04-19 17:56:33164#include "chrome/browser/memory_details.h"
phajdan.jr@chromium.org7c927b62010-02-24 09:54:13165#include "chrome/browser/metrics/histogram_synchronizer.h"
erg@google.com679082052010-07-21 21:30:13166#include "chrome/browser/metrics/metrics_log.h"
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10167#include "chrome/browser/metrics/metrics_log_serializer.h"
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16168#include "chrome/browser/metrics/metrics_reporting_scheduler.h"
isherman@chromium.orged0fd002012-04-25 23:10:34169#include "chrome/browser/metrics/tracking_synchronizer.h"
simonjam@chromium.orgadbb3762012-03-09 22:20:08170#include "chrome/browser/net/http_pipelining_compatibility_client.h"
rtenneti@chromium.orgd67d1052011-06-09 05:11:41171#include "chrome/browser/net/network_stats.h"
evan@chromium.org37858e52010-08-26 00:22:02172#include "chrome/browser/prefs/pref_service.h"
battre@chromium.orgf8628c22011-04-05 12:10:18173#include "chrome/browser/prefs/scoped_user_pref_update.h"
ben@chromium.org8ecad5e2010-12-02 21:18:33174#include "chrome/browser/profiles/profile.h"
erg@google.com8e5c89a2011-06-07 18:13:33175#include "chrome/browser/search_engines/template_url_service.h"
tfarina@chromium.org71b73f02011-04-06 15:57:29176#include "chrome/browser/ui/browser_list.h"
kuchhal@chromium.org157d5472009-11-05 22:31:03177#include "chrome/common/child_process_logging.h"
ananta@chromium.org432115822011-07-10 15:52:27178#include "chrome/common/chrome_notification_types.h"
jar@chromium.org92745242009-06-12 16:52:21179#include "chrome/common/chrome_switches.h"
sergeyu@chromium.org3eb0d8f72010-12-15 23:38:25180#include "chrome/common/guid.h"
isherman@chromium.org2e4cd1a2012-01-12 08:51:03181#include "chrome/common/metrics/metrics_log_manager.h"
simonjam@chromium.orgb4a72d842012-03-22 20:09:09182#include "chrome/common/net/test_server_locations.h"
initial.commit09911bf2008-07-26 23:55:29183#include "chrome/common/pref_names.h"
jam@chromium.orge09ba552009-02-05 03:26:29184#include "chrome/common/render_messages.h"
jam@chromium.org4967f792012-01-20 22:14:40185#include "content/public/browser/child_process_data.h"
tfarina@chromium.org09d31d52012-03-11 22:30:27186#include "content/public/browser/load_notification_details.h"
jam@chromium.orgad50def52011-10-19 23:17:07187#include "content/public/browser/notification_service.h"
jam@chromium.org3a5180ae2011-12-21 02:39:38188#include "content/public/browser/plugin_service.h"
ananta@chromium.orgf3b1a082011-11-18 00:34:30189#include "content/public/browser/render_process_host.h"
jam@chromium.org36aea2702011-10-26 01:12:22190#include "content/public/common/url_fetcher.h"
isherman@chromium.orgfe58acc22012-02-29 01:29:58191#include "net/base/load_flags.h"
cpu@chromium.org91d9f3d2011-08-14 05:24:44192#include "webkit/plugins/webplugininfo.h"
initial.commit09911bf2008-07-26 23:55:29193
phajdan.jr@chromium.orge06131d2010-02-10 18:40:33194// TODO(port): port browser_distribution.h.
195#if !defined(OS_POSIX)
kuchhal@chromium.org79bf0b72009-04-27 21:30:55196#include "chrome/installer/util/browser_distribution.h"
paul@chromium.orgdc6f4962009-02-13 01:25:50197#endif
198
rvargas@google.com5ccaa412009-11-13 22:00:16199#if defined(OS_CHROMEOS)
stevenjb@chromium.orgdb342d52010-08-09 21:19:37200#include "chrome/browser/chromeos/cros/cros_library.h"
rvargas@google.com5ccaa412009-11-13 22:00:16201#include "chrome/browser/chromeos/external_metrics.h"
satorux@chromium.orgd43970a72011-07-10 06:24:52202#include "chrome/browser/chromeos/system/statistics_provider.h"
rvargas@google.com5ccaa412009-11-13 22:00:16203#endif
204
dsh@google.come1acf6f2008-10-27 20:43:33205using base::Time;
joi@chromium.org631bb742011-11-02 11:29:39206using content::BrowserThread;
jam@chromium.org4967f792012-01-20 22:14:40207using content::ChildProcessData;
tfarina@chromium.org09d31d52012-03-11 22:30:27208using content::LoadNotificationDetails;
jam@chromium.org3a5180ae2011-12-21 02:39:38209using content::PluginService;
dsh@google.come1acf6f2008-10-27 20:43:33210
isherman@chromium.orgfe58acc22012-02-29 01:29:58211namespace {
isherman@chromium.orgb2a4812d2012-02-28 05:31:31212
isherman@chromium.orgfe58acc22012-02-29 01:29:58213// Check to see that we're being called on only one thread.
214bool IsSingleThreaded() {
215 static base::PlatformThreadId thread_id = 0;
216 if (!thread_id)
217 thread_id = base::PlatformThread::CurrentId();
218 return base::PlatformThread::CurrentId() == thread_id;
219}
220
221const char kMetricsTypeXml[] = "application/vnd.mozilla.metrics.bz2";
222const char kMetricsTypeProto[] = "application/vnd.chrome.uma";
223
224const char kServerUrlXml[] =
225 "https://clients4.google.com/firefox/metrics/collect";
226const char kServerUrlProto[] = "https://clients4.google.com/uma/v2";
initial.commit09911bf2008-07-26 23:55:29227
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16228// The delay, in seconds, after starting recording before doing expensive
229// initialization work.
isherman@chromium.orgfe58acc22012-02-29 01:29:58230const int kInitializationDelaySeconds = 30;
petersont@google.com252873ef2008-08-04 21:59:45231
jar@chromium.orgc9a3ef82009-05-28 22:02:46232// This specifies the amount of time to wait for all renderers to send their
233// data.
isherman@chromium.orgfe58acc22012-02-29 01:29:58234const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
jar@chromium.orgc9a3ef82009-05-28 22:02:46235
stuartmorgan@chromium.org54702c92011-04-15 15:06:43236// The maximum number of events in a log uploaded to the UMA server.
isherman@chromium.orgfe58acc22012-02-29 01:29:58237const int kEventLimit = 2400;
jar@google.com68475e602008-08-22 03:21:15238
239// If an upload fails, and the transmission was over this byte count, then we
240// will discard the log, and not try to retransmit it. We also don't persist
241// the log to the prefs for transmission during the next chrome session if this
242// limit is exceeded.
isherman@chromium.orgfe58acc22012-02-29 01:29:58243const size_t kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29244
tedvessenes@gmail.comfc4252a72012-01-12 21:58:47245// Interval, in minutes, between state saves.
isherman@chromium.orgfe58acc22012-02-29 01:29:58246const int kSaveStateIntervalMinutes = 5;
247
isherman@chromium.org6b44e9b52012-03-27 07:46:19248// Used to indicate that the response code is currently not set at all --
249// RESPONSE_CODE_INVALID can sometimes be returned in response to a request if,
250// e.g., the server is down.
251const int kNoResponseCode = content::URLFetcher::RESPONSE_CODE_INVALID - 1;
252
isherman@chromium.orgfe58acc22012-02-29 01:29:58253}
initial.commit09911bf2008-07-26 23:55:29254
jar@chromium.orgc0c55e92011-09-10 18:47:30255// static
256MetricsService::ShutdownCleanliness MetricsService::clean_shutdown_status_ =
257 MetricsService::CLEANLY_SHUTDOWN;
258
erg@google.com679082052010-07-21 21:30:13259// This is used to quickly log stats from child process related notifications in
260// MetricsService::child_stats_buffer_. The buffer's contents are transferred
261// out when Local State is periodically saved. The information is then
262// reported to the UMA server on next launch.
263struct MetricsService::ChildProcessStats {
264 public:
jam@chromium.orgbd5d6cf2011-12-01 00:39:12265 explicit ChildProcessStats(content::ProcessType type)
erg@google.com679082052010-07-21 21:30:13266 : process_launches(0),
267 process_crashes(0),
268 instances(0),
269 process_type(type) {}
270
271 // This constructor is only used by the map to return some default value for
272 // an index for which no value has been assigned.
273 ChildProcessStats()
274 : process_launches(0),
pkasting@chromium.orgd88bf0a2011-08-30 23:55:57275 process_crashes(0),
276 instances(0),
jam@chromium.orgbd5d6cf2011-12-01 00:39:12277 process_type(content::PROCESS_TYPE_UNKNOWN) {}
erg@google.com679082052010-07-21 21:30:13278
279 // The number of times that the given child process has been launched
280 int process_launches;
281
282 // The number of times that the given child process has crashed
283 int process_crashes;
284
285 // The number of instances of this child process that have been created.
286 // An instance is a DOM object rendered by this child process during a page
287 // load.
288 int instances;
289
jam@chromium.orgbd5d6cf2011-12-01 00:39:12290 content::ProcessType process_type;
erg@google.com679082052010-07-21 21:30:13291};
initial.commit09911bf2008-07-26 23:55:29292
sail@chromium.org84c988a2011-04-19 17:56:33293// Handles asynchronous fetching of memory details.
294// Will run the provided task after finished.
295class MetricsMemoryDetails : public MemoryDetails {
296 public:
dcheng@chromium.org2226c222011-11-22 00:08:40297 explicit MetricsMemoryDetails(const base::Closure& callback)
298 : callback_(callback) {}
sail@chromium.org84c988a2011-04-19 17:56:33299
300 virtual void OnDetailsAvailable() {
dcheng@chromium.org2226c222011-11-22 00:08:40301 MessageLoop::current()->PostTask(FROM_HERE, callback_);
sail@chromium.org84c988a2011-04-19 17:56:33302 }
303
304 private:
305 ~MetricsMemoryDetails() {}
306
dcheng@chromium.org2226c222011-11-22 00:08:40307 base::Closure callback_;
sail@chromium.org84c988a2011-04-19 17:56:33308 DISALLOW_COPY_AND_ASSIGN(MetricsMemoryDetails);
309};
310
initial.commit09911bf2008-07-26 23:55:29311// static
312void MetricsService::RegisterPrefs(PrefService* local_state) {
313 DCHECK(IsSingleThreaded());
estade@chromium.org20ce516d2010-06-18 02:20:04314 local_state->RegisterStringPref(prefs::kMetricsClientID, "");
robertshield@google.com0bb1a622009-03-04 03:22:32315 local_state->RegisterInt64Pref(prefs::kMetricsClientIDTimestamp, 0);
316 local_state->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
317 local_state->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
estade@chromium.org20ce516d2010-06-18 02:20:04318 local_state->RegisterStringPref(prefs::kStabilityStatsVersion, "");
jar@chromium.org225c50842010-01-19 21:19:13319 local_state->RegisterInt64Pref(prefs::kStabilityStatsBuildTime, 0);
initial.commit09911bf2008-07-26 23:55:29320 local_state->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
321 local_state->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
322 local_state->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
323 local_state->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
324 local_state->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
325 local_state->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount,
326 0);
327 local_state->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
initial.commit09911bf2008-07-26 23:55:29328 local_state->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
asargent@chromium.org1f085622009-12-04 05:33:45329 local_state->RegisterIntegerPref(prefs::kStabilityExtensionRendererCrashCount,
330 0);
initial.commit09911bf2008-07-26 23:55:29331 local_state->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
asargent@chromium.org1f085622009-12-04 05:33:45332 local_state->RegisterIntegerPref(prefs::kStabilityChildProcessCrashCount, 0);
cpu@google.come73c01972008-08-13 00:18:24333 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail,
334 0);
335 local_state->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
336 0);
337 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
338 local_state->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
petkov@chromium.orgc1834a92011-01-21 18:21:03339#if defined(OS_CHROMEOS)
340 local_state->RegisterIntegerPref(prefs::kStabilityOtherUserCrashCount, 0);
341 local_state->RegisterIntegerPref(prefs::kStabilityKernelCrashCount, 0);
342 local_state->RegisterIntegerPref(prefs::kStabilitySystemUncleanShutdownCount,
343 0);
344#endif // OS_CHROMEOS
cpu@google.come73c01972008-08-13 00:18:24345
initial.commit09911bf2008-07-26 23:55:29346 local_state->RegisterDictionaryPref(prefs::kProfileMetrics);
347 local_state->RegisterIntegerPref(prefs::kNumBookmarksOnBookmarkBar, 0);
348 local_state->RegisterIntegerPref(prefs::kNumFoldersOnBookmarkBar, 0);
349 local_state->RegisterIntegerPref(prefs::kNumBookmarksInOtherBookmarkFolder,
350 0);
351 local_state->RegisterIntegerPref(prefs::kNumFoldersInOtherBookmarkFolder, 0);
352 local_state->RegisterIntegerPref(prefs::kNumKeywords, 0);
isherman@chromium.orgfe58acc22012-02-29 01:29:58353 local_state->RegisterListPref(prefs::kMetricsInitialLogsXml);
354 local_state->RegisterListPref(prefs::kMetricsOngoingLogsXml);
355 local_state->RegisterListPref(prefs::kMetricsInitialLogsProto);
356 local_state->RegisterListPref(prefs::kMetricsOngoingLogsProto);
robertshield@google.com0bb1a622009-03-04 03:22:32357
358 local_state->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
359 local_state->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
robertshield@google.com6b5f21d2009-04-13 17:01:35360 local_state->RegisterInt64Pref(prefs::kUninstallMetricsInstallDate, 0);
robertshield@google.com0bb1a622009-03-04 03:22:32361 local_state->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
362 local_state->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
363 local_state->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
initial.commit09911bf2008-07-26 23:55:29364}
365
jar@chromium.org541f77922009-02-23 21:14:38366// static
367void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
368 local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
jar@chromium.orgc9abf242009-07-18 06:00:38369 local_state->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
jar@chromium.org541f77922009-02-23 21:14:38370
371 local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
372 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
373 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
374 local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
375 local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
376
377 local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
378 local_state->SetInteger(prefs::kStabilityCrashCount, 0);
379
380 local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
381 local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
382 local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
383
jar@chromium.org9165f742010-03-10 22:55:01384 local_state->SetInt64(prefs::kStabilityLaunchTimeSec, 0);
385 local_state->SetInt64(prefs::kStabilityLastTimestampSec, 0);
jar@chromium.org541f77922009-02-23 21:14:38386
387 local_state->ClearPref(prefs::kStabilityPluginStats);
jar@chromium.orgae155cb92009-06-19 06:10:37388
isherman@chromium.orgfe58acc22012-02-29 01:29:58389 local_state->ClearPref(prefs::kMetricsInitialLogsXml);
390 local_state->ClearPref(prefs::kMetricsOngoingLogsXml);
391 local_state->ClearPref(prefs::kMetricsInitialLogsProto);
392 local_state->ClearPref(prefs::kMetricsOngoingLogsProto);
jar@chromium.org541f77922009-02-23 21:14:38393}
394
initial.commit09911bf2008-07-26 23:55:29395MetricsService::MetricsService()
petersont@google.comd01b8732008-10-16 02:18:07396 : recording_active_(false),
397 reporting_active_(false),
petersont@google.comd01b8732008-10-16 02:18:07398 state_(INITIALIZED),
petersont@google.comd01b8732008-10-16 02:18:07399 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29400 next_window_id_(0),
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40401 ALLOW_THIS_IN_INITIALIZER_LIST(self_ptr_factory_(this)),
maruel@chromium.org40bcc302009-03-02 20:50:39402 ALLOW_THIS_IN_INITIALIZER_LIST(state_saver_factory_(this)),
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16403 waiting_for_asynchronus_reporting_step_(false) {
initial.commit09911bf2008-07-26 23:55:29404 DCHECK(IsSingleThreaded());
405 InitializeMetricsState();
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16406
407 base::Closure callback = base::Bind(&MetricsService::StartScheduledUpload,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40408 self_ptr_factory_.GetWeakPtr());
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16409 scheduler_.reset(new MetricsReportingScheduler(callback));
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10410 log_manager_.set_log_serializer(new MetricsLogSerializer());
411 log_manager_.set_max_ongoing_log_store_size(kUploadLogAvoidRetransmitSize);
initial.commit09911bf2008-07-26 23:55:29412}
413
414MetricsService::~MetricsService() {
415 SetRecording(false);
416}
417
petersont@google.comd01b8732008-10-16 02:18:07418void MetricsService::Start() {
stuartmorgan@chromium.orgb1c8dc02011-04-13 18:32:04419 HandleIdleSinceLastTransmission(false);
petersont@google.comd01b8732008-10-16 02:18:07420 SetRecording(true);
421 SetReporting(true);
422}
423
424void MetricsService::StartRecordingOnly() {
425 SetRecording(true);
426 SetReporting(false);
427}
428
429void MetricsService::Stop() {
stuartmorgan@chromium.orgb1c8dc02011-04-13 18:32:04430 HandleIdleSinceLastTransmission(false);
petersont@google.comd01b8732008-10-16 02:18:07431 SetReporting(false);
432 SetRecording(false);
433}
434
joi@chromium.orgedafd4c2011-05-10 17:18:53435std::string MetricsService::GetClientId() {
436 return client_id_;
437}
438
jam@chromium.org5cbeeef72012-02-08 02:05:18439void MetricsService::ForceClientIdCreation() {
440 if (!client_id_.empty())
441 return;
442 PrefService* pref = g_browser_process->local_state();
443 client_id_ = pref->GetString(prefs::kMetricsClientID);
444 if (!client_id_.empty())
445 return;
446
447 client_id_ = GenerateClientID();
448 pref->SetString(prefs::kMetricsClientID, client_id_);
449
450 // Might as well make a note of how long this ID has existed
451 pref->SetString(prefs::kMetricsClientIDTimestamp,
452 base::Int64ToString(Time::Now().ToTimeT()));
453}
454
initial.commit09911bf2008-07-26 23:55:29455void MetricsService::SetRecording(bool enabled) {
456 DCHECK(IsSingleThreaded());
457
petersont@google.comd01b8732008-10-16 02:18:07458 if (enabled == recording_active_)
initial.commit09911bf2008-07-26 23:55:29459 return;
460
461 if (enabled) {
jam@chromium.org5cbeeef72012-02-08 02:05:18462 ForceClientIdCreation();
kuchhal@chromium.org157d5472009-11-05 22:31:03463 child_process_logging::SetClientId(client_id_);
initial.commit09911bf2008-07-26 23:55:29464 StartRecording();
pkasting@chromium.org005ef3e2009-05-22 20:55:46465
stuartmorgan@chromium.org3ffd3ae2011-03-17 22:17:52466 SetUpNotifications(&registrar_, this);
initial.commit09911bf2008-07-26 23:55:29467 } else {
pkasting@chromium.org005ef3e2009-05-22 20:55:46468 registrar_.RemoveAll();
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10469 PushPendingLogsToPersistentStorage();
470 DCHECK(!log_manager_.has_staged_log());
471 if (state_ > INITIAL_LOG_READY && log_manager_.has_unsent_logs())
472 state_ = SENDING_OLD_LOGS;
initial.commit09911bf2008-07-26 23:55:29473 }
petersont@google.comd01b8732008-10-16 02:18:07474 recording_active_ = enabled;
initial.commit09911bf2008-07-26 23:55:29475}
476
petersont@google.comd01b8732008-10-16 02:18:07477bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29478 DCHECK(IsSingleThreaded());
petersont@google.comd01b8732008-10-16 02:18:07479 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29480}
481
petersont@google.comd01b8732008-10-16 02:18:07482void MetricsService::SetReporting(bool enable) {
483 if (reporting_active_ != enable) {
484 reporting_active_ = enable;
485 if (reporting_active_)
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16486 StartSchedulerIfNecessary();
initial.commit09911bf2008-07-26 23:55:29487 }
petersont@google.comd01b8732008-10-16 02:18:07488}
489
490bool MetricsService::reporting_active() const {
491 DCHECK(IsSingleThreaded());
492 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29493}
494
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15495// static
jam@chromium.org6c2381d2011-10-19 02:52:53496void MetricsService::SetUpNotifications(
497 content::NotificationRegistrar* registrar,
498 content::NotificationObserver* observer) {
499 registrar->Add(observer, chrome::NOTIFICATION_BROWSER_OPENED,
jam@chromium.orgad50def52011-10-19 23:17:07500 content::NotificationService::AllBrowserContextsAndSources());
jam@chromium.org6c2381d2011-10-19 02:52:53501 registrar->Add(observer, chrome::NOTIFICATION_BROWSER_CLOSED,
jam@chromium.orgad50def52011-10-19 23:17:07502 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53503 registrar->Add(observer, content::NOTIFICATION_USER_ACTION,
jam@chromium.orgad50def52011-10-19 23:17:07504 content::NotificationService::AllSources());
avi@chromium.org884033e2012-04-16 19:38:42505 registrar->Add(observer, chrome::NOTIFICATION_TAB_PARENTED,
jam@chromium.orgad50def52011-10-19 23:17:07506 content::NotificationService::AllSources());
avi@chromium.org884033e2012-04-16 19:38:42507 registrar->Add(observer, chrome::NOTIFICATION_TAB_CLOSING,
jam@chromium.orgad50def52011-10-19 23:17:07508 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53509 registrar->Add(observer, content::NOTIFICATION_LOAD_START,
jam@chromium.orgad50def52011-10-19 23:17:07510 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53511 registrar->Add(observer, content::NOTIFICATION_LOAD_STOP,
jam@chromium.orgad50def52011-10-19 23:17:07512 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53513 registrar->Add(observer, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
jam@chromium.orgad50def52011-10-19 23:17:07514 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53515 registrar->Add(observer, content::NOTIFICATION_RENDERER_PROCESS_HANG,
jam@chromium.orgad50def52011-10-19 23:17:07516 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53517 registrar->Add(observer, content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED,
jam@chromium.orgad50def52011-10-19 23:17:07518 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53519 registrar->Add(observer, content::NOTIFICATION_CHILD_INSTANCE_CREATED,
jam@chromium.orgad50def52011-10-19 23:17:07520 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53521 registrar->Add(observer, content::NOTIFICATION_CHILD_PROCESS_CRASHED,
jam@chromium.orgad50def52011-10-19 23:17:07522 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53523 registrar->Add(observer, chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED,
jam@chromium.orgad50def52011-10-19 23:17:07524 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53525 registrar->Add(observer, chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
jam@chromium.orgad50def52011-10-19 23:17:07526 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53527 registrar->Add(observer, chrome::NOTIFICATION_BOOKMARK_MODEL_LOADED,
jam@chromium.orgad50def52011-10-19 23:17:07528 content::NotificationService::AllBrowserContextsAndSources());
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15529}
530
ananta@chromium.org432115822011-07-10 15:52:27531void MetricsService::Observe(int type,
jam@chromium.org6c2381d2011-10-19 02:52:53532 const content::NotificationSource& source,
533 const content::NotificationDetails& details) {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10534 DCHECK(log_manager_.current_log());
initial.commit09911bf2008-07-26 23:55:29535 DCHECK(IsSingleThreaded());
536
537 if (!CanLogNotification(type, source, details))
538 return;
539
ananta@chromium.org432115822011-07-10 15:52:27540 switch (type) {
541 case content::NOTIFICATION_USER_ACTION:
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10542 log_manager_.current_log()->RecordUserAction(
jam@chromium.org6c2381d2011-10-19 02:52:53543 *content::Details<const char*>(details).ptr());
initial.commit09911bf2008-07-26 23:55:29544 break;
545
ananta@chromium.org432115822011-07-10 15:52:27546 case chrome::NOTIFICATION_BROWSER_OPENED:
547 case chrome::NOTIFICATION_BROWSER_CLOSED:
initial.commit09911bf2008-07-26 23:55:29548 LogWindowChange(type, source, details);
549 break;
550
avi@chromium.org884033e2012-04-16 19:38:42551 case chrome::NOTIFICATION_TAB_PARENTED:
552 case chrome::NOTIFICATION_TAB_CLOSING:
initial.commit09911bf2008-07-26 23:55:29553 LogWindowChange(type, source, details);
554 break;
555
ananta@chromium.org432115822011-07-10 15:52:27556 case content::NOTIFICATION_LOAD_STOP:
initial.commit09911bf2008-07-26 23:55:29557 LogLoadComplete(type, source, details);
558 break;
559
ananta@chromium.org432115822011-07-10 15:52:27560 case content::NOTIFICATION_LOAD_START:
initial.commit09911bf2008-07-26 23:55:29561 LogLoadStarted();
562 break;
563
ananta@chromium.org432115822011-07-10 15:52:27564 case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: {
ananta@chromium.orgf3b1a082011-11-18 00:34:30565 content::RenderProcessHost::RendererClosedDetails* process_details =
566 content::Details<
567 content::RenderProcessHost::RendererClosedDetails>(
568 details).ptr();
569 content::RenderProcessHost* host =
570 content::Source<content::RenderProcessHost>(source).ptr();
jar@chromium.orgc3721482012-03-23 16:21:48571 LogRendererCrash(
572 host, process_details->status, process_details->was_alive);
asargent@chromium.org1f085622009-12-04 05:33:45573 }
initial.commit09911bf2008-07-26 23:55:29574 break;
575
ananta@chromium.org432115822011-07-10 15:52:27576 case content::NOTIFICATION_RENDERER_PROCESS_HANG:
initial.commit09911bf2008-07-26 23:55:29577 LogRendererHang();
578 break;
579
ananta@chromium.org432115822011-07-10 15:52:27580 case content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED:
581 case content::NOTIFICATION_CHILD_PROCESS_CRASHED:
582 case content::NOTIFICATION_CHILD_INSTANCE_CREATED:
jam@chromium.orga27a9382009-02-11 23:55:10583 LogChildProcessChange(type, source, details);
initial.commit09911bf2008-07-26 23:55:29584 break;
585
ananta@chromium.org432115822011-07-10 15:52:27586 case chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED:
pkasting@chromium.org604d8a062012-03-16 21:37:46587 LogKeywordCount(content::Source<TemplateURLService>(
588 source)->GetTemplateURLs().size());
initial.commit09911bf2008-07-26 23:55:29589 break;
590
ananta@chromium.org432115822011-07-10 15:52:27591 case chrome::NOTIFICATION_OMNIBOX_OPENED_URL: {
isherman@chromium.org279703f2012-01-20 22:23:26592 MetricsLog* current_log =
593 static_cast<MetricsLog*>(log_manager_.current_log());
ananta@chromium.org1226abb2010-06-10 18:01:28594 DCHECK(current_log);
595 current_log->RecordOmniboxOpenedURL(
jam@chromium.org6c2381d2011-10-19 02:52:53596 *content::Details<AutocompleteLog>(details).ptr());
initial.commit09911bf2008-07-26 23:55:29597 break;
ananta@chromium.org1226abb2010-06-10 18:01:28598 }
initial.commit09911bf2008-07-26 23:55:29599
ananta@chromium.org432115822011-07-10 15:52:27600 case chrome::NOTIFICATION_BOOKMARK_MODEL_LOADED: {
jam@chromium.org6c2381d2011-10-19 02:52:53601 Profile* p = content::Source<Profile>(source).ptr();
tim@chromium.orgb61236c62009-04-09 22:43:55602 if (p)
603 LogBookmarks(p->GetBookmarkModel());
initial.commit09911bf2008-07-26 23:55:29604 break;
tim@chromium.orgb61236c62009-04-09 22:43:55605 }
initial.commit09911bf2008-07-26 23:55:29606 default:
jar@chromium.orga063c102010-07-22 22:20:19607 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:29608 break;
609 }
petersont@google.comd01b8732008-10-16 02:18:07610
611 HandleIdleSinceLastTransmission(false);
612
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10613 if (log_manager_.current_log())
614 DVLOG(1) << "METRICS: NUMBER OF EVENTS = "
615 << log_manager_.current_log()->num_events();
petersont@google.comd01b8732008-10-16 02:18:07616}
617
618void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
619 // If there wasn't a lot of action, maybe the computer was asleep, in which
620 // case, the log transmissions should have stopped. Here we start them up
621 // again.
pkasting@chromium.orgcac78842008-11-27 01:02:20622 if (!in_idle && idle_since_last_transmission_)
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16623 StartSchedulerIfNecessary();
pkasting@chromium.orgcac78842008-11-27 01:02:20624 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29625}
626
initial.commit09911bf2008-07-26 23:55:29627void MetricsService::RecordStartOfSessionEnd() {
stuartmorgan@chromium.org466f3c12011-03-23 21:20:38628 LogCleanShutdown();
initial.commit09911bf2008-07-26 23:55:29629 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
630}
631
632void MetricsService::RecordCompletedSessionEnd() {
stuartmorgan@chromium.org466f3c12011-03-23 21:20:38633 LogCleanShutdown();
initial.commit09911bf2008-07-26 23:55:29634 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
635}
636
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16637void MetricsService::RecordBreakpadRegistration(bool success) {
jar@google.com68475e602008-08-22 03:21:15638 if (!success)
cpu@google.come73c01972008-08-13 00:18:24639 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
640 else
641 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
642}
643
644void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
645 if (!has_debugger)
646 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
647 else
jar@google.com68475e602008-08-22 03:21:15648 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
cpu@google.come73c01972008-08-13 00:18:24649}
650
initial.commit09911bf2008-07-26 23:55:29651//------------------------------------------------------------------------------
652// private methods
653//------------------------------------------------------------------------------
654
655
656//------------------------------------------------------------------------------
657// Initialization methods
658
659void MetricsService::InitializeMetricsState() {
kuchhal@chromium.org79bf0b72009-04-27 21:30:55660#if defined(OS_POSIX)
isherman@chromium.orgfe58acc22012-02-29 01:29:58661 server_url_xml_ = ASCIIToUTF16(kServerUrlXml);
662 server_url_proto_ = ASCIIToUTF16(kServerUrlProto);
simonjam@chromium.orgb4a72d842012-03-22 20:09:09663 network_stats_server_ = chrome_common_net::kEchoTestServerLocation;
664 http_pipelining_test_server_ = chrome_common_net::kPipelineTestServerBaseUrl;
kuchhal@chromium.org79bf0b72009-04-27 21:30:55665#else
666 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
isherman@chromium.orgfe58acc22012-02-29 01:29:58667 server_url_xml_ = dist->GetStatsServerURL();
668 server_url_proto_ = ASCIIToUTF16(kServerUrlProto);
rtenneti@chromium.orgd67d1052011-06-09 05:11:41669 network_stats_server_ = dist->GetNetworkStatsServer();
simonjam@chromium.orgadbb3762012-03-09 22:20:08670 http_pipelining_test_server_ = dist->GetHttpPipeliningTestServer();
kuchhal@chromium.org79bf0b72009-04-27 21:30:55671#endif
672
initial.commit09911bf2008-07-26 23:55:29673 PrefService* pref = g_browser_process->local_state();
674 DCHECK(pref);
675
jar@chromium.org225c50842010-01-19 21:19:13676 if ((pref->GetInt64(prefs::kStabilityStatsBuildTime)
677 != MetricsLog::GetBuildTime()) ||
estade@chromium.orgddd231e2010-06-29 20:35:19678 (pref->GetString(prefs::kStabilityStatsVersion)
jar@chromium.org225c50842010-01-19 21:19:13679 != MetricsLog::GetVersionString())) {
jar@chromium.org541f77922009-02-23 21:14:38680 // This is a new version, so we don't want to confuse the stats about the
681 // old version with info that we upload.
682 DiscardOldStabilityStats(pref);
683 pref->SetString(prefs::kStabilityStatsVersion,
estade@chromium.orgddd231e2010-06-29 20:35:19684 MetricsLog::GetVersionString());
jar@chromium.org225c50842010-01-19 21:19:13685 pref->SetInt64(prefs::kStabilityStatsBuildTime,
686 MetricsLog::GetBuildTime());
jar@chromium.org541f77922009-02-23 21:14:38687 }
688
initial.commit09911bf2008-07-26 23:55:29689 // Update session ID
690 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
691 ++session_id_;
692 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
693
initial.commit09911bf2008-07-26 23:55:29694 // Stability bookkeeping
cpu@google.come73c01972008-08-13 00:18:24695 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29696
cpu@google.come73c01972008-08-13 00:18:24697 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
698 IncrementPrefValue(prefs::kStabilityCrashCount);
jar@chromium.orgc0c55e92011-09-10 18:47:30699 // Reset flag, and wait until we call LogNeedForCleanShutdown() before
700 // monitoring.
701 pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
initial.commit09911bf2008-07-26 23:55:29702 }
cpu@google.come73c01972008-08-13 00:18:24703
cpu@google.come73c01972008-08-13 00:18:24704 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
705 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
jar@chromium.orgc9abf242009-07-18 06:00:38706 // This is marked false when we get a WM_ENDSESSION.
707 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
initial.commit09911bf2008-07-26 23:55:29708 }
initial.commit09911bf2008-07-26 23:55:29709
jar@chromium.org9165f742010-03-10 22:55:01710 // Initialize uptime counters.
711 int64 startup_uptime = MetricsLog::GetIncrementalUptime(pref);
mad@google.comae393ec702010-06-27 16:23:14712 DCHECK_EQ(0, startup_uptime);
jar@chromium.org9165f742010-03-10 22:55:01713 // For backwards compatibility, leave this intact in case Omaha is checking
714 // them. prefs::kStabilityLastTimestampSec may also be useless now.
715 // TODO(jar): Delete these if they have no uses.
robertshield@google.com0bb1a622009-03-04 03:22:32716 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
717
718 // Bookkeeping for the uninstall metrics.
719 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29720
721 // Save profile metrics.
722 PrefService* prefs = g_browser_process->local_state();
723 if (prefs) {
724 // Remove the current dictionary and store it for use when sending data to
725 // server. By removing the value we prune potentially dead profiles
726 // (and keys). All valid values are added back once services startup.
727 const DictionaryValue* profile_dictionary =
728 prefs->GetDictionary(prefs::kProfileMetrics);
729 if (profile_dictionary) {
730 // Do a deep copy of profile_dictionary since ClearPref will delete it.
731 profile_dictionary_.reset(static_cast<DictionaryValue*>(
732 profile_dictionary->DeepCopy()));
733 prefs->ClearPref(prefs::kProfileMetrics);
734 }
735 }
736
jar@chromium.org92745242009-06-12 16:52:21737 // Get stats on use of command line.
738 const CommandLine* command_line(CommandLine::ForCurrentProcess());
739 size_t common_commands = 0;
740 if (command_line->HasSwitch(switches::kUserDataDir)) {
741 ++common_commands;
742 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
743 }
744
745 if (command_line->HasSwitch(switches::kApp)) {
746 ++common_commands;
747 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
748 }
749
msw@chromium.org62b4e522011-07-13 21:46:32750 size_t switch_count = command_line->GetSwitches().size();
751 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount", switch_count);
jar@chromium.org92745242009-06-12 16:52:21752 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
msw@chromium.org62b4e522011-07-13 21:46:32753 switch_count - common_commands);
jar@chromium.org92745242009-06-12 16:52:21754
initial.commit09911bf2008-07-26 23:55:29755 // Kick off the process of saving the state (so the uptime numbers keep
756 // getting updated) every n minutes.
757 ScheduleNextStateSave();
758}
759
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40760// static
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56761void MetricsService::InitTaskGetHardwareClass(
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40762 base::WeakPtr<MetricsService> self,
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56763 base::MessageLoopProxy* target_loop) {
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56764 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
765
766 std::string hardware_class;
767#if defined(OS_CHROMEOS)
768 chromeos::system::StatisticsProvider::GetInstance()->GetMachineStatistic(
769 "hardware_class", &hardware_class);
770#endif // OS_CHROMEOS
771
772 target_loop->PostTask(FROM_HERE,
773 base::Bind(&MetricsService::OnInitTaskGotHardwareClass,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40774 self, hardware_class));
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56775}
776
777void MetricsService::OnInitTaskGotHardwareClass(
778 const std::string& hardware_class) {
isherman@chromium.orged0fd002012-04-25 23:10:34779 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
zelidrag@chromium.org85ed9d42010-06-08 22:37:44780 hardware_class_ = hardware_class;
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56781
782 // Start the next part of the init task: loading plugin information.
783 PluginService::GetInstance()->GetPlugins(
784 base::Bind(&MetricsService::OnInitTaskGotPluginInfo,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40785 self_ptr_factory_.GetWeakPtr()));
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56786}
787
788void MetricsService::OnInitTaskGotPluginInfo(
789 const std::vector<webkit::WebPluginInfo>& plugins) {
isherman@chromium.orged0fd002012-04-25 23:10:34790 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
jam@chromium.org35fa6a22009-08-15 00:04:01791 plugins_ = plugins;
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56792
isherman@chromium.orged0fd002012-04-25 23:10:34793 // Start the next part of the init task: fetching performance data. This will
794 // call into |FinishedReceivingProfilerData()| when the task completes.
795 chrome_browser_metrics::TrackingSynchronizer::FetchProfilerDataAsynchronously(
796 self_ptr_factory_.GetWeakPtr());
797}
798
799void MetricsService::ReceivedProfilerData(
800 const tracked_objects::ProcessDataSnapshot& process_data,
801 content::ProcessType process_type) {
802 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
803
804 // Upon the first callback, create the initial log so that we can immediately
805 // save the profiler data.
806 if (!initial_log_.get())
807 initial_log_.reset(new MetricsLog(client_id_, session_id_));
808
809 initial_log_->RecordProfilerData(process_data, process_type);
810}
811
812void MetricsService::FinishedReceivingProfilerData() {
813 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
jam@chromium.org3a7b66d2012-04-26 16:34:16814 state_ = INIT_TASK_DONE;
initial.commit09911bf2008-07-26 23:55:29815}
816
817std::string MetricsService::GenerateClientID() {
dhollowa@chromium.org3469e7e2010-10-14 20:34:59818 return guid::GenerateGUID();
initial.commit09911bf2008-07-26 23:55:29819}
820
initial.commit09911bf2008-07-26 23:55:29821//------------------------------------------------------------------------------
822// State save methods
823
824void MetricsService::ScheduleNextStateSave() {
isherman@chromium.org8454aeb2011-11-19 23:38:20825 state_saver_factory_.InvalidateWeakPtrs();
initial.commit09911bf2008-07-26 23:55:29826
827 MessageLoop::current()->PostDelayedTask(FROM_HERE,
isherman@chromium.org8454aeb2011-11-19 23:38:20828 base::Bind(&MetricsService::SaveLocalState,
829 state_saver_factory_.GetWeakPtr()),
tedvessenes@gmail.comfc4252a72012-01-12 21:58:47830 base::TimeDelta::FromMinutes(kSaveStateIntervalMinutes));
initial.commit09911bf2008-07-26 23:55:29831}
832
833void MetricsService::SaveLocalState() {
834 PrefService* pref = g_browser_process->local_state();
835 if (!pref) {
jar@chromium.orga063c102010-07-22 22:20:19836 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:29837 return;
838 }
839
840 RecordCurrentState(pref);
initial.commit09911bf2008-07-26 23:55:29841
tedvessenes@gmail.comfc4252a72012-01-12 21:58:47842 // TODO(jar):110021 Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29843 ScheduleNextStateSave();
844}
845
846
847//------------------------------------------------------------------------------
848// Recording control methods
849
850void MetricsService::StartRecording() {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10851 if (log_manager_.current_log())
initial.commit09911bf2008-07-26 23:55:29852 return;
853
stuartmorgan@chromium.org29948262012-03-01 12:15:08854 log_manager_.BeginLoggingWithLog(new MetricsLog(client_id_, session_id_),
855 MetricsLogManager::ONGOING_LOG);
initial.commit09911bf2008-07-26 23:55:29856 if (state_ == INITIALIZED) {
857 // We only need to schedule that run once.
zelidrag@chromium.org85ed9d42010-06-08 22:37:44858 state_ = INIT_TASK_SCHEDULED;
initial.commit09911bf2008-07-26 23:55:29859
zelidrag@chromium.org85ed9d42010-06-08 22:37:44860 // Schedules a task on the file thread for execution of slower
861 // initialization steps (such as plugin list generation) necessary
862 // for sending the initial log. This avoids blocking the main UI
863 // thread.
joi@chromium.orged10dd12011-12-07 12:03:42864 BrowserThread::PostDelayedTask(
865 BrowserThread::FILE,
866 FROM_HERE,
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56867 base::Bind(&MetricsService::InitTaskGetHardwareClass,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40868 self_ptr_factory_.GetWeakPtr(),
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56869 MessageLoop::current()->message_loop_proxy()),
tedvessenes@gmail.com7e560102012-03-08 20:58:42870 base::TimeDelta::FromSeconds(kInitializationDelaySeconds));
initial.commit09911bf2008-07-26 23:55:29871 }
872}
873
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:38874void MetricsService::StopRecording() {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10875 if (!log_manager_.current_log())
initial.commit09911bf2008-07-26 23:55:29876 return;
877
jar@google.com68475e602008-08-22 03:21:15878 // TODO(jar): Integrate bounds on log recording more consistently, so that we
879 // can stop recording logs that are too big much sooner.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10880 if (log_manager_.current_log()->num_events() > kEventLimit) {
dsh@google.com553dba62009-02-24 19:08:23881 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10882 log_manager_.current_log()->num_events());
883 log_manager_.DiscardCurrentLog();
jar@google.com68475e602008-08-22 03:21:15884 StartRecording(); // Start trivial log to hold our histograms.
885 }
886
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10887 // Adds to ongoing logs.
888 log_manager_.current_log()->set_hardware_class(hardware_class_);
jar@chromium.orgaccdfa62011-09-20 01:56:52889
jar@google.com0b33f80b2008-12-17 21:34:36890 // Put incremental data (histogram deltas, and realtime stats deltas) at the
jar@google.com147bbc0b2009-01-06 19:37:40891 // end of all log transmissions (initial log handles this separately).
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:38892 // RecordIncrementalStabilityElements only exists on the derived
893 // MetricsLog class.
isherman@chromium.org279703f2012-01-20 22:23:26894 MetricsLog* current_log =
895 static_cast<MetricsLog*>(log_manager_.current_log());
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:38896 DCHECK(current_log);
isherman@chromium.orgbc66d532012-03-23 01:57:05897 current_log->RecordEnvironmentProto(plugins_);
isherman@chromium.orgfe58acc22012-02-29 01:29:58898 current_log->RecordIncrementalStabilityElements(plugins_);
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:38899 RecordCurrentHistograms();
initial.commit09911bf2008-07-26 23:55:29900
stuartmorgan@chromium.org29948262012-03-01 12:15:08901 log_manager_.FinishCurrentLog();
initial.commit09911bf2008-07-26 23:55:29902}
903
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10904void MetricsService::PushPendingLogsToPersistentStorage() {
initial.commit09911bf2008-07-26 23:55:29905 if (state_ < INITIAL_LOG_READY)
avi@google.com28ab7f92009-01-06 21:39:04906 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29907
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10908 if (log_manager_.has_staged_log()) {
stuartmorgan@chromium.org29948262012-03-01 12:15:08909 // We may race here, and send second copy of initial log later.
910 if (state_ == INITIAL_LOG_READY)
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10911 state_ = SENDING_OLD_LOGS;
stuartmorgan@chromium.orge7508d82012-05-03 15:59:53912 MetricsLogManager::StoreType store_type = current_fetch_xml_.get() ?
913 MetricsLogManager::PROVISIONAL_STORE : MetricsLogManager::NORMAL_STORE;
914 log_manager_.StoreStagedLogAsUnsent(store_type);
initial.commit09911bf2008-07-26 23:55:29915 }
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10916 DCHECK(!log_manager_.has_staged_log());
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:38917 StopRecording();
initial.commit09911bf2008-07-26 23:55:29918 StoreUnsentLogs();
919}
920
921//------------------------------------------------------------------------------
922// Transmission of logs methods
923
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16924void MetricsService::StartSchedulerIfNecessary() {
925 if (reporting_active() && recording_active())
926 scheduler_->Start();
initial.commit09911bf2008-07-26 23:55:29927}
928
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16929void MetricsService::StartScheduledUpload() {
930 // If reporting has been turned off, the scheduler doesn't need to run.
931 if (!reporting_active() || !recording_active()) {
932 scheduler_->Stop();
933 scheduler_->UploadCancelled();
934 return;
935 }
936
stuartmorgan@chromium.org29948262012-03-01 12:15:08937 StartFinalLogInfoCollection();
938}
939
940void MetricsService::StartFinalLogInfoCollection() {
941 // Begin the multi-step process of collecting memory usage histograms:
942 // First spawn a task to collect the memory details; when that task is
943 // finished, it will call OnMemoryDetailCollectionDone. That will in turn
944 // call HistogramSynchronization to collect histograms from all renderers and
945 // then call OnHistogramSynchronizationDone to continue processing.
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16946 DCHECK(!waiting_for_asynchronus_reporting_step_);
947 waiting_for_asynchronus_reporting_step_ = true;
948
dcheng@chromium.org2226c222011-11-22 00:08:40949 base::Closure callback =
950 base::Bind(&MetricsService::OnMemoryDetailCollectionDone,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40951 self_ptr_factory_.GetWeakPtr());
sail@chromium.org84c988a2011-04-19 17:56:33952
dcheng@chromium.org2226c222011-11-22 00:08:40953 scoped_refptr<MetricsMemoryDetails> details(
954 new MetricsMemoryDetails(callback));
jamescook@chromium.org4306df762012-04-20 18:58:57955 details->StartFetch(MemoryDetails::UPDATE_USER_METRICS);
sail@chromium.org84c988a2011-04-19 17:56:33956
957 // Collect WebCore cache information to put into a histogram.
ananta@chromium.orgf3b1a082011-11-18 00:34:30958 for (content::RenderProcessHost::iterator i(
959 content::RenderProcessHost::AllHostsIterator());
sail@chromium.org84c988a2011-04-19 17:56:33960 !i.IsAtEnd(); i.Advance())
ananta@chromium.org2ccf45c2011-08-19 23:35:50961 i.GetCurrentValue()->Send(new ChromeViewMsg_GetCacheResourceStats());
sail@chromium.org84c988a2011-04-19 17:56:33962}
963
964void MetricsService::OnMemoryDetailCollectionDone() {
jar@chromium.orgc9a3ef82009-05-28 22:02:46965 DCHECK(IsSingleThreaded());
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16966 // This function should only be called as the callback from an ansynchronous
967 // step.
968 DCHECK(waiting_for_asynchronus_reporting_step_);
jar@chromium.orgc9a3ef82009-05-28 22:02:46969
jar@chromium.orgc9a3ef82009-05-28 22:02:46970 // Create a callback_task for OnHistogramSynchronizationDone.
dcheng@chromium.org2226c222011-11-22 00:08:40971 base::Closure callback = base::Bind(
972 &MetricsService::OnHistogramSynchronizationDone,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40973 self_ptr_factory_.GetWeakPtr());
jar@chromium.orgc9a3ef82009-05-28 22:02:46974
rtenneti@chromium.org908de522011-10-20 00:55:00975 base::StatisticsRecorder::CollectHistogramStats("Browser");
976
jar@chromium.orgc9a3ef82009-05-28 22:02:46977 // Set up the callback to task to call after we receive histograms from all
978 // renderer processes. Wait time specifies how long to wait before absolutely
979 // calling us back on the task.
980 HistogramSynchronizer::FetchRendererHistogramsAsynchronously(
dcheng@chromium.org2226c222011-11-22 00:08:40981 MessageLoop::current(), callback,
tedvessenes@gmail.com7e560102012-03-08 20:58:42982 base::TimeDelta::FromMilliseconds(kMaxHistogramGatheringWaitDuration));
jar@chromium.orgc9a3ef82009-05-28 22:02:46983}
984
985void MetricsService::OnHistogramSynchronizationDone() {
initial.commit09911bf2008-07-26 23:55:29986 DCHECK(IsSingleThreaded());
stuartmorgan@chromium.org29948262012-03-01 12:15:08987 // This function should only be called as the callback from an ansynchronous
988 // step.
989 DCHECK(waiting_for_asynchronus_reporting_step_);
initial.commit09911bf2008-07-26 23:55:29990
stuartmorgan@chromium.org29948262012-03-01 12:15:08991 waiting_for_asynchronus_reporting_step_ = false;
992 OnFinalLogInfoCollectionDone();
993}
994
995void MetricsService::OnFinalLogInfoCollectionDone() {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16996 // If somehow there is a fetch in progress, we return and hope things work
997 // out. The scheduler isn't informed since if this happens, the scheduler
998 // will get a response from the upload.
isherman@chromium.orgfe58acc22012-02-29 01:29:58999 DCHECK(!current_fetch_xml_.get());
1000 DCHECK(!current_fetch_proto_.get());
1001 if (current_fetch_xml_.get() || current_fetch_proto_.get())
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161002 return;
1003
petersont@google.comd01b8732008-10-16 02:18:071004 // If we're getting no notifications, then the log won't have much in it, and
1005 // it's possible the computer is about to go to sleep, so don't upload and
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161006 // stop the scheduler.
1007 // Similarly, if logs should no longer be uploaded, stop here.
1008 if (idle_since_last_transmission_ ||
1009 !recording_active() || !reporting_active()) {
1010 scheduler_->Stop();
1011 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:071012 return;
1013 }
1014
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101015 MakeStagedLog();
initial.commit09911bf2008-07-26 23:55:291016
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101017 // MakeStagedLog should have prepared log text; if it didn't, skip this
1018 // upload and hope things work out next time.
1019 if (log_manager_.staged_log_text().empty()) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161020 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:071021 return;
1022 }
initial.commit09911bf2008-07-26 23:55:291023
stuartmorgan@chromium.org29948262012-03-01 12:15:081024 SendStagedLog();
1025}
1026
1027void MetricsService::MakeStagedLog() {
1028 if (log_manager_.has_staged_log())
1029 return;
1030
1031 switch (state_) {
1032 case INITIALIZED:
1033 case INIT_TASK_SCHEDULED: // We should be further along by now.
1034 DCHECK(false);
1035 return;
1036
1037 case INIT_TASK_DONE:
1038 // We need to wait for the initial log to be ready before sending
1039 // anything, because the server will tell us whether it wants to hear
1040 // from us.
1041 PrepareInitialLog();
isherman@chromium.orged0fd002012-04-25 23:10:341042 DCHECK_EQ(INIT_TASK_DONE, state_);
stuartmorgan@chromium.org29948262012-03-01 12:15:081043 log_manager_.LoadPersistedUnsentLogs();
1044 state_ = INITIAL_LOG_READY;
1045 break;
1046
1047 case SENDING_OLD_LOGS:
1048 if (log_manager_.has_unsent_logs()) {
1049 log_manager_.StageNextLogForUpload();
1050 break;
1051 }
1052 state_ = SENDING_CURRENT_LOGS;
1053 // Fall through.
1054
1055 case SENDING_CURRENT_LOGS:
1056 StopRecording();
1057 StartRecording();
1058 log_manager_.StageNextLogForUpload();
1059 break;
1060
1061 default:
1062 NOTREACHED();
1063 return;
1064 }
1065
1066 DCHECK(log_manager_.has_staged_log());
1067}
1068
1069void MetricsService::PrepareInitialLog() {
isherman@chromium.orged0fd002012-04-25 23:10:341070 DCHECK_EQ(INIT_TASK_DONE, state_);
stuartmorgan@chromium.org29948262012-03-01 12:15:081071
isherman@chromium.orged0fd002012-04-25 23:10:341072 DCHECK(initial_log_.get());
1073 initial_log_->set_hardware_class(hardware_class_);
1074 initial_log_->RecordEnvironment(plugins_, profile_dictionary_.get());
stuartmorgan@chromium.org29948262012-03-01 12:15:081075
1076 // Histograms only get written to the current log, so make the new log current
1077 // before writing them.
1078 log_manager_.PauseCurrentLog();
isherman@chromium.orged0fd002012-04-25 23:10:341079 log_manager_.BeginLoggingWithLog(initial_log_.release(),
1080 MetricsLogManager::INITIAL_LOG);
stuartmorgan@chromium.org29948262012-03-01 12:15:081081 RecordCurrentHistograms();
1082 log_manager_.FinishCurrentLog();
1083 log_manager_.ResumePausedLog();
1084
1085 DCHECK(!log_manager_.has_staged_log());
1086 log_manager_.StageNextLogForUpload();
1087}
1088
1089void MetricsService::StoreUnsentLogs() {
1090 if (state_ < INITIAL_LOG_READY)
1091 return; // We never Recalled the prior unsent logs.
1092
1093 log_manager_.PersistUnsentLogs();
1094}
1095
1096void MetricsService::SendStagedLog() {
1097 DCHECK(log_manager_.has_staged_log());
1098
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101099 PrepareFetchWithStagedLog();
petersont@google.comd01b8732008-10-16 02:18:071100
isherman@chromium.orgfe58acc22012-02-29 01:29:581101 if (!current_fetch_xml_.get()) {
1102 DCHECK(!current_fetch_proto_.get());
petersont@google.comd01b8732008-10-16 02:18:071103 // Compression failed, and log discarded :-/.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101104 log_manager_.DiscardStagedLog();
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161105 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:071106 // TODO(jar): If compression failed, we should have created a tiny log and
1107 // compressed that, so that we can signal that we're losing logs.
1108 return;
1109 }
isherman@chromium.orgfe58acc22012-02-29 01:29:581110 // Currently, the staged log for the protobuf version of the data is discarded
1111 // after we create the URL request, so that there is no chance for
1112 // re-transmission in case the corresponding XML request fails. We will
1113 // handle protobuf failures more carefully once that becomes the main
1114 // pipeline, i.e. once we switch away from the XML pipeline.
1115 DCHECK(current_fetch_proto_.get() || !log_manager_.has_staged_log_proto());
petersont@google.comd01b8732008-10-16 02:18:071116
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161117 DCHECK(!waiting_for_asynchronus_reporting_step_);
petersont@google.comd01b8732008-10-16 02:18:071118
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161119 waiting_for_asynchronus_reporting_step_ = true;
isherman@chromium.orgfe58acc22012-02-29 01:29:581120 current_fetch_xml_->Start();
1121 if (current_fetch_proto_.get())
1122 current_fetch_proto_->Start();
petersont@google.comd01b8732008-10-16 02:18:071123
1124 HandleIdleSinceLastTransmission(true);
1125}
1126
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101127void MetricsService::PrepareFetchWithStagedLog() {
1128 DCHECK(!log_manager_.staged_log_text().empty());
pkasting@chromium.orgcac78842008-11-27 01:02:201129
isherman@chromium.orgfe58acc22012-02-29 01:29:581130 // Prepare the XML version.
1131 DCHECK(!current_fetch_xml_.get());
1132 current_fetch_xml_.reset(content::URLFetcher::Create(
1133 GURL(server_url_xml_), content::URLFetcher::POST, this));
1134 current_fetch_xml_->SetRequestContext(
nkostylev@chromium.org8ef3d8052011-07-22 09:03:001135 g_browser_process->system_request_context());
isherman@chromium.orgfe58acc22012-02-29 01:29:581136 current_fetch_xml_->SetUploadData(kMetricsTypeXml,
1137 log_manager_.staged_log_text().xml);
1138 // We already drop cookies server-side, but we might as well strip them out
1139 // client-side as well.
1140 current_fetch_xml_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES |
1141 net::LOAD_DO_NOT_SEND_COOKIES);
1142
1143 // Prepare the protobuf version.
1144 DCHECK(!current_fetch_proto_.get());
1145 if (log_manager_.has_staged_log_proto()) {
1146 current_fetch_proto_.reset(content::URLFetcher::Create(
1147 GURL(server_url_proto_), content::URLFetcher::POST, this));
1148 current_fetch_proto_->SetRequestContext(
1149 g_browser_process->system_request_context());
1150 current_fetch_proto_->SetUploadData(kMetricsTypeProto,
1151 log_manager_.staged_log_text().proto);
1152 // We already drop cookies server-side, but we might as well strip them out
1153 // client-side as well.
1154 current_fetch_proto_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES |
1155 net::LOAD_DO_NOT_SEND_COOKIES);
1156
1157 // Discard the protobuf version of the staged log, so that we will avoid
1158 // re-uploading it even if we need to re-upload the XML version.
1159 // TODO(isherman): Handle protobuf upload failures more gracefully once we
1160 // transition away from the XML-based pipeline.
1161 log_manager_.DiscardStagedLogProto();
1162 }
initial.commit09911bf2008-07-26 23:55:291163}
1164
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441165static const char* StatusToString(const net::URLRequestStatus& status) {
initial.commit09911bf2008-07-26 23:55:291166 switch (status.status()) {
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441167 case net::URLRequestStatus::SUCCESS:
initial.commit09911bf2008-07-26 23:55:291168 return "SUCCESS";
1169
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441170 case net::URLRequestStatus::IO_PENDING:
initial.commit09911bf2008-07-26 23:55:291171 return "IO_PENDING";
1172
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441173 case net::URLRequestStatus::HANDLED_EXTERNALLY:
initial.commit09911bf2008-07-26 23:55:291174 return "HANDLED_EXTERNALLY";
1175
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441176 case net::URLRequestStatus::CANCELED:
initial.commit09911bf2008-07-26 23:55:291177 return "CANCELED";
1178
tfarina@chromium.orgf90bf0d92011-01-13 02:12:441179 case net::URLRequestStatus::FAILED:
initial.commit09911bf2008-07-26 23:55:291180 return "FAILED";
1181
1182 default:
jar@chromium.orga063c102010-07-22 22:20:191183 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291184 return "Unknown";
1185 }
1186}
1187
isherman@chromium.orgfe58acc22012-02-29 01:29:581188// We need to wait for two responses: the response to the XML upload, and the
1189// response to the protobuf upload. For now, only the XML upload's response
1190// affects decisions like whether to retry the upload, whether to abandon the
1191// upload because it is too large, etc. However, we still need to wait for the
1192// protobuf upload, as we cannot reset |current_fetch_proto_| until we have
1193// confirmation that the network request was sent; and the easiest way to do
1194// that is to wait for the response. In case the XML upload's response arrives
1195// first, we cache that response until the protobuf upload's response also
1196// arrives.
1197//
1198// Note that if the XML upload succeeds but the protobuf upload fails, we will
1199// not retry the protobuf upload. If the XML upload fails while the protobuf
1200// upload succeeds, we will still avoid re-uploading the protobuf data because
1201// we "zap" the data after the first upload attempt. This means that we might
1202// lose protobuf uploads when XML ones succeed; but we will never duplicate any
1203// protobuf uploads. Protobuf failures should be rare enough to where this
1204// should be ok while we have the two pipelines running in parallel.
jam@chromium.org7cc6e5632011-10-25 17:56:121205void MetricsService::OnURLFetchComplete(const content::URLFetcher* source) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161206 DCHECK(waiting_for_asynchronus_reporting_step_);
isherman@chromium.orgfe58acc22012-02-29 01:29:581207
1208 // We're not allowed to re-use the existing |URLFetcher|s, so free them here.
1209 scoped_ptr<content::URLFetcher> s;
1210 if (source == current_fetch_xml_.get()) {
1211 s.reset(current_fetch_xml_.release());
1212
1213 // Cache the XML responses, in case we still need to wait for the protobuf
1214 // response.
1215 response_code_ = source->GetResponseCode();
1216 response_status_ = StatusToString(source->GetStatus());
1217 source->GetResponseAsString(&response_data_);
1218 } else if (source == current_fetch_proto_.get()) {
1219 s.reset(current_fetch_proto_.release());
1220 } else {
1221 NOTREACHED();
1222 return;
1223 }
1224
1225 // If we're still waiting for one of the responses, keep waiting...
1226 if (current_fetch_xml_.get() || current_fetch_proto_.get())
1227 return;
1228
1229 // We should only be able to reach here once we've received responses to both
1230 // the XML and the protobuf requests. We should always have the response code
1231 // available.
isherman@chromium.org6b44e9b52012-03-27 07:46:191232 DCHECK_NE(response_code_, kNoResponseCode);
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161233 waiting_for_asynchronus_reporting_step_ = false;
isherman@chromium.orgfe58acc22012-02-29 01:29:581234
stuartmorgan@chromium.orge7508d82012-05-03 15:59:531235 // If the upload was provisionally stored, drop it now that the upload is
1236 // known to have gone through.
1237 log_manager_.DiscardLastProvisionalStore();
initial.commit09911bf2008-07-26 23:55:291238
1239 // Confirm send so that we can move on.
isherman@chromium.orgfe58acc22012-02-29 01:29:581240 VLOG(1) << "METRICS RESPONSE CODE: " << response_code_
1241 << " status=" << response_status_;
petersont@google.com252873ef2008-08-04 21:59:451242
isherman@chromium.orgfe58acc22012-02-29 01:29:581243 bool upload_succeeded = response_code_ == 200;
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161244
jar@chromium.org0eb34fee2009-01-21 08:04:381245 // Provide boolean for error recovery (allow us to ignore response_code).
paul@chromium.orgdc6f4962009-02-13 01:25:501246 bool discard_log = false;
jar@chromium.org0eb34fee2009-01-21 08:04:381247
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161248 if (!upload_succeeded &&
isherman@chromium.orgfe58acc22012-02-29 01:29:581249 log_manager_.staged_log_text().xml.length() >
1250 kUploadLogAvoidRetransmitSize) {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101251 UMA_HISTOGRAM_COUNTS(
1252 "UMA.Large Rejected Log was Discarded",
isherman@chromium.orgfe58acc22012-02-29 01:29:581253 static_cast<int>(log_manager_.staged_log_text().xml.length()));
jar@chromium.org0eb34fee2009-01-21 08:04:381254 discard_log = true;
isherman@chromium.orgfe58acc22012-02-29 01:29:581255 } else if (response_code_ == 400) {
jar@chromium.org0eb34fee2009-01-21 08:04:381256 // Bad syntax. Retransmission won't work.
dsh@google.com553dba62009-02-24 19:08:231257 UMA_HISTOGRAM_COUNTS("UMA.Unacceptable_Log_Discarded", state_);
jar@chromium.org0eb34fee2009-01-21 08:04:381258 discard_log = true;
jar@google.com68475e602008-08-22 03:21:151259 }
1260
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161261 if (!upload_succeeded && !discard_log) {
pkasting@chromium.org666205032010-10-21 20:56:581262 VLOG(1) << "METRICS: transmission attempt returned a failure code: "
isherman@chromium.orgfe58acc22012-02-29 01:29:581263 << response_code_ << ". Verify network connectivity";
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161264 LogBadResponseCode();
jar@chromium.org0eb34fee2009-01-21 08:04:381265 } else { // Successful receipt (or we are discarding log).
isherman@chromium.orgfe58acc22012-02-29 01:29:581266 VLOG(1) << "METRICS RESPONSE DATA: " << response_data_;
initial.commit09911bf2008-07-26 23:55:291267 switch (state_) {
1268 case INITIAL_LOG_READY:
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101269 state_ = SENDING_OLD_LOGS;
initial.commit09911bf2008-07-26 23:55:291270 break;
1271
initial.commit09911bf2008-07-26 23:55:291272 case SENDING_OLD_LOGS:
stuartmorgan@chromium.orgd53e2232011-06-30 15:54:571273 // Store the updated list to disk now that the removed log is uploaded.
initial.commit09911bf2008-07-26 23:55:291274 StoreUnsentLogs();
1275 break;
1276
1277 case SENDING_CURRENT_LOGS:
1278 break;
1279
1280 default:
jar@chromium.orga063c102010-07-22 22:20:191281 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291282 break;
1283 }
petersont@google.comd01b8732008-10-16 02:18:071284
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101285 log_manager_.DiscardStagedLog();
petersont@google.com252873ef2008-08-04 21:59:451286
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101287 if (log_manager_.has_unsent_logs())
isherman@chromium.orged0fd002012-04-25 23:10:341288 DCHECK_LT(state_, SENDING_CURRENT_LOGS);
initial.commit09911bf2008-07-26 23:55:291289 }
petersont@google.com252873ef2008-08-04 21:59:451290
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161291 // Error 400 indicates a problem with the log, not with the server, so
1292 // don't consider that a sign that the server is in trouble.
isherman@chromium.orgfe58acc22012-02-29 01:29:581293 bool server_is_healthy = upload_succeeded || response_code_ == 400;
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161294
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101295 scheduler_->UploadFinished(server_is_healthy,
1296 log_manager_.has_unsent_logs());
rtenneti@chromium.orgd67d1052011-06-09 05:11:411297
1298 // Collect network stats if UMA upload succeeded.
isherman@chromium.orgb8ddb052012-04-19 02:36:061299 IOThread* io_thread = g_browser_process->io_thread();
1300 if (server_is_healthy && io_thread) {
1301 chrome_browser_net::CollectNetworkStats(network_stats_server_, io_thread);
simonjam@chromium.orgadbb3762012-03-09 22:20:081302 chrome_browser_net::CollectPipeliningCapabilityStatsOnUIThread(
isherman@chromium.orgb8ddb052012-04-19 02:36:061303 http_pipelining_test_server_, io_thread);
simonjam@chromium.orgadbb3762012-03-09 22:20:081304 }
isherman@chromium.orgfe58acc22012-02-29 01:29:581305
1306 // Reset the cached response data.
isherman@chromium.org6b44e9b52012-03-27 07:46:191307 response_code_ = kNoResponseCode;
isherman@chromium.orgfe58acc22012-02-29 01:29:581308 response_data_ = std::string();
1309 response_status_ = std::string();
initial.commit09911bf2008-07-26 23:55:291310}
1311
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161312void MetricsService::LogBadResponseCode() {
pkasting@chromium.org666205032010-10-21 20:56:581313 VLOG(1) << "Verify your metrics logs are formatted correctly. Verify server "
isherman@chromium.orgfe58acc22012-02-29 01:29:581314 "is active at " << server_url_xml_;
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101315 if (!log_manager_.has_staged_log()) {
pkasting@chromium.org666205032010-10-21 20:56:581316 VLOG(1) << "METRICS: Recorder shutdown during log transmission.";
petersont@google.com252873ef2008-08-04 21:59:451317 } else {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161318 VLOG(1) << "METRICS: transmission retry being scheduled for "
isherman@chromium.orgfe58acc22012-02-29 01:29:581319 << log_manager_.staged_log_text().xml;
initial.commit09911bf2008-07-26 23:55:291320 }
initial.commit09911bf2008-07-26 23:55:291321}
1322
jam@chromium.org6c2381d2011-10-19 02:52:531323void MetricsService::LogWindowChange(
1324 int type,
1325 const content::NotificationSource& source,
1326 const content::NotificationDetails& details) {
brettw@google.com534e54b2008-08-13 15:40:091327 int controller_id = -1;
1328 uintptr_t window_or_tab = source.map_key();
initial.commit09911bf2008-07-26 23:55:291329 MetricsLog::WindowEventType window_type;
1330
1331 // Note: since we stop all logging when a single OTR session is active, it is
1332 // possible that we start getting notifications about a window that we don't
1333 // know about.
brettw@google.com534e54b2008-08-13 15:40:091334 if (window_map_.find(window_or_tab) == window_map_.end()) {
1335 controller_id = next_window_id_++;
1336 window_map_[window_or_tab] = controller_id;
initial.commit09911bf2008-07-26 23:55:291337 } else {
brettw@google.com534e54b2008-08-13 15:40:091338 controller_id = window_map_[window_or_tab];
initial.commit09911bf2008-07-26 23:55:291339 }
jar@chromium.org92745242009-06-12 16:52:211340 DCHECK_NE(controller_id, -1);
initial.commit09911bf2008-07-26 23:55:291341
ananta@chromium.org432115822011-07-10 15:52:271342 switch (type) {
avi@chromium.org884033e2012-04-16 19:38:421343 case chrome::NOTIFICATION_TAB_PARENTED:
ananta@chromium.org432115822011-07-10 15:52:271344 case chrome::NOTIFICATION_BROWSER_OPENED:
initial.commit09911bf2008-07-26 23:55:291345 window_type = MetricsLog::WINDOW_CREATE;
1346 break;
1347
avi@chromium.org884033e2012-04-16 19:38:421348 case chrome::NOTIFICATION_TAB_CLOSING:
ananta@chromium.org432115822011-07-10 15:52:271349 case chrome::NOTIFICATION_BROWSER_CLOSED:
brettw@google.com534e54b2008-08-13 15:40:091350 window_map_.erase(window_map_.find(window_or_tab));
initial.commit09911bf2008-07-26 23:55:291351 window_type = MetricsLog::WINDOW_DESTROY;
1352 break;
1353
1354 default:
jar@chromium.orga063c102010-07-22 22:20:191355 NOTREACHED();
paul@chromium.org68d74f02009-02-13 01:36:501356 return;
initial.commit09911bf2008-07-26 23:55:291357 }
1358
brettw@google.com534e54b2008-08-13 15:40:091359 // TODO(brettw) we should have some kind of ID for the parent.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101360 log_manager_.current_log()->RecordWindowEvent(window_type, controller_id, 0);
initial.commit09911bf2008-07-26 23:55:291361}
1362
jam@chromium.org6c2381d2011-10-19 02:52:531363void MetricsService::LogLoadComplete(
1364 int type,
1365 const content::NotificationSource& source,
1366 const content::NotificationDetails& details) {
jam@chromium.orgad50def52011-10-19 23:17:071367 if (details == content::NotificationService::NoDetails())
initial.commit09911bf2008-07-26 23:55:291368 return;
1369
jar@google.com68475e602008-08-22 03:21:151370 // TODO(jar): There is a bug causing this to be called too many times, and
1371 // the log overflows. For now, we won't record these events.
dsh@google.com553dba62009-02-24 19:08:231372 UMA_HISTOGRAM_COUNTS("UMA.LogLoadComplete called", 1);
jar@google.com68475e602008-08-22 03:21:151373 return;
1374
jam@chromium.org6c2381d2011-10-19 02:52:531375 const content::Details<LoadNotificationDetails> load_details(details);
brettw@google.com534e54b2008-08-13 15:40:091376 int controller_id = window_map_[details.map_key()];
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101377 log_manager_.current_log()->RecordLoadEvent(controller_id,
tfarina@chromium.org09d31d52012-03-11 22:30:271378 load_details->url,
1379 load_details->origin,
1380 load_details->session_index,
1381 load_details->load_time);
initial.commit09911bf2008-07-26 23:55:291382}
1383
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511384void MetricsService::IncrementPrefValue(const char* path) {
cpu@google.come73c01972008-08-13 00:18:241385 PrefService* pref = g_browser_process->local_state();
1386 DCHECK(pref);
1387 int value = pref->GetInteger(path);
1388 pref->SetInteger(path, value + 1);
1389}
1390
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511391void MetricsService::IncrementLongPrefsValue(const char* path) {
robertshield@google.com0bb1a622009-03-04 03:22:321392 PrefService* pref = g_browser_process->local_state();
1393 DCHECK(pref);
1394 int64 value = pref->GetInt64(path);
jar@chromium.orgb42c5e42010-06-03 20:43:251395 pref->SetInt64(path, value + 1);
robertshield@google.com0bb1a622009-03-04 03:22:321396}
1397
initial.commit09911bf2008-07-26 23:55:291398void MetricsService::LogLoadStarted() {
jar@chromium.orgdd8d12a2011-09-02 02:10:151399 HISTOGRAM_ENUMERATION("Chrome.UmaPageloadCounter", 1, 2);
cpu@google.come73c01972008-08-13 00:18:241400 IncrementPrefValue(prefs::kStabilityPageLoadCount);
robertshield@google.com0bb1a622009-03-04 03:22:321401 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
jar@google.com0b33f80b2008-12-17 21:34:361402 // We need to save the prefs, as page load count is a critical stat, and it
1403 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291404}
1405
jar@chromium.orgc3721482012-03-23 16:21:481406void MetricsService::LogRendererCrash(content::RenderProcessHost* host,
1407 base::TerminationStatus status,
1408 bool was_alive) {
ananta@chromium.orgf3b1a082011-11-18 00:34:301409 Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
aa@chromium.org6f371442011-11-09 06:45:461410 ExtensionService* service = profile->GetExtensionService();
1411 bool was_extension_process =
ananta@chromium.orgf3b1a082011-11-18 00:34:301412 service && service->process_map()->Contains(host->GetID());
jar@chromium.orgc3721482012-03-23 16:21:481413 if (status == base::TERMINATION_STATUS_PROCESS_CRASHED ||
1414 status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
1415 if (was_extension_process)
jochen@chromium.org718eab62011-10-05 21:16:521416 IncrementPrefValue(prefs::kStabilityExtensionRendererCrashCount);
jar@chromium.orgc3721482012-03-23 16:21:481417 else
jochen@chromium.org718eab62011-10-05 21:16:521418 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291419
jochen@chromium.org718eab62011-10-05 21:16:521420 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildCrashes",
1421 was_extension_process ? 2 : 1);
jar@chromium.orgc3721482012-03-23 16:21:481422 if (was_alive) {
jochen@chromium.org718eab62011-10-05 21:16:521423 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildCrashesWasAlive",
1424 was_extension_process ? 2 : 1);
1425 }
jar@chromium.orgc3721482012-03-23 16:21:481426 } else if (status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED) {
jochen@chromium.org718eab62011-10-05 21:16:521427 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildKills",
1428 was_extension_process ? 2 : 1);
jar@chromium.orgc3721482012-03-23 16:21:481429 if (was_alive) {
jochen@chromium.org718eab62011-10-05 21:16:521430 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildKillsWasAlive",
1431 was_extension_process ? 2 : 1);
1432 }
1433 }
asargent@chromium.org1f085622009-12-04 05:33:451434}
1435
initial.commit09911bf2008-07-26 23:55:291436void MetricsService::LogRendererHang() {
cpu@google.come73c01972008-08-13 00:18:241437 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291438}
1439
jar@chromium.orgc0c55e92011-09-10 18:47:301440void MetricsService::LogNeedForCleanShutdown() {
1441 PrefService* pref = g_browser_process->local_state();
1442 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
1443 // Redundant setting to be sure we call for a clean shutdown.
1444 clean_shutdown_status_ = NEED_TO_SHUTDOWN;
1445}
1446
1447bool MetricsService::UmaMetricsProperlyShutdown() {
1448 CHECK(clean_shutdown_status_ == CLEANLY_SHUTDOWN ||
1449 clean_shutdown_status_ == NEED_TO_SHUTDOWN);
1450 return clean_shutdown_status_ == CLEANLY_SHUTDOWN;
1451}
1452
jar@chromium.org67c4e952011-09-17 00:44:271453// For use in hack in LogCleanShutdown.
1454static void Signal(base::WaitableEvent* event) {
1455 event->Signal();
1456}
1457
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381458void MetricsService::LogCleanShutdown() {
jar@chromium.orgacd55b32011-09-05 17:35:311459 // Redundant hack to write pref ASAP.
1460 PrefService* pref = g_browser_process->local_state();
1461 pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
bauerb@chromium.orgfbe17c8a2011-12-27 16:41:481462 pref->CommitPendingWrite();
jar@chromium.org67c4e952011-09-17 00:44:271463 // Hack: TBD: Remove this wait.
1464 // We are so concerned that the pref gets written, we are now willing to stall
1465 // the UI thread until we get assurance that a pref-writing task has
1466 // completed.
1467 base::WaitableEvent done_writing(false, false);
1468 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
isherman@chromium.org8454aeb2011-11-19 23:38:201469 base::Bind(Signal, &done_writing));
jam@chromium.org3a7b66d2012-04-26 16:34:161470 // http://crbug.com/124954
1471 base::ThreadRestrictions::ScopedAllowWait allow_wait;
jar@chromium.org67c4e952011-09-17 00:44:271472 done_writing.TimedWait(base::TimeDelta::FromHours(1));
1473
jar@chromium.orgc0c55e92011-09-10 18:47:301474 // Redundant setting to assure that we always reset this value at shutdown
1475 // (and that we don't use some alternate path, and not call LogCleanShutdown).
1476 clean_shutdown_status_ = CLEANLY_SHUTDOWN;
jar@chromium.orgacd55b32011-09-05 17:35:311477
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381478 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
1479}
1480
petkov@chromium.orgc1834a92011-01-21 18:21:031481#if defined(OS_CHROMEOS)
1482void MetricsService::LogChromeOSCrash(const std::string &crash_type) {
1483 if (crash_type == "user")
1484 IncrementPrefValue(prefs::kStabilityOtherUserCrashCount);
1485 else if (crash_type == "kernel")
1486 IncrementPrefValue(prefs::kStabilityKernelCrashCount);
1487 else if (crash_type == "uncleanshutdown")
1488 IncrementPrefValue(prefs::kStabilitySystemUncleanShutdownCount);
1489 else
1490 NOTREACHED() << "Unexpected Chrome OS crash type " << crash_type;
1491 // Wake up metrics logs sending if necessary now that new
1492 // log data is available.
1493 HandleIdleSinceLastTransmission(false);
1494}
1495#endif // OS_CHROMEOS
1496
jam@chromium.orga27a9382009-02-11 23:55:101497void MetricsService::LogChildProcessChange(
ananta@chromium.org432115822011-07-10 15:52:271498 int type,
jam@chromium.org6c2381d2011-10-19 02:52:531499 const content::NotificationSource& source,
1500 const content::NotificationDetails& details) {
jam@chromium.org4967f792012-01-20 22:14:401501 content::Details<ChildProcessData> child_details(details);
jam@chromium.org4306c3792011-12-02 01:57:531502 const string16& child_name = child_details->name;
gregoryd@google.com0d84c5d2009-10-09 01:10:421503
jam@chromium.orga27a9382009-02-11 23:55:101504 if (child_process_stats_buffer_.find(child_name) ==
1505 child_process_stats_buffer_.end()) {
gregoryd@google.com0d84c5d2009-10-09 01:10:421506 child_process_stats_buffer_[child_name] =
jam@chromium.org4306c3792011-12-02 01:57:531507 ChildProcessStats(child_details->type);
initial.commit09911bf2008-07-26 23:55:291508 }
1509
jam@chromium.orga27a9382009-02-11 23:55:101510 ChildProcessStats& stats = child_process_stats_buffer_[child_name];
ananta@chromium.org432115822011-07-10 15:52:271511 switch (type) {
1512 case content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED:
initial.commit09911bf2008-07-26 23:55:291513 stats.process_launches++;
1514 break;
1515
ananta@chromium.org432115822011-07-10 15:52:271516 case content::NOTIFICATION_CHILD_INSTANCE_CREATED:
initial.commit09911bf2008-07-26 23:55:291517 stats.instances++;
1518 break;
1519
ananta@chromium.org432115822011-07-10 15:52:271520 case content::NOTIFICATION_CHILD_PROCESS_CRASHED:
initial.commit09911bf2008-07-26 23:55:291521 stats.process_crashes++;
asargent@chromium.org1f085622009-12-04 05:33:451522 // Exclude plugin crashes from the count below because we report them via
1523 // a separate UMA metric.
jam@chromium.org4306c3792011-12-02 01:57:531524 if (!IsPluginProcess(child_details->type)) {
asargent@chromium.org1f085622009-12-04 05:33:451525 IncrementPrefValue(prefs::kStabilityChildProcessCrashCount);
1526 }
initial.commit09911bf2008-07-26 23:55:291527 break;
1528
1529 default:
ananta@chromium.org432115822011-07-10 15:52:271530 NOTREACHED() << "Unexpected notification type " << type;
initial.commit09911bf2008-07-26 23:55:291531 return;
1532 }
1533}
1534
1535// Recursively counts the number of bookmarks and folders in node.
munjal@chromium.orgb3c33d462009-06-26 22:29:201536static void CountBookmarks(const BookmarkNode* node,
1537 int* bookmarks,
1538 int* folders) {
tfarina@chromium.org0890e60e2011-06-27 14:55:211539 if (node->is_url())
initial.commit09911bf2008-07-26 23:55:291540 (*bookmarks)++;
1541 else
1542 (*folders)++;
tfarina@chromium.org9c1a75a2011-03-10 02:38:121543 for (int i = 0; i < node->child_count(); ++i)
initial.commit09911bf2008-07-26 23:55:291544 CountBookmarks(node->GetChild(i), bookmarks, folders);
1545}
1546
munjal@chromium.orgb3c33d462009-06-26 22:29:201547void MetricsService::LogBookmarks(const BookmarkNode* node,
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511548 const char* num_bookmarks_key,
1549 const char* num_folders_key) {
initial.commit09911bf2008-07-26 23:55:291550 DCHECK(node);
1551 int num_bookmarks = 0;
1552 int num_folders = 0;
1553 CountBookmarks(node, &num_bookmarks, &num_folders);
1554 num_folders--; // Don't include the root folder in the count.
1555
1556 PrefService* pref = g_browser_process->local_state();
1557 DCHECK(pref);
1558 pref->SetInteger(num_bookmarks_key, num_bookmarks);
1559 pref->SetInteger(num_folders_key, num_folders);
1560}
1561
sky@google.comd8e41ed2008-09-11 15:22:321562void MetricsService::LogBookmarks(BookmarkModel* model) {
initial.commit09911bf2008-07-26 23:55:291563 DCHECK(model);
tfarina@chromium.org72bdcfe2011-07-22 17:21:581564 LogBookmarks(model->bookmark_bar_node(),
initial.commit09911bf2008-07-26 23:55:291565 prefs::kNumBookmarksOnBookmarkBar,
1566 prefs::kNumFoldersOnBookmarkBar);
1567 LogBookmarks(model->other_node(),
1568 prefs::kNumBookmarksInOtherBookmarkFolder,
1569 prefs::kNumFoldersInOtherBookmarkFolder);
1570 ScheduleNextStateSave();
1571}
1572
pkasting@chromium.org604d8a062012-03-16 21:37:461573void MetricsService::LogKeywordCount(size_t keyword_count) {
initial.commit09911bf2008-07-26 23:55:291574 PrefService* pref = g_browser_process->local_state();
1575 DCHECK(pref);
pkasting@chromium.org604d8a062012-03-16 21:37:461576 pref->SetInteger(prefs::kNumKeywords, static_cast<int>(keyword_count));
initial.commit09911bf2008-07-26 23:55:291577 ScheduleNextStateSave();
1578}
1579
1580void MetricsService::RecordPluginChanges(PrefService* pref) {
battre@chromium.orgf8628c22011-04-05 12:10:181581 ListPrefUpdate update(pref, prefs::kStabilityPluginStats);
1582 ListValue* plugins = update.Get();
initial.commit09911bf2008-07-26 23:55:291583 DCHECK(plugins);
1584
1585 for (ListValue::iterator value_iter = plugins->begin();
1586 value_iter != plugins->end(); ++value_iter) {
1587 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
jar@chromium.orga063c102010-07-22 22:20:191588 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291589 continue;
1590 }
1591
1592 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511593 std::string plugin_name;
nsylvain@chromium.org8e50b602009-03-03 22:59:431594 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
nsylvain@chromium.org6470ee8f2009-03-03 20:46:401595 if (plugin_name.empty()) {
jar@chromium.orga063c102010-07-22 22:20:191596 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291597 continue;
1598 }
1599
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511600 // TODO(viettrungluu): remove conversions
evan@chromium.org68b9e72b2011-08-05 23:08:221601 string16 name16 = UTF8ToUTF16(plugin_name);
1602 if (child_process_stats_buffer_.find(name16) ==
1603 child_process_stats_buffer_.end()) {
initial.commit09911bf2008-07-26 23:55:291604 continue;
evan@chromium.org68b9e72b2011-08-05 23:08:221605 }
initial.commit09911bf2008-07-26 23:55:291606
evan@chromium.org68b9e72b2011-08-05 23:08:221607 ChildProcessStats stats = child_process_stats_buffer_[name16];
initial.commit09911bf2008-07-26 23:55:291608 if (stats.process_launches) {
1609 int launches = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431610 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291611 launches += stats.process_launches;
nsylvain@chromium.org8e50b602009-03-03 22:59:431612 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291613 }
1614 if (stats.process_crashes) {
1615 int crashes = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431616 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291617 crashes += stats.process_crashes;
nsylvain@chromium.org8e50b602009-03-03 22:59:431618 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291619 }
1620 if (stats.instances) {
1621 int instances = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431622 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291623 instances += stats.instances;
nsylvain@chromium.org8e50b602009-03-03 22:59:431624 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291625 }
1626
evan@chromium.org68b9e72b2011-08-05 23:08:221627 child_process_stats_buffer_.erase(name16);
initial.commit09911bf2008-07-26 23:55:291628 }
1629
1630 // Now go through and add dictionaries for plugins that didn't already have
1631 // reports in Local State.
evan@chromium.org68b9e72b2011-08-05 23:08:221632 for (std::map<string16, ChildProcessStats>::iterator cache_iter =
jam@chromium.orga27a9382009-02-11 23:55:101633 child_process_stats_buffer_.begin();
1634 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
jam@chromium.orga27a9382009-02-11 23:55:101635 ChildProcessStats stats = cache_iter->second;
gregoryd@google.com0d84c5d2009-10-09 01:10:421636
1637 // Insert only plugins information into the plugins list.
petkov@chromium.org8d5f1dae2011-11-11 14:30:411638 if (!IsPluginProcess(stats.process_type))
gregoryd@google.com0d84c5d2009-10-09 01:10:421639 continue;
1640
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511641 // TODO(viettrungluu): remove conversion
evan@chromium.org68b9e72b2011-08-05 23:08:221642 std::string plugin_name = UTF16ToUTF8(cache_iter->first);
gregoryd@google.com0d84c5d2009-10-09 01:10:421643
initial.commit09911bf2008-07-26 23:55:291644 DictionaryValue* plugin_dict = new DictionaryValue;
1645
nsylvain@chromium.org8e50b602009-03-03 22:59:431646 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
1647 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:291648 stats.process_launches);
nsylvain@chromium.org8e50b602009-03-03 22:59:431649 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:291650 stats.process_crashes);
nsylvain@chromium.org8e50b602009-03-03 22:59:431651 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:291652 stats.instances);
1653 plugins->Append(plugin_dict);
1654 }
jam@chromium.orga27a9382009-02-11 23:55:101655 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291656}
1657
jam@chromium.org6c2381d2011-10-19 02:52:531658bool MetricsService::CanLogNotification(
1659 int type,
1660 const content::NotificationSource& source,
1661 const content::NotificationDetails& details) {
akalin@chromium.org2c910b72011-03-08 21:16:321662 // We simply don't log anything to UMA if there is a single incognito
initial.commit09911bf2008-07-26 23:55:291663 // session visible. The problem is that we always notify using the orginal
1664 // profile in order to simplify notification processing.
1665 return !BrowserList::IsOffTheRecordSessionActive();
1666}
1667
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511668void MetricsService::RecordBooleanPrefValue(const char* path, bool value) {
initial.commit09911bf2008-07-26 23:55:291669 DCHECK(IsSingleThreaded());
1670
1671 PrefService* pref = g_browser_process->local_state();
1672 DCHECK(pref);
1673
1674 pref->SetBoolean(path, value);
1675 RecordCurrentState(pref);
1676}
1677
1678void MetricsService::RecordCurrentState(PrefService* pref) {
robertshield@google.com0bb1a622009-03-04 03:22:321679 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291680
1681 RecordPluginChanges(pref);
1682}
1683
petkov@chromium.org8d5f1dae2011-11-11 14:30:411684// static
jam@chromium.orgbd5d6cf2011-12-01 00:39:121685bool MetricsService::IsPluginProcess(content::ProcessType type) {
1686 return (type == content::PROCESS_TYPE_PLUGIN||
1687 type == content::PROCESS_TYPE_PPAPI_PLUGIN);
petkov@chromium.org8d5f1dae2011-11-11 14:30:411688}
1689
rvargas@google.com5ccaa412009-11-13 22:00:161690#if defined(OS_CHROMEOS)
sky@chromium.org29cf16772010-04-21 15:13:471691void MetricsService::StartExternalMetrics() {
rvargas@google.com5ccaa412009-11-13 22:00:161692 external_metrics_ = new chromeos::ExternalMetrics;
sky@chromium.org29cf16772010-04-21 15:13:471693 external_metrics_->Start();
rvargas@google.com5ccaa412009-11-13 22:00:161694}
1695#endif
sreeram@chromium.org3819f2ee2011-08-21 09:44:381696
1697// static
1698bool MetricsServiceHelper::IsMetricsReportingEnabled() {
1699 bool result = false;
1700 const PrefService* local_state = g_browser_process->local_state();
1701 if (local_state) {
1702 const PrefService::Preference* uma_pref =
1703 local_state->FindPreference(prefs::kMetricsReportingEnabled);
1704 if (uma_pref) {
1705 bool success = uma_pref->GetValue()->GetAsBoolean(&result);
1706 DCHECK(success);
1707 }
1708 }
1709 return result;
1710}