blob: 87d32669d97e2aefd8bb9bd6fd670d7f41160464 [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//
isherman@chromium.orge3eb0c42013-04-18 06:18:5810// A MetricsService instance is typically created at application startup. It is
11// the central controller for the acquisition of log data, and the automatic
initial.commit09911bf2008-07-26 23:55:2912// 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,
isherman@chromium.orge3eb0c42013-04-18 06:18:5816// closing the logs, translating to protocol buffer format, and compressing the
17// results for transmission. Transmission includes submitting a compressed log
18// as data in a URL-post, and retransmitting (or retaining at process
19// termination) if the attempted transmission failed. Retention across process
20// terminations is done using the the PrefServices facilities. The retained logs
21// (the ones that never got transmitted) are compressed and base64-encoded
22// before being persisted.
initial.commit09911bf2008-07-26 23:55:2923//
jar@chromium.org281d2882009-01-20 20:32:4224// Logs fall into one of two categories: "initial logs," and "ongoing logs."
25// There is at most one initial log sent for each complete run of the chromium
initial.commit09911bf2008-07-26 23:55:2926// product (from startup, to browser shutdown). An initial log is generally
27// transmitted some short time (1 minute?) after startup, and includes stats
28// such as recent crash info, the number and types of plugins, etc. The
jar@chromium.org281d2882009-01-20 20:32:4229// external server's response to the initial log conceptually tells this MS if
30// it should continue transmitting logs (during this session). The server
31// response can actually be much more detailed, and always includes (at a
32// minimum) how often additional ongoing logs should be sent.
initial.commit09911bf2008-07-26 23:55:2933//
34// After the above initial log, a series of ongoing logs will be transmitted.
35// The first ongoing log actually begins to accumulate information stating when
36// the MS was first constructed. Note that even though the initial log is
37// commonly sent a full minute after startup, the initial log does not include
38// much in the way of user stats. The most common interlog period (delay)
asharif@chromium.org3a668152013-06-21 23:56:4239// is 30 minutes. That time period starts when the first user action causes a
initial.commit09911bf2008-07-26 23:55:2940// logging event. This means that if there is no user action, there may be long
jar@chromium.org281d2882009-01-20 20:32:4241// periods without any (ongoing) log transmissions. Ongoing logs typically
initial.commit09911bf2008-07-26 23:55:2942// contain very detailed records of user activities (ex: opened tab, closed
43// tab, fetched URL, maximized window, etc.) In addition, just before an
44// ongoing log is closed out, a call is made to gather memory statistics. Those
45// memory statistics are deposited into a histogram, and the log finalization
46// code is then called. In the finalization, a call to a Histogram server
47// acquires a list of all local histograms that have been flagged for upload
jar@chromium.org281d2882009-01-20 20:32:4248// to the UMA server. The finalization also acquires a the most recent number
49// of page loads, along with any counts of renderer or plugin crashes.
initial.commit09911bf2008-07-26 23:55:2950//
51// When the browser shuts down, there will typically be a fragment of an ongoing
52// log that has not yet been transmitted. At shutdown time, that fragment
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:1053// is closed (including snapshotting histograms), and persisted, for
initial.commit09911bf2008-07-26 23:55:2954// potential transmission during a future run of the product.
55//
56// There are two slightly abnormal shutdown conditions. There is a
57// "disconnected scenario," and a "really fast startup and shutdown" scenario.
58// In the "never connected" situation, the user has (during the running of the
59// process) never established an internet connection. As a result, attempts to
60// transmit the initial log have failed, and a lot(?) of data has accumulated in
61// the ongoing log (which didn't yet get closed, because there was never even a
62// contemplation of sending it). There is also a kindred "lost connection"
63// situation, where a loss of connection prevented an ongoing log from being
64// transmitted, and a (still open) log was stuck accumulating a lot(?) of data,
65// while the earlier log retried its transmission. In both of these
66// disconnected situations, two logs need to be, and are, persistently stored
67// for future transmission.
68//
69// The other unusual shutdown condition, termed "really fast startup and
70// shutdown," involves the deliberate user termination of the process before
71// the initial log is even formed or transmitted. In that situation, no logging
72// is done, but the historical crash statistics remain (unlogged) for inclusion
73// in a future run's initial log. (i.e., we don't lose crash stats).
74//
75// With the above overview, we can now describe the state machine's various
76// stats, based on the State enum specified in the state_ member. Those states
77// are:
78//
79// INITIALIZED, // Constructor was called.
zelidrag@chromium.org85ed9d42010-06-08 22:37:4480// INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to complete.
81// INIT_TASK_DONE, // Waiting for timer to send initial log.
initial.commit09911bf2008-07-26 23:55:2982// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
initial.commit09911bf2008-07-26 23:55:2983// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
84// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
85//
86// In more detail, we have:
87//
88// INITIALIZED, // Constructor was called.
89// The MS has been constructed, but has taken no actions to compose the
90// initial log.
91//
zelidrag@chromium.org85ed9d42010-06-08 22:37:4492// INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to complete.
initial.commit09911bf2008-07-26 23:55:2993// Typically about 30 seconds after startup, a task is sent to a second thread
zelidrag@chromium.org85ed9d42010-06-08 22:37:4494// (the file thread) to perform deferred (lower priority and slower)
95// initialization steps such as getting the list of plugins. That task will
96// (when complete) make an async callback (via a Task) to indicate the
97// completion.
initial.commit09911bf2008-07-26 23:55:2998//
zelidrag@chromium.org85ed9d42010-06-08 22:37:4499// INIT_TASK_DONE, // Waiting for timer to send initial log.
initial.commit09911bf2008-07-26 23:55:29100// The callback has arrived, and it is now possible for an initial log to be
101// created. This callback typically arrives back less than one second after
zelidrag@chromium.org85ed9d42010-06-08 22:37:44102// the deferred init task is dispatched.
initial.commit09911bf2008-07-26 23:55:29103//
104// INITIAL_LOG_READY, // Initial log generated, and waiting for reply.
105// This state is entered only after an initial log has been composed, and
106// prepared for transmission. It is also the case that any previously unsent
107// logs have been loaded into instance variables for possible transmission.
108//
initial.commit09911bf2008-07-26 23:55:29109// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10110// This state indicates that the initial log for this session has been
111// successfully sent and it is now time to send any logs that were
112// saved from previous sessions. All such logs will be transmitted before
113// exiting this state, and proceeding with ongoing logs from the current session
114// (see next state).
initial.commit09911bf2008-07-26 23:55:29115//
116// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
jar@google.com0b33f80b2008-12-17 21:34:36117// Current logs are being accumulated. Typically every 20 minutes a log is
initial.commit09911bf2008-07-26 23:55:29118// closed and finalized for transmission, at the same time as a new log is
119// started.
120//
121// The progression through the above states is simple, and sequential, in the
122// most common use cases. States proceed from INITIAL to SENDING_CURRENT_LOGS,
123// and remain in the latter until shutdown.
124//
125// The one unusual case is when the user asks that we stop logging. When that
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10126// happens, any staged (transmission in progress) log is persisted, and any log
stuartmorgan@chromium.org410938e02012-10-24 16:33:59127// that is currently accumulating is also finalized and persisted. We then
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10128// regress back to the SEND_OLD_LOGS state in case the user enables log
129// recording again during this session. This way anything we have persisted
130// will be sent automatically if/when we progress back to SENDING_CURRENT_LOG
131// state.
initial.commit09911bf2008-07-26 23:55:29132//
stuartmorgan@chromium.org410938e02012-10-24 16:33:59133// Another similar case is on mobile, when the application is backgrounded and
134// then foregrounded again. Backgrounding created new "old" stored logs, so the
135// state drops back from SENDING_CURRENT_LOGS to SENDING_OLD_LOGS so those logs
136// will be sent.
137//
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10138// Also note that whenever we successfully send an old log, we mirror the list
139// of logs into the PrefService. This ensures that IF we crash, we won't start
140// up and retransmit our old logs again.
initial.commit09911bf2008-07-26 23:55:29141//
142// Due to race conditions, it is always possible that a log file could be sent
143// twice. For example, if a log file is sent, but not yet acknowledged by
144// the external server, and the user shuts down, then a copy of the log may be
145// saved for re-transmission. These duplicates could be filtered out server
jar@chromium.org281d2882009-01-20 20:32:42146// side, but are not expected to be a significant problem.
initial.commit09911bf2008-07-26 23:55:29147//
148//
149//------------------------------------------------------------------------------
150
maruel@chromium.org40bcc302009-03-02 20:50:39151#include "chrome/browser/metrics/metrics_service.h"
152
eroman@chromium.orgd7c1fa62012-06-15 23:35:30153#include <algorithm>
154
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16155#include "base/bind.h"
156#include "base/callback.h"
erg@google.com5d91c9e2010-07-28 17:25:28157#include "base/command_line.h"
akalin@chromium.org3dc1bc42012-06-19 08:20:53158#include "base/guid.h"
ziadh@chromium.org46f89e142010-07-19 08:00:42159#include "base/md5.h"
brettw@chromium.org835d7c82010-10-14 04:38:38160#include "base/metrics/histogram.h"
eroman@chromium.org1026afd2013-03-20 14:28:54161#include "base/metrics/sparse_histogram.h"
kaiwang@chromium.org567d30e2012-07-13 21:48:29162#include "base/metrics/statistics_recorder.h"
joi@chromium.org3853a4c2013-02-11 17:15:57163#include "base/prefs/pref_registry_simple.h"
164#include "base/prefs/pref_service.h"
derat@chromium.org9eec53fe2013-10-30 20:21:17165#include "base/prefs/scoped_user_pref_update.h"
stevet@chromium.orge61003a2012-05-24 17:03:19166#include "base/rand_util.h"
brettw@chromium.org3ea1b182013-02-08 22:38:41167#include "base/strings/string_number_conversions.h"
avi@chromium.org112158af2013-06-07 23:46:18168#include "base/strings/utf_string_conversions.h"
brettw@chromium.orgce072a72010-12-31 20:02:16169#include "base/threading/platform_thread.h"
tfarina@chromium.orgb3841c502011-03-09 01:21:31170#include "base/threading/thread.h"
jam@chromium.org3a7b66d2012-04-26 16:34:16171#include "base/threading/thread_restrictions.h"
isherman@chromium.orged0fd002012-04-25 23:10:34172#include "base/tracked_objects.h"
erg@google.com679082052010-07-21 21:30:13173#include "base/values.h"
initial.commit09911bf2008-07-26 23:55:29174#include "chrome/browser/browser_process.h"
jam@chromium.org9ea0cd32013-07-12 01:50:36175#include "chrome/browser/chrome_notification_types.h"
aa@chromium.org6f371442011-11-09 06:45:46176#include "chrome/browser/extensions/extension_service.h"
isherman@chromium.orgb8ddb052012-04-19 02:36:06177#include "chrome/browser/io_thread.h"
sail@chromium.org84c988a2011-04-19 17:56:33178#include "chrome/browser/memory_details.h"
asharif@chromium.org537c638d2013-07-04 00:49:19179#include "chrome/browser/metrics/compression_utils.h"
erg@google.com679082052010-07-21 21:30:13180#include "chrome/browser/metrics/metrics_log.h"
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10181#include "chrome/browser/metrics/metrics_log_serializer.h"
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16182#include "chrome/browser/metrics/metrics_reporting_scheduler.h"
simonjam@chromium.orgaa312812013-04-30 19:46:05183#include "chrome/browser/metrics/time_ticks_experiment_win.h"
isherman@chromium.orged0fd002012-04-25 23:10:34184#include "chrome/browser/metrics/tracking_synchronizer.h"
bengr@chromium.org60677562013-11-17 15:52:55185#include "chrome/common/metrics/variations/variations_util.h"
simonjam@chromium.orgadbb3762012-03-09 22:20:08186#include "chrome/browser/net/http_pipelining_compatibility_client.h"
rtenneti@chromium.orgd67d1052011-06-09 05:11:41187#include "chrome/browser/net/network_stats.h"
tfarina@chromium.org0fafc8d2013-06-01 00:09:50188#include "chrome/browser/omnibox/omnibox_log.h"
ben@chromium.org8ecad5e2010-12-02 21:18:33189#include "chrome/browser/profiles/profile.h"
tfarina@chromium.org71b73f02011-04-06 15:57:29190#include "chrome/browser/ui/browser_list.h"
dtrainor@chromium.org10b132b02012-07-27 20:46:18191#include "chrome/browser/ui/browser_otr_state.h"
rlp@chromium.org752a5262013-06-23 14:53:42192#include "chrome/browser/ui/search/search_tab_helper.h"
rogerm@chromium.org261ab7c2013-08-19 15:04:58193#include "chrome/common/chrome_constants.h"
eroman@chromium.orgd7c1fa62012-06-15 23:35:30194#include "chrome/common/chrome_result_codes.h"
jar@chromium.org92745242009-06-12 16:52:21195#include "chrome/common/chrome_switches.h"
rsesek@chromium.org264c0acac2013-10-01 13:33:30196#include "chrome/common/crash_keys.h"
asvitkine@chromium.orgc277e2b2013-08-02 15:41:08197#include "chrome/common/metrics/caching_permuted_entropy_provider.h"
isherman@chromium.org2e4cd1a2012-01-12 08:51:03198#include "chrome/common/metrics/metrics_log_manager.h"
simonjam@chromium.orgb4a72d842012-03-22 20:09:09199#include "chrome/common/net/test_server_locations.h"
initial.commit09911bf2008-07-26 23:55:29200#include "chrome/common/pref_names.h"
jam@chromium.orge09ba552009-02-05 03:26:29201#include "chrome/common/render_messages.h"
asvitkine@chromium.org50ae9f12013-08-29 18:03:22202#include "components/variations/entropy_provider.h"
bengr@chromium.org60677562013-11-17 15:52:55203#include "components/variations/metrics_util.h"
jam@chromium.org4967f792012-01-20 22:14:40204#include "content/public/browser/child_process_data.h"
rtenneti@google.com83ab4a282012-07-12 18:19:45205#include "content/public/browser/histogram_fetcher.h"
tfarina@chromium.org09d31d52012-03-11 22:30:27206#include "content/public/browser/load_notification_details.h"
jam@chromium.orgad50def52011-10-19 23:17:07207#include "content/public/browser/notification_service.h"
jam@chromium.org3a5180ae2011-12-21 02:39:38208#include "content/public/browser/plugin_service.h"
ananta@chromium.orgf3b1a082011-11-18 00:34:30209#include "content/public/browser/render_process_host.h"
mpearson@chromium.org5d490e42012-08-30 05:16:43210#include "content/public/browser/user_metrics.h"
avi@chromium.org459f3502012-09-17 17:08:12211#include "content/public/browser/web_contents.h"
yael.aharon@intel.comd5d383252013-07-04 14:44:32212#include "content/public/common/process_type.h"
jam@chromium.orgd7bd3e52013-07-21 04:29:20213#include "content/public/common/webplugininfo.h"
benwells@chromium.org50de9aa22013-11-14 06:30:34214#include "extensions/browser/process_map.h"
isherman@chromium.orgfe58acc22012-02-29 01:29:58215#include "net/base/load_flags.h"
akalin@chromium.org3dc1bc42012-06-19 08:20:53216#include "net/url_request/url_fetcher.h"
initial.commit09911bf2008-07-26 23:55:29217
phajdan.jr@chromium.orge06131d2010-02-10 18:40:33218// TODO(port): port browser_distribution.h.
219#if !defined(OS_POSIX)
kuchhal@chromium.org79bf0b72009-04-27 21:30:55220#include "chrome/installer/util/browser_distribution.h"
paul@chromium.orgdc6f4962009-02-13 01:25:50221#endif
222
rvargas@google.com5ccaa412009-11-13 22:00:16223#if defined(OS_CHROMEOS)
224#include "chrome/browser/chromeos/external_metrics.h"
stevenjb@chromium.org279690f82013-10-09 08:23:52225#include "chromeos/system/statistics_provider.h"
rvargas@google.com5ccaa412009-11-13 22:00:16226#endif
227
eroman@chromium.orgd7c1fa62012-06-15 23:35:30228#if defined(OS_WIN)
229#include <windows.h> // Needed for STATUS_* codes
rogerm@chromium.org261ab7c2013-08-19 15:04:58230#include "base/win/registry.h"
eroman@chromium.orgd7c1fa62012-06-15 23:35:30231#endif
232
vitalybuka@chromium.orga3079832013-10-24 20:29:36233#if !defined(OS_ANDROID)
jianli@chromium.orgcbf160aa2013-11-05 17:54:55234#include "chrome/browser/service_process/service_process_control.h"
vitalybuka@chromium.orga3079832013-10-24 20:29:36235#endif
236
dsh@google.come1acf6f2008-10-27 20:43:33237using base::Time;
joi@chromium.org631bb742011-11-02 11:29:39238using content::BrowserThread;
jam@chromium.org4967f792012-01-20 22:14:40239using content::ChildProcessData;
tfarina@chromium.org09d31d52012-03-11 22:30:27240using content::LoadNotificationDetails;
jam@chromium.org3a5180ae2011-12-21 02:39:38241using content::PluginService;
dsh@google.come1acf6f2008-10-27 20:43:33242
isherman@chromium.orgfe58acc22012-02-29 01:29:58243namespace {
isherman@chromium.orgb2a4812d2012-02-28 05:31:31244
isherman@chromium.orgfe58acc22012-02-29 01:29:58245// Check to see that we're being called on only one thread.
246bool IsSingleThreaded() {
247 static base::PlatformThreadId thread_id = 0;
248 if (!thread_id)
249 thread_id = base::PlatformThread::CurrentId();
250 return base::PlatformThread::CurrentId() == thread_id;
251}
252
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16253// The delay, in seconds, after starting recording before doing expensive
254// initialization work.
dfalcantara@chromium.org12180f82012-10-10 21:13:30255#if defined(OS_ANDROID) || defined(OS_IOS)
256// On mobile devices, a significant portion of sessions last less than a minute.
257// Use a shorter timer on these platforms to avoid losing data.
258// TODO(dfalcantara): To avoid delaying startup, tighten up initialization so
259// that it occurs after the user gets their initial page.
260const int kInitializationDelaySeconds = 5;
261#else
isherman@chromium.orgfe58acc22012-02-29 01:29:58262const int kInitializationDelaySeconds = 30;
dfalcantara@chromium.org12180f82012-10-10 21:13:30263#endif
petersont@google.com252873ef2008-08-04 21:59:45264
jar@chromium.orgc9a3ef82009-05-28 22:02:46265// This specifies the amount of time to wait for all renderers to send their
266// data.
isherman@chromium.orgfe58acc22012-02-29 01:29:58267const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
jar@chromium.orgc9a3ef82009-05-28 22:02:46268
stuartmorgan@chromium.org54702c92011-04-15 15:06:43269// The maximum number of events in a log uploaded to the UMA server.
isherman@chromium.orgfe58acc22012-02-29 01:29:58270const int kEventLimit = 2400;
jar@google.com68475e602008-08-22 03:21:15271
272// If an upload fails, and the transmission was over this byte count, then we
273// will discard the log, and not try to retransmit it. We also don't persist
274// the log to the prefs for transmission during the next chrome session if this
275// limit is exceeded.
isherman@chromium.orgfe58acc22012-02-29 01:29:58276const size_t kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29277
tedvessenes@gmail.comfc4252a72012-01-12 21:58:47278// Interval, in minutes, between state saves.
isherman@chromium.orgfe58acc22012-02-29 01:29:58279const int kSaveStateIntervalMinutes = 5;
280
isherman@chromium.org4266def22012-05-17 01:02:40281enum ResponseStatus {
282 UNKNOWN_FAILURE,
283 SUCCESS,
284 BAD_REQUEST, // Invalid syntax or log too large.
isherman@chromium.org9f5c1ce82012-05-23 23:11:28285 NO_RESPONSE,
isherman@chromium.org4266def22012-05-17 01:02:40286 NUM_RESPONSE_STATUSES
287};
288
289ResponseStatus ResponseCodeToStatus(int response_code) {
290 switch (response_code) {
291 case 200:
292 return SUCCESS;
293 case 400:
294 return BAD_REQUEST;
isherman@chromium.org9f5c1ce82012-05-23 23:11:28295 case net::URLFetcher::RESPONSE_CODE_INVALID:
296 return NO_RESPONSE;
isherman@chromium.org4266def22012-05-17 01:02:40297 default:
298 return UNKNOWN_FAILURE;
299 }
300}
301
stevet@chromium.orge61003a2012-05-24 17:03:19302// The argument used to generate a non-identifying entropy source. We want no
asvitkine@chromium.org9556a892013-06-21 16:53:20303// more than 13 bits of entropy, so use this max to return a number in the range
304// [0, 7999] as the entropy source (12.97 bits of entropy).
305const int kMaxLowEntropySize = 8000;
stevet@chromium.orge61003a2012-05-24 17:03:19306
asvitkine@chromium.orge63a9ef2012-08-30 15:29:42307// Default prefs value for prefs::kMetricsLowEntropySource to indicate that the
308// value has not yet been set.
309const int kLowEntropySourceNotSet = -1;
310
stevet@chromium.orge61003a2012-05-24 17:03:19311// Generates a new non-identifying entropy source used to seed persistent
312// activities.
313int GenerateLowEntropySource() {
asvitkine@chromium.org20f999b52012-08-24 22:32:59314 return base::RandInt(0, kMaxLowEntropySize - 1);
stevet@chromium.orge61003a2012-05-24 17:03:19315}
316
eroman@chromium.orgd7c1fa62012-06-15 23:35:30317// Converts an exit code into something that can be inserted into our
318// histograms (which expect non-negative numbers less than MAX_INT).
319int MapCrashExitCodeForHistogram(int exit_code) {
320#if defined(OS_WIN)
321 // Since |abs(STATUS_GUARD_PAGE_VIOLATION) == MAX_INT| it causes problems in
322 // histograms.cc. Solve this by remapping it to a smaller value, which
323 // hopefully doesn't conflict with other codes.
324 if (exit_code == STATUS_GUARD_PAGE_VIOLATION)
325 return 0x1FCF7EC3; // Randomly picked number.
326#endif
327
328 return std::abs(exit_code);
329}
330
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19331void MarkAppCleanShutdownAndCommit() {
332 PrefService* pref = g_browser_process->local_state();
333 pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19334 pref->SetInteger(prefs::kStabilityExecutionPhase,
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21335 MetricsService::SHUTDOWN_COMPLETE);
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19336 // Start writing right away (write happens on a different thread).
337 pref->CommitPendingWrite();
338}
339
asvitkine@chromium.org20f999b52012-08-24 22:32:59340} // namespace
initial.commit09911bf2008-07-26 23:55:29341
bengr@chromium.org60677562013-11-17 15:52:55342
343SyntheticTrialGroup::SyntheticTrialGroup(uint32 trial,
344 uint32 group,
345 base::TimeTicks start)
346 : start_time(start) {
347 id.name = trial;
348 id.group = group;
349}
350
351SyntheticTrialGroup::~SyntheticTrialGroup() {
352}
353
jar@chromium.orgc0c55e92011-09-10 18:47:30354// static
355MetricsService::ShutdownCleanliness MetricsService::clean_shutdown_status_ =
356 MetricsService::CLEANLY_SHUTDOWN;
357
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19358MetricsService::ExecutionPhase MetricsService::execution_phase_ =
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21359 MetricsService::UNINITIALIZED_PHASE;
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19360
erg@google.com679082052010-07-21 21:30:13361// This is used to quickly log stats from child process related notifications in
362// MetricsService::child_stats_buffer_. The buffer's contents are transferred
363// out when Local State is periodically saved. The information is then
364// reported to the UMA server on next launch.
365struct MetricsService::ChildProcessStats {
366 public:
jam@chromium.orgf3b357692013-03-22 05:16:13367 explicit ChildProcessStats(int process_type)
erg@google.com679082052010-07-21 21:30:13368 : process_launches(0),
369 process_crashes(0),
370 instances(0),
bauerb@chromium.orgcd937072012-07-02 09:00:29371 loading_errors(0),
jam@chromium.orgf3b357692013-03-22 05:16:13372 process_type(process_type) {}
erg@google.com679082052010-07-21 21:30:13373
374 // This constructor is only used by the map to return some default value for
375 // an index for which no value has been assigned.
376 ChildProcessStats()
377 : process_launches(0),
pkasting@chromium.orgd88bf0a2011-08-30 23:55:57378 process_crashes(0),
379 instances(0),
bauerb@chromium.orgcd937072012-07-02 09:00:29380 loading_errors(0),
jam@chromium.orgbd5d6cf2011-12-01 00:39:12381 process_type(content::PROCESS_TYPE_UNKNOWN) {}
erg@google.com679082052010-07-21 21:30:13382
383 // The number of times that the given child process has been launched
384 int process_launches;
385
386 // The number of times that the given child process has crashed
387 int process_crashes;
388
389 // The number of instances of this child process that have been created.
390 // An instance is a DOM object rendered by this child process during a page
391 // load.
392 int instances;
393
bauerb@chromium.orgcd937072012-07-02 09:00:29394 // The number of times there was an error loading an instance of this child
395 // process.
396 int loading_errors;
397
jam@chromium.orgf3b357692013-03-22 05:16:13398 int process_type;
erg@google.com679082052010-07-21 21:30:13399};
initial.commit09911bf2008-07-26 23:55:29400
sail@chromium.org84c988a2011-04-19 17:56:33401// Handles asynchronous fetching of memory details.
402// Will run the provided task after finished.
403class MetricsMemoryDetails : public MemoryDetails {
404 public:
dcheng@chromium.org2226c222011-11-22 00:08:40405 explicit MetricsMemoryDetails(const base::Closure& callback)
406 : callback_(callback) {}
sail@chromium.org84c988a2011-04-19 17:56:33407
rsleevi@chromium.orgb94584a2013-02-07 03:02:08408 virtual void OnDetailsAvailable() OVERRIDE {
xhwang@chromium.orgb3a25092013-05-28 22:08:16409 base::MessageLoop::current()->PostTask(FROM_HERE, callback_);
sail@chromium.org84c988a2011-04-19 17:56:33410 }
411
412 private:
rsleevi@chromium.orgb94584a2013-02-07 03:02:08413 virtual ~MetricsMemoryDetails() {}
sail@chromium.org84c988a2011-04-19 17:56:33414
dcheng@chromium.org2226c222011-11-22 00:08:40415 base::Closure callback_;
sail@chromium.org84c988a2011-04-19 17:56:33416 DISALLOW_COPY_AND_ASSIGN(MetricsMemoryDetails);
417};
418
initial.commit09911bf2008-07-26 23:55:29419// static
joi@chromium.orgb1de2c72013-02-06 02:45:47420void MetricsService::RegisterPrefs(PrefRegistrySimple* registry) {
initial.commit09911bf2008-07-26 23:55:29421 DCHECK(IsSingleThreaded());
dcheng@chromium.org007b3f82013-04-09 08:46:45422 registry->RegisterStringPref(prefs::kMetricsClientID, std::string());
joi@chromium.orgb1de2c72013-02-06 02:45:47423 registry->RegisterIntegerPref(prefs::kMetricsLowEntropySource,
424 kLowEntropySourceNotSet);
425 registry->RegisterInt64Pref(prefs::kMetricsClientIDTimestamp, 0);
426 registry->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
427 registry->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
dcheng@chromium.org007b3f82013-04-09 08:46:45428 registry->RegisterStringPref(prefs::kStabilityStatsVersion, std::string());
joi@chromium.orgb1de2c72013-02-06 02:45:47429 registry->RegisterInt64Pref(prefs::kStabilityStatsBuildTime, 0);
430 registry->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19431 registry->RegisterIntegerPref(prefs::kStabilityExecutionPhase,
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21432 UNINITIALIZED_PHASE);
joi@chromium.orgb1de2c72013-02-06 02:45:47433 registry->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
434 registry->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
435 registry->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
436 registry->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
437 registry->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount, 0);
438 registry->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
439 registry->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
440 registry->RegisterIntegerPref(prefs::kStabilityExtensionRendererCrashCount,
441 0);
442 registry->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
443 registry->RegisterIntegerPref(prefs::kStabilityChildProcessCrashCount, 0);
444 registry->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail, 0);
445 registry->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
446 0);
447 registry->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
448 registry->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
petkov@chromium.orgc1834a92011-01-21 18:21:03449#if defined(OS_CHROMEOS)
joi@chromium.orgb1de2c72013-02-06 02:45:47450 registry->RegisterIntegerPref(prefs::kStabilityOtherUserCrashCount, 0);
451 registry->RegisterIntegerPref(prefs::kStabilityKernelCrashCount, 0);
452 registry->RegisterIntegerPref(prefs::kStabilitySystemUncleanShutdownCount, 0);
petkov@chromium.orgc1834a92011-01-21 18:21:03453#endif // OS_CHROMEOS
cpu@google.come73c01972008-08-13 00:18:24454
isherman@chromium.org5f3e1642013-05-05 03:37:34455 registry->RegisterListPref(prefs::kMetricsInitialLogs);
456 registry->RegisterListPref(prefs::kMetricsOngoingLogs);
robertshield@google.com0bb1a622009-03-04 03:22:32457
isherman@chromium.org5c181552013-02-07 09:12:52458 registry->RegisterInt64Pref(prefs::kInstallDate, 0);
joi@chromium.orgb1de2c72013-02-06 02:45:47459 registry->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
460 registry->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
joi@chromium.orgb1de2c72013-02-06 02:45:47461 registry->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
462 registry->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
463 registry->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
initial.commit09911bf2008-07-26 23:55:29464}
465
jar@chromium.org541f77922009-02-23 21:14:38466// static
467void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
468 local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21469 local_state->SetInteger(prefs::kStabilityExecutionPhase, UNINITIALIZED_PHASE);
jar@chromium.orgc9abf242009-07-18 06:00:38470 local_state->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
jar@chromium.org541f77922009-02-23 21:14:38471
472 local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
473 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
474 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
475 local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
476 local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
477
478 local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
479 local_state->SetInteger(prefs::kStabilityCrashCount, 0);
480
481 local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
482 local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
483 local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
484
jar@chromium.org9165f742010-03-10 22:55:01485 local_state->SetInt64(prefs::kStabilityLaunchTimeSec, 0);
486 local_state->SetInt64(prefs::kStabilityLastTimestampSec, 0);
jar@chromium.org541f77922009-02-23 21:14:38487
488 local_state->ClearPref(prefs::kStabilityPluginStats);
jar@chromium.orgae155cb92009-06-19 06:10:37489
isherman@chromium.org5f3e1642013-05-05 03:37:34490 local_state->ClearPref(prefs::kMetricsInitialLogs);
491 local_state->ClearPref(prefs::kMetricsOngoingLogs);
jar@chromium.org541f77922009-02-23 21:14:38492}
493
initial.commit09911bf2008-07-26 23:55:29494MetricsService::MetricsService()
petersont@google.comd01b8732008-10-16 02:18:07495 : recording_active_(false),
496 reporting_active_(false),
stuartmorgan@chromium.org410938e02012-10-24 16:33:59497 test_mode_active_(false),
petersont@google.comd01b8732008-10-16 02:18:07498 state_(INITIALIZED),
asvitkine@chromium.orge88be472e2013-04-26 22:36:36499 low_entropy_source_(kLowEntropySourceNotSet),
petersont@google.comd01b8732008-10-16 02:18:07500 idle_since_last_transmission_(false),
initial.commit09911bf2008-07-26 23:55:29501 next_window_id_(0),
tfarina@chromium.org9c009092013-05-01 03:14:09502 self_ptr_factory_(this),
503 state_saver_factory_(this),
stevet@chromium.orge5354322012-08-09 23:07:37504 waiting_for_asynchronous_reporting_step_(false),
vitalybuka@chromium.orga3079832013-10-24 20:29:36505 num_async_histogram_fetches_in_progress_(0),
stevet@chromium.orge5354322012-08-09 23:07:37506 entropy_source_returned_(LAST_ENTROPY_NONE) {
initial.commit09911bf2008-07-26 23:55:29507 DCHECK(IsSingleThreaded());
508 InitializeMetricsState();
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16509
510 base::Closure callback = base::Bind(&MetricsService::StartScheduledUpload,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40511 self_ptr_factory_.GetWeakPtr());
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16512 scheduler_.reset(new MetricsReportingScheduler(callback));
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10513 log_manager_.set_log_serializer(new MetricsLogSerializer());
514 log_manager_.set_max_ongoing_log_store_size(kUploadLogAvoidRetransmitSize);
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:40515
516 BrowserChildProcessObserver::Add(this);
initial.commit09911bf2008-07-26 23:55:29517}
518
519MetricsService::~MetricsService() {
stuartmorgan@chromium.org410938e02012-10-24 16:33:59520 DisableRecording();
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:40521
522 BrowserChildProcessObserver::Remove(this);
initial.commit09911bf2008-07-26 23:55:29523}
524
petersont@google.comd01b8732008-10-16 02:18:07525void MetricsService::Start() {
stuartmorgan@chromium.orgb1c8dc02011-04-13 18:32:04526 HandleIdleSinceLastTransmission(false);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59527 EnableRecording();
528 EnableReporting();
petersont@google.comd01b8732008-10-16 02:18:07529}
530
stuartmorgan@chromium.org410938e02012-10-24 16:33:59531void MetricsService::StartRecordingForTests() {
532 test_mode_active_ = true;
533 EnableRecording();
534 DisableReporting();
petersont@google.comd01b8732008-10-16 02:18:07535}
536
537void MetricsService::Stop() {
stuartmorgan@chromium.orgb1c8dc02011-04-13 18:32:04538 HandleIdleSinceLastTransmission(false);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59539 DisableReporting();
540 DisableRecording();
541}
542
543void MetricsService::EnableReporting() {
544 if (reporting_active_)
545 return;
546 reporting_active_ = true;
547 StartSchedulerIfNecessary();
548}
549
550void MetricsService::DisableReporting() {
551 reporting_active_ = false;
petersont@google.comd01b8732008-10-16 02:18:07552}
553
joi@chromium.orgedafd4c2011-05-10 17:18:53554std::string MetricsService::GetClientId() {
555 return client_id_;
556}
557
asvitkine@chromium.org20f999b52012-08-24 22:32:59558scoped_ptr<const base::FieldTrial::EntropyProvider>
559 MetricsService::CreateEntropyProvider(bool reporting_will_be_enabled) {
stevet@chromium.org29d81ee02012-05-25 05:45:42560 // For metrics reporting-enabled users, we combine the client ID and low
561 // entropy source to get the final entropy source. Otherwise, only use the low
562 // entropy source.
563 // This has two useful properties:
stevet@chromium.orge61003a2012-05-24 17:03:19564 // 1) It makes the entropy source less identifiable for parties that do not
565 // know the low entropy source.
566 // 2) It makes the final entropy source resettable.
asvitkine@chromium.orgd0a82c82013-06-13 16:31:18567 const int low_entropy_source_value = GetLowEntropySource();
568 UMA_HISTOGRAM_SPARSE_SLOWLY("UMA.LowEntropySourceValue",
569 low_entropy_source_value);
stevet@chromium.orge5354322012-08-09 23:07:37570 if (reporting_will_be_enabled) {
stevet@chromium.org5fbffb72012-08-18 01:59:18571 if (entropy_source_returned_ == LAST_ENTROPY_NONE)
572 entropy_source_returned_ = LAST_ENTROPY_HIGH;
573 DCHECK_EQ(LAST_ENTROPY_HIGH, entropy_source_returned_);
asvitkine@chromium.org20f999b52012-08-24 22:32:59574 const std::string high_entropy_source =
asvitkine@chromium.orgd0a82c82013-06-13 16:31:18575 client_id_ + base::IntToString(low_entropy_source_value);
asvitkine@chromium.org20f999b52012-08-24 22:32:59576 return scoped_ptr<const base::FieldTrial::EntropyProvider>(
577 new metrics::SHA1EntropyProvider(high_entropy_source));
stevet@chromium.orge5354322012-08-09 23:07:37578 }
asvitkine@chromium.org20f999b52012-08-24 22:32:59579
stevet@chromium.org5fbffb72012-08-18 01:59:18580 if (entropy_source_returned_ == LAST_ENTROPY_NONE)
581 entropy_source_returned_ = LAST_ENTROPY_LOW;
582 DCHECK_EQ(LAST_ENTROPY_LOW, entropy_source_returned_);
asvitkine@chromium.org9d7c4a82013-05-07 12:10:49583
584#if defined(OS_ANDROID) || defined(OS_IOS)
585 return scoped_ptr<const base::FieldTrial::EntropyProvider>(
586 new metrics::CachingPermutedEntropyProvider(
587 g_browser_process->local_state(),
asvitkine@chromium.orgd0a82c82013-06-13 16:31:18588 low_entropy_source_value,
asvitkine@chromium.org9d7c4a82013-05-07 12:10:49589 kMaxLowEntropySize));
590#else
asvitkine@chromium.org20f999b52012-08-24 22:32:59591 return scoped_ptr<const base::FieldTrial::EntropyProvider>(
asvitkine@chromium.orgd0a82c82013-06-13 16:31:18592 new metrics::PermutedEntropyProvider(low_entropy_source_value,
asvitkine@chromium.org20f999b52012-08-24 22:32:59593 kMaxLowEntropySize));
asvitkine@chromium.org9d7c4a82013-05-07 12:10:49594#endif
stevet@chromium.orge61003a2012-05-24 17:03:19595}
596
jam@chromium.org5cbeeef72012-02-08 02:05:18597void MetricsService::ForceClientIdCreation() {
598 if (!client_id_.empty())
599 return;
600 PrefService* pref = g_browser_process->local_state();
601 client_id_ = pref->GetString(prefs::kMetricsClientID);
602 if (!client_id_.empty())
603 return;
604
605 client_id_ = GenerateClientID();
606 pref->SetString(prefs::kMetricsClientID, client_id_);
607
608 // Might as well make a note of how long this ID has existed
609 pref->SetString(prefs::kMetricsClientIDTimestamp,
610 base::Int64ToString(Time::Now().ToTimeT()));
611}
612
stuartmorgan@chromium.org410938e02012-10-24 16:33:59613void MetricsService::EnableRecording() {
initial.commit09911bf2008-07-26 23:55:29614 DCHECK(IsSingleThreaded());
615
stuartmorgan@chromium.org410938e02012-10-24 16:33:59616 if (recording_active_)
initial.commit09911bf2008-07-26 23:55:29617 return;
stuartmorgan@chromium.org410938e02012-10-24 16:33:59618 recording_active_ = true;
initial.commit09911bf2008-07-26 23:55:29619
stuartmorgan@chromium.org410938e02012-10-24 16:33:59620 ForceClientIdCreation();
rsesek@chromium.org264c0acac2013-10-01 13:33:30621 crash_keys::SetClientID(client_id_);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59622 if (!log_manager_.current_log())
623 OpenNewLog();
pkasting@chromium.org005ef3e2009-05-22 20:55:46624
stuartmorgan@chromium.org410938e02012-10-24 16:33:59625 SetUpNotifications(&registrar_, this);
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:22626 content::RemoveActionCallback(action_callback_);
627 action_callback_ = base::Bind(&MetricsService::OnUserAction,
628 base::Unretained(this));
629 content::AddActionCallback(action_callback_);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59630}
631
632void MetricsService::DisableRecording() {
633 DCHECK(IsSingleThreaded());
634
635 if (!recording_active_)
636 return;
637 recording_active_ = false;
638
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:22639 content::RemoveActionCallback(action_callback_);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59640 registrar_.RemoveAll();
641 PushPendingLogsToPersistentStorage();
642 DCHECK(!log_manager_.has_staged_log());
initial.commit09911bf2008-07-26 23:55:29643}
644
petersont@google.comd01b8732008-10-16 02:18:07645bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29646 DCHECK(IsSingleThreaded());
petersont@google.comd01b8732008-10-16 02:18:07647 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29648}
649
petersont@google.comd01b8732008-10-16 02:18:07650bool MetricsService::reporting_active() const {
651 DCHECK(IsSingleThreaded());
652 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29653}
654
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15655// static
jam@chromium.org6c2381d2011-10-19 02:52:53656void MetricsService::SetUpNotifications(
657 content::NotificationRegistrar* registrar,
658 content::NotificationObserver* observer) {
659 registrar->Add(observer, chrome::NOTIFICATION_BROWSER_OPENED,
jam@chromium.orgad50def52011-10-19 23:17:07660 content::NotificationService::AllBrowserContextsAndSources());
jam@chromium.org6c2381d2011-10-19 02:52:53661 registrar->Add(observer, chrome::NOTIFICATION_BROWSER_CLOSED,
jam@chromium.orgad50def52011-10-19 23:17:07662 content::NotificationService::AllSources());
avi@chromium.org884033e2012-04-16 19:38:42663 registrar->Add(observer, chrome::NOTIFICATION_TAB_PARENTED,
jam@chromium.orgad50def52011-10-19 23:17:07664 content::NotificationService::AllSources());
avi@chromium.org884033e2012-04-16 19:38:42665 registrar->Add(observer, chrome::NOTIFICATION_TAB_CLOSING,
jam@chromium.orgad50def52011-10-19 23:17:07666 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53667 registrar->Add(observer, content::NOTIFICATION_LOAD_START,
jam@chromium.orgad50def52011-10-19 23:17:07668 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53669 registrar->Add(observer, content::NOTIFICATION_LOAD_STOP,
jam@chromium.orgad50def52011-10-19 23:17:07670 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53671 registrar->Add(observer, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
jam@chromium.orgad50def52011-10-19 23:17:07672 content::NotificationService::AllSources());
avi@chromium.org42d8d7582013-11-09 01:24:38673 registrar->Add(observer, content::NOTIFICATION_RENDER_WIDGET_HOST_HANG,
jam@chromium.orgad50def52011-10-19 23:17:07674 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53675 registrar->Add(observer, chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
jam@chromium.orgad50def52011-10-19 23:17:07676 content::NotificationService::AllSources());
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15677}
678
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:40679void MetricsService::BrowserChildProcessHostConnected(
680 const content::ChildProcessData& data) {
681 GetChildProcessStats(data).process_launches++;
682}
683
684void MetricsService::BrowserChildProcessCrashed(
685 const content::ChildProcessData& data) {
686 GetChildProcessStats(data).process_crashes++;
687 // Exclude plugin crashes from the count below because we report them via
688 // a separate UMA metric.
jam@chromium.orgf3b357692013-03-22 05:16:13689 if (!IsPluginProcess(data.process_type))
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:40690 IncrementPrefValue(prefs::kStabilityChildProcessCrashCount);
691}
692
693void MetricsService::BrowserChildProcessInstanceCreated(
694 const content::ChildProcessData& data) {
695 GetChildProcessStats(data).instances++;
696}
697
ananta@chromium.org432115822011-07-10 15:52:27698void MetricsService::Observe(int type,
jam@chromium.org6c2381d2011-10-19 02:52:53699 const content::NotificationSource& source,
700 const content::NotificationDetails& details) {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10701 DCHECK(log_manager_.current_log());
initial.commit09911bf2008-07-26 23:55:29702 DCHECK(IsSingleThreaded());
703
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:22704 if (!CanLogNotification())
initial.commit09911bf2008-07-26 23:55:29705 return;
706
ananta@chromium.org432115822011-07-10 15:52:27707 switch (type) {
ananta@chromium.org432115822011-07-10 15:52:27708 case chrome::NOTIFICATION_BROWSER_OPENED:
isherman@chromium.org46a0efc2013-07-17 15:40:47709 case chrome::NOTIFICATION_BROWSER_CLOSED:
710 case chrome::NOTIFICATION_TAB_PARENTED:
711 case chrome::NOTIFICATION_TAB_CLOSING:
ananta@chromium.org432115822011-07-10 15:52:27712 case content::NOTIFICATION_LOAD_STOP:
isherman@chromium.org46a0efc2013-07-17 15:40:47713 // These notifications are currently used only to break out of idle mode.
initial.commit09911bf2008-07-26 23:55:29714 break;
715
rlp@chromium.org752a5262013-06-23 14:53:42716 case content::NOTIFICATION_LOAD_START: {
717 content::NavigationController* controller =
718 content::Source<content::NavigationController>(source).ptr();
719 content::WebContents* web_contents = controller->GetWebContents();
720 LogLoadStarted(web_contents);
initial.commit09911bf2008-07-26 23:55:29721 break;
rlp@chromium.org752a5262013-06-23 14:53:42722 }
initial.commit09911bf2008-07-26 23:55:29723
ananta@chromium.org432115822011-07-10 15:52:27724 case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: {
ananta@chromium.orgf3b1a082011-11-18 00:34:30725 content::RenderProcessHost::RendererClosedDetails* process_details =
726 content::Details<
727 content::RenderProcessHost::RendererClosedDetails>(
728 details).ptr();
729 content::RenderProcessHost* host =
730 content::Source<content::RenderProcessHost>(source).ptr();
jar@chromium.orgc3721482012-03-23 16:21:48731 LogRendererCrash(
jam@chromium.orgf1675202012-07-09 15:18:00732 host, process_details->status, process_details->exit_code);
asargent@chromium.org1f085622009-12-04 05:33:45733 }
initial.commit09911bf2008-07-26 23:55:29734 break;
735
avi@chromium.org42d8d7582013-11-09 01:24:38736 case content::NOTIFICATION_RENDER_WIDGET_HOST_HANG:
initial.commit09911bf2008-07-26 23:55:29737 LogRendererHang();
738 break;
739
ananta@chromium.org432115822011-07-10 15:52:27740 case chrome::NOTIFICATION_OMNIBOX_OPENED_URL: {
isherman@chromium.org279703f2012-01-20 22:23:26741 MetricsLog* current_log =
742 static_cast<MetricsLog*>(log_manager_.current_log());
ananta@chromium.org1226abb2010-06-10 18:01:28743 DCHECK(current_log);
744 current_log->RecordOmniboxOpenedURL(
tfarina@chromium.org0fafc8d2013-06-01 00:09:50745 *content::Details<OmniboxLog>(details).ptr());
initial.commit09911bf2008-07-26 23:55:29746 break;
ananta@chromium.org1226abb2010-06-10 18:01:28747 }
initial.commit09911bf2008-07-26 23:55:29748
initial.commit09911bf2008-07-26 23:55:29749 default:
jar@chromium.orga063c102010-07-22 22:20:19750 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:29751 break;
752 }
petersont@google.comd01b8732008-10-16 02:18:07753
754 HandleIdleSinceLastTransmission(false);
petersont@google.comd01b8732008-10-16 02:18:07755}
756
757void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
758 // If there wasn't a lot of action, maybe the computer was asleep, in which
759 // case, the log transmissions should have stopped. Here we start them up
760 // again.
pkasting@chromium.orgcac78842008-11-27 01:02:20761 if (!in_idle && idle_since_last_transmission_)
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16762 StartSchedulerIfNecessary();
pkasting@chromium.orgcac78842008-11-27 01:02:20763 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29764}
765
initial.commit09911bf2008-07-26 23:55:29766void MetricsService::RecordStartOfSessionEnd() {
stuartmorgan@chromium.org466f3c12011-03-23 21:20:38767 LogCleanShutdown();
initial.commit09911bf2008-07-26 23:55:29768 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
769}
770
771void MetricsService::RecordCompletedSessionEnd() {
stuartmorgan@chromium.org466f3c12011-03-23 21:20:38772 LogCleanShutdown();
initial.commit09911bf2008-07-26 23:55:29773 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
774}
775
stuartmorgan@chromium.org410938e02012-10-24 16:33:59776#if defined(OS_ANDROID) || defined(OS_IOS)
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39777void MetricsService::OnAppEnterBackground() {
778 scheduler_->Stop();
779
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19780 MarkAppCleanShutdownAndCommit();
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39781
782 // At this point, there's no way of knowing when the process will be
783 // killed, so this has to be treated similar to a shutdown, closing and
784 // persisting all logs. Unlinke a shutdown, the state is primed to be ready
785 // to continue logging and uploading if the process does return.
786 if (recording_active() && state_ >= INITIAL_LOG_READY) {
787 PushPendingLogsToPersistentStorage();
stuartmorgan@chromium.org410938e02012-10-24 16:33:59788 // Persisting logs closes the current log, so start recording a new log
789 // immediately to capture any background work that might be done before the
790 // process is killed.
791 OpenNewLog();
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39792 }
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39793}
794
795void MetricsService::OnAppEnterForeground() {
796 PrefService* pref = g_browser_process->local_state();
797 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39798
799 StartSchedulerIfNecessary();
800}
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19801#else
802void MetricsService::LogNeedForCleanShutdown() {
803 PrefService* pref = g_browser_process->local_state();
804 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19805 // Redundant setting to be sure we call for a clean shutdown.
806 clean_shutdown_status_ = NEED_TO_SHUTDOWN;
807}
808#endif // defined(OS_ANDROID) || defined(OS_IOS)
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39809
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21810// static
811void MetricsService::SetExecutionPhase(ExecutionPhase execution_phase) {
812 execution_phase_ = execution_phase;
813 PrefService* pref = g_browser_process->local_state();
814 pref->SetInteger(prefs::kStabilityExecutionPhase, execution_phase_);
815}
816
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16817void MetricsService::RecordBreakpadRegistration(bool success) {
jar@google.com68475e602008-08-22 03:21:15818 if (!success)
cpu@google.come73c01972008-08-13 00:18:24819 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
820 else
821 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
822}
823
824void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
825 if (!has_debugger)
826 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
827 else
jar@google.com68475e602008-08-22 03:21:15828 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
cpu@google.come73c01972008-08-13 00:18:24829}
830
rogerm@chromium.org261ab7c2013-08-19 15:04:58831#if defined(OS_WIN)
832void MetricsService::CountBrowserCrashDumpAttempts() {
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45833 // Open the registry key for iteration.
rogerm@chromium.org261ab7c2013-08-19 15:04:58834 base::win::RegKey regkey;
835 if (regkey.Open(HKEY_CURRENT_USER,
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45836 chrome::kBrowserCrashDumpAttemptsRegistryPath,
rogerm@chromium.org261ab7c2013-08-19 15:04:58837 KEY_ALL_ACCESS) != ERROR_SUCCESS) {
838 return;
839 }
840
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45841 // The values we're interested in counting are all prefixed with the version.
842 base::string16 chrome_version(base::ASCIIToUTF16(chrome::kChromeVersion));
843
844 // Track a list of values to delete. We don't modify the registry key while
845 // we're iterating over its values.
846 typedef std::vector<base::string16> StringVector;
847 StringVector to_delete;
848
849 // Iterate over the values in the key counting dumps with and without crashes.
850 // We directly walk the values instead of using RegistryValueIterator in order
851 // to read all of the values as DWORDS instead of strings.
852 base::string16 name;
853 DWORD value = 0;
854 int dumps_with_crash = 0;
855 int dumps_with_no_crash = 0;
rogerm@chromium.org261ab7c2013-08-19 15:04:58856 for (int i = regkey.GetValueCount() - 1; i >= 0; --i) {
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45857 if (regkey.GetValueNameAt(i, &name) == ERROR_SUCCESS &&
858 StartsWith(name, chrome_version, false) &&
859 regkey.ReadValueDW(name.c_str(), &value) == ERROR_SUCCESS) {
860 to_delete.push_back(name);
861 if (value == 0)
862 ++dumps_with_no_crash;
863 else
864 ++dumps_with_crash;
rogerm@chromium.org261ab7c2013-08-19 15:04:58865 }
866 }
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45867
868 // Delete the registry keys we've just counted.
869 for (StringVector::iterator i = to_delete.begin(); i != to_delete.end(); ++i)
870 regkey.DeleteValue(i->c_str());
871
872 // Capture the histogram samples.
873 if (dumps_with_crash != 0)
874 UMA_HISTOGRAM_COUNTS("Chrome.BrowserDumpsWithCrash", dumps_with_crash);
875 if (dumps_with_no_crash != 0)
876 UMA_HISTOGRAM_COUNTS("Chrome.BrowserDumpsWithNoCrash", dumps_with_no_crash);
877 int total_dumps = dumps_with_crash + dumps_with_no_crash;
878 if (total_dumps != 0)
879 UMA_HISTOGRAM_COUNTS("Chrome.BrowserCrashDumpAttempts", total_dumps);
rogerm@chromium.org261ab7c2013-08-19 15:04:58880}
881#endif // defined(OS_WIN)
882
initial.commit09911bf2008-07-26 23:55:29883//------------------------------------------------------------------------------
884// private methods
885//------------------------------------------------------------------------------
886
887
888//------------------------------------------------------------------------------
889// Initialization methods
890
891void MetricsService::InitializeMetricsState() {
kuchhal@chromium.org79bf0b72009-04-27 21:30:55892#if defined(OS_POSIX)
simonjam@chromium.orgb4a72d842012-03-22 20:09:09893 network_stats_server_ = chrome_common_net::kEchoTestServerLocation;
894 http_pipelining_test_server_ = chrome_common_net::kPipelineTestServerBaseUrl;
kuchhal@chromium.org79bf0b72009-04-27 21:30:55895#else
896 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
rtenneti@chromium.orgd67d1052011-06-09 05:11:41897 network_stats_server_ = dist->GetNetworkStatsServer();
simonjam@chromium.orgadbb3762012-03-09 22:20:08898 http_pipelining_test_server_ = dist->GetHttpPipeliningTestServer();
kuchhal@chromium.org79bf0b72009-04-27 21:30:55899#endif
900
initial.commit09911bf2008-07-26 23:55:29901 PrefService* pref = g_browser_process->local_state();
902 DCHECK(pref);
903
jar@chromium.org225c50842010-01-19 21:19:13904 if ((pref->GetInt64(prefs::kStabilityStatsBuildTime)
905 != MetricsLog::GetBuildTime()) ||
estade@chromium.orgddd231e2010-06-29 20:35:19906 (pref->GetString(prefs::kStabilityStatsVersion)
jar@chromium.org225c50842010-01-19 21:19:13907 != MetricsLog::GetVersionString())) {
jar@chromium.org541f77922009-02-23 21:14:38908 // This is a new version, so we don't want to confuse the stats about the
909 // old version with info that we upload.
910 DiscardOldStabilityStats(pref);
911 pref->SetString(prefs::kStabilityStatsVersion,
estade@chromium.orgddd231e2010-06-29 20:35:19912 MetricsLog::GetVersionString());
jar@chromium.org225c50842010-01-19 21:19:13913 pref->SetInt64(prefs::kStabilityStatsBuildTime,
914 MetricsLog::GetBuildTime());
jar@chromium.org541f77922009-02-23 21:14:38915 }
916
initial.commit09911bf2008-07-26 23:55:29917 // Update session ID
918 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
919 ++session_id_;
920 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
921
initial.commit09911bf2008-07-26 23:55:29922 // Stability bookkeeping
cpu@google.come73c01972008-08-13 00:18:24923 IncrementPrefValue(prefs::kStabilityLaunchCount);
initial.commit09911bf2008-07-26 23:55:29924
cpu@google.come73c01972008-08-13 00:18:24925 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
926 IncrementPrefValue(prefs::kStabilityCrashCount);
jar@chromium.orgc0c55e92011-09-10 18:47:30927 // Reset flag, and wait until we call LogNeedForCleanShutdown() before
928 // monitoring.
929 pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19930
931 // TODO(rtenneti): On windows, consider saving/getting execution_phase from
932 // the registry.
933 int execution_phase = pref->GetInteger(prefs::kStabilityExecutionPhase);
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21934 UMA_HISTOGRAM_SPARSE_SLOWLY("Chrome.Browser.CrashedExecutionPhase",
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19935 execution_phase);
initial.commit09911bf2008-07-26 23:55:29936 }
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21937 DCHECK_EQ(UNINITIALIZED_PHASE, execution_phase_);
938 SetExecutionPhase(START_METRICS_RECORDING);
cpu@google.come73c01972008-08-13 00:18:24939
rogerm@chromium.org261ab7c2013-08-19 15:04:58940#if defined(OS_WIN)
941 CountBrowserCrashDumpAttempts();
942#endif // defined(OS_WIN)
943
cpu@google.come73c01972008-08-13 00:18:24944 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
945 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
jar@chromium.orgc9abf242009-07-18 06:00:38946 // This is marked false when we get a WM_ENDSESSION.
947 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
initial.commit09911bf2008-07-26 23:55:29948 }
initial.commit09911bf2008-07-26 23:55:29949
jar@chromium.org9165f742010-03-10 22:55:01950 // Initialize uptime counters.
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36951 const base::TimeDelta startup_uptime = GetIncrementalUptime(pref);
952 DCHECK_EQ(0, startup_uptime.InMicroseconds());
jar@chromium.org9165f742010-03-10 22:55:01953 // For backwards compatibility, leave this intact in case Omaha is checking
954 // them. prefs::kStabilityLastTimestampSec may also be useless now.
955 // TODO(jar): Delete these if they have no uses.
robertshield@google.com0bb1a622009-03-04 03:22:32956 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
957
958 // Bookkeeping for the uninstall metrics.
959 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29960
jar@chromium.org92745242009-06-12 16:52:21961 // Get stats on use of command line.
962 const CommandLine* command_line(CommandLine::ForCurrentProcess());
963 size_t common_commands = 0;
964 if (command_line->HasSwitch(switches::kUserDataDir)) {
965 ++common_commands;
966 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
967 }
968
969 if (command_line->HasSwitch(switches::kApp)) {
970 ++common_commands;
971 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
972 }
973
msw@chromium.org62b4e522011-07-13 21:46:32974 size_t switch_count = command_line->GetSwitches().size();
975 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount", switch_count);
jar@chromium.org92745242009-06-12 16:52:21976 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
msw@chromium.org62b4e522011-07-13 21:46:32977 switch_count - common_commands);
jar@chromium.org92745242009-06-12 16:52:21978
initial.commit09911bf2008-07-26 23:55:29979 // Kick off the process of saving the state (so the uptime numbers keep
980 // getting updated) every n minutes.
981 ScheduleNextStateSave();
982}
983
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40984// static
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56985void MetricsService::InitTaskGetHardwareClass(
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40986 base::WeakPtr<MetricsService> self,
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56987 base::MessageLoopProxy* target_loop) {
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56988 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
989
990 std::string hardware_class;
991#if defined(OS_CHROMEOS)
992 chromeos::system::StatisticsProvider::GetInstance()->GetMachineStatistic(
993 "hardware_class", &hardware_class);
994#endif // OS_CHROMEOS
995
996 target_loop->PostTask(FROM_HERE,
997 base::Bind(&MetricsService::OnInitTaskGotHardwareClass,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40998 self, hardware_class));
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56999}
1000
1001void MetricsService::OnInitTaskGotHardwareClass(
1002 const std::string& hardware_class) {
isherman@chromium.orged0fd002012-04-25 23:10:341003 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
zelidrag@chromium.org85ed9d42010-06-08 22:37:441004 hardware_class_ = hardware_class;
rsesek@chromium.orgd33e7cc2011-09-23 01:43:561005
nileshagrawal@chromium.orgebd71962012-12-20 02:56:551006#if defined(ENABLE_PLUGINS)
rsesek@chromium.orgd33e7cc2011-09-23 01:43:561007 // Start the next part of the init task: loading plugin information.
1008 PluginService::GetInstance()->GetPlugins(
1009 base::Bind(&MetricsService::OnInitTaskGotPluginInfo,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401010 self_ptr_factory_.GetWeakPtr()));
nileshagrawal@chromium.orgebd71962012-12-20 02:56:551011#else
jam@chromium.orgd7bd3e52013-07-21 04:29:201012 std::vector<content::WebPluginInfo> plugin_list_empty;
nileshagrawal@chromium.orgebd71962012-12-20 02:56:551013 OnInitTaskGotPluginInfo(plugin_list_empty);
1014#endif // defined(ENABLE_PLUGINS)
rsesek@chromium.orgd33e7cc2011-09-23 01:43:561015}
1016
1017void MetricsService::OnInitTaskGotPluginInfo(
jam@chromium.orgd7bd3e52013-07-21 04:29:201018 const std::vector<content::WebPluginInfo>& plugins) {
isherman@chromium.orged0fd002012-04-25 23:10:341019 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
jam@chromium.org35fa6a22009-08-15 00:04:011020 plugins_ = plugins;
rsesek@chromium.orgd33e7cc2011-09-23 01:43:561021
ryanmyers@chromium.org197c0772012-05-14 23:50:511022 // Schedules a task on a blocking pool thread to gather Google Update
1023 // statistics (requires Registry reads).
1024 BrowserThread::PostBlockingPoolTask(
1025 FROM_HERE,
1026 base::Bind(&MetricsService::InitTaskGetGoogleUpdateData,
1027 self_ptr_factory_.GetWeakPtr(),
xhwang@chromium.orgb3a25092013-05-28 22:08:161028 base::MessageLoop::current()->message_loop_proxy()));
ryanmyers@chromium.org197c0772012-05-14 23:50:511029}
1030
1031// static
1032void MetricsService::InitTaskGetGoogleUpdateData(
1033 base::WeakPtr<MetricsService> self,
1034 base::MessageLoopProxy* target_loop) {
1035 GoogleUpdateMetrics google_update_metrics;
1036
1037#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
1038 const bool system_install = GoogleUpdateSettings::IsSystemInstall();
1039
1040 google_update_metrics.is_system_install = system_install;
1041 google_update_metrics.last_started_au =
1042 GoogleUpdateSettings::GetGoogleUpdateLastStartedAU(system_install);
1043 google_update_metrics.last_checked =
1044 GoogleUpdateSettings::GetGoogleUpdateLastChecked(system_install);
1045 GoogleUpdateSettings::GetUpdateDetailForGoogleUpdate(
1046 system_install,
1047 &google_update_metrics.google_update_data);
1048 GoogleUpdateSettings::GetUpdateDetail(
1049 system_install,
1050 &google_update_metrics.product_data);
1051#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
1052
1053 target_loop->PostTask(FROM_HERE,
1054 base::Bind(&MetricsService::OnInitTaskGotGoogleUpdateData,
1055 self, google_update_metrics));
1056}
1057
1058void MetricsService::OnInitTaskGotGoogleUpdateData(
1059 const GoogleUpdateMetrics& google_update_metrics) {
1060 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
1061
1062 google_update_metrics_ = google_update_metrics;
1063
isherman@chromium.orged0fd002012-04-25 23:10:341064 // Start the next part of the init task: fetching performance data. This will
1065 // call into |FinishedReceivingProfilerData()| when the task completes.
1066 chrome_browser_metrics::TrackingSynchronizer::FetchProfilerDataAsynchronously(
1067 self_ptr_factory_.GetWeakPtr());
1068}
1069
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:221070void MetricsService::OnUserAction(const std::string& action) {
1071 if (!CanLogNotification())
1072 return;
1073
1074 log_manager_.current_log()->RecordUserAction(action.c_str());
1075 HandleIdleSinceLastTransmission(false);
1076}
1077
isherman@chromium.orged0fd002012-04-25 23:10:341078void MetricsService::ReceivedProfilerData(
1079 const tracked_objects::ProcessDataSnapshot& process_data,
jam@chromium.orgf3b357692013-03-22 05:16:131080 int process_type) {
isherman@chromium.orged0fd002012-04-25 23:10:341081 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
1082
1083 // Upon the first callback, create the initial log so that we can immediately
1084 // save the profiler data.
1085 if (!initial_log_.get())
1086 initial_log_.reset(new MetricsLog(client_id_, session_id_));
1087
1088 initial_log_->RecordProfilerData(process_data, process_type);
1089}
1090
1091void MetricsService::FinishedReceivingProfilerData() {
1092 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361093 state_ = INIT_TASK_DONE;
1094}
1095
1096base::TimeDelta MetricsService::GetIncrementalUptime(PrefService* pref) {
1097 base::TimeTicks now = base::TimeTicks::Now();
1098 // If this is the first call, init |last_updated_time_|.
1099 if (last_updated_time_.is_null())
1100 last_updated_time_ = now;
1101 const base::TimeDelta incremental_time = now - last_updated_time_;
1102 last_updated_time_ = now;
1103
1104 const int64 incremental_time_secs = incremental_time.InSeconds();
1105 if (incremental_time_secs > 0) {
1106 int64 metrics_uptime = pref->GetInt64(prefs::kUninstallMetricsUptimeSec);
1107 metrics_uptime += incremental_time_secs;
1108 pref->SetInt64(prefs::kUninstallMetricsUptimeSec, metrics_uptime);
1109 }
1110
1111 return incremental_time;
initial.commit09911bf2008-07-26 23:55:291112}
1113
stevet@chromium.orge61003a2012-05-24 17:03:191114int MetricsService::GetLowEntropySource() {
1115 // Note that the default value for the low entropy source and the default pref
asvitkine@chromium.orge88be472e2013-04-26 22:36:361116 // value are both kLowEntropySourceNotSet, which is used to identify if the
1117 // value has been set or not.
1118 if (low_entropy_source_ != kLowEntropySourceNotSet)
stevet@chromium.orge61003a2012-05-24 17:03:191119 return low_entropy_source_;
1120
asvitkine@chromium.org9d7c4a82013-05-07 12:10:491121 PrefService* local_state = g_browser_process->local_state();
stevet@chromium.orge61003a2012-05-24 17:03:191122 const CommandLine* command_line(CommandLine::ForCurrentProcess());
1123 // Only try to load the value from prefs if the user did not request a reset.
1124 // Otherwise, skip to generating a new value.
stevet@chromium.org1862c0c2013-04-18 06:30:481125 if (!command_line->HasSwitch(switches::kResetVariationState)) {
asvitkine@chromium.org9556a892013-06-21 16:53:201126 int value = local_state->GetInteger(prefs::kMetricsLowEntropySource);
1127 // Old versions of the code would generate values in the range of [1, 8192],
1128 // before the range was switched to [0, 8191] and then to [0, 7999]. Map
1129 // 8192 to 0, so that the 0th bucket remains uniform, while re-generating
1130 // the low entropy source for old values in the [8000, 8191] range.
1131 if (value == 8192)
1132 value = 0;
1133 // If the value is outside the [0, kMaxLowEntropySize) range, re-generate
1134 // it below.
1135 if (value >= 0 && value < kMaxLowEntropySize) {
1136 low_entropy_source_ = value;
stevet@chromium.org0c906e92012-10-18 15:24:131137 UMA_HISTOGRAM_BOOLEAN("UMA.GeneratedLowEntropySource", false);
stevet@chromium.orge61003a2012-05-24 17:03:191138 return low_entropy_source_;
asvitkine@chromium.orge63a9ef2012-08-30 15:29:421139 }
stevet@chromium.orge61003a2012-05-24 17:03:191140 }
1141
stevet@chromium.org0c906e92012-10-18 15:24:131142 UMA_HISTOGRAM_BOOLEAN("UMA.GeneratedLowEntropySource", true);
stevet@chromium.orge61003a2012-05-24 17:03:191143 low_entropy_source_ = GenerateLowEntropySource();
asvitkine@chromium.org9d7c4a82013-05-07 12:10:491144 local_state->SetInteger(prefs::kMetricsLowEntropySource, low_entropy_source_);
1145 metrics::CachingPermutedEntropyProvider::ClearCache(local_state);
stevet@chromium.orge61003a2012-05-24 17:03:191146
1147 return low_entropy_source_;
1148}
1149
1150// static
initial.commit09911bf2008-07-26 23:55:291151std::string MetricsService::GenerateClientID() {
marja@chromium.org7e49ad32012-06-14 14:22:071152 return base::GenerateGUID();
initial.commit09911bf2008-07-26 23:55:291153}
1154
initial.commit09911bf2008-07-26 23:55:291155//------------------------------------------------------------------------------
1156// State save methods
1157
1158void MetricsService::ScheduleNextStateSave() {
isherman@chromium.org8454aeb2011-11-19 23:38:201159 state_saver_factory_.InvalidateWeakPtrs();
initial.commit09911bf2008-07-26 23:55:291160
xhwang@chromium.orgb3a25092013-05-28 22:08:161161 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
isherman@chromium.org8454aeb2011-11-19 23:38:201162 base::Bind(&MetricsService::SaveLocalState,
1163 state_saver_factory_.GetWeakPtr()),
tedvessenes@gmail.comfc4252a72012-01-12 21:58:471164 base::TimeDelta::FromMinutes(kSaveStateIntervalMinutes));
initial.commit09911bf2008-07-26 23:55:291165}
1166
1167void MetricsService::SaveLocalState() {
1168 PrefService* pref = g_browser_process->local_state();
1169 if (!pref) {
jar@chromium.orga063c102010-07-22 22:20:191170 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291171 return;
1172 }
1173
1174 RecordCurrentState(pref);
initial.commit09911bf2008-07-26 23:55:291175
tedvessenes@gmail.comfc4252a72012-01-12 21:58:471176 // TODO(jar):110021 Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:291177 ScheduleNextStateSave();
1178}
1179
1180
1181//------------------------------------------------------------------------------
1182// Recording control methods
1183
stuartmorgan@chromium.org410938e02012-10-24 16:33:591184void MetricsService::OpenNewLog() {
1185 DCHECK(!log_manager_.current_log());
initial.commit09911bf2008-07-26 23:55:291186
stuartmorgan@chromium.org29948262012-03-01 12:15:081187 log_manager_.BeginLoggingWithLog(new MetricsLog(client_id_, session_id_),
asvitkine@chromium.org0edf8762013-11-21 18:33:301188 MetricsLog::ONGOING_LOG);
initial.commit09911bf2008-07-26 23:55:291189 if (state_ == INITIALIZED) {
1190 // We only need to schedule that run once.
zelidrag@chromium.org85ed9d42010-06-08 22:37:441191 state_ = INIT_TASK_SCHEDULED;
initial.commit09911bf2008-07-26 23:55:291192
zelidrag@chromium.org85ed9d42010-06-08 22:37:441193 // Schedules a task on the file thread for execution of slower
1194 // initialization steps (such as plugin list generation) necessary
1195 // for sending the initial log. This avoids blocking the main UI
1196 // thread.
joi@chromium.orged10dd12011-12-07 12:03:421197 BrowserThread::PostDelayedTask(
1198 BrowserThread::FILE,
1199 FROM_HERE,
rsesek@chromium.orgd33e7cc2011-09-23 01:43:561200 base::Bind(&MetricsService::InitTaskGetHardwareClass,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401201 self_ptr_factory_.GetWeakPtr(),
xhwang@chromium.orgb3a25092013-05-28 22:08:161202 base::MessageLoop::current()->message_loop_proxy()),
tedvessenes@gmail.com7e560102012-03-08 20:58:421203 base::TimeDelta::FromSeconds(kInitializationDelaySeconds));
initial.commit09911bf2008-07-26 23:55:291204 }
1205}
1206
stuartmorgan@chromium.org410938e02012-10-24 16:33:591207void MetricsService::CloseCurrentLog() {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101208 if (!log_manager_.current_log())
initial.commit09911bf2008-07-26 23:55:291209 return;
1210
jar@google.com68475e602008-08-22 03:21:151211 // TODO(jar): Integrate bounds on log recording more consistently, so that we
1212 // can stop recording logs that are too big much sooner.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101213 if (log_manager_.current_log()->num_events() > kEventLimit) {
dsh@google.com553dba62009-02-24 19:08:231214 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101215 log_manager_.current_log()->num_events());
1216 log_manager_.DiscardCurrentLog();
stuartmorgan@chromium.org410938e02012-10-24 16:33:591217 OpenNewLog(); // Start trivial log to hold our histograms.
jar@google.com68475e602008-08-22 03:21:151218 }
1219
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101220 // Adds to ongoing logs.
1221 log_manager_.current_log()->set_hardware_class(hardware_class_);
jar@chromium.orgaccdfa62011-09-20 01:56:521222
jar@google.com0b33f80b2008-12-17 21:34:361223 // Put incremental data (histogram deltas, and realtime stats deltas) at the
jar@google.com147bbc0b2009-01-06 19:37:401224 // end of all log transmissions (initial log handles this separately).
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:381225 // RecordIncrementalStabilityElements only exists on the derived
1226 // MetricsLog class.
isherman@chromium.org279703f2012-01-20 22:23:261227 MetricsLog* current_log =
1228 static_cast<MetricsLog*>(log_manager_.current_log());
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:381229 DCHECK(current_log);
bengr@chromium.org60677562013-11-17 15:52:551230 std::vector<chrome_variations::ActiveGroupId> synthetic_trials;
1231 GetCurrentSyntheticFieldTrials(&synthetic_trials);
asvitkine@chromium.org0edf8762013-11-21 18:33:301232 current_log->RecordEnvironment(plugins_, google_update_metrics_,
1233 synthetic_trials);
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361234 PrefService* pref = g_browser_process->local_state();
asvitkine@chromium.org0edf8762013-11-21 18:33:301235 current_log->RecordStabilityMetrics(plugins_, GetIncrementalUptime(pref),
1236 MetricsLog::ONGOING_LOG);
bengr@chromium.org60677562013-11-17 15:52:551237
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:381238 RecordCurrentHistograms();
initial.commit09911bf2008-07-26 23:55:291239
stuartmorgan@chromium.org29948262012-03-01 12:15:081240 log_manager_.FinishCurrentLog();
initial.commit09911bf2008-07-26 23:55:291241}
1242
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101243void MetricsService::PushPendingLogsToPersistentStorage() {
initial.commit09911bf2008-07-26 23:55:291244 if (state_ < INITIAL_LOG_READY)
avi@google.com28ab7f92009-01-06 21:39:041245 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:291246
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101247 if (log_manager_.has_staged_log()) {
stuartmorgan@chromium.org7d41ae6d2012-06-26 08:53:031248 // We may race here, and send second copy of the log later.
isherman@chromium.orgdc61fe92012-06-12 00:13:501249 MetricsLogManager::StoreType store_type;
isherman@chromium.orge3eb0c42013-04-18 06:18:581250 if (current_fetch_.get())
isherman@chromium.orgdc61fe92012-06-12 00:13:501251 store_type = MetricsLogManager::PROVISIONAL_STORE;
1252 else
1253 store_type = MetricsLogManager::NORMAL_STORE;
stuartmorgan@chromium.orge7508d82012-05-03 15:59:531254 log_manager_.StoreStagedLogAsUnsent(store_type);
initial.commit09911bf2008-07-26 23:55:291255 }
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101256 DCHECK(!log_manager_.has_staged_log());
stuartmorgan@chromium.org410938e02012-10-24 16:33:591257 CloseCurrentLog();
initial.commit09911bf2008-07-26 23:55:291258 StoreUnsentLogs();
stuartmorgan@chromium.org7d41ae6d2012-06-26 08:53:031259
1260 // If there was a staged and/or current log, then there is now at least one
1261 // log waiting to be uploaded.
1262 if (log_manager_.has_unsent_logs())
1263 state_ = SENDING_OLD_LOGS;
initial.commit09911bf2008-07-26 23:55:291264}
1265
1266//------------------------------------------------------------------------------
1267// Transmission of logs methods
1268
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161269void MetricsService::StartSchedulerIfNecessary() {
stuartmorgan@chromium.org410938e02012-10-24 16:33:591270 // Never schedule cutting or uploading of logs in test mode.
1271 if (test_mode_active_)
1272 return;
1273
1274 // Even if reporting is disabled, the scheduler is needed to trigger the
1275 // creation of the initial log, which must be done in order for any logs to be
1276 // persisted on shutdown or backgrounding.
1277 if (recording_active() && (reporting_active() || state_ < INITIAL_LOG_READY))
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161278 scheduler_->Start();
initial.commit09911bf2008-07-26 23:55:291279}
1280
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161281void MetricsService::StartScheduledUpload() {
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471282 // If we're getting no notifications, then the log won't have much in it, and
1283 // it's possible the computer is about to go to sleep, so don't upload and
1284 // stop the scheduler.
stuartmorgan@chromium.org410938e02012-10-24 16:33:591285 // If recording has been turned off, the scheduler doesn't need to run.
1286 // If reporting is off, proceed if the initial log hasn't been created, since
1287 // that has to happen in order for logs to be cut and stored when persisting.
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471288 // TODO(stuartmorgan): Call Stop() on the schedule when reporting and/or
1289 // recording are turned off instead of letting it fire and then aborting.
1290 if (idle_since_last_transmission_ ||
stuartmorgan@chromium.org410938e02012-10-24 16:33:591291 !recording_active() ||
1292 (!reporting_active() && state_ >= INITIAL_LOG_READY)) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161293 scheduler_->Stop();
1294 scheduler_->UploadCancelled();
1295 return;
1296 }
1297
stuartmorgan@chromium.orgc15faf372012-07-11 06:01:341298 // If the callback was to upload an old log, but there no longer is one,
1299 // just report success back to the scheduler to begin the ongoing log
1300 // callbacks.
1301 // TODO(stuartmorgan): Consider removing the distinction between
1302 // SENDING_OLD_LOGS and SENDING_CURRENT_LOGS to simplify the state machine
1303 // now that the log upload flow is the same for both modes.
1304 if (state_ == SENDING_OLD_LOGS && !log_manager_.has_unsent_logs()) {
1305 state_ = SENDING_CURRENT_LOGS;
1306 scheduler_->UploadFinished(true /* healthy */, false /* no unsent logs */);
1307 return;
1308 }
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471309 // If there are unsent logs, send the next one. If not, start the asynchronous
1310 // process of finalizing the current log for upload.
1311 if (state_ == SENDING_OLD_LOGS) {
1312 DCHECK(log_manager_.has_unsent_logs());
1313 log_manager_.StageNextLogForUpload();
1314 SendStagedLog();
1315 } else {
1316 StartFinalLogInfoCollection();
1317 }
stuartmorgan@chromium.org29948262012-03-01 12:15:081318}
1319
1320void MetricsService::StartFinalLogInfoCollection() {
1321 // Begin the multi-step process of collecting memory usage histograms:
1322 // First spawn a task to collect the memory details; when that task is
1323 // finished, it will call OnMemoryDetailCollectionDone. That will in turn
1324 // call HistogramSynchronization to collect histograms from all renderers and
1325 // then call OnHistogramSynchronizationDone to continue processing.
isherman@chromium.orgd119f222012-06-08 02:33:271326 DCHECK(!waiting_for_asynchronous_reporting_step_);
1327 waiting_for_asynchronous_reporting_step_ = true;
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161328
dcheng@chromium.org2226c222011-11-22 00:08:401329 base::Closure callback =
1330 base::Bind(&MetricsService::OnMemoryDetailCollectionDone,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401331 self_ptr_factory_.GetWeakPtr());
sail@chromium.org84c988a2011-04-19 17:56:331332
dcheng@chromium.org2226c222011-11-22 00:08:401333 scoped_refptr<MetricsMemoryDetails> details(
1334 new MetricsMemoryDetails(callback));
jamescook@chromium.org4306df72012-04-20 18:58:571335 details->StartFetch(MemoryDetails::UPDATE_USER_METRICS);
sail@chromium.org84c988a2011-04-19 17:56:331336
1337 // Collect WebCore cache information to put into a histogram.
ananta@chromium.orgf3b1a082011-11-18 00:34:301338 for (content::RenderProcessHost::iterator i(
1339 content::RenderProcessHost::AllHostsIterator());
sail@chromium.org84c988a2011-04-19 17:56:331340 !i.IsAtEnd(); i.Advance())
ananta@chromium.org2ccf45c2011-08-19 23:35:501341 i.GetCurrentValue()->Send(new ChromeViewMsg_GetCacheResourceStats());
sail@chromium.org84c988a2011-04-19 17:56:331342}
1343
1344void MetricsService::OnMemoryDetailCollectionDone() {
jar@chromium.orgc9a3ef82009-05-28 22:02:461345 DCHECK(IsSingleThreaded());
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161346 // This function should only be called as the callback from an ansynchronous
1347 // step.
isherman@chromium.orgd119f222012-06-08 02:33:271348 DCHECK(waiting_for_asynchronous_reporting_step_);
jar@chromium.orgc9a3ef82009-05-28 22:02:461349
jar@chromium.orgc9a3ef82009-05-28 22:02:461350 // Create a callback_task for OnHistogramSynchronizationDone.
dcheng@chromium.org2226c222011-11-22 00:08:401351 base::Closure callback = base::Bind(
1352 &MetricsService::OnHistogramSynchronizationDone,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401353 self_ptr_factory_.GetWeakPtr());
jar@chromium.orgc9a3ef82009-05-28 22:02:461354
vitalybuka@chromium.orga3079832013-10-24 20:29:361355 base::TimeDelta timeout =
1356 base::TimeDelta::FromMilliseconds(kMaxHistogramGatheringWaitDuration);
1357
1358 DCHECK_EQ(num_async_histogram_fetches_in_progress_, 0);
1359
1360#if defined(OS_ANDROID)
1361 // Android has no service process.
1362 num_async_histogram_fetches_in_progress_ = 1;
1363#else // OS_ANDROID
1364 num_async_histogram_fetches_in_progress_ = 2;
1365 // Run requests to service and content in parallel.
1366 if (!ServiceProcessControl::GetInstance()->GetHistograms(callback, timeout)) {
1367 // Assume |num_async_histogram_fetches_in_progress_| is not changed by
1368 // |GetHistograms()|.
1369 DCHECK_EQ(num_async_histogram_fetches_in_progress_, 2);
1370 // Assign |num_async_histogram_fetches_in_progress_| above and decrement it
1371 // here to make code work even if |GetHistograms()| fired |callback|.
1372 --num_async_histogram_fetches_in_progress_;
1373 }
1374#endif // OS_ANDROID
1375
jar@chromium.orgc9a3ef82009-05-28 22:02:461376 // Set up the callback to task to call after we receive histograms from all
rtenneti@google.com83ab4a282012-07-12 18:19:451377 // child processes. Wait time specifies how long to wait before absolutely
jar@chromium.orgc9a3ef82009-05-28 22:02:461378 // calling us back on the task.
vitalybuka@chromium.orga3079832013-10-24 20:29:361379 content::FetchHistogramsAsynchronously(base::MessageLoop::current(), callback,
1380 timeout);
jar@chromium.orgc9a3ef82009-05-28 22:02:461381}
1382
1383void MetricsService::OnHistogramSynchronizationDone() {
initial.commit09911bf2008-07-26 23:55:291384 DCHECK(IsSingleThreaded());
stuartmorgan@chromium.org29948262012-03-01 12:15:081385 // This function should only be called as the callback from an ansynchronous
1386 // step.
isherman@chromium.orgd119f222012-06-08 02:33:271387 DCHECK(waiting_for_asynchronous_reporting_step_);
vitalybuka@chromium.orga3079832013-10-24 20:29:361388 DCHECK_GT(num_async_histogram_fetches_in_progress_, 0);
1389
1390 // Check if all expected requests finished.
1391 if (--num_async_histogram_fetches_in_progress_ > 0)
1392 return;
initial.commit09911bf2008-07-26 23:55:291393
isherman@chromium.orgd119f222012-06-08 02:33:271394 waiting_for_asynchronous_reporting_step_ = false;
stuartmorgan@chromium.org29948262012-03-01 12:15:081395 OnFinalLogInfoCollectionDone();
1396}
1397
1398void MetricsService::OnFinalLogInfoCollectionDone() {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161399 // If somehow there is a fetch in progress, we return and hope things work
1400 // out. The scheduler isn't informed since if this happens, the scheduler
1401 // will get a response from the upload.
isherman@chromium.orge3eb0c42013-04-18 06:18:581402 DCHECK(!current_fetch_.get());
1403 if (current_fetch_.get())
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161404 return;
1405
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471406 // Abort if metrics were turned off during the final info gathering.
stuartmorgan@chromium.org410938e02012-10-24 16:33:591407 if (!recording_active()) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161408 scheduler_->Stop();
1409 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:071410 return;
1411 }
1412
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471413 StageNewLog();
stuartmorgan@chromium.org410938e02012-10-24 16:33:591414
1415 // If logs shouldn't be uploaded, stop here. It's important that this check
1416 // be after StageNewLog(), otherwise the previous logs will never be loaded,
1417 // and thus the open log won't be persisted.
1418 // TODO(stuartmorgan): This is unnecessarily complicated; restructure loading
1419 // of previous logs to not require running part of the upload logic.
1420 // http://crbug.com/157337
1421 if (!reporting_active()) {
1422 scheduler_->Stop();
1423 scheduler_->UploadCancelled();
1424 return;
1425 }
1426
stuartmorgan@chromium.org29948262012-03-01 12:15:081427 SendStagedLog();
1428}
1429
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471430void MetricsService::StageNewLog() {
stuartmorgan@chromium.org29948262012-03-01 12:15:081431 if (log_manager_.has_staged_log())
1432 return;
1433
1434 switch (state_) {
1435 case INITIALIZED:
1436 case INIT_TASK_SCHEDULED: // We should be further along by now.
isherman@chromium.orgdc61fe92012-06-12 00:13:501437 NOTREACHED();
stuartmorgan@chromium.org29948262012-03-01 12:15:081438 return;
1439
1440 case INIT_TASK_DONE:
stuartmorgan@chromium.org29948262012-03-01 12:15:081441 PrepareInitialLog();
isherman@chromium.orged0fd002012-04-25 23:10:341442 DCHECK_EQ(INIT_TASK_DONE, state_);
stuartmorgan@chromium.org29948262012-03-01 12:15:081443 log_manager_.LoadPersistedUnsentLogs();
1444 state_ = INITIAL_LOG_READY;
1445 break;
1446
1447 case SENDING_OLD_LOGS:
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471448 NOTREACHED(); // Shouldn't be staging a new log during old log sending.
1449 return;
stuartmorgan@chromium.org29948262012-03-01 12:15:081450
1451 case SENDING_CURRENT_LOGS:
stuartmorgan@chromium.org410938e02012-10-24 16:33:591452 CloseCurrentLog();
1453 OpenNewLog();
stuartmorgan@chromium.org29948262012-03-01 12:15:081454 log_manager_.StageNextLogForUpload();
1455 break;
1456
1457 default:
1458 NOTREACHED();
1459 return;
1460 }
1461
1462 DCHECK(log_manager_.has_staged_log());
1463}
1464
1465void MetricsService::PrepareInitialLog() {
isherman@chromium.orged0fd002012-04-25 23:10:341466 DCHECK_EQ(INIT_TASK_DONE, state_);
stuartmorgan@chromium.org29948262012-03-01 12:15:081467
isherman@chromium.orged0fd002012-04-25 23:10:341468 DCHECK(initial_log_.get());
1469 initial_log_->set_hardware_class(hardware_class_);
asvitkine@chromium.org0edf8762013-11-21 18:33:301470
bengr@chromium.org60677562013-11-17 15:52:551471 std::vector<chrome_variations::ActiveGroupId> synthetic_trials;
1472 GetCurrentSyntheticFieldTrials(&synthetic_trials);
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361473 initial_log_->RecordEnvironment(plugins_, google_update_metrics_,
asvitkine@chromium.org0edf8762013-11-21 18:33:301474 synthetic_trials);
1475 PrefService* pref = g_browser_process->local_state();
1476 initial_log_->RecordStabilityMetrics(plugins_, GetIncrementalUptime(pref),
1477 MetricsLog::INITIAL_LOG);
stuartmorgan@chromium.org29948262012-03-01 12:15:081478
1479 // Histograms only get written to the current log, so make the new log current
1480 // before writing them.
1481 log_manager_.PauseCurrentLog();
isherman@chromium.orged0fd002012-04-25 23:10:341482 log_manager_.BeginLoggingWithLog(initial_log_.release(),
asvitkine@chromium.org0edf8762013-11-21 18:33:301483 MetricsLog::INITIAL_LOG);
stuartmorgan@chromium.org29948262012-03-01 12:15:081484 RecordCurrentHistograms();
1485 log_manager_.FinishCurrentLog();
1486 log_manager_.ResumePausedLog();
1487
1488 DCHECK(!log_manager_.has_staged_log());
1489 log_manager_.StageNextLogForUpload();
1490}
1491
1492void MetricsService::StoreUnsentLogs() {
1493 if (state_ < INITIAL_LOG_READY)
1494 return; // We never Recalled the prior unsent logs.
1495
1496 log_manager_.PersistUnsentLogs();
1497}
1498
1499void MetricsService::SendStagedLog() {
1500 DCHECK(log_manager_.has_staged_log());
1501
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101502 PrepareFetchWithStagedLog();
petersont@google.comd01b8732008-10-16 02:18:071503
isherman@chromium.orge3eb0c42013-04-18 06:18:581504 bool upload_created = (current_fetch_.get() != NULL);
isherman@chromium.orgd6bebb92012-06-13 23:14:551505 UMA_HISTOGRAM_BOOLEAN("UMA.UploadCreation", upload_created);
1506 if (!upload_created) {
petersont@google.comd01b8732008-10-16 02:18:071507 // Compression failed, and log discarded :-/.
isherman@chromium.orgdc61fe92012-06-12 00:13:501508 // Skip this upload and hope things work out next time.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101509 log_manager_.DiscardStagedLog();
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161510 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:071511 return;
1512 }
1513
isherman@chromium.orgd119f222012-06-08 02:33:271514 DCHECK(!waiting_for_asynchronous_reporting_step_);
isherman@chromium.orgd119f222012-06-08 02:33:271515 waiting_for_asynchronous_reporting_step_ = true;
isherman@chromium.orgdc61fe92012-06-12 00:13:501516
isherman@chromium.orge3eb0c42013-04-18 06:18:581517 current_fetch_->Start();
petersont@google.comd01b8732008-10-16 02:18:071518
1519 HandleIdleSinceLastTransmission(true);
1520}
1521
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101522void MetricsService::PrepareFetchWithStagedLog() {
isherman@chromium.orgdc61fe92012-06-12 00:13:501523 DCHECK(log_manager_.has_staged_log());
pkasting@chromium.orgcac78842008-11-27 01:02:201524
isherman@chromium.orgfe58acc22012-02-29 01:29:581525 // Prepare the protobuf version.
isherman@chromium.orge3eb0c42013-04-18 06:18:581526 DCHECK(!current_fetch_.get());
isherman@chromium.org5f3e1642013-05-05 03:37:341527 if (log_manager_.has_staged_log()) {
isherman@chromium.orge3eb0c42013-04-18 06:18:581528 current_fetch_.reset(net::URLFetcher::Create(
isherman@chromium.org5f3e1642013-05-05 03:37:341529 GURL(kServerUrl), net::URLFetcher::POST, this));
isherman@chromium.orge3eb0c42013-04-18 06:18:581530 current_fetch_->SetRequestContext(
isherman@chromium.orgfe58acc22012-02-29 01:29:581531 g_browser_process->system_request_context());
asharif@chromium.org537c638d2013-07-04 00:49:191532
asharif@chromium.org8df71322013-09-13 18:40:001533 std::string log_text = log_manager_.staged_log_text();
1534 std::string compressed_log_text;
1535 bool compression_successful = chrome::GzipCompress(log_text,
1536 &compressed_log_text);
1537 DCHECK(compression_successful);
1538 if (compression_successful) {
1539 current_fetch_->SetUploadData(kMimeType, compressed_log_text);
1540 // Tell the server that we're uploading gzipped protobufs.
1541 current_fetch_->SetExtraRequestHeaders("content-encoding: gzip");
asvitkine@chromium.orgcfee9aa52013-10-19 17:53:051542 const std::string hash =
1543 base::HexEncode(log_manager_.staged_log_hash().data(),
1544 log_manager_.staged_log_hash().size());
1545 DCHECK(!hash.empty());
1546 current_fetch_->AddExtraRequestHeader("X-Chrome-UMA-Log-SHA1: " + hash);
asharif@chromium.org8df71322013-09-13 18:40:001547 UMA_HISTOGRAM_PERCENTAGE(
1548 "UMA.ProtoCompressionRatio",
1549 100 * compressed_log_text.size() / log_text.size());
1550 UMA_HISTOGRAM_CUSTOM_COUNTS(
1551 "UMA.ProtoGzippedKBSaved",
1552 (log_text.size() - compressed_log_text.size()) / 1024,
1553 1, 2000, 50);
asharif@chromium.org537c638d2013-07-04 00:49:191554 }
asharif@chromium.org537c638d2013-07-04 00:49:191555
isherman@chromium.orgfe58acc22012-02-29 01:29:581556 // We already drop cookies server-side, but we might as well strip them out
1557 // client-side as well.
isherman@chromium.orge3eb0c42013-04-18 06:18:581558 current_fetch_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES |
1559 net::LOAD_DO_NOT_SEND_COOKIES);
isherman@chromium.orgfe58acc22012-02-29 01:29:581560 }
initial.commit09911bf2008-07-26 23:55:291561}
1562
akalin@chromium.org10c2d692012-05-11 05:32:231563void MetricsService::OnURLFetchComplete(const net::URLFetcher* source) {
isherman@chromium.orgd119f222012-06-08 02:33:271564 DCHECK(waiting_for_asynchronous_reporting_step_);
isherman@chromium.orgfe58acc22012-02-29 01:29:581565
1566 // We're not allowed to re-use the existing |URLFetcher|s, so free them here.
isherman@chromium.orge3eb0c42013-04-18 06:18:581567 // Note however that |source| is aliased to the fetcher, so we should be
isherman@chromium.org4266def22012-05-17 01:02:401568 // careful not to delete it too early.
isherman@chromium.orge3eb0c42013-04-18 06:18:581569 DCHECK_EQ(current_fetch_.get(), source);
1570 scoped_ptr<net::URLFetcher> s(current_fetch_.Pass());
isherman@chromium.orgfe58acc22012-02-29 01:29:581571
isherman@chromium.orgdc61fe92012-06-12 00:13:501572 int response_code = source->GetResponseCode();
isherman@chromium.orgfe58acc22012-02-29 01:29:581573
isherman@chromium.orgdc61fe92012-06-12 00:13:501574 // Log a histogram to track response success vs. failure rates.
isherman@chromium.orge3eb0c42013-04-18 06:18:581575 UMA_HISTOGRAM_ENUMERATION("UMA.UploadResponseStatus.Protobuf",
1576 ResponseCodeToStatus(response_code),
1577 NUM_RESPONSE_STATUSES);
isherman@chromium.orgfe58acc22012-02-29 01:29:581578
stuartmorgan@chromium.orge7508d82012-05-03 15:59:531579 // If the upload was provisionally stored, drop it now that the upload is
1580 // known to have gone through.
1581 log_manager_.DiscardLastProvisionalStore();
initial.commit09911bf2008-07-26 23:55:291582
isherman@chromium.orgdc61fe92012-06-12 00:13:501583 bool upload_succeeded = response_code == 200;
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161584
jar@chromium.org0eb34fee2009-01-21 08:04:381585 // Provide boolean for error recovery (allow us to ignore response_code).
paul@chromium.orgdc6f4962009-02-13 01:25:501586 bool discard_log = false;
isherman@chromium.org5f3e1642013-05-05 03:37:341587 const size_t log_size = log_manager_.staged_log_text().length();
isherman@chromium.orgdc61fe92012-06-12 00:13:501588 if (!upload_succeeded && log_size > kUploadLogAvoidRetransmitSize) {
1589 UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
1590 static_cast<int>(log_size));
jar@chromium.org0eb34fee2009-01-21 08:04:381591 discard_log = true;
isherman@chromium.orgdc61fe92012-06-12 00:13:501592 } else if (response_code == 400) {
jar@chromium.org0eb34fee2009-01-21 08:04:381593 // Bad syntax. Retransmission won't work.
jar@chromium.org0eb34fee2009-01-21 08:04:381594 discard_log = true;
jar@google.com68475e602008-08-22 03:21:151595 }
1596
isherman@chromium.orge3eb0c42013-04-18 06:18:581597 if (upload_succeeded || discard_log)
isherman@chromium.org5f3e1642013-05-05 03:37:341598 log_manager_.DiscardStagedLog();
isherman@chromium.orgdc61fe92012-06-12 00:13:501599
1600 waiting_for_asynchronous_reporting_step_ = false;
1601
1602 if (!log_manager_.has_staged_log()) {
initial.commit09911bf2008-07-26 23:55:291603 switch (state_) {
1604 case INITIAL_LOG_READY:
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471605 state_ = log_manager_.has_unsent_logs() ? SENDING_OLD_LOGS
1606 : SENDING_CURRENT_LOGS;
initial.commit09911bf2008-07-26 23:55:291607 break;
1608
initial.commit09911bf2008-07-26 23:55:291609 case SENDING_OLD_LOGS:
stuartmorgan@chromium.orgd53e2232011-06-30 15:54:571610 // Store the updated list to disk now that the removed log is uploaded.
initial.commit09911bf2008-07-26 23:55:291611 StoreUnsentLogs();
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471612 if (!log_manager_.has_unsent_logs())
1613 state_ = SENDING_CURRENT_LOGS;
initial.commit09911bf2008-07-26 23:55:291614 break;
1615
1616 case SENDING_CURRENT_LOGS:
1617 break;
1618
1619 default:
jar@chromium.orga063c102010-07-22 22:20:191620 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291621 break;
1622 }
petersont@google.comd01b8732008-10-16 02:18:071623
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101624 if (log_manager_.has_unsent_logs())
isherman@chromium.orged0fd002012-04-25 23:10:341625 DCHECK_LT(state_, SENDING_CURRENT_LOGS);
initial.commit09911bf2008-07-26 23:55:291626 }
petersont@google.com252873ef2008-08-04 21:59:451627
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161628 // Error 400 indicates a problem with the log, not with the server, so
1629 // don't consider that a sign that the server is in trouble.
isherman@chromium.orgdc61fe92012-06-12 00:13:501630 bool server_is_healthy = upload_succeeded || response_code == 400;
isherman@chromium.orgdc61fe92012-06-12 00:13:501631 scheduler_->UploadFinished(server_is_healthy, log_manager_.has_unsent_logs());
rtenneti@chromium.orgd67d1052011-06-09 05:11:411632
1633 // Collect network stats if UMA upload succeeded.
isherman@chromium.orgb8ddb052012-04-19 02:36:061634 IOThread* io_thread = g_browser_process->io_thread();
1635 if (server_is_healthy && io_thread) {
1636 chrome_browser_net::CollectNetworkStats(network_stats_server_, io_thread);
simonjam@chromium.orgadbb3762012-03-09 22:20:081637 chrome_browser_net::CollectPipeliningCapabilityStatsOnUIThread(
isherman@chromium.orgb8ddb052012-04-19 02:36:061638 http_pipelining_test_server_, io_thread);
simonjam@chromium.orgaa312812013-04-30 19:46:051639#if defined(OS_WIN)
1640 chrome::CollectTimeTicksStats();
1641#endif
simonjam@chromium.orgadbb3762012-03-09 22:20:081642 }
initial.commit09911bf2008-07-26 23:55:291643}
1644
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511645void MetricsService::IncrementPrefValue(const char* path) {
cpu@google.come73c01972008-08-13 00:18:241646 PrefService* pref = g_browser_process->local_state();
1647 DCHECK(pref);
1648 int value = pref->GetInteger(path);
1649 pref->SetInteger(path, value + 1);
1650}
1651
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511652void MetricsService::IncrementLongPrefsValue(const char* path) {
robertshield@google.com0bb1a622009-03-04 03:22:321653 PrefService* pref = g_browser_process->local_state();
1654 DCHECK(pref);
1655 int64 value = pref->GetInt64(path);
jar@chromium.orgb42c5e42010-06-03 20:43:251656 pref->SetInt64(path, value + 1);
robertshield@google.com0bb1a622009-03-04 03:22:321657}
1658
rlp@chromium.org752a5262013-06-23 14:53:421659void MetricsService::LogLoadStarted(content::WebContents* web_contents) {
mpearson@chromium.org5d490e42012-08-30 05:16:431660 content::RecordAction(content::UserMetricsAction("PageLoad"));
jar@chromium.orgdd8d12a2011-09-02 02:10:151661 HISTOGRAM_ENUMERATION("Chrome.UmaPageloadCounter", 1, 2);
cpu@google.come73c01972008-08-13 00:18:241662 IncrementPrefValue(prefs::kStabilityPageLoadCount);
robertshield@google.com0bb1a622009-03-04 03:22:321663 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
jar@google.com0b33f80b2008-12-17 21:34:361664 // We need to save the prefs, as page load count is a critical stat, and it
1665 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291666}
1667
jar@chromium.orgc3721482012-03-23 16:21:481668void MetricsService::LogRendererCrash(content::RenderProcessHost* host,
1669 base::TerminationStatus status,
jam@chromium.orgf1675202012-07-09 15:18:001670 int exit_code) {
ananta@chromium.orgf3b1a082011-11-18 00:34:301671 Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
aa@chromium.org6f371442011-11-09 06:45:461672 ExtensionService* service = profile->GetExtensionService();
1673 bool was_extension_process =
ananta@chromium.orgf3b1a082011-11-18 00:34:301674 service && service->process_map()->Contains(host->GetID());
jar@chromium.orgc3721482012-03-23 16:21:481675 if (status == base::TERMINATION_STATUS_PROCESS_CRASHED ||
1676 status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
eroman@chromium.orgd7c1fa62012-06-15 23:35:301677 if (was_extension_process) {
jochen@chromium.org718eab62011-10-05 21:16:521678 IncrementPrefValue(prefs::kStabilityExtensionRendererCrashCount);
eroman@chromium.orgd7c1fa62012-06-15 23:35:301679
eroman@chromium.org1026afd2013-03-20 14:28:541680 UMA_HISTOGRAM_SPARSE_SLOWLY("CrashExitCodes.Extension",
1681 MapCrashExitCodeForHistogram(exit_code));
eroman@chromium.orgd7c1fa62012-06-15 23:35:301682 } else {
jochen@chromium.org718eab62011-10-05 21:16:521683 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291684
eroman@chromium.org1026afd2013-03-20 14:28:541685 UMA_HISTOGRAM_SPARSE_SLOWLY("CrashExitCodes.Renderer",
1686 MapCrashExitCodeForHistogram(exit_code));
eroman@chromium.orgd7c1fa62012-06-15 23:35:301687 }
1688
jochen@chromium.org718eab62011-10-05 21:16:521689 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildCrashes",
1690 was_extension_process ? 2 : 1);
jar@chromium.orgc3721482012-03-23 16:21:481691 } else if (status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED) {
jochen@chromium.org718eab62011-10-05 21:16:521692 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildKills",
1693 was_extension_process ? 2 : 1);
jam@chromium.orgf1675202012-07-09 15:18:001694 } else if (status == base::TERMINATION_STATUS_STILL_RUNNING) {
1695 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.DisconnectedAlive",
jochen@chromium.org718eab62011-10-05 21:16:521696 was_extension_process ? 2 : 1);
1697 }
1698 }
asargent@chromium.org1f085622009-12-04 05:33:451699
initial.commit09911bf2008-07-26 23:55:291700void MetricsService::LogRendererHang() {
cpu@google.come73c01972008-08-13 00:18:241701 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291702}
1703
jar@chromium.orgc0c55e92011-09-10 18:47:301704bool MetricsService::UmaMetricsProperlyShutdown() {
1705 CHECK(clean_shutdown_status_ == CLEANLY_SHUTDOWN ||
1706 clean_shutdown_status_ == NEED_TO_SHUTDOWN);
1707 return clean_shutdown_status_ == CLEANLY_SHUTDOWN;
1708}
1709
bengr@chromium.org60677562013-11-17 15:52:551710void MetricsService::RegisterSyntheticFieldTrial(
1711 const SyntheticTrialGroup& trial) {
1712 for (size_t i = 0; i < synthetic_trial_groups_.size(); ++i) {
1713 if (synthetic_trial_groups_[i].id.name == trial.id.name) {
1714 if (synthetic_trial_groups_[i].id.group != trial.id.group) {
1715 synthetic_trial_groups_[i].id.group = trial.id.group;
1716 synthetic_trial_groups_[i].start_time = trial.start_time;
1717 }
1718 return;
1719 }
1720 }
1721
1722 SyntheticTrialGroup trial_group(
1723 trial.id.name, trial.id.group, base::TimeTicks::Now());
1724 synthetic_trial_groups_.push_back(trial_group);
1725}
1726
1727void MetricsService::GetCurrentSyntheticFieldTrials(
1728 std::vector<chrome_variations::ActiveGroupId>* synthetic_trials) {
1729 DCHECK(synthetic_trials);
1730 synthetic_trials->clear();
1731 const MetricsLog* current_log =
1732 static_cast<const MetricsLog*>(log_manager_.current_log());
1733 for (size_t i = 0; i < synthetic_trial_groups_.size(); ++i) {
1734 if (synthetic_trial_groups_[i].start_time <= current_log->creation_time())
1735 synthetic_trials->push_back(synthetic_trial_groups_[i].id);
1736 }
1737}
1738
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381739void MetricsService::LogCleanShutdown() {
jar@chromium.orgacd55b32011-09-05 17:35:311740 // Redundant hack to write pref ASAP.
nileshagrawal@chromium.org84c384e2013-03-01 23:20:191741 MarkAppCleanShutdownAndCommit();
1742
jar@chromium.orgc0c55e92011-09-10 18:47:301743 // Redundant setting to assure that we always reset this value at shutdown
1744 // (and that we don't use some alternate path, and not call LogCleanShutdown).
1745 clean_shutdown_status_ = CLEANLY_SHUTDOWN;
jar@chromium.orgacd55b32011-09-05 17:35:311746
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381747 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6a6d0d12013-10-28 15:58:191748 PrefService* pref = g_browser_process->local_state();
1749 pref->SetInteger(prefs::kStabilityExecutionPhase,
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:211750 MetricsService::SHUTDOWN_COMPLETE);
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381751}
1752
petkov@chromium.orgc1834a92011-01-21 18:21:031753#if defined(OS_CHROMEOS)
1754void MetricsService::LogChromeOSCrash(const std::string &crash_type) {
1755 if (crash_type == "user")
1756 IncrementPrefValue(prefs::kStabilityOtherUserCrashCount);
1757 else if (crash_type == "kernel")
1758 IncrementPrefValue(prefs::kStabilityKernelCrashCount);
1759 else if (crash_type == "uncleanshutdown")
1760 IncrementPrefValue(prefs::kStabilitySystemUncleanShutdownCount);
1761 else
1762 NOTREACHED() << "Unexpected Chrome OS crash type " << crash_type;
1763 // Wake up metrics logs sending if necessary now that new
1764 // log data is available.
1765 HandleIdleSinceLastTransmission(false);
1766}
1767#endif // OS_CHROMEOS
1768
brettw@chromium.org650b2d52013-02-10 03:41:451769void MetricsService::LogPluginLoadingError(const base::FilePath& plugin_path) {
jam@chromium.orgd7bd3e52013-07-21 04:29:201770 content::WebPluginInfo plugin;
bauerb@chromium.orgcd937072012-07-02 09:00:291771 bool success =
1772 content::PluginService::GetInstance()->GetPluginInfoByPath(plugin_path,
1773 &plugin);
1774 DCHECK(success);
1775 ChildProcessStats& stats = child_process_stats_buffer_[plugin.name];
1776 // Initialize the type if this entry is new.
1777 if (stats.process_type == content::PROCESS_TYPE_UNKNOWN) {
1778 // The plug-in process might not actually of type PLUGIN (which means
1779 // NPAPI), but we only care that it is *a* plug-in process.
1780 stats.process_type = content::PROCESS_TYPE_PLUGIN;
1781 } else {
1782 DCHECK(IsPluginProcess(stats.process_type));
1783 }
1784 stats.loading_errors++;
1785}
1786
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:401787MetricsService::ChildProcessStats& MetricsService::GetChildProcessStats(
1788 const content::ChildProcessData& data) {
1789 const string16& child_name = data.name;
jam@chromium.orgf3b357692013-03-22 05:16:131790 if (!ContainsKey(child_process_stats_buffer_, child_name)) {
1791 child_process_stats_buffer_[child_name] =
1792 ChildProcessStats(data.process_type);
1793 }
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:401794 return child_process_stats_buffer_[child_name];
initial.commit09911bf2008-07-26 23:55:291795}
1796
initial.commit09911bf2008-07-26 23:55:291797void MetricsService::RecordPluginChanges(PrefService* pref) {
battre@chromium.orgf8628c22011-04-05 12:10:181798 ListPrefUpdate update(pref, prefs::kStabilityPluginStats);
1799 ListValue* plugins = update.Get();
initial.commit09911bf2008-07-26 23:55:291800 DCHECK(plugins);
1801
1802 for (ListValue::iterator value_iter = plugins->begin();
1803 value_iter != plugins->end(); ++value_iter) {
1804 if (!(*value_iter)->IsType(Value::TYPE_DICTIONARY)) {
jar@chromium.orga063c102010-07-22 22:20:191805 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291806 continue;
1807 }
1808
1809 DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*value_iter);
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511810 std::string plugin_name;
nsylvain@chromium.org8e50b602009-03-03 22:59:431811 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
nsylvain@chromium.org6470ee8f2009-03-03 20:46:401812 if (plugin_name.empty()) {
jar@chromium.orga063c102010-07-22 22:20:191813 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291814 continue;
1815 }
1816
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511817 // TODO(viettrungluu): remove conversions
evan@chromium.org68b9e72b2011-08-05 23:08:221818 string16 name16 = UTF8ToUTF16(plugin_name);
1819 if (child_process_stats_buffer_.find(name16) ==
1820 child_process_stats_buffer_.end()) {
initial.commit09911bf2008-07-26 23:55:291821 continue;
evan@chromium.org68b9e72b2011-08-05 23:08:221822 }
initial.commit09911bf2008-07-26 23:55:291823
evan@chromium.org68b9e72b2011-08-05 23:08:221824 ChildProcessStats stats = child_process_stats_buffer_[name16];
initial.commit09911bf2008-07-26 23:55:291825 if (stats.process_launches) {
1826 int launches = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431827 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291828 launches += stats.process_launches;
nsylvain@chromium.org8e50b602009-03-03 22:59:431829 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291830 }
1831 if (stats.process_crashes) {
1832 int crashes = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431833 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291834 crashes += stats.process_crashes;
nsylvain@chromium.org8e50b602009-03-03 22:59:431835 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291836 }
1837 if (stats.instances) {
1838 int instances = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431839 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291840 instances += stats.instances;
nsylvain@chromium.org8e50b602009-03-03 22:59:431841 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291842 }
bauerb@chromium.orgcd937072012-07-02 09:00:291843 if (stats.loading_errors) {
1844 int loading_errors = 0;
1845 plugin_dict->GetInteger(prefs::kStabilityPluginLoadingErrors,
1846 &loading_errors);
1847 loading_errors += stats.loading_errors;
1848 plugin_dict->SetInteger(prefs::kStabilityPluginLoadingErrors,
1849 loading_errors);
1850 }
initial.commit09911bf2008-07-26 23:55:291851
evan@chromium.org68b9e72b2011-08-05 23:08:221852 child_process_stats_buffer_.erase(name16);
initial.commit09911bf2008-07-26 23:55:291853 }
1854
1855 // Now go through and add dictionaries for plugins that didn't already have
1856 // reports in Local State.
evan@chromium.org68b9e72b2011-08-05 23:08:221857 for (std::map<string16, ChildProcessStats>::iterator cache_iter =
jam@chromium.orga27a9382009-02-11 23:55:101858 child_process_stats_buffer_.begin();
1859 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
jam@chromium.orga27a9382009-02-11 23:55:101860 ChildProcessStats stats = cache_iter->second;
gregoryd@google.com0d84c5d2009-10-09 01:10:421861
1862 // Insert only plugins information into the plugins list.
petkov@chromium.org8d5f1dae2011-11-11 14:30:411863 if (!IsPluginProcess(stats.process_type))
gregoryd@google.com0d84c5d2009-10-09 01:10:421864 continue;
1865
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511866 // TODO(viettrungluu): remove conversion
evan@chromium.org68b9e72b2011-08-05 23:08:221867 std::string plugin_name = UTF16ToUTF8(cache_iter->first);
gregoryd@google.com0d84c5d2009-10-09 01:10:421868
initial.commit09911bf2008-07-26 23:55:291869 DictionaryValue* plugin_dict = new DictionaryValue;
1870
nsylvain@chromium.org8e50b602009-03-03 22:59:431871 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
1872 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:291873 stats.process_launches);
nsylvain@chromium.org8e50b602009-03-03 22:59:431874 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:291875 stats.process_crashes);
nsylvain@chromium.org8e50b602009-03-03 22:59:431876 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:291877 stats.instances);
bauerb@chromium.orgcd937072012-07-02 09:00:291878 plugin_dict->SetInteger(prefs::kStabilityPluginLoadingErrors,
1879 stats.loading_errors);
initial.commit09911bf2008-07-26 23:55:291880 plugins->Append(plugin_dict);
1881 }
jam@chromium.orga27a9382009-02-11 23:55:101882 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291883}
1884
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:221885bool MetricsService::CanLogNotification() {
akalin@chromium.org2c910b72011-03-08 21:16:321886 // We simply don't log anything to UMA if there is a single incognito
initial.commit09911bf2008-07-26 23:55:291887 // session visible. The problem is that we always notify using the orginal
1888 // profile in order to simplify notification processing.
tfarina@chromium.orge764e582012-08-01 03:01:291889 return !chrome::IsOffTheRecordSessionActive();
initial.commit09911bf2008-07-26 23:55:291890}
1891
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511892void MetricsService::RecordBooleanPrefValue(const char* path, bool value) {
initial.commit09911bf2008-07-26 23:55:291893 DCHECK(IsSingleThreaded());
1894
1895 PrefService* pref = g_browser_process->local_state();
1896 DCHECK(pref);
1897
1898 pref->SetBoolean(path, value);
1899 RecordCurrentState(pref);
1900}
1901
1902void MetricsService::RecordCurrentState(PrefService* pref) {
robertshield@google.com0bb1a622009-03-04 03:22:321903 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291904
1905 RecordPluginChanges(pref);
1906}
1907
petkov@chromium.org8d5f1dae2011-11-11 14:30:411908// static
jam@chromium.orgf3b357692013-03-22 05:16:131909bool MetricsService::IsPluginProcess(int process_type) {
1910 return (process_type == content::PROCESS_TYPE_PLUGIN ||
1911 process_type == content::PROCESS_TYPE_PPAPI_PLUGIN ||
1912 process_type == content::PROCESS_TYPE_PPAPI_BROKER);
petkov@chromium.org8d5f1dae2011-11-11 14:30:411913}
1914
rvargas@google.com5ccaa412009-11-13 22:00:161915#if defined(OS_CHROMEOS)
sky@chromium.org29cf16772010-04-21 15:13:471916void MetricsService::StartExternalMetrics() {
rvargas@google.com5ccaa412009-11-13 22:00:161917 external_metrics_ = new chromeos::ExternalMetrics;
sky@chromium.org29cf16772010-04-21 15:13:471918 external_metrics_->Start();
rvargas@google.com5ccaa412009-11-13 22:00:161919}
1920#endif
sreeram@chromium.org3819f2ee2011-08-21 09:44:381921
1922// static
1923bool MetricsServiceHelper::IsMetricsReportingEnabled() {
1924 bool result = false;
1925 const PrefService* local_state = g_browser_process->local_state();
1926 if (local_state) {
1927 const PrefService::Preference* uma_pref =
1928 local_state->FindPreference(prefs::kMetricsReportingEnabled);
1929 if (uma_pref) {
1930 bool success = uma_pref->GetValue()->GetAsBoolean(&result);
1931 DCHECK(success);
1932 }
1933 }
1934 return result;
1935}