blob: 80fa3967492518625cb2e8ab0ad36cbf27271133 [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."
asvitkine@chromium.org80a8f312013-12-16 18:00:3025// There is at most one initial log sent for each complete run of Chrome (from
26// startup, to browser shutdown). An initial log is generally transmitted some
27// short time (1 minute?) after startup, and includes stats such as recent crash
28// info, the number and types of plugins, etc. The external server's response
29// to the initial log conceptually tells this MS if it should continue
30// transmitting logs (during this session). The server response can actually be
31// much more detailed, and always includes (at a minimum) how often additional
32// 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
asvitkine@chromium.org80a8f312013-12-16 18:00:3048// to the UMA server. The finalization also acquires the most recent number
jar@chromium.org281d2882009-01-20 20:32:4249// 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
asvitkine@chromium.org80a8f312013-12-16 18:00:3052// log that has not yet been transmitted. At shutdown time, that fragment is
53// closed (including snapshotting histograms), and persisted, for potential
54// transmission during a future run of the product.
initial.commit09911bf2008-07-26 23:55:2955//
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
asvitkine@chromium.org80a8f312013-12-16 18:00:3076// states, based on the State enum specified in the state_ member. Those states
initial.commit09911bf2008-07-26 23:55:2977// are:
78//
asvitkine@chromium.org80a8f312013-12-16 18:00:3079// INITIALIZED, // Constructor was called.
80// INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to finish.
81// INIT_TASK_DONE, // Waiting for timer to send initial log.
82// SENDING_INITIAL_STABILITY_LOG, // Initial stability log being sent.
83// SENDING_INITIAL_METRICS_LOG, // Initial metrics log being sent.
84// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
85// SENDING_CURRENT_LOGS, // Sending ongoing logs as they acrue.
initial.commit09911bf2008-07-26 23:55:2986//
87// In more detail, we have:
88//
89// INITIALIZED, // Constructor was called.
90// The MS has been constructed, but has taken no actions to compose the
91// initial log.
92//
asvitkine@chromium.org80a8f312013-12-16 18:00:3093// INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to finish.
initial.commit09911bf2008-07-26 23:55:2994// Typically about 30 seconds after startup, a task is sent to a second thread
zelidrag@chromium.org85ed9d42010-06-08 22:37:4495// (the file thread) to perform deferred (lower priority and slower)
96// initialization steps such as getting the list of plugins. That task will
97// (when complete) make an async callback (via a Task) to indicate the
98// completion.
initial.commit09911bf2008-07-26 23:55:2999//
zelidrag@chromium.org85ed9d42010-06-08 22:37:44100// INIT_TASK_DONE, // Waiting for timer to send initial log.
initial.commit09911bf2008-07-26 23:55:29101// The callback has arrived, and it is now possible for an initial log to be
102// created. This callback typically arrives back less than one second after
zelidrag@chromium.org85ed9d42010-06-08 22:37:44103// the deferred init task is dispatched.
initial.commit09911bf2008-07-26 23:55:29104//
asvitkine@chromium.org80a8f312013-12-16 18:00:30105// SENDING_INITIAL_STABILITY_LOG, // Initial stability log being sent.
106// During initialization, if a crash occurred during the previous session, an
107// initial stability log will be generated and registered with the log manager.
108// This state will be entered if a stability log was prepared during metrics
109// service initialization (in InitializeMetricsRecordingState()) and is waiting
110// to be transmitted when it's time to send up the first log (per the reporting
111// scheduler). If there is no initial stability log (e.g. there was no previous
112// crash), then this state will be skipped and the state will advance to
113// SENDING_INITIAL_METRICS_LOG.
114//
115// SENDING_INITIAL_METRICS_LOG, // Initial metrics log being sent.
116// This state is entered after the initial metrics log has been composed, and
117// prepared for transmission. This happens after SENDING_INITIAL_STABILITY_LOG
118// if there was an initial stability log (see above). It is also the case that
119// any previously unsent logs have been loaded into instance variables for
120// possible transmission.
initial.commit09911bf2008-07-26 23:55:29121//
initial.commit09911bf2008-07-26 23:55:29122// SENDING_OLD_LOGS, // Sending unsent logs from previous session.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10123// This state indicates that the initial log for this session has been
124// successfully sent and it is now time to send any logs that were
125// saved from previous sessions. All such logs will be transmitted before
126// exiting this state, and proceeding with ongoing logs from the current session
127// (see next state).
initial.commit09911bf2008-07-26 23:55:29128//
129// SENDING_CURRENT_LOGS, // Sending standard current logs as they accrue.
jar@google.com0b33f80b2008-12-17 21:34:36130// Current logs are being accumulated. Typically every 20 minutes a log is
initial.commit09911bf2008-07-26 23:55:29131// closed and finalized for transmission, at the same time as a new log is
132// started.
133//
134// The progression through the above states is simple, and sequential, in the
135// most common use cases. States proceed from INITIAL to SENDING_CURRENT_LOGS,
136// and remain in the latter until shutdown.
137//
138// The one unusual case is when the user asks that we stop logging. When that
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10139// happens, any staged (transmission in progress) log is persisted, and any log
stuartmorgan@chromium.org410938e02012-10-24 16:33:59140// that is currently accumulating is also finalized and persisted. We then
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10141// regress back to the SEND_OLD_LOGS state in case the user enables log
142// recording again during this session. This way anything we have persisted
143// will be sent automatically if/when we progress back to SENDING_CURRENT_LOG
144// state.
initial.commit09911bf2008-07-26 23:55:29145//
stuartmorgan@chromium.org410938e02012-10-24 16:33:59146// Another similar case is on mobile, when the application is backgrounded and
147// then foregrounded again. Backgrounding created new "old" stored logs, so the
148// state drops back from SENDING_CURRENT_LOGS to SENDING_OLD_LOGS so those logs
149// will be sent.
150//
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10151// Also note that whenever we successfully send an old log, we mirror the list
152// of logs into the PrefService. This ensures that IF we crash, we won't start
153// up and retransmit our old logs again.
initial.commit09911bf2008-07-26 23:55:29154//
155// Due to race conditions, it is always possible that a log file could be sent
156// twice. For example, if a log file is sent, but not yet acknowledged by
157// the external server, and the user shuts down, then a copy of the log may be
158// saved for re-transmission. These duplicates could be filtered out server
jar@chromium.org281d2882009-01-20 20:32:42159// side, but are not expected to be a significant problem.
initial.commit09911bf2008-07-26 23:55:29160//
161//
162//------------------------------------------------------------------------------
163
maruel@chromium.org40bcc302009-03-02 20:50:39164#include "chrome/browser/metrics/metrics_service.h"
165
eroman@chromium.orgd7c1fa62012-06-15 23:35:30166#include <algorithm>
167
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16168#include "base/bind.h"
169#include "base/callback.h"
erg@google.com5d91c9e2010-07-28 17:25:28170#include "base/command_line.h"
akalin@chromium.org3dc1bc42012-06-19 08:20:53171#include "base/guid.h"
ziadh@chromium.org46f89e142010-07-19 08:00:42172#include "base/md5.h"
brettw@chromium.org835d7c82010-10-14 04:38:38173#include "base/metrics/histogram.h"
eroman@chromium.org1026afd2013-03-20 14:28:54174#include "base/metrics/sparse_histogram.h"
kaiwang@chromium.org567d30e2012-07-13 21:48:29175#include "base/metrics/statistics_recorder.h"
joi@chromium.org3853a4c2013-02-11 17:15:57176#include "base/prefs/pref_registry_simple.h"
177#include "base/prefs/pref_service.h"
derat@chromium.org9eec53fe2013-10-30 20:21:17178#include "base/prefs/scoped_user_pref_update.h"
stevet@chromium.orge61003a2012-05-24 17:03:19179#include "base/rand_util.h"
brettw@chromium.org3ea1b182013-02-08 22:38:41180#include "base/strings/string_number_conversions.h"
avi@chromium.org112158af2013-06-07 23:46:18181#include "base/strings/utf_string_conversions.h"
brettw@chromium.orgce072a72010-12-31 20:02:16182#include "base/threading/platform_thread.h"
tfarina@chromium.orgb3841c502011-03-09 01:21:31183#include "base/threading/thread.h"
jam@chromium.org3a7b66d2012-04-26 16:34:16184#include "base/threading/thread_restrictions.h"
isherman@chromium.orged0fd002012-04-25 23:10:34185#include "base/tracked_objects.h"
erg@google.com679082052010-07-21 21:30:13186#include "base/values.h"
initial.commit09911bf2008-07-26 23:55:29187#include "chrome/browser/browser_process.h"
jam@chromium.org9ea0cd32013-07-12 01:50:36188#include "chrome/browser/chrome_notification_types.h"
isherman@chromium.orgb8ddb052012-04-19 02:36:06189#include "chrome/browser/io_thread.h"
sail@chromium.org84c988a2011-04-19 17:56:33190#include "chrome/browser/memory_details.h"
asharif@chromium.org537c638d2013-07-04 00:49:19191#include "chrome/browser/metrics/compression_utils.h"
erg@google.com679082052010-07-21 21:30:13192#include "chrome/browser/metrics/metrics_log.h"
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10193#include "chrome/browser/metrics/metrics_log_serializer.h"
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16194#include "chrome/browser/metrics/metrics_reporting_scheduler.h"
simonjam@chromium.orgaa312812013-04-30 19:46:05195#include "chrome/browser/metrics/time_ticks_experiment_win.h"
isherman@chromium.orged0fd002012-04-25 23:10:34196#include "chrome/browser/metrics/tracking_synchronizer.h"
bengr@chromium.org60677562013-11-17 15:52:55197#include "chrome/common/metrics/variations/variations_util.h"
simonjam@chromium.orgadbb3762012-03-09 22:20:08198#include "chrome/browser/net/http_pipelining_compatibility_client.h"
rtenneti@chromium.orgd67d1052011-06-09 05:11:41199#include "chrome/browser/net/network_stats.h"
tfarina@chromium.org0fafc8d2013-06-01 00:09:50200#include "chrome/browser/omnibox/omnibox_log.h"
tfarina@chromium.org71b73f02011-04-06 15:57:29201#include "chrome/browser/ui/browser_list.h"
dtrainor@chromium.org10b132b02012-07-27 20:46:18202#include "chrome/browser/ui/browser_otr_state.h"
rlp@chromium.org752a5262013-06-23 14:53:42203#include "chrome/browser/ui/search/search_tab_helper.h"
rogerm@chromium.org261ab7c2013-08-19 15:04:58204#include "chrome/common/chrome_constants.h"
eroman@chromium.orgd7c1fa62012-06-15 23:35:30205#include "chrome/common/chrome_result_codes.h"
jar@chromium.org92745242009-06-12 16:52:21206#include "chrome/common/chrome_switches.h"
rsesek@chromium.org264c0acac2013-10-01 13:33:30207#include "chrome/common/crash_keys.h"
asvitkine@chromium.orgc277e2b2013-08-02 15:41:08208#include "chrome/common/metrics/caching_permuted_entropy_provider.h"
isherman@chromium.org2e4cd1a2012-01-12 08:51:03209#include "chrome/common/metrics/metrics_log_manager.h"
simonjam@chromium.orgb4a72d842012-03-22 20:09:09210#include "chrome/common/net/test_server_locations.h"
initial.commit09911bf2008-07-26 23:55:29211#include "chrome/common/pref_names.h"
jam@chromium.orge09ba552009-02-05 03:26:29212#include "chrome/common/render_messages.h"
asvitkine@chromium.org50ae9f12013-08-29 18:03:22213#include "components/variations/entropy_provider.h"
bengr@chromium.org60677562013-11-17 15:52:55214#include "components/variations/metrics_util.h"
jam@chromium.org4967f792012-01-20 22:14:40215#include "content/public/browser/child_process_data.h"
rtenneti@google.com83ab4a282012-07-12 18:19:45216#include "content/public/browser/histogram_fetcher.h"
tfarina@chromium.org09d31d52012-03-11 22:30:27217#include "content/public/browser/load_notification_details.h"
jam@chromium.orgad50def52011-10-19 23:17:07218#include "content/public/browser/notification_service.h"
jam@chromium.org3a5180ae2011-12-21 02:39:38219#include "content/public/browser/plugin_service.h"
ananta@chromium.orgf3b1a082011-11-18 00:34:30220#include "content/public/browser/render_process_host.h"
mpearson@chromium.org5d490e42012-08-30 05:16:43221#include "content/public/browser/user_metrics.h"
avi@chromium.org459f3502012-09-17 17:08:12222#include "content/public/browser/web_contents.h"
yael.aharon@intel.comd5d383252013-07-04 14:44:32223#include "content/public/common/process_type.h"
jam@chromium.orgd7bd3e52013-07-21 04:29:20224#include "content/public/common/webplugininfo.h"
benwells@chromium.org50de9aa22013-11-14 06:30:34225#include "extensions/browser/process_map.h"
isherman@chromium.orgfe58acc22012-02-29 01:29:58226#include "net/base/load_flags.h"
akalin@chromium.org3dc1bc42012-06-19 08:20:53227#include "net/url_request/url_fetcher.h"
initial.commit09911bf2008-07-26 23:55:29228
phajdan.jr@chromium.orge06131d2010-02-10 18:40:33229// TODO(port): port browser_distribution.h.
230#if !defined(OS_POSIX)
kuchhal@chromium.org79bf0b72009-04-27 21:30:55231#include "chrome/installer/util/browser_distribution.h"
paul@chromium.orgdc6f4962009-02-13 01:25:50232#endif
233
rvargas@google.com5ccaa412009-11-13 22:00:16234#if defined(OS_CHROMEOS)
235#include "chrome/browser/chromeos/external_metrics.h"
stevenjb@chromium.org279690f82013-10-09 08:23:52236#include "chromeos/system/statistics_provider.h"
rvargas@google.com5ccaa412009-11-13 22:00:16237#endif
238
eroman@chromium.orgd7c1fa62012-06-15 23:35:30239#if defined(OS_WIN)
240#include <windows.h> // Needed for STATUS_* codes
rogerm@chromium.org261ab7c2013-08-19 15:04:58241#include "base/win/registry.h"
eroman@chromium.orgd7c1fa62012-06-15 23:35:30242#endif
243
vitalybuka@chromium.orga3079832013-10-24 20:29:36244#if !defined(OS_ANDROID)
jianli@chromium.orgcbf160aa2013-11-05 17:54:55245#include "chrome/browser/service_process/service_process_control.h"
vitalybuka@chromium.orga3079832013-10-24 20:29:36246#endif
247
dsh@google.come1acf6f2008-10-27 20:43:33248using base::Time;
joi@chromium.org631bb742011-11-02 11:29:39249using content::BrowserThread;
jam@chromium.org4967f792012-01-20 22:14:40250using content::ChildProcessData;
tfarina@chromium.org09d31d52012-03-11 22:30:27251using content::LoadNotificationDetails;
jam@chromium.org3a5180ae2011-12-21 02:39:38252using content::PluginService;
dsh@google.come1acf6f2008-10-27 20:43:33253
isherman@chromium.orgfe58acc22012-02-29 01:29:58254namespace {
isherman@chromium.orgb2a4812d2012-02-28 05:31:31255
isherman@chromium.orgfe58acc22012-02-29 01:29:58256// Check to see that we're being called on only one thread.
257bool IsSingleThreaded() {
258 static base::PlatformThreadId thread_id = 0;
259 if (!thread_id)
260 thread_id = base::PlatformThread::CurrentId();
261 return base::PlatformThread::CurrentId() == thread_id;
262}
263
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16264// The delay, in seconds, after starting recording before doing expensive
265// initialization work.
dfalcantara@chromium.org12180f82012-10-10 21:13:30266#if defined(OS_ANDROID) || defined(OS_IOS)
267// On mobile devices, a significant portion of sessions last less than a minute.
268// Use a shorter timer on these platforms to avoid losing data.
269// TODO(dfalcantara): To avoid delaying startup, tighten up initialization so
270// that it occurs after the user gets their initial page.
271const int kInitializationDelaySeconds = 5;
272#else
isherman@chromium.orgfe58acc22012-02-29 01:29:58273const int kInitializationDelaySeconds = 30;
dfalcantara@chromium.org12180f82012-10-10 21:13:30274#endif
petersont@google.com252873ef2008-08-04 21:59:45275
jar@chromium.orgc9a3ef82009-05-28 22:02:46276// This specifies the amount of time to wait for all renderers to send their
277// data.
isherman@chromium.orgfe58acc22012-02-29 01:29:58278const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
jar@chromium.orgc9a3ef82009-05-28 22:02:46279
stuartmorgan@chromium.org54702c92011-04-15 15:06:43280// The maximum number of events in a log uploaded to the UMA server.
isherman@chromium.orgfe58acc22012-02-29 01:29:58281const int kEventLimit = 2400;
jar@google.com68475e602008-08-22 03:21:15282
283// If an upload fails, and the transmission was over this byte count, then we
284// will discard the log, and not try to retransmit it. We also don't persist
285// the log to the prefs for transmission during the next chrome session if this
286// limit is exceeded.
isherman@chromium.orgfe58acc22012-02-29 01:29:58287const size_t kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29288
tedvessenes@gmail.comfc4252a72012-01-12 21:58:47289// Interval, in minutes, between state saves.
isherman@chromium.orgfe58acc22012-02-29 01:29:58290const int kSaveStateIntervalMinutes = 5;
291
isherman@chromium.org4266def22012-05-17 01:02:40292enum ResponseStatus {
293 UNKNOWN_FAILURE,
294 SUCCESS,
295 BAD_REQUEST, // Invalid syntax or log too large.
isherman@chromium.org9f5c1ce82012-05-23 23:11:28296 NO_RESPONSE,
isherman@chromium.org4266def22012-05-17 01:02:40297 NUM_RESPONSE_STATUSES
298};
299
300ResponseStatus ResponseCodeToStatus(int response_code) {
301 switch (response_code) {
302 case 200:
303 return SUCCESS;
304 case 400:
305 return BAD_REQUEST;
isherman@chromium.org9f5c1ce82012-05-23 23:11:28306 case net::URLFetcher::RESPONSE_CODE_INVALID:
307 return NO_RESPONSE;
isherman@chromium.org4266def22012-05-17 01:02:40308 default:
309 return UNKNOWN_FAILURE;
310 }
311}
312
stevet@chromium.orge61003a2012-05-24 17:03:19313// The argument used to generate a non-identifying entropy source. We want no
asvitkine@chromium.org9556a892013-06-21 16:53:20314// more than 13 bits of entropy, so use this max to return a number in the range
315// [0, 7999] as the entropy source (12.97 bits of entropy).
316const int kMaxLowEntropySize = 8000;
stevet@chromium.orge61003a2012-05-24 17:03:19317
asvitkine@chromium.orge63a9ef2012-08-30 15:29:42318// Default prefs value for prefs::kMetricsLowEntropySource to indicate that the
319// value has not yet been set.
320const int kLowEntropySourceNotSet = -1;
321
stevet@chromium.orge61003a2012-05-24 17:03:19322// Generates a new non-identifying entropy source used to seed persistent
323// activities.
324int GenerateLowEntropySource() {
asvitkine@chromium.org20f999b52012-08-24 22:32:59325 return base::RandInt(0, kMaxLowEntropySize - 1);
stevet@chromium.orge61003a2012-05-24 17:03:19326}
327
eroman@chromium.orgd7c1fa62012-06-15 23:35:30328// Converts an exit code into something that can be inserted into our
329// histograms (which expect non-negative numbers less than MAX_INT).
330int MapCrashExitCodeForHistogram(int exit_code) {
331#if defined(OS_WIN)
332 // Since |abs(STATUS_GUARD_PAGE_VIOLATION) == MAX_INT| it causes problems in
333 // histograms.cc. Solve this by remapping it to a smaller value, which
334 // hopefully doesn't conflict with other codes.
335 if (exit_code == STATUS_GUARD_PAGE_VIOLATION)
336 return 0x1FCF7EC3; // Randomly picked number.
337#endif
338
339 return std::abs(exit_code);
340}
341
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19342void MarkAppCleanShutdownAndCommit() {
343 PrefService* pref = g_browser_process->local_state();
344 pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19345 pref->SetInteger(prefs::kStabilityExecutionPhase,
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21346 MetricsService::SHUTDOWN_COMPLETE);
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19347 // Start writing right away (write happens on a different thread).
348 pref->CommitPendingWrite();
349}
350
asvitkine@chromium.org80a8f312013-12-16 18:00:30351// Returns whether initial stability metrics should be sent in a separate log.
352bool SendSeparateInitialStabilityLog() {
353 return base::FieldTrialList::FindFullName("UMAStability") == "SeparateLog";
354}
355
asvitkine@chromium.org20f999b52012-08-24 22:32:59356} // namespace
initial.commit09911bf2008-07-26 23:55:29357
bengr@chromium.org60677562013-11-17 15:52:55358
asvitkine@chromium.org7a5c07812014-02-26 11:45:41359SyntheticTrialGroup::SyntheticTrialGroup(uint32 trial, uint32 group) {
bengr@chromium.org60677562013-11-17 15:52:55360 id.name = trial;
361 id.group = group;
362}
363
364SyntheticTrialGroup::~SyntheticTrialGroup() {
365}
366
jar@chromium.orgc0c55e92011-09-10 18:47:30367// static
368MetricsService::ShutdownCleanliness MetricsService::clean_shutdown_status_ =
369 MetricsService::CLEANLY_SHUTDOWN;
370
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19371MetricsService::ExecutionPhase MetricsService::execution_phase_ =
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21372 MetricsService::UNINITIALIZED_PHASE;
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19373
erg@google.com679082052010-07-21 21:30:13374// This is used to quickly log stats from child process related notifications in
375// MetricsService::child_stats_buffer_. The buffer's contents are transferred
376// out when Local State is periodically saved. The information is then
377// reported to the UMA server on next launch.
378struct MetricsService::ChildProcessStats {
379 public:
jam@chromium.orgf3b357692013-03-22 05:16:13380 explicit ChildProcessStats(int process_type)
erg@google.com679082052010-07-21 21:30:13381 : process_launches(0),
382 process_crashes(0),
383 instances(0),
bauerb@chromium.orgcd937072012-07-02 09:00:29384 loading_errors(0),
jam@chromium.orgf3b357692013-03-22 05:16:13385 process_type(process_type) {}
erg@google.com679082052010-07-21 21:30:13386
387 // This constructor is only used by the map to return some default value for
388 // an index for which no value has been assigned.
389 ChildProcessStats()
390 : process_launches(0),
pkasting@chromium.orgd88bf0a2011-08-30 23:55:57391 process_crashes(0),
392 instances(0),
bauerb@chromium.orgcd937072012-07-02 09:00:29393 loading_errors(0),
jam@chromium.orgbd5d6cf2011-12-01 00:39:12394 process_type(content::PROCESS_TYPE_UNKNOWN) {}
erg@google.com679082052010-07-21 21:30:13395
396 // The number of times that the given child process has been launched
397 int process_launches;
398
399 // The number of times that the given child process has crashed
400 int process_crashes;
401
402 // The number of instances of this child process that have been created.
403 // An instance is a DOM object rendered by this child process during a page
404 // load.
405 int instances;
406
bauerb@chromium.orgcd937072012-07-02 09:00:29407 // The number of times there was an error loading an instance of this child
408 // process.
409 int loading_errors;
410
jam@chromium.orgf3b357692013-03-22 05:16:13411 int process_type;
erg@google.com679082052010-07-21 21:30:13412};
initial.commit09911bf2008-07-26 23:55:29413
sail@chromium.org84c988a2011-04-19 17:56:33414// Handles asynchronous fetching of memory details.
415// Will run the provided task after finished.
416class MetricsMemoryDetails : public MemoryDetails {
417 public:
dcheng@chromium.org2226c222011-11-22 00:08:40418 explicit MetricsMemoryDetails(const base::Closure& callback)
419 : callback_(callback) {}
sail@chromium.org84c988a2011-04-19 17:56:33420
rsleevi@chromium.orgb94584a2013-02-07 03:02:08421 virtual void OnDetailsAvailable() OVERRIDE {
xhwang@chromium.orgb3a25092013-05-28 22:08:16422 base::MessageLoop::current()->PostTask(FROM_HERE, callback_);
sail@chromium.org84c988a2011-04-19 17:56:33423 }
424
425 private:
rsleevi@chromium.orgb94584a2013-02-07 03:02:08426 virtual ~MetricsMemoryDetails() {}
sail@chromium.org84c988a2011-04-19 17:56:33427
dcheng@chromium.org2226c222011-11-22 00:08:40428 base::Closure callback_;
sail@chromium.org84c988a2011-04-19 17:56:33429 DISALLOW_COPY_AND_ASSIGN(MetricsMemoryDetails);
430};
431
initial.commit09911bf2008-07-26 23:55:29432// static
joi@chromium.orgb1de2c72013-02-06 02:45:47433void MetricsService::RegisterPrefs(PrefRegistrySimple* registry) {
initial.commit09911bf2008-07-26 23:55:29434 DCHECK(IsSingleThreaded());
dcheng@chromium.org007b3f82013-04-09 08:46:45435 registry->RegisterStringPref(prefs::kMetricsClientID, std::string());
joi@chromium.orgb1de2c72013-02-06 02:45:47436 registry->RegisterIntegerPref(prefs::kMetricsLowEntropySource,
437 kLowEntropySourceNotSet);
438 registry->RegisterInt64Pref(prefs::kMetricsClientIDTimestamp, 0);
439 registry->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
440 registry->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
dcheng@chromium.org007b3f82013-04-09 08:46:45441 registry->RegisterStringPref(prefs::kStabilityStatsVersion, std::string());
joi@chromium.orgb1de2c72013-02-06 02:45:47442 registry->RegisterInt64Pref(prefs::kStabilityStatsBuildTime, 0);
443 registry->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19444 registry->RegisterIntegerPref(prefs::kStabilityExecutionPhase,
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21445 UNINITIALIZED_PHASE);
joi@chromium.orgb1de2c72013-02-06 02:45:47446 registry->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
447 registry->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
448 registry->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
449 registry->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
450 registry->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount, 0);
451 registry->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
452 registry->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
453 registry->RegisterIntegerPref(prefs::kStabilityExtensionRendererCrashCount,
454 0);
455 registry->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
456 registry->RegisterIntegerPref(prefs::kStabilityChildProcessCrashCount, 0);
457 registry->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail, 0);
458 registry->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
459 0);
460 registry->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
461 registry->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
petkov@chromium.orgc1834a92011-01-21 18:21:03462#if defined(OS_CHROMEOS)
joi@chromium.orgb1de2c72013-02-06 02:45:47463 registry->RegisterIntegerPref(prefs::kStabilityOtherUserCrashCount, 0);
464 registry->RegisterIntegerPref(prefs::kStabilityKernelCrashCount, 0);
465 registry->RegisterIntegerPref(prefs::kStabilitySystemUncleanShutdownCount, 0);
petkov@chromium.orgc1834a92011-01-21 18:21:03466#endif // OS_CHROMEOS
cpu@google.come73c01972008-08-13 00:18:24467
asvitkine@chromium.org0f2f7792013-11-28 16:09:14468 registry->RegisterStringPref(prefs::kStabilitySavedSystemProfile,
469 std::string());
470 registry->RegisterStringPref(prefs::kStabilitySavedSystemProfileHash,
471 std::string());
472
isherman@chromium.org5f3e1642013-05-05 03:37:34473 registry->RegisterListPref(prefs::kMetricsInitialLogs);
474 registry->RegisterListPref(prefs::kMetricsOngoingLogs);
robertshield@google.com0bb1a622009-03-04 03:22:32475
isherman@chromium.org5c181552013-02-07 09:12:52476 registry->RegisterInt64Pref(prefs::kInstallDate, 0);
joi@chromium.orgb1de2c72013-02-06 02:45:47477 registry->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
478 registry->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
joi@chromium.orgb1de2c72013-02-06 02:45:47479 registry->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
480 registry->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
481 registry->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
kkimlabs@chromium.orgc778687a2014-02-11 14:46:45482
483#if defined(OS_ANDROID)
484 RegisterPrefsAndroid(registry);
485#endif // defined(OS_ANDROID)
initial.commit09911bf2008-07-26 23:55:29486}
487
jar@chromium.org541f77922009-02-23 21:14:38488// static
489void MetricsService::DiscardOldStabilityStats(PrefService* local_state) {
490 local_state->SetBoolean(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21491 local_state->SetInteger(prefs::kStabilityExecutionPhase, UNINITIALIZED_PHASE);
jar@chromium.orgc9abf242009-07-18 06:00:38492 local_state->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
jar@chromium.org541f77922009-02-23 21:14:38493
494 local_state->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
495 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
496 local_state->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
497 local_state->SetInteger(prefs::kStabilityDebuggerPresent, 0);
498 local_state->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);
499
500 local_state->SetInteger(prefs::kStabilityLaunchCount, 0);
501 local_state->SetInteger(prefs::kStabilityCrashCount, 0);
502
503 local_state->SetInteger(prefs::kStabilityPageLoadCount, 0);
504 local_state->SetInteger(prefs::kStabilityRendererCrashCount, 0);
505 local_state->SetInteger(prefs::kStabilityRendererHangCount, 0);
506
jar@chromium.org9165f742010-03-10 22:55:01507 local_state->SetInt64(prefs::kStabilityLaunchTimeSec, 0);
508 local_state->SetInt64(prefs::kStabilityLastTimestampSec, 0);
jar@chromium.org541f77922009-02-23 21:14:38509
510 local_state->ClearPref(prefs::kStabilityPluginStats);
jar@chromium.orgae155cb92009-06-19 06:10:37511
isherman@chromium.org5f3e1642013-05-05 03:37:34512 local_state->ClearPref(prefs::kMetricsInitialLogs);
513 local_state->ClearPref(prefs::kMetricsOngoingLogs);
kkimlabs@chromium.orgc778687a2014-02-11 14:46:45514
515#if defined(OS_ANDROID)
516 DiscardOldStabilityStatsAndroid(local_state);
517#endif // defined(OS_ANDROID)
jar@chromium.org541f77922009-02-23 21:14:38518}
519
initial.commit09911bf2008-07-26 23:55:29520MetricsService::MetricsService()
petersont@google.comd01b8732008-10-16 02:18:07521 : recording_active_(false),
522 reporting_active_(false),
stuartmorgan@chromium.org410938e02012-10-24 16:33:59523 test_mode_active_(false),
petersont@google.comd01b8732008-10-16 02:18:07524 state_(INITIALIZED),
asvitkine@chromium.org80a8f312013-12-16 18:00:30525 has_initial_stability_log_(false),
asvitkine@chromium.orge88be472e2013-04-26 22:36:36526 low_entropy_source_(kLowEntropySourceNotSet),
petersont@google.comd01b8732008-10-16 02:18:07527 idle_since_last_transmission_(false),
asvitkine@chromium.org80a8f312013-12-16 18:00:30528 session_id_(-1),
initial.commit09911bf2008-07-26 23:55:29529 next_window_id_(0),
tfarina@chromium.org9c009092013-05-01 03:14:09530 self_ptr_factory_(this),
531 state_saver_factory_(this),
stevet@chromium.orge5354322012-08-09 23:07:37532 waiting_for_asynchronous_reporting_step_(false),
vitalybuka@chromium.orga3079832013-10-24 20:29:36533 num_async_histogram_fetches_in_progress_(0),
stevet@chromium.orge5354322012-08-09 23:07:37534 entropy_source_returned_(LAST_ENTROPY_NONE) {
initial.commit09911bf2008-07-26 23:55:29535 DCHECK(IsSingleThreaded());
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16536
asvitkine@chromium.org80a8f312013-12-16 18:00:30537 log_manager_.set_log_serializer(new MetricsLogSerializer);
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10538 log_manager_.set_max_ongoing_log_store_size(kUploadLogAvoidRetransmitSize);
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:40539
540 BrowserChildProcessObserver::Add(this);
initial.commit09911bf2008-07-26 23:55:29541}
542
543MetricsService::~MetricsService() {
stuartmorgan@chromium.org410938e02012-10-24 16:33:59544 DisableRecording();
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:40545
546 BrowserChildProcessObserver::Remove(this);
initial.commit09911bf2008-07-26 23:55:29547}
548
asvitkine@chromium.org80a8f312013-12-16 18:00:30549void MetricsService::InitializeMetricsRecordingState(
550 ReportingState reporting_state) {
551 InitializeMetricsState(reporting_state);
552
553 base::Closure callback = base::Bind(&MetricsService::StartScheduledUpload,
554 self_ptr_factory_.GetWeakPtr());
555 scheduler_.reset(new MetricsReportingScheduler(callback));
556}
557
petersont@google.comd01b8732008-10-16 02:18:07558void MetricsService::Start() {
stuartmorgan@chromium.orgb1c8dc02011-04-13 18:32:04559 HandleIdleSinceLastTransmission(false);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59560 EnableRecording();
561 EnableReporting();
petersont@google.comd01b8732008-10-16 02:18:07562}
563
stuartmorgan@chromium.org410938e02012-10-24 16:33:59564void MetricsService::StartRecordingForTests() {
565 test_mode_active_ = true;
566 EnableRecording();
567 DisableReporting();
petersont@google.comd01b8732008-10-16 02:18:07568}
569
570void MetricsService::Stop() {
stuartmorgan@chromium.orgb1c8dc02011-04-13 18:32:04571 HandleIdleSinceLastTransmission(false);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59572 DisableReporting();
573 DisableRecording();
574}
575
576void MetricsService::EnableReporting() {
577 if (reporting_active_)
578 return;
579 reporting_active_ = true;
580 StartSchedulerIfNecessary();
581}
582
583void MetricsService::DisableReporting() {
584 reporting_active_ = false;
petersont@google.comd01b8732008-10-16 02:18:07585}
586
joi@chromium.orgedafd4c2011-05-10 17:18:53587std::string MetricsService::GetClientId() {
588 return client_id_;
589}
590
asvitkine@chromium.org20f999b52012-08-24 22:32:59591scoped_ptr<const base::FieldTrial::EntropyProvider>
asvitkine@chromium.org80a8f312013-12-16 18:00:30592MetricsService::CreateEntropyProvider(ReportingState reporting_state) {
stevet@chromium.org29d81ee02012-05-25 05:45:42593 // For metrics reporting-enabled users, we combine the client ID and low
594 // entropy source to get the final entropy source. Otherwise, only use the low
595 // entropy source.
596 // This has two useful properties:
stevet@chromium.orge61003a2012-05-24 17:03:19597 // 1) It makes the entropy source less identifiable for parties that do not
598 // know the low entropy source.
599 // 2) It makes the final entropy source resettable.
asvitkine@chromium.orgd0a82c82013-06-13 16:31:18600 const int low_entropy_source_value = GetLowEntropySource();
601 UMA_HISTOGRAM_SPARSE_SLOWLY("UMA.LowEntropySourceValue",
602 low_entropy_source_value);
asvitkine@chromium.org80a8f312013-12-16 18:00:30603 if (reporting_state == REPORTING_ENABLED) {
stevet@chromium.org5fbffb72012-08-18 01:59:18604 if (entropy_source_returned_ == LAST_ENTROPY_NONE)
605 entropy_source_returned_ = LAST_ENTROPY_HIGH;
606 DCHECK_EQ(LAST_ENTROPY_HIGH, entropy_source_returned_);
asvitkine@chromium.org20f999b52012-08-24 22:32:59607 const std::string high_entropy_source =
asvitkine@chromium.orgd0a82c82013-06-13 16:31:18608 client_id_ + base::IntToString(low_entropy_source_value);
asvitkine@chromium.org20f999b52012-08-24 22:32:59609 return scoped_ptr<const base::FieldTrial::EntropyProvider>(
610 new metrics::SHA1EntropyProvider(high_entropy_source));
stevet@chromium.orge5354322012-08-09 23:07:37611 }
asvitkine@chromium.org20f999b52012-08-24 22:32:59612
stevet@chromium.org5fbffb72012-08-18 01:59:18613 if (entropy_source_returned_ == LAST_ENTROPY_NONE)
614 entropy_source_returned_ = LAST_ENTROPY_LOW;
615 DCHECK_EQ(LAST_ENTROPY_LOW, entropy_source_returned_);
asvitkine@chromium.org9d7c4a82013-05-07 12:10:49616
617#if defined(OS_ANDROID) || defined(OS_IOS)
618 return scoped_ptr<const base::FieldTrial::EntropyProvider>(
619 new metrics::CachingPermutedEntropyProvider(
620 g_browser_process->local_state(),
asvitkine@chromium.orgd0a82c82013-06-13 16:31:18621 low_entropy_source_value,
asvitkine@chromium.org9d7c4a82013-05-07 12:10:49622 kMaxLowEntropySize));
623#else
asvitkine@chromium.org20f999b52012-08-24 22:32:59624 return scoped_ptr<const base::FieldTrial::EntropyProvider>(
asvitkine@chromium.orgd0a82c82013-06-13 16:31:18625 new metrics::PermutedEntropyProvider(low_entropy_source_value,
asvitkine@chromium.org20f999b52012-08-24 22:32:59626 kMaxLowEntropySize));
asvitkine@chromium.org9d7c4a82013-05-07 12:10:49627#endif
stevet@chromium.orge61003a2012-05-24 17:03:19628}
629
jam@chromium.org5cbeeef72012-02-08 02:05:18630void MetricsService::ForceClientIdCreation() {
631 if (!client_id_.empty())
632 return;
633 PrefService* pref = g_browser_process->local_state();
634 client_id_ = pref->GetString(prefs::kMetricsClientID);
635 if (!client_id_.empty())
636 return;
637
638 client_id_ = GenerateClientID();
639 pref->SetString(prefs::kMetricsClientID, client_id_);
640
641 // Might as well make a note of how long this ID has existed
642 pref->SetString(prefs::kMetricsClientIDTimestamp,
643 base::Int64ToString(Time::Now().ToTimeT()));
644}
645
stuartmorgan@chromium.org410938e02012-10-24 16:33:59646void MetricsService::EnableRecording() {
initial.commit09911bf2008-07-26 23:55:29647 DCHECK(IsSingleThreaded());
648
stuartmorgan@chromium.org410938e02012-10-24 16:33:59649 if (recording_active_)
initial.commit09911bf2008-07-26 23:55:29650 return;
stuartmorgan@chromium.org410938e02012-10-24 16:33:59651 recording_active_ = true;
initial.commit09911bf2008-07-26 23:55:29652
stuartmorgan@chromium.org410938e02012-10-24 16:33:59653 ForceClientIdCreation();
rsesek@chromium.org264c0acac2013-10-01 13:33:30654 crash_keys::SetClientID(client_id_);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59655 if (!log_manager_.current_log())
656 OpenNewLog();
pkasting@chromium.org005ef3e2009-05-22 20:55:46657
stuartmorgan@chromium.org410938e02012-10-24 16:33:59658 SetUpNotifications(&registrar_, this);
ben@chromium.orge6e30ac2014-01-13 21:24:39659 base::RemoveActionCallback(action_callback_);
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:22660 action_callback_ = base::Bind(&MetricsService::OnUserAction,
661 base::Unretained(this));
ben@chromium.orge6e30ac2014-01-13 21:24:39662 base::AddActionCallback(action_callback_);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59663}
664
665void MetricsService::DisableRecording() {
666 DCHECK(IsSingleThreaded());
667
668 if (!recording_active_)
669 return;
670 recording_active_ = false;
671
ben@chromium.orge6e30ac2014-01-13 21:24:39672 base::RemoveActionCallback(action_callback_);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59673 registrar_.RemoveAll();
674 PushPendingLogsToPersistentStorage();
675 DCHECK(!log_manager_.has_staged_log());
initial.commit09911bf2008-07-26 23:55:29676}
677
petersont@google.comd01b8732008-10-16 02:18:07678bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29679 DCHECK(IsSingleThreaded());
petersont@google.comd01b8732008-10-16 02:18:07680 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29681}
682
petersont@google.comd01b8732008-10-16 02:18:07683bool MetricsService::reporting_active() const {
684 DCHECK(IsSingleThreaded());
685 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29686}
687
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15688// static
jam@chromium.org6c2381d2011-10-19 02:52:53689void MetricsService::SetUpNotifications(
690 content::NotificationRegistrar* registrar,
691 content::NotificationObserver* observer) {
692 registrar->Add(observer, chrome::NOTIFICATION_BROWSER_OPENED,
jam@chromium.orgad50def52011-10-19 23:17:07693 content::NotificationService::AllBrowserContextsAndSources());
jam@chromium.org6c2381d2011-10-19 02:52:53694 registrar->Add(observer, chrome::NOTIFICATION_BROWSER_CLOSED,
jam@chromium.orgad50def52011-10-19 23:17:07695 content::NotificationService::AllSources());
avi@chromium.org884033e2012-04-16 19:38:42696 registrar->Add(observer, chrome::NOTIFICATION_TAB_PARENTED,
jam@chromium.orgad50def52011-10-19 23:17:07697 content::NotificationService::AllSources());
avi@chromium.org884033e2012-04-16 19:38:42698 registrar->Add(observer, chrome::NOTIFICATION_TAB_CLOSING,
jam@chromium.orgad50def52011-10-19 23:17:07699 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53700 registrar->Add(observer, content::NOTIFICATION_LOAD_START,
jam@chromium.orgad50def52011-10-19 23:17:07701 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53702 registrar->Add(observer, content::NOTIFICATION_LOAD_STOP,
jam@chromium.orgad50def52011-10-19 23:17:07703 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53704 registrar->Add(observer, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
jam@chromium.orgad50def52011-10-19 23:17:07705 content::NotificationService::AllSources());
avi@chromium.org42d8d7582013-11-09 01:24:38706 registrar->Add(observer, content::NOTIFICATION_RENDER_WIDGET_HOST_HANG,
jam@chromium.orgad50def52011-10-19 23:17:07707 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53708 registrar->Add(observer, chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
jam@chromium.orgad50def52011-10-19 23:17:07709 content::NotificationService::AllSources());
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15710}
711
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:40712void MetricsService::BrowserChildProcessHostConnected(
713 const content::ChildProcessData& data) {
714 GetChildProcessStats(data).process_launches++;
715}
716
717void MetricsService::BrowserChildProcessCrashed(
718 const content::ChildProcessData& data) {
719 GetChildProcessStats(data).process_crashes++;
720 // Exclude plugin crashes from the count below because we report them via
721 // a separate UMA metric.
jam@chromium.orgf3b357692013-03-22 05:16:13722 if (!IsPluginProcess(data.process_type))
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:40723 IncrementPrefValue(prefs::kStabilityChildProcessCrashCount);
724}
725
726void MetricsService::BrowserChildProcessInstanceCreated(
727 const content::ChildProcessData& data) {
728 GetChildProcessStats(data).instances++;
729}
730
ananta@chromium.org432115822011-07-10 15:52:27731void MetricsService::Observe(int type,
jam@chromium.org6c2381d2011-10-19 02:52:53732 const content::NotificationSource& source,
733 const content::NotificationDetails& details) {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10734 DCHECK(log_manager_.current_log());
initial.commit09911bf2008-07-26 23:55:29735 DCHECK(IsSingleThreaded());
736
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04737 // Check for notifications related to core stability metrics, or that are
738 // just triggers to end idle mode. Anything else should be added in the later
739 // switch statement, where they take effect only if general metrics should be
740 // logged.
741 bool handled = false;
ananta@chromium.org432115822011-07-10 15:52:27742 switch (type) {
ananta@chromium.org432115822011-07-10 15:52:27743 case chrome::NOTIFICATION_BROWSER_OPENED:
isherman@chromium.org46a0efc2013-07-17 15:40:47744 case chrome::NOTIFICATION_BROWSER_CLOSED:
745 case chrome::NOTIFICATION_TAB_PARENTED:
746 case chrome::NOTIFICATION_TAB_CLOSING:
ananta@chromium.org432115822011-07-10 15:52:27747 case content::NOTIFICATION_LOAD_STOP:
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04748 // These notifications are used only to break out of idle mode.
749 handled = true;
initial.commit09911bf2008-07-26 23:55:29750 break;
751
rlp@chromium.org752a5262013-06-23 14:53:42752 case content::NOTIFICATION_LOAD_START: {
753 content::NavigationController* controller =
754 content::Source<content::NavigationController>(source).ptr();
755 content::WebContents* web_contents = controller->GetWebContents();
756 LogLoadStarted(web_contents);
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04757 handled = true;
initial.commit09911bf2008-07-26 23:55:29758 break;
rlp@chromium.org752a5262013-06-23 14:53:42759 }
initial.commit09911bf2008-07-26 23:55:29760
ananta@chromium.org432115822011-07-10 15:52:27761 case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: {
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04762 content::RenderProcessHost::RendererClosedDetails* process_details =
763 content::Details<
764 content::RenderProcessHost::RendererClosedDetails>(
765 details).ptr();
766 content::RenderProcessHost* host =
767 content::Source<content::RenderProcessHost>(source).ptr();
768 LogRendererCrash(
769 host, process_details->status, process_details->exit_code);
770 handled = true;
initial.commit09911bf2008-07-26 23:55:29771 break;
ananta@chromium.org1226abb2010-06-10 18:01:28772 }
initial.commit09911bf2008-07-26 23:55:29773
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04774 case content::NOTIFICATION_RENDER_WIDGET_HOST_HANG:
775 LogRendererHang();
776 handled = true;
initial.commit09911bf2008-07-26 23:55:29777 break;
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04778
779 default:
780 // Everything else is handled after the early return check below.
781 break;
782 }
783
784 // If it wasn't one of the stability-related notifications, and event
785 // logging isn't suppressed, handle it.
786 if (!handled && ShouldLogEvents()) {
787 switch (type) {
788 case chrome::NOTIFICATION_OMNIBOX_OPENED_URL: {
789 MetricsLog* current_log =
790 static_cast<MetricsLog*>(log_manager_.current_log());
791 DCHECK(current_log);
792 current_log->RecordOmniboxOpenedURL(
793 *content::Details<OmniboxLog>(details).ptr());
794 break;
795 }
796
797 default:
798 NOTREACHED();
799 break;
800 }
initial.commit09911bf2008-07-26 23:55:29801 }
petersont@google.comd01b8732008-10-16 02:18:07802
803 HandleIdleSinceLastTransmission(false);
petersont@google.comd01b8732008-10-16 02:18:07804}
805
806void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
807 // If there wasn't a lot of action, maybe the computer was asleep, in which
808 // case, the log transmissions should have stopped. Here we start them up
809 // again.
pkasting@chromium.orgcac78842008-11-27 01:02:20810 if (!in_idle && idle_since_last_transmission_)
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16811 StartSchedulerIfNecessary();
pkasting@chromium.orgcac78842008-11-27 01:02:20812 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29813}
814
initial.commit09911bf2008-07-26 23:55:29815void MetricsService::RecordStartOfSessionEnd() {
stuartmorgan@chromium.org466f3c12011-03-23 21:20:38816 LogCleanShutdown();
initial.commit09911bf2008-07-26 23:55:29817 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
818}
819
820void MetricsService::RecordCompletedSessionEnd() {
stuartmorgan@chromium.org466f3c12011-03-23 21:20:38821 LogCleanShutdown();
initial.commit09911bf2008-07-26 23:55:29822 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
823}
824
stuartmorgan@chromium.org410938e02012-10-24 16:33:59825#if defined(OS_ANDROID) || defined(OS_IOS)
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39826void MetricsService::OnAppEnterBackground() {
827 scheduler_->Stop();
828
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19829 MarkAppCleanShutdownAndCommit();
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39830
831 // At this point, there's no way of knowing when the process will be
832 // killed, so this has to be treated similar to a shutdown, closing and
833 // persisting all logs. Unlinke a shutdown, the state is primed to be ready
834 // to continue logging and uploading if the process does return.
asvitkine@chromium.org80a8f312013-12-16 18:00:30835 if (recording_active() && state_ >= SENDING_INITIAL_STABILITY_LOG) {
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39836 PushPendingLogsToPersistentStorage();
stuartmorgan@chromium.org410938e02012-10-24 16:33:59837 // Persisting logs closes the current log, so start recording a new log
838 // immediately to capture any background work that might be done before the
839 // process is killed.
840 OpenNewLog();
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39841 }
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39842}
843
844void MetricsService::OnAppEnterForeground() {
845 PrefService* pref = g_browser_process->local_state();
846 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
847
848 StartSchedulerIfNecessary();
849}
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19850#else
851void MetricsService::LogNeedForCleanShutdown() {
852 PrefService* pref = g_browser_process->local_state();
853 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
854 // Redundant setting to be sure we call for a clean shutdown.
855 clean_shutdown_status_ = NEED_TO_SHUTDOWN;
856}
857#endif // defined(OS_ANDROID) || defined(OS_IOS)
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39858
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21859// static
860void MetricsService::SetExecutionPhase(ExecutionPhase execution_phase) {
861 execution_phase_ = execution_phase;
862 PrefService* pref = g_browser_process->local_state();
863 pref->SetInteger(prefs::kStabilityExecutionPhase, execution_phase_);
864}
865
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16866void MetricsService::RecordBreakpadRegistration(bool success) {
jar@google.com68475e602008-08-22 03:21:15867 if (!success)
cpu@google.come73c01972008-08-13 00:18:24868 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
869 else
870 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
871}
872
873void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
874 if (!has_debugger)
875 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
876 else
jar@google.com68475e602008-08-22 03:21:15877 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
cpu@google.come73c01972008-08-13 00:18:24878}
879
rogerm@chromium.org261ab7c2013-08-19 15:04:58880#if defined(OS_WIN)
881void MetricsService::CountBrowserCrashDumpAttempts() {
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45882 // Open the registry key for iteration.
rogerm@chromium.org261ab7c2013-08-19 15:04:58883 base::win::RegKey regkey;
884 if (regkey.Open(HKEY_CURRENT_USER,
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45885 chrome::kBrowserCrashDumpAttemptsRegistryPath,
rogerm@chromium.org261ab7c2013-08-19 15:04:58886 KEY_ALL_ACCESS) != ERROR_SUCCESS) {
887 return;
888 }
889
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45890 // The values we're interested in counting are all prefixed with the version.
891 base::string16 chrome_version(base::ASCIIToUTF16(chrome::kChromeVersion));
892
893 // Track a list of values to delete. We don't modify the registry key while
894 // we're iterating over its values.
895 typedef std::vector<base::string16> StringVector;
896 StringVector to_delete;
897
898 // Iterate over the values in the key counting dumps with and without crashes.
899 // We directly walk the values instead of using RegistryValueIterator in order
900 // to read all of the values as DWORDS instead of strings.
901 base::string16 name;
902 DWORD value = 0;
903 int dumps_with_crash = 0;
904 int dumps_with_no_crash = 0;
rogerm@chromium.org261ab7c2013-08-19 15:04:58905 for (int i = regkey.GetValueCount() - 1; i >= 0; --i) {
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45906 if (regkey.GetValueNameAt(i, &name) == ERROR_SUCCESS &&
907 StartsWith(name, chrome_version, false) &&
908 regkey.ReadValueDW(name.c_str(), &value) == ERROR_SUCCESS) {
909 to_delete.push_back(name);
910 if (value == 0)
911 ++dumps_with_no_crash;
912 else
913 ++dumps_with_crash;
rogerm@chromium.org261ab7c2013-08-19 15:04:58914 }
915 }
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45916
917 // Delete the registry keys we've just counted.
918 for (StringVector::iterator i = to_delete.begin(); i != to_delete.end(); ++i)
919 regkey.DeleteValue(i->c_str());
920
921 // Capture the histogram samples.
922 if (dumps_with_crash != 0)
923 UMA_HISTOGRAM_COUNTS("Chrome.BrowserDumpsWithCrash", dumps_with_crash);
924 if (dumps_with_no_crash != 0)
925 UMA_HISTOGRAM_COUNTS("Chrome.BrowserDumpsWithNoCrash", dumps_with_no_crash);
926 int total_dumps = dumps_with_crash + dumps_with_no_crash;
927 if (total_dumps != 0)
928 UMA_HISTOGRAM_COUNTS("Chrome.BrowserCrashDumpAttempts", total_dumps);
rogerm@chromium.org261ab7c2013-08-19 15:04:58929}
930#endif // defined(OS_WIN)
931
initial.commit09911bf2008-07-26 23:55:29932//------------------------------------------------------------------------------
933// private methods
934//------------------------------------------------------------------------------
935
936
937//------------------------------------------------------------------------------
938// Initialization methods
939
asvitkine@chromium.org80a8f312013-12-16 18:00:30940void MetricsService::InitializeMetricsState(ReportingState reporting_state) {
kuchhal@chromium.org79bf0b72009-04-27 21:30:55941#if defined(OS_POSIX)
simonjam@chromium.orgb4a72d842012-03-22 20:09:09942 network_stats_server_ = chrome_common_net::kEchoTestServerLocation;
943 http_pipelining_test_server_ = chrome_common_net::kPipelineTestServerBaseUrl;
kuchhal@chromium.org79bf0b72009-04-27 21:30:55944#else
945 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
rtenneti@chromium.orgd67d1052011-06-09 05:11:41946 network_stats_server_ = dist->GetNetworkStatsServer();
simonjam@chromium.orgadbb3762012-03-09 22:20:08947 http_pipelining_test_server_ = dist->GetHttpPipeliningTestServer();
kuchhal@chromium.org79bf0b72009-04-27 21:30:55948#endif
949
initial.commit09911bf2008-07-26 23:55:29950 PrefService* pref = g_browser_process->local_state();
951 DCHECK(pref);
952
asvitkine@chromium.org80a8f312013-12-16 18:00:30953 // TODO(asvitkine): Kill this logic when SendSeparateInitialStabilityLog() is
954 // is made the default behavior.
jar@chromium.org225c50842010-01-19 21:19:13955 if ((pref->GetInt64(prefs::kStabilityStatsBuildTime)
956 != MetricsLog::GetBuildTime()) ||
estade@chromium.orgddd231e2010-06-29 20:35:19957 (pref->GetString(prefs::kStabilityStatsVersion)
jar@chromium.org225c50842010-01-19 21:19:13958 != MetricsLog::GetVersionString())) {
jar@chromium.org541f77922009-02-23 21:14:38959 // This is a new version, so we don't want to confuse the stats about the
960 // old version with info that we upload.
961 DiscardOldStabilityStats(pref);
962 pref->SetString(prefs::kStabilityStatsVersion,
estade@chromium.orgddd231e2010-06-29 20:35:19963 MetricsLog::GetVersionString());
jar@chromium.org225c50842010-01-19 21:19:13964 pref->SetInt64(prefs::kStabilityStatsBuildTime,
965 MetricsLog::GetBuildTime());
jar@chromium.org541f77922009-02-23 21:14:38966 }
967
initial.commit09911bf2008-07-26 23:55:29968 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
initial.commit09911bf2008-07-26 23:55:29969
kkimlabs@chromium.orgc778687a2014-02-11 14:46:45970#if defined(OS_ANDROID)
971 LogAndroidStabilityToPrefs(pref);
972#endif // defined(OS_ANDROID)
973
cpu@google.come73c01972008-08-13 00:18:24974 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
975 IncrementPrefValue(prefs::kStabilityCrashCount);
jar@chromium.orgc0c55e92011-09-10 18:47:30976 // Reset flag, and wait until we call LogNeedForCleanShutdown() before
977 // monitoring.
978 pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19979
980 // TODO(rtenneti): On windows, consider saving/getting execution_phase from
981 // the registry.
982 int execution_phase = pref->GetInteger(prefs::kStabilityExecutionPhase);
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21983 UMA_HISTOGRAM_SPARSE_SLOWLY("Chrome.Browser.CrashedExecutionPhase",
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19984 execution_phase);
asvitkine@chromium.org80a8f312013-12-16 18:00:30985
986 // If the previous session didn't exit cleanly, then prepare an initial
987 // stability log if UMA is enabled.
988 bool reporting_will_be_enabled = (reporting_state == REPORTING_ENABLED);
989 if (reporting_will_be_enabled && SendSeparateInitialStabilityLog())
990 PrepareInitialStabilityLog();
initial.commit09911bf2008-07-26 23:55:29991 }
asvitkine@chromium.org80a8f312013-12-16 18:00:30992
993 // Update session ID.
994 ++session_id_;
995 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
996
997 // Stability bookkeeping
998 IncrementPrefValue(prefs::kStabilityLaunchCount);
999
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:211000 DCHECK_EQ(UNINITIALIZED_PHASE, execution_phase_);
1001 SetExecutionPhase(START_METRICS_RECORDING);
cpu@google.come73c01972008-08-13 00:18:241002
rogerm@chromium.org261ab7c2013-08-19 15:04:581003#if defined(OS_WIN)
1004 CountBrowserCrashDumpAttempts();
1005#endif // defined(OS_WIN)
1006
cpu@google.come73c01972008-08-13 00:18:241007 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
1008 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
jar@chromium.orgc9abf242009-07-18 06:00:381009 // This is marked false when we get a WM_ENDSESSION.
1010 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
initial.commit09911bf2008-07-26 23:55:291011 }
initial.commit09911bf2008-07-26 23:55:291012
mpearson@chromium.org076961c2014-03-12 22:23:561013 // Call GetUptimes() for the first time, thus allowing all later calls
1014 // to record incremental uptimes accurately.
1015 base::TimeDelta ignored_uptime_parameter;
1016 base::TimeDelta startup_uptime;
1017 GetUptimes(pref, &startup_uptime, &ignored_uptime_parameter);
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361018 DCHECK_EQ(0, startup_uptime.InMicroseconds());
jar@chromium.org9165f742010-03-10 22:55:011019 // For backwards compatibility, leave this intact in case Omaha is checking
1020 // them. prefs::kStabilityLastTimestampSec may also be useless now.
1021 // TODO(jar): Delete these if they have no uses.
robertshield@google.com0bb1a622009-03-04 03:22:321022 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
1023
1024 // Bookkeeping for the uninstall metrics.
1025 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:291026
jar@chromium.org92745242009-06-12 16:52:211027 // Get stats on use of command line.
1028 const CommandLine* command_line(CommandLine::ForCurrentProcess());
1029 size_t common_commands = 0;
1030 if (command_line->HasSwitch(switches::kUserDataDir)) {
1031 ++common_commands;
1032 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
1033 }
1034
1035 if (command_line->HasSwitch(switches::kApp)) {
1036 ++common_commands;
1037 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
1038 }
1039
msw@chromium.org62b4e522011-07-13 21:46:321040 size_t switch_count = command_line->GetSwitches().size();
1041 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount", switch_count);
jar@chromium.org92745242009-06-12 16:52:211042 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
msw@chromium.org62b4e522011-07-13 21:46:321043 switch_count - common_commands);
jar@chromium.org92745242009-06-12 16:52:211044
initial.commit09911bf2008-07-26 23:55:291045 // Kick off the process of saving the state (so the uptime numbers keep
1046 // getting updated) every n minutes.
1047 ScheduleNextStateSave();
1048}
1049
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401050// static
rsesek@chromium.orgd33e7cc2011-09-23 01:43:561051void MetricsService::InitTaskGetHardwareClass(
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401052 base::WeakPtr<MetricsService> self,
rsesek@chromium.orgd33e7cc2011-09-23 01:43:561053 base::MessageLoopProxy* target_loop) {
rsesek@chromium.orgd33e7cc2011-09-23 01:43:561054 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
1055
1056 std::string hardware_class;
1057#if defined(OS_CHROMEOS)
1058 chromeos::system::StatisticsProvider::GetInstance()->GetMachineStatistic(
1059 "hardware_class", &hardware_class);
1060#endif // OS_CHROMEOS
1061
1062 target_loop->PostTask(FROM_HERE,
1063 base::Bind(&MetricsService::OnInitTaskGotHardwareClass,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401064 self, hardware_class));
rsesek@chromium.orgd33e7cc2011-09-23 01:43:561065}
1066
1067void MetricsService::OnInitTaskGotHardwareClass(
1068 const std::string& hardware_class) {
isherman@chromium.orged0fd002012-04-25 23:10:341069 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
zelidrag@chromium.org85ed9d42010-06-08 22:37:441070 hardware_class_ = hardware_class;
rsesek@chromium.orgd33e7cc2011-09-23 01:43:561071
nileshagrawal@chromium.orgebd71962012-12-20 02:56:551072#if defined(ENABLE_PLUGINS)
rsesek@chromium.orgd33e7cc2011-09-23 01:43:561073 // Start the next part of the init task: loading plugin information.
1074 PluginService::GetInstance()->GetPlugins(
1075 base::Bind(&MetricsService::OnInitTaskGotPluginInfo,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401076 self_ptr_factory_.GetWeakPtr()));
nileshagrawal@chromium.orgebd71962012-12-20 02:56:551077#else
jam@chromium.orgd7bd3e52013-07-21 04:29:201078 std::vector<content::WebPluginInfo> plugin_list_empty;
nileshagrawal@chromium.orgebd71962012-12-20 02:56:551079 OnInitTaskGotPluginInfo(plugin_list_empty);
1080#endif // defined(ENABLE_PLUGINS)
rsesek@chromium.orgd33e7cc2011-09-23 01:43:561081}
1082
1083void MetricsService::OnInitTaskGotPluginInfo(
jam@chromium.orgd7bd3e52013-07-21 04:29:201084 const std::vector<content::WebPluginInfo>& plugins) {
isherman@chromium.orged0fd002012-04-25 23:10:341085 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
jam@chromium.org35fa6a22009-08-15 00:04:011086 plugins_ = plugins;
rsesek@chromium.orgd33e7cc2011-09-23 01:43:561087
ryanmyers@chromium.org197c0772012-05-14 23:50:511088 // Schedules a task on a blocking pool thread to gather Google Update
1089 // statistics (requires Registry reads).
1090 BrowserThread::PostBlockingPoolTask(
1091 FROM_HERE,
1092 base::Bind(&MetricsService::InitTaskGetGoogleUpdateData,
1093 self_ptr_factory_.GetWeakPtr(),
xhwang@chromium.orgb3a25092013-05-28 22:08:161094 base::MessageLoop::current()->message_loop_proxy()));
ryanmyers@chromium.org197c0772012-05-14 23:50:511095}
1096
1097// static
1098void MetricsService::InitTaskGetGoogleUpdateData(
1099 base::WeakPtr<MetricsService> self,
1100 base::MessageLoopProxy* target_loop) {
1101 GoogleUpdateMetrics google_update_metrics;
1102
1103#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
1104 const bool system_install = GoogleUpdateSettings::IsSystemInstall();
1105
1106 google_update_metrics.is_system_install = system_install;
1107 google_update_metrics.last_started_au =
1108 GoogleUpdateSettings::GetGoogleUpdateLastStartedAU(system_install);
1109 google_update_metrics.last_checked =
1110 GoogleUpdateSettings::GetGoogleUpdateLastChecked(system_install);
1111 GoogleUpdateSettings::GetUpdateDetailForGoogleUpdate(
1112 system_install,
1113 &google_update_metrics.google_update_data);
1114 GoogleUpdateSettings::GetUpdateDetail(
1115 system_install,
1116 &google_update_metrics.product_data);
1117#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
1118
1119 target_loop->PostTask(FROM_HERE,
1120 base::Bind(&MetricsService::OnInitTaskGotGoogleUpdateData,
1121 self, google_update_metrics));
1122}
1123
1124void MetricsService::OnInitTaskGotGoogleUpdateData(
1125 const GoogleUpdateMetrics& google_update_metrics) {
1126 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
1127
1128 google_update_metrics_ = google_update_metrics;
1129
isherman@chromium.orged0fd002012-04-25 23:10:341130 // Start the next part of the init task: fetching performance data. This will
1131 // call into |FinishedReceivingProfilerData()| when the task completes.
1132 chrome_browser_metrics::TrackingSynchronizer::FetchProfilerDataAsynchronously(
1133 self_ptr_factory_.GetWeakPtr());
1134}
1135
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:221136void MetricsService::OnUserAction(const std::string& action) {
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:041137 if (!ShouldLogEvents())
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:221138 return;
1139
1140 log_manager_.current_log()->RecordUserAction(action.c_str());
1141 HandleIdleSinceLastTransmission(false);
1142}
1143
isherman@chromium.orged0fd002012-04-25 23:10:341144void MetricsService::ReceivedProfilerData(
1145 const tracked_objects::ProcessDataSnapshot& process_data,
jam@chromium.orgf3b357692013-03-22 05:16:131146 int process_type) {
isherman@chromium.orged0fd002012-04-25 23:10:341147 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
1148
1149 // Upon the first callback, create the initial log so that we can immediately
1150 // save the profiler data.
asvitkine@chromium.org80a8f312013-12-16 18:00:301151 if (!initial_metrics_log_.get())
1152 initial_metrics_log_.reset(new MetricsLog(client_id_, session_id_));
isherman@chromium.orged0fd002012-04-25 23:10:341153
asvitkine@chromium.org80a8f312013-12-16 18:00:301154 initial_metrics_log_->RecordProfilerData(process_data, process_type);
isherman@chromium.orged0fd002012-04-25 23:10:341155}
1156
1157void MetricsService::FinishedReceivingProfilerData() {
1158 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361159 state_ = INIT_TASK_DONE;
asvitkine@chromium.org70886cd2013-12-04 05:53:421160 scheduler_->InitTaskComplete();
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361161}
1162
mpearson@chromium.org076961c2014-03-12 22:23:561163void MetricsService::GetUptimes(PrefService* pref,
1164 base::TimeDelta* incremental_uptime,
1165 base::TimeDelta* uptime) {
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361166 base::TimeTicks now = base::TimeTicks::Now();
mpearson@chromium.org076961c2014-03-12 22:23:561167 // If this is the first call, init |first_updated_time_| and
1168 // |last_updated_time_|.
1169 if (last_updated_time_.is_null()) {
1170 first_updated_time_ = now;
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361171 last_updated_time_ = now;
mpearson@chromium.org076961c2014-03-12 22:23:561172 }
1173 *incremental_uptime = now - last_updated_time_;
1174 *uptime = now - first_updated_time_;
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361175 last_updated_time_ = now;
1176
mpearson@chromium.org076961c2014-03-12 22:23:561177 const int64 incremental_time_secs = incremental_uptime->InSeconds();
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361178 if (incremental_time_secs > 0) {
1179 int64 metrics_uptime = pref->GetInt64(prefs::kUninstallMetricsUptimeSec);
1180 metrics_uptime += incremental_time_secs;
1181 pref->SetInt64(prefs::kUninstallMetricsUptimeSec, metrics_uptime);
1182 }
initial.commit09911bf2008-07-26 23:55:291183}
1184
stevet@chromium.orge61003a2012-05-24 17:03:191185int MetricsService::GetLowEntropySource() {
1186 // Note that the default value for the low entropy source and the default pref
asvitkine@chromium.orge88be472e2013-04-26 22:36:361187 // value are both kLowEntropySourceNotSet, which is used to identify if the
1188 // value has been set or not.
1189 if (low_entropy_source_ != kLowEntropySourceNotSet)
stevet@chromium.orge61003a2012-05-24 17:03:191190 return low_entropy_source_;
1191
asvitkine@chromium.org9d7c4a82013-05-07 12:10:491192 PrefService* local_state = g_browser_process->local_state();
stevet@chromium.orge61003a2012-05-24 17:03:191193 const CommandLine* command_line(CommandLine::ForCurrentProcess());
1194 // Only try to load the value from prefs if the user did not request a reset.
1195 // Otherwise, skip to generating a new value.
stevet@chromium.org1862c0c2013-04-18 06:30:481196 if (!command_line->HasSwitch(switches::kResetVariationState)) {
asvitkine@chromium.org9556a892013-06-21 16:53:201197 int value = local_state->GetInteger(prefs::kMetricsLowEntropySource);
1198 // Old versions of the code would generate values in the range of [1, 8192],
1199 // before the range was switched to [0, 8191] and then to [0, 7999]. Map
1200 // 8192 to 0, so that the 0th bucket remains uniform, while re-generating
1201 // the low entropy source for old values in the [8000, 8191] range.
1202 if (value == 8192)
1203 value = 0;
1204 // If the value is outside the [0, kMaxLowEntropySize) range, re-generate
1205 // it below.
1206 if (value >= 0 && value < kMaxLowEntropySize) {
1207 low_entropy_source_ = value;
stevet@chromium.org0c906e92012-10-18 15:24:131208 UMA_HISTOGRAM_BOOLEAN("UMA.GeneratedLowEntropySource", false);
stevet@chromium.orge61003a2012-05-24 17:03:191209 return low_entropy_source_;
asvitkine@chromium.orge63a9ef2012-08-30 15:29:421210 }
stevet@chromium.orge61003a2012-05-24 17:03:191211 }
1212
stevet@chromium.org0c906e92012-10-18 15:24:131213 UMA_HISTOGRAM_BOOLEAN("UMA.GeneratedLowEntropySource", true);
stevet@chromium.orge61003a2012-05-24 17:03:191214 low_entropy_source_ = GenerateLowEntropySource();
asvitkine@chromium.org9d7c4a82013-05-07 12:10:491215 local_state->SetInteger(prefs::kMetricsLowEntropySource, low_entropy_source_);
1216 metrics::CachingPermutedEntropyProvider::ClearCache(local_state);
stevet@chromium.orge61003a2012-05-24 17:03:191217
1218 return low_entropy_source_;
1219}
1220
1221// static
initial.commit09911bf2008-07-26 23:55:291222std::string MetricsService::GenerateClientID() {
marja@chromium.org7e49ad32012-06-14 14:22:071223 return base::GenerateGUID();
initial.commit09911bf2008-07-26 23:55:291224}
1225
initial.commit09911bf2008-07-26 23:55:291226//------------------------------------------------------------------------------
1227// State save methods
1228
1229void MetricsService::ScheduleNextStateSave() {
isherman@chromium.org8454aeb2011-11-19 23:38:201230 state_saver_factory_.InvalidateWeakPtrs();
initial.commit09911bf2008-07-26 23:55:291231
xhwang@chromium.orgb3a25092013-05-28 22:08:161232 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
isherman@chromium.org8454aeb2011-11-19 23:38:201233 base::Bind(&MetricsService::SaveLocalState,
1234 state_saver_factory_.GetWeakPtr()),
tedvessenes@gmail.comfc4252a72012-01-12 21:58:471235 base::TimeDelta::FromMinutes(kSaveStateIntervalMinutes));
initial.commit09911bf2008-07-26 23:55:291236}
1237
1238void MetricsService::SaveLocalState() {
1239 PrefService* pref = g_browser_process->local_state();
1240 if (!pref) {
jar@chromium.orga063c102010-07-22 22:20:191241 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291242 return;
1243 }
1244
1245 RecordCurrentState(pref);
initial.commit09911bf2008-07-26 23:55:291246
tedvessenes@gmail.comfc4252a72012-01-12 21:58:471247 // TODO(jar):110021 Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:291248 ScheduleNextStateSave();
1249}
1250
1251
1252//------------------------------------------------------------------------------
1253// Recording control methods
1254
stuartmorgan@chromium.org410938e02012-10-24 16:33:591255void MetricsService::OpenNewLog() {
1256 DCHECK(!log_manager_.current_log());
initial.commit09911bf2008-07-26 23:55:291257
stuartmorgan@chromium.org29948262012-03-01 12:15:081258 log_manager_.BeginLoggingWithLog(new MetricsLog(client_id_, session_id_),
asvitkine@chromium.org0edf8762013-11-21 18:33:301259 MetricsLog::ONGOING_LOG);
initial.commit09911bf2008-07-26 23:55:291260 if (state_ == INITIALIZED) {
1261 // We only need to schedule that run once.
zelidrag@chromium.org85ed9d42010-06-08 22:37:441262 state_ = INIT_TASK_SCHEDULED;
initial.commit09911bf2008-07-26 23:55:291263
zelidrag@chromium.org85ed9d42010-06-08 22:37:441264 // Schedules a task on the file thread for execution of slower
1265 // initialization steps (such as plugin list generation) necessary
1266 // for sending the initial log. This avoids blocking the main UI
1267 // thread.
joi@chromium.orged10dd12011-12-07 12:03:421268 BrowserThread::PostDelayedTask(
1269 BrowserThread::FILE,
1270 FROM_HERE,
rsesek@chromium.orgd33e7cc2011-09-23 01:43:561271 base::Bind(&MetricsService::InitTaskGetHardwareClass,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401272 self_ptr_factory_.GetWeakPtr(),
xhwang@chromium.orgb3a25092013-05-28 22:08:161273 base::MessageLoop::current()->message_loop_proxy()),
tedvessenes@gmail.com7e560102012-03-08 20:58:421274 base::TimeDelta::FromSeconds(kInitializationDelaySeconds));
initial.commit09911bf2008-07-26 23:55:291275 }
1276}
1277
stuartmorgan@chromium.org410938e02012-10-24 16:33:591278void MetricsService::CloseCurrentLog() {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101279 if (!log_manager_.current_log())
initial.commit09911bf2008-07-26 23:55:291280 return;
1281
jar@google.com68475e602008-08-22 03:21:151282 // TODO(jar): Integrate bounds on log recording more consistently, so that we
1283 // can stop recording logs that are too big much sooner.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101284 if (log_manager_.current_log()->num_events() > kEventLimit) {
dsh@google.com553dba62009-02-24 19:08:231285 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101286 log_manager_.current_log()->num_events());
1287 log_manager_.DiscardCurrentLog();
stuartmorgan@chromium.org410938e02012-10-24 16:33:591288 OpenNewLog(); // Start trivial log to hold our histograms.
jar@google.com68475e602008-08-22 03:21:151289 }
1290
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101291 // Adds to ongoing logs.
1292 log_manager_.current_log()->set_hardware_class(hardware_class_);
jar@chromium.orgaccdfa62011-09-20 01:56:521293
jar@google.com0b33f80b2008-12-17 21:34:361294 // Put incremental data (histogram deltas, and realtime stats deltas) at the
jar@google.com147bbc0b2009-01-06 19:37:401295 // end of all log transmissions (initial log handles this separately).
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:381296 // RecordIncrementalStabilityElements only exists on the derived
1297 // MetricsLog class.
isherman@chromium.org279703f2012-01-20 22:23:261298 MetricsLog* current_log =
1299 static_cast<MetricsLog*>(log_manager_.current_log());
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:381300 DCHECK(current_log);
bengr@chromium.org60677562013-11-17 15:52:551301 std::vector<chrome_variations::ActiveGroupId> synthetic_trials;
1302 GetCurrentSyntheticFieldTrials(&synthetic_trials);
asvitkine@chromium.org0edf8762013-11-21 18:33:301303 current_log->RecordEnvironment(plugins_, google_update_metrics_,
1304 synthetic_trials);
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361305 PrefService* pref = g_browser_process->local_state();
mpearson@chromium.org076961c2014-03-12 22:23:561306 base::TimeDelta incremental_uptime;
1307 base::TimeDelta uptime;
1308 GetUptimes(pref, &incremental_uptime, &uptime);
1309 current_log->RecordStabilityMetrics(incremental_uptime, uptime,
asvitkine@chromium.org0edf8762013-11-21 18:33:301310 MetricsLog::ONGOING_LOG);
bengr@chromium.org60677562013-11-17 15:52:551311
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:381312 RecordCurrentHistograms();
initial.commit09911bf2008-07-26 23:55:291313
stuartmorgan@chromium.org29948262012-03-01 12:15:081314 log_manager_.FinishCurrentLog();
initial.commit09911bf2008-07-26 23:55:291315}
1316
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101317void MetricsService::PushPendingLogsToPersistentStorage() {
asvitkine@chromium.org80a8f312013-12-16 18:00:301318 if (state_ < SENDING_INITIAL_STABILITY_LOG)
avi@google.com28ab7f92009-01-06 21:39:041319 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:291320
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101321 if (log_manager_.has_staged_log()) {
stuartmorgan@chromium.org7d41ae6d2012-06-26 08:53:031322 // We may race here, and send second copy of the log later.
isherman@chromium.orgdc61fe92012-06-12 00:13:501323 MetricsLogManager::StoreType store_type;
isherman@chromium.orge3eb0c42013-04-18 06:18:581324 if (current_fetch_.get())
isherman@chromium.orgdc61fe92012-06-12 00:13:501325 store_type = MetricsLogManager::PROVISIONAL_STORE;
1326 else
1327 store_type = MetricsLogManager::NORMAL_STORE;
stuartmorgan@chromium.orge7508d82012-05-03 15:59:531328 log_manager_.StoreStagedLogAsUnsent(store_type);
initial.commit09911bf2008-07-26 23:55:291329 }
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101330 DCHECK(!log_manager_.has_staged_log());
stuartmorgan@chromium.org410938e02012-10-24 16:33:591331 CloseCurrentLog();
asvitkine@chromium.org80a8f312013-12-16 18:00:301332 log_manager_.PersistUnsentLogs();
stuartmorgan@chromium.org7d41ae6d2012-06-26 08:53:031333
1334 // If there was a staged and/or current log, then there is now at least one
1335 // log waiting to be uploaded.
1336 if (log_manager_.has_unsent_logs())
1337 state_ = SENDING_OLD_LOGS;
initial.commit09911bf2008-07-26 23:55:291338}
1339
1340//------------------------------------------------------------------------------
1341// Transmission of logs methods
1342
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161343void MetricsService::StartSchedulerIfNecessary() {
stuartmorgan@chromium.org410938e02012-10-24 16:33:591344 // Never schedule cutting or uploading of logs in test mode.
1345 if (test_mode_active_)
1346 return;
1347
1348 // Even if reporting is disabled, the scheduler is needed to trigger the
1349 // creation of the initial log, which must be done in order for any logs to be
1350 // persisted on shutdown or backgrounding.
asvitkine@chromium.org80a8f312013-12-16 18:00:301351 if (recording_active() &&
1352 (reporting_active() || state_ < SENDING_INITIAL_STABILITY_LOG)) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161353 scheduler_->Start();
asvitkine@chromium.org80a8f312013-12-16 18:00:301354 }
initial.commit09911bf2008-07-26 23:55:291355}
1356
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161357void MetricsService::StartScheduledUpload() {
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471358 // If we're getting no notifications, then the log won't have much in it, and
1359 // it's possible the computer is about to go to sleep, so don't upload and
1360 // stop the scheduler.
stuartmorgan@chromium.org410938e02012-10-24 16:33:591361 // If recording has been turned off, the scheduler doesn't need to run.
1362 // If reporting is off, proceed if the initial log hasn't been created, since
1363 // that has to happen in order for logs to be cut and stored when persisting.
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471364 // TODO(stuartmorgan): Call Stop() on the schedule when reporting and/or
1365 // recording are turned off instead of letting it fire and then aborting.
1366 if (idle_since_last_transmission_ ||
stuartmorgan@chromium.org410938e02012-10-24 16:33:591367 !recording_active() ||
asvitkine@chromium.org80a8f312013-12-16 18:00:301368 (!reporting_active() && state_ >= SENDING_INITIAL_STABILITY_LOG)) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161369 scheduler_->Stop();
1370 scheduler_->UploadCancelled();
1371 return;
1372 }
1373
stuartmorgan@chromium.orgc15faf372012-07-11 06:01:341374 // If the callback was to upload an old log, but there no longer is one,
1375 // just report success back to the scheduler to begin the ongoing log
1376 // callbacks.
1377 // TODO(stuartmorgan): Consider removing the distinction between
1378 // SENDING_OLD_LOGS and SENDING_CURRENT_LOGS to simplify the state machine
1379 // now that the log upload flow is the same for both modes.
1380 if (state_ == SENDING_OLD_LOGS && !log_manager_.has_unsent_logs()) {
1381 state_ = SENDING_CURRENT_LOGS;
1382 scheduler_->UploadFinished(true /* healthy */, false /* no unsent logs */);
1383 return;
1384 }
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471385 // If there are unsent logs, send the next one. If not, start the asynchronous
1386 // process of finalizing the current log for upload.
1387 if (state_ == SENDING_OLD_LOGS) {
1388 DCHECK(log_manager_.has_unsent_logs());
1389 log_manager_.StageNextLogForUpload();
1390 SendStagedLog();
1391 } else {
1392 StartFinalLogInfoCollection();
1393 }
stuartmorgan@chromium.org29948262012-03-01 12:15:081394}
1395
1396void MetricsService::StartFinalLogInfoCollection() {
1397 // Begin the multi-step process of collecting memory usage histograms:
1398 // First spawn a task to collect the memory details; when that task is
1399 // finished, it will call OnMemoryDetailCollectionDone. That will in turn
1400 // call HistogramSynchronization to collect histograms from all renderers and
1401 // then call OnHistogramSynchronizationDone to continue processing.
isherman@chromium.orgd119f222012-06-08 02:33:271402 DCHECK(!waiting_for_asynchronous_reporting_step_);
1403 waiting_for_asynchronous_reporting_step_ = true;
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161404
dcheng@chromium.org2226c222011-11-22 00:08:401405 base::Closure callback =
1406 base::Bind(&MetricsService::OnMemoryDetailCollectionDone,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401407 self_ptr_factory_.GetWeakPtr());
sail@chromium.org84c988a2011-04-19 17:56:331408
dcheng@chromium.org2226c222011-11-22 00:08:401409 scoped_refptr<MetricsMemoryDetails> details(
1410 new MetricsMemoryDetails(callback));
jamescook@chromium.org4306df72012-04-20 18:58:571411 details->StartFetch(MemoryDetails::UPDATE_USER_METRICS);
sail@chromium.org84c988a2011-04-19 17:56:331412
1413 // Collect WebCore cache information to put into a histogram.
ananta@chromium.orgf3b1a082011-11-18 00:34:301414 for (content::RenderProcessHost::iterator i(
1415 content::RenderProcessHost::AllHostsIterator());
sail@chromium.org84c988a2011-04-19 17:56:331416 !i.IsAtEnd(); i.Advance())
ananta@chromium.org2ccf45c2011-08-19 23:35:501417 i.GetCurrentValue()->Send(new ChromeViewMsg_GetCacheResourceStats());
sail@chromium.org84c988a2011-04-19 17:56:331418}
1419
1420void MetricsService::OnMemoryDetailCollectionDone() {
jar@chromium.orgc9a3ef82009-05-28 22:02:461421 DCHECK(IsSingleThreaded());
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161422 // This function should only be called as the callback from an ansynchronous
1423 // step.
isherman@chromium.orgd119f222012-06-08 02:33:271424 DCHECK(waiting_for_asynchronous_reporting_step_);
jar@chromium.orgc9a3ef82009-05-28 22:02:461425
jar@chromium.orgc9a3ef82009-05-28 22:02:461426 // Create a callback_task for OnHistogramSynchronizationDone.
dcheng@chromium.org2226c222011-11-22 00:08:401427 base::Closure callback = base::Bind(
1428 &MetricsService::OnHistogramSynchronizationDone,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401429 self_ptr_factory_.GetWeakPtr());
jar@chromium.orgc9a3ef82009-05-28 22:02:461430
vitalybuka@chromium.orga3079832013-10-24 20:29:361431 base::TimeDelta timeout =
1432 base::TimeDelta::FromMilliseconds(kMaxHistogramGatheringWaitDuration);
1433
1434 DCHECK_EQ(num_async_histogram_fetches_in_progress_, 0);
1435
1436#if defined(OS_ANDROID)
1437 // Android has no service process.
1438 num_async_histogram_fetches_in_progress_ = 1;
1439#else // OS_ANDROID
1440 num_async_histogram_fetches_in_progress_ = 2;
1441 // Run requests to service and content in parallel.
1442 if (!ServiceProcessControl::GetInstance()->GetHistograms(callback, timeout)) {
1443 // Assume |num_async_histogram_fetches_in_progress_| is not changed by
1444 // |GetHistograms()|.
1445 DCHECK_EQ(num_async_histogram_fetches_in_progress_, 2);
1446 // Assign |num_async_histogram_fetches_in_progress_| above and decrement it
1447 // here to make code work even if |GetHistograms()| fired |callback|.
1448 --num_async_histogram_fetches_in_progress_;
1449 }
1450#endif // OS_ANDROID
1451
jar@chromium.orgc9a3ef82009-05-28 22:02:461452 // Set up the callback to task to call after we receive histograms from all
rtenneti@google.com83ab4a282012-07-12 18:19:451453 // child processes. Wait time specifies how long to wait before absolutely
jar@chromium.orgc9a3ef82009-05-28 22:02:461454 // calling us back on the task.
vitalybuka@chromium.orga3079832013-10-24 20:29:361455 content::FetchHistogramsAsynchronously(base::MessageLoop::current(), callback,
1456 timeout);
jar@chromium.orgc9a3ef82009-05-28 22:02:461457}
1458
1459void MetricsService::OnHistogramSynchronizationDone() {
initial.commit09911bf2008-07-26 23:55:291460 DCHECK(IsSingleThreaded());
stuartmorgan@chromium.org29948262012-03-01 12:15:081461 // This function should only be called as the callback from an ansynchronous
1462 // step.
isherman@chromium.orgd119f222012-06-08 02:33:271463 DCHECK(waiting_for_asynchronous_reporting_step_);
vitalybuka@chromium.orga3079832013-10-24 20:29:361464 DCHECK_GT(num_async_histogram_fetches_in_progress_, 0);
1465
1466 // Check if all expected requests finished.
1467 if (--num_async_histogram_fetches_in_progress_ > 0)
1468 return;
initial.commit09911bf2008-07-26 23:55:291469
isherman@chromium.orgd119f222012-06-08 02:33:271470 waiting_for_asynchronous_reporting_step_ = false;
stuartmorgan@chromium.org29948262012-03-01 12:15:081471 OnFinalLogInfoCollectionDone();
1472}
1473
1474void MetricsService::OnFinalLogInfoCollectionDone() {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161475 // If somehow there is a fetch in progress, we return and hope things work
1476 // out. The scheduler isn't informed since if this happens, the scheduler
1477 // will get a response from the upload.
isherman@chromium.orge3eb0c42013-04-18 06:18:581478 DCHECK(!current_fetch_.get());
1479 if (current_fetch_.get())
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161480 return;
1481
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471482 // Abort if metrics were turned off during the final info gathering.
stuartmorgan@chromium.org410938e02012-10-24 16:33:591483 if (!recording_active()) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161484 scheduler_->Stop();
1485 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:071486 return;
1487 }
1488
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471489 StageNewLog();
stuartmorgan@chromium.org410938e02012-10-24 16:33:591490
1491 // If logs shouldn't be uploaded, stop here. It's important that this check
1492 // be after StageNewLog(), otherwise the previous logs will never be loaded,
1493 // and thus the open log won't be persisted.
1494 // TODO(stuartmorgan): This is unnecessarily complicated; restructure loading
1495 // of previous logs to not require running part of the upload logic.
1496 // http://crbug.com/157337
1497 if (!reporting_active()) {
1498 scheduler_->Stop();
1499 scheduler_->UploadCancelled();
1500 return;
1501 }
1502
stuartmorgan@chromium.org29948262012-03-01 12:15:081503 SendStagedLog();
1504}
1505
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471506void MetricsService::StageNewLog() {
stuartmorgan@chromium.org29948262012-03-01 12:15:081507 if (log_manager_.has_staged_log())
1508 return;
1509
1510 switch (state_) {
1511 case INITIALIZED:
1512 case INIT_TASK_SCHEDULED: // We should be further along by now.
isherman@chromium.orgdc61fe92012-06-12 00:13:501513 NOTREACHED();
stuartmorgan@chromium.org29948262012-03-01 12:15:081514 return;
1515
1516 case INIT_TASK_DONE:
asvitkine@chromium.org80a8f312013-12-16 18:00:301517 if (has_initial_stability_log_) {
1518 // There's an initial stability log, ready to send.
1519 log_manager_.StageNextLogForUpload();
1520 has_initial_stability_log_ = false;
asvitkine@chromium.orgf61eb842014-01-22 10:59:131521 // Note: No need to call LoadPersistedUnsentLogs() here because unsent
1522 // logs have already been loaded by PrepareInitialStabilityLog().
asvitkine@chromium.org80a8f312013-12-16 18:00:301523 state_ = SENDING_INITIAL_STABILITY_LOG;
1524 } else {
1525 // TODO(asvitkine): When the field trial is removed, the |log_type|
1526 // arg should be removed and PrepareInitialMetricsLog() should always
1527 // use ONGOING_LOG. Use INITIAL_LOG only to match to the old behavior
1528 // when the field trial is off.
1529 MetricsLog::LogType log_type = SendSeparateInitialStabilityLog() ?
1530 MetricsLog::ONGOING_LOG : MetricsLog::INITIAL_LOG;
1531 PrepareInitialMetricsLog(log_type);
asvitkine@chromium.orgf61eb842014-01-22 10:59:131532 // Load unsent logs (if any) from local state.
1533 log_manager_.LoadPersistedUnsentLogs();
asvitkine@chromium.org80a8f312013-12-16 18:00:301534 state_ = SENDING_INITIAL_METRICS_LOG;
1535 }
stuartmorgan@chromium.org29948262012-03-01 12:15:081536 break;
1537
1538 case SENDING_OLD_LOGS:
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471539 NOTREACHED(); // Shouldn't be staging a new log during old log sending.
1540 return;
stuartmorgan@chromium.org29948262012-03-01 12:15:081541
1542 case SENDING_CURRENT_LOGS:
stuartmorgan@chromium.org410938e02012-10-24 16:33:591543 CloseCurrentLog();
1544 OpenNewLog();
stuartmorgan@chromium.org29948262012-03-01 12:15:081545 log_manager_.StageNextLogForUpload();
1546 break;
1547
1548 default:
1549 NOTREACHED();
1550 return;
1551 }
1552
1553 DCHECK(log_manager_.has_staged_log());
1554}
1555
asvitkine@chromium.org80a8f312013-12-16 18:00:301556void MetricsService::PrepareInitialStabilityLog() {
1557 DCHECK_EQ(INITIALIZED, state_);
1558 PrefService* pref = g_browser_process->local_state();
1559 DCHECK_NE(0, pref->GetInteger(prefs::kStabilityCrashCount));
stuartmorgan@chromium.org29948262012-03-01 12:15:081560
asvitkine@chromium.org80a8f312013-12-16 18:00:301561 scoped_ptr<MetricsLog> initial_stability_log(
1562 new MetricsLog(client_id_, session_id_));
1563 if (!initial_stability_log->LoadSavedEnvironmentFromPrefs())
1564 return;
mpearson@chromium.org076961c2014-03-12 22:23:561565 initial_stability_log->RecordStabilityMetrics(
1566 base::TimeDelta(), base::TimeDelta(), MetricsLog::INITIAL_LOG);
asvitkine@chromium.org80a8f312013-12-16 18:00:301567 log_manager_.LoadPersistedUnsentLogs();
1568
1569 log_manager_.PauseCurrentLog();
1570 log_manager_.BeginLoggingWithLog(initial_stability_log.release(),
1571 MetricsLog::INITIAL_LOG);
kkimlabs@chromium.orgc778687a2014-02-11 14:46:451572#if defined(OS_ANDROID)
1573 ConvertAndroidStabilityPrefsToHistograms(pref);
1574 RecordCurrentStabilityHistograms();
1575#endif // defined(OS_ANDROID)
asvitkine@chromium.org80a8f312013-12-16 18:00:301576 log_manager_.FinishCurrentLog();
1577 log_manager_.ResumePausedLog();
1578
1579 // Store unsent logs, including the stability log that was just saved, so
1580 // that they're not lost in case of a crash before upload time.
1581 log_manager_.PersistUnsentLogs();
1582
1583 has_initial_stability_log_ = true;
1584}
1585
1586void MetricsService::PrepareInitialMetricsLog(MetricsLog::LogType log_type) {
1587 DCHECK(state_ == INIT_TASK_DONE || state_ == SENDING_INITIAL_STABILITY_LOG);
1588 initial_metrics_log_->set_hardware_class(hardware_class_);
asvitkine@chromium.org0edf8762013-11-21 18:33:301589
bengr@chromium.org60677562013-11-17 15:52:551590 std::vector<chrome_variations::ActiveGroupId> synthetic_trials;
1591 GetCurrentSyntheticFieldTrials(&synthetic_trials);
asvitkine@chromium.org80a8f312013-12-16 18:00:301592 initial_metrics_log_->RecordEnvironment(plugins_, google_update_metrics_,
1593 synthetic_trials);
asvitkine@chromium.org0edf8762013-11-21 18:33:301594 PrefService* pref = g_browser_process->local_state();
mpearson@chromium.org076961c2014-03-12 22:23:561595 base::TimeDelta incremental_uptime;
1596 base::TimeDelta uptime;
1597 GetUptimes(pref, &incremental_uptime, &uptime);
1598 initial_metrics_log_->RecordStabilityMetrics(incremental_uptime, uptime,
asvitkine@chromium.org80a8f312013-12-16 18:00:301599 log_type);
stuartmorgan@chromium.org29948262012-03-01 12:15:081600
1601 // Histograms only get written to the current log, so make the new log current
1602 // before writing them.
1603 log_manager_.PauseCurrentLog();
asvitkine@chromium.org80a8f312013-12-16 18:00:301604 log_manager_.BeginLoggingWithLog(initial_metrics_log_.release(), log_type);
kkimlabs@chromium.orgc778687a2014-02-11 14:46:451605#if defined(OS_ANDROID)
1606 ConvertAndroidStabilityPrefsToHistograms(pref);
1607#endif // defined(OS_ANDROID)
stuartmorgan@chromium.org29948262012-03-01 12:15:081608 RecordCurrentHistograms();
1609 log_manager_.FinishCurrentLog();
1610 log_manager_.ResumePausedLog();
1611
1612 DCHECK(!log_manager_.has_staged_log());
1613 log_manager_.StageNextLogForUpload();
1614}
1615
stuartmorgan@chromium.org29948262012-03-01 12:15:081616void MetricsService::SendStagedLog() {
1617 DCHECK(log_manager_.has_staged_log());
1618
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101619 PrepareFetchWithStagedLog();
petersont@google.comd01b8732008-10-16 02:18:071620
isherman@chromium.orge3eb0c42013-04-18 06:18:581621 bool upload_created = (current_fetch_.get() != NULL);
isherman@chromium.orgd6bebb92012-06-13 23:14:551622 UMA_HISTOGRAM_BOOLEAN("UMA.UploadCreation", upload_created);
1623 if (!upload_created) {
petersont@google.comd01b8732008-10-16 02:18:071624 // Compression failed, and log discarded :-/.
isherman@chromium.orgdc61fe92012-06-12 00:13:501625 // Skip this upload and hope things work out next time.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101626 log_manager_.DiscardStagedLog();
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161627 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:071628 return;
1629 }
1630
isherman@chromium.orgd119f222012-06-08 02:33:271631 DCHECK(!waiting_for_asynchronous_reporting_step_);
isherman@chromium.orgd119f222012-06-08 02:33:271632 waiting_for_asynchronous_reporting_step_ = true;
isherman@chromium.orgdc61fe92012-06-12 00:13:501633
isherman@chromium.orge3eb0c42013-04-18 06:18:581634 current_fetch_->Start();
petersont@google.comd01b8732008-10-16 02:18:071635
1636 HandleIdleSinceLastTransmission(true);
1637}
1638
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101639void MetricsService::PrepareFetchWithStagedLog() {
isherman@chromium.orgdc61fe92012-06-12 00:13:501640 DCHECK(log_manager_.has_staged_log());
pkasting@chromium.orgcac78842008-11-27 01:02:201641
isherman@chromium.orgfe58acc22012-02-29 01:29:581642 // Prepare the protobuf version.
isherman@chromium.orge3eb0c42013-04-18 06:18:581643 DCHECK(!current_fetch_.get());
isherman@chromium.org5f3e1642013-05-05 03:37:341644 if (log_manager_.has_staged_log()) {
isherman@chromium.orge3eb0c42013-04-18 06:18:581645 current_fetch_.reset(net::URLFetcher::Create(
isherman@chromium.org5f3e1642013-05-05 03:37:341646 GURL(kServerUrl), net::URLFetcher::POST, this));
isherman@chromium.orge3eb0c42013-04-18 06:18:581647 current_fetch_->SetRequestContext(
isherman@chromium.orgfe58acc22012-02-29 01:29:581648 g_browser_process->system_request_context());
asharif@chromium.org537c638d2013-07-04 00:49:191649
asharif@chromium.org8df71322013-09-13 18:40:001650 std::string log_text = log_manager_.staged_log_text();
1651 std::string compressed_log_text;
1652 bool compression_successful = chrome::GzipCompress(log_text,
1653 &compressed_log_text);
1654 DCHECK(compression_successful);
1655 if (compression_successful) {
1656 current_fetch_->SetUploadData(kMimeType, compressed_log_text);
1657 // Tell the server that we're uploading gzipped protobufs.
1658 current_fetch_->SetExtraRequestHeaders("content-encoding: gzip");
asvitkine@chromium.orgcfee9aa52013-10-19 17:53:051659 const std::string hash =
1660 base::HexEncode(log_manager_.staged_log_hash().data(),
1661 log_manager_.staged_log_hash().size());
1662 DCHECK(!hash.empty());
1663 current_fetch_->AddExtraRequestHeader("X-Chrome-UMA-Log-SHA1: " + hash);
asharif@chromium.org8df71322013-09-13 18:40:001664 UMA_HISTOGRAM_PERCENTAGE(
1665 "UMA.ProtoCompressionRatio",
1666 100 * compressed_log_text.size() / log_text.size());
1667 UMA_HISTOGRAM_CUSTOM_COUNTS(
1668 "UMA.ProtoGzippedKBSaved",
1669 (log_text.size() - compressed_log_text.size()) / 1024,
1670 1, 2000, 50);
asharif@chromium.org537c638d2013-07-04 00:49:191671 }
asharif@chromium.org537c638d2013-07-04 00:49:191672
isherman@chromium.orgfe58acc22012-02-29 01:29:581673 // We already drop cookies server-side, but we might as well strip them out
1674 // client-side as well.
isherman@chromium.orge3eb0c42013-04-18 06:18:581675 current_fetch_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES |
1676 net::LOAD_DO_NOT_SEND_COOKIES);
isherman@chromium.orgfe58acc22012-02-29 01:29:581677 }
initial.commit09911bf2008-07-26 23:55:291678}
1679
akalin@chromium.org10c2d692012-05-11 05:32:231680void MetricsService::OnURLFetchComplete(const net::URLFetcher* source) {
isherman@chromium.orgd119f222012-06-08 02:33:271681 DCHECK(waiting_for_asynchronous_reporting_step_);
isherman@chromium.orgfe58acc22012-02-29 01:29:581682
1683 // We're not allowed to re-use the existing |URLFetcher|s, so free them here.
isherman@chromium.orge3eb0c42013-04-18 06:18:581684 // Note however that |source| is aliased to the fetcher, so we should be
isherman@chromium.org4266def22012-05-17 01:02:401685 // careful not to delete it too early.
isherman@chromium.orge3eb0c42013-04-18 06:18:581686 DCHECK_EQ(current_fetch_.get(), source);
1687 scoped_ptr<net::URLFetcher> s(current_fetch_.Pass());
isherman@chromium.orgfe58acc22012-02-29 01:29:581688
isherman@chromium.orgdc61fe92012-06-12 00:13:501689 int response_code = source->GetResponseCode();
isherman@chromium.orgfe58acc22012-02-29 01:29:581690
isherman@chromium.orgdc61fe92012-06-12 00:13:501691 // Log a histogram to track response success vs. failure rates.
isherman@chromium.orge3eb0c42013-04-18 06:18:581692 UMA_HISTOGRAM_ENUMERATION("UMA.UploadResponseStatus.Protobuf",
1693 ResponseCodeToStatus(response_code),
1694 NUM_RESPONSE_STATUSES);
isherman@chromium.orgfe58acc22012-02-29 01:29:581695
stuartmorgan@chromium.orge7508d82012-05-03 15:59:531696 // If the upload was provisionally stored, drop it now that the upload is
1697 // known to have gone through.
1698 log_manager_.DiscardLastProvisionalStore();
initial.commit09911bf2008-07-26 23:55:291699
isherman@chromium.orgdc61fe92012-06-12 00:13:501700 bool upload_succeeded = response_code == 200;
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161701
jar@chromium.org0eb34fee2009-01-21 08:04:381702 // Provide boolean for error recovery (allow us to ignore response_code).
paul@chromium.orgdc6f4962009-02-13 01:25:501703 bool discard_log = false;
isherman@chromium.org5f3e1642013-05-05 03:37:341704 const size_t log_size = log_manager_.staged_log_text().length();
isherman@chromium.orgdc61fe92012-06-12 00:13:501705 if (!upload_succeeded && log_size > kUploadLogAvoidRetransmitSize) {
1706 UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
1707 static_cast<int>(log_size));
jar@chromium.org0eb34fee2009-01-21 08:04:381708 discard_log = true;
isherman@chromium.orgdc61fe92012-06-12 00:13:501709 } else if (response_code == 400) {
jar@chromium.org0eb34fee2009-01-21 08:04:381710 // Bad syntax. Retransmission won't work.
jar@chromium.org0eb34fee2009-01-21 08:04:381711 discard_log = true;
jar@google.com68475e602008-08-22 03:21:151712 }
1713
isherman@chromium.orge3eb0c42013-04-18 06:18:581714 if (upload_succeeded || discard_log)
isherman@chromium.org5f3e1642013-05-05 03:37:341715 log_manager_.DiscardStagedLog();
isherman@chromium.orgdc61fe92012-06-12 00:13:501716
1717 waiting_for_asynchronous_reporting_step_ = false;
1718
1719 if (!log_manager_.has_staged_log()) {
initial.commit09911bf2008-07-26 23:55:291720 switch (state_) {
asvitkine@chromium.org80a8f312013-12-16 18:00:301721 case SENDING_INITIAL_STABILITY_LOG:
1722 // Store the updated list to disk now that the removed log is uploaded.
1723 log_manager_.PersistUnsentLogs();
1724 PrepareInitialMetricsLog(MetricsLog::ONGOING_LOG);
1725 SendStagedLog();
1726 state_ = SENDING_INITIAL_METRICS_LOG;
1727 break;
1728
1729 case SENDING_INITIAL_METRICS_LOG:
1730 // The initial metrics log never gets persisted to local state, so it's
1731 // not necessary to call log_manager_.PersistUnsentLogs() here.
1732 // TODO(asvitkine): It should be persisted like the initial stability
1733 // log and old unsent logs. http://crbug.com/328417
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471734 state_ = log_manager_.has_unsent_logs() ? SENDING_OLD_LOGS
1735 : SENDING_CURRENT_LOGS;
initial.commit09911bf2008-07-26 23:55:291736 break;
1737
initial.commit09911bf2008-07-26 23:55:291738 case SENDING_OLD_LOGS:
stuartmorgan@chromium.orgd53e2232011-06-30 15:54:571739 // Store the updated list to disk now that the removed log is uploaded.
asvitkine@chromium.org80a8f312013-12-16 18:00:301740 log_manager_.PersistUnsentLogs();
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471741 if (!log_manager_.has_unsent_logs())
1742 state_ = SENDING_CURRENT_LOGS;
initial.commit09911bf2008-07-26 23:55:291743 break;
1744
1745 case SENDING_CURRENT_LOGS:
1746 break;
1747
1748 default:
jar@chromium.orga063c102010-07-22 22:20:191749 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291750 break;
1751 }
petersont@google.comd01b8732008-10-16 02:18:071752
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101753 if (log_manager_.has_unsent_logs())
isherman@chromium.orged0fd002012-04-25 23:10:341754 DCHECK_LT(state_, SENDING_CURRENT_LOGS);
initial.commit09911bf2008-07-26 23:55:291755 }
petersont@google.com252873ef2008-08-04 21:59:451756
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161757 // Error 400 indicates a problem with the log, not with the server, so
1758 // don't consider that a sign that the server is in trouble.
isherman@chromium.orgdc61fe92012-06-12 00:13:501759 bool server_is_healthy = upload_succeeded || response_code == 400;
asvitkine@chromium.org80a8f312013-12-16 18:00:301760 // Don't notify the scheduler that the upload is finished if we've only sent
1761 // the initial stability log, but not yet the initial metrics log (treat the
1762 // two as a single unit of work as far as the scheduler is concerned).
1763 if (state_ != SENDING_INITIAL_METRICS_LOG) {
1764 scheduler_->UploadFinished(server_is_healthy,
1765 log_manager_.has_unsent_logs());
1766 }
rtenneti@chromium.orgd67d1052011-06-09 05:11:411767
1768 // Collect network stats if UMA upload succeeded.
isherman@chromium.orgb8ddb052012-04-19 02:36:061769 IOThread* io_thread = g_browser_process->io_thread();
1770 if (server_is_healthy && io_thread) {
1771 chrome_browser_net::CollectNetworkStats(network_stats_server_, io_thread);
simonjam@chromium.orgadbb3762012-03-09 22:20:081772 chrome_browser_net::CollectPipeliningCapabilityStatsOnUIThread(
isherman@chromium.orgb8ddb052012-04-19 02:36:061773 http_pipelining_test_server_, io_thread);
simonjam@chromium.orgaa312812013-04-30 19:46:051774#if defined(OS_WIN)
1775 chrome::CollectTimeTicksStats();
1776#endif
simonjam@chromium.orgadbb3762012-03-09 22:20:081777 }
initial.commit09911bf2008-07-26 23:55:291778}
1779
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511780void MetricsService::IncrementPrefValue(const char* path) {
cpu@google.come73c01972008-08-13 00:18:241781 PrefService* pref = g_browser_process->local_state();
1782 DCHECK(pref);
1783 int value = pref->GetInteger(path);
1784 pref->SetInteger(path, value + 1);
1785}
1786
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511787void MetricsService::IncrementLongPrefsValue(const char* path) {
robertshield@google.com0bb1a622009-03-04 03:22:321788 PrefService* pref = g_browser_process->local_state();
1789 DCHECK(pref);
1790 int64 value = pref->GetInt64(path);
jar@chromium.orgb42c5e42010-06-03 20:43:251791 pref->SetInt64(path, value + 1);
robertshield@google.com0bb1a622009-03-04 03:22:321792}
1793
rlp@chromium.org752a5262013-06-23 14:53:421794void MetricsService::LogLoadStarted(content::WebContents* web_contents) {
ben@chromium.orge6e30ac2014-01-13 21:24:391795 content::RecordAction(base::UserMetricsAction("PageLoad"));
jar@chromium.orgdd8d12a2011-09-02 02:10:151796 HISTOGRAM_ENUMERATION("Chrome.UmaPageloadCounter", 1, 2);
cpu@google.come73c01972008-08-13 00:18:241797 IncrementPrefValue(prefs::kStabilityPageLoadCount);
robertshield@google.com0bb1a622009-03-04 03:22:321798 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
jar@google.com0b33f80b2008-12-17 21:34:361799 // We need to save the prefs, as page load count is a critical stat, and it
1800 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291801}
1802
jar@chromium.orgc3721482012-03-23 16:21:481803void MetricsService::LogRendererCrash(content::RenderProcessHost* host,
1804 base::TerminationStatus status,
jam@chromium.orgf1675202012-07-09 15:18:001805 int exit_code) {
aa@chromium.org6f371442011-11-09 06:45:461806 bool was_extension_process =
jamescook@chromium.orgfafdc842014-01-17 18:09:081807 extensions::ProcessMap::Get(host->GetBrowserContext())
1808 ->Contains(host->GetID());
jar@chromium.orgc3721482012-03-23 16:21:481809 if (status == base::TERMINATION_STATUS_PROCESS_CRASHED ||
1810 status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
eroman@chromium.orgd7c1fa62012-06-15 23:35:301811 if (was_extension_process) {
jochen@chromium.org718eab62011-10-05 21:16:521812 IncrementPrefValue(prefs::kStabilityExtensionRendererCrashCount);
eroman@chromium.orgd7c1fa62012-06-15 23:35:301813
eroman@chromium.org1026afd2013-03-20 14:28:541814 UMA_HISTOGRAM_SPARSE_SLOWLY("CrashExitCodes.Extension",
1815 MapCrashExitCodeForHistogram(exit_code));
eroman@chromium.orgd7c1fa62012-06-15 23:35:301816 } else {
jochen@chromium.org718eab62011-10-05 21:16:521817 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291818
eroman@chromium.org1026afd2013-03-20 14:28:541819 UMA_HISTOGRAM_SPARSE_SLOWLY("CrashExitCodes.Renderer",
1820 MapCrashExitCodeForHistogram(exit_code));
eroman@chromium.orgd7c1fa62012-06-15 23:35:301821 }
1822
jochen@chromium.org718eab62011-10-05 21:16:521823 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildCrashes",
1824 was_extension_process ? 2 : 1);
jar@chromium.orgc3721482012-03-23 16:21:481825 } else if (status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED) {
jochen@chromium.org718eab62011-10-05 21:16:521826 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildKills",
1827 was_extension_process ? 2 : 1);
jam@chromium.orgf1675202012-07-09 15:18:001828 } else if (status == base::TERMINATION_STATUS_STILL_RUNNING) {
1829 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.DisconnectedAlive",
jochen@chromium.org718eab62011-10-05 21:16:521830 was_extension_process ? 2 : 1);
jochen@chromium.org718eab62011-10-05 21:16:521831 }
asvitkine@chromium.org80a8f312013-12-16 18:00:301832}
asargent@chromium.org1f085622009-12-04 05:33:451833
initial.commit09911bf2008-07-26 23:55:291834void MetricsService::LogRendererHang() {
cpu@google.come73c01972008-08-13 00:18:241835 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291836}
1837
jar@chromium.orgc0c55e92011-09-10 18:47:301838bool MetricsService::UmaMetricsProperlyShutdown() {
1839 CHECK(clean_shutdown_status_ == CLEANLY_SHUTDOWN ||
1840 clean_shutdown_status_ == NEED_TO_SHUTDOWN);
1841 return clean_shutdown_status_ == CLEANLY_SHUTDOWN;
1842}
1843
bengr@chromium.org60677562013-11-17 15:52:551844void MetricsService::RegisterSyntheticFieldTrial(
1845 const SyntheticTrialGroup& trial) {
1846 for (size_t i = 0; i < synthetic_trial_groups_.size(); ++i) {
1847 if (synthetic_trial_groups_[i].id.name == trial.id.name) {
1848 if (synthetic_trial_groups_[i].id.group != trial.id.group) {
1849 synthetic_trial_groups_[i].id.group = trial.id.group;
asvitkine@chromium.org7a5c07812014-02-26 11:45:411850 synthetic_trial_groups_[i].start_time = base::TimeTicks::Now();
bengr@chromium.org60677562013-11-17 15:52:551851 }
1852 return;
1853 }
1854 }
1855
asvitkine@chromium.org7a5c07812014-02-26 11:45:411856 SyntheticTrialGroup trial_group = trial;
1857 trial_group.start_time = base::TimeTicks::Now();
bengr@chromium.org60677562013-11-17 15:52:551858 synthetic_trial_groups_.push_back(trial_group);
1859}
1860
1861void MetricsService::GetCurrentSyntheticFieldTrials(
1862 std::vector<chrome_variations::ActiveGroupId>* synthetic_trials) {
1863 DCHECK(synthetic_trials);
1864 synthetic_trials->clear();
1865 const MetricsLog* current_log =
1866 static_cast<const MetricsLog*>(log_manager_.current_log());
1867 for (size_t i = 0; i < synthetic_trial_groups_.size(); ++i) {
1868 if (synthetic_trial_groups_[i].start_time <= current_log->creation_time())
1869 synthetic_trials->push_back(synthetic_trial_groups_[i].id);
1870 }
1871}
1872
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381873void MetricsService::LogCleanShutdown() {
jar@chromium.orgacd55b32011-09-05 17:35:311874 // Redundant hack to write pref ASAP.
nileshagrawal@chromium.org84c384e2013-03-01 23:20:191875 MarkAppCleanShutdownAndCommit();
1876
jar@chromium.orgc0c55e92011-09-10 18:47:301877 // Redundant setting to assure that we always reset this value at shutdown
1878 // (and that we don't use some alternate path, and not call LogCleanShutdown).
1879 clean_shutdown_status_ = CLEANLY_SHUTDOWN;
jar@chromium.orgacd55b32011-09-05 17:35:311880
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381881 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6a6d0d12013-10-28 15:58:191882 PrefService* pref = g_browser_process->local_state();
1883 pref->SetInteger(prefs::kStabilityExecutionPhase,
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:211884 MetricsService::SHUTDOWN_COMPLETE);
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381885}
1886
petkov@chromium.orgc1834a92011-01-21 18:21:031887#if defined(OS_CHROMEOS)
1888void MetricsService::LogChromeOSCrash(const std::string &crash_type) {
1889 if (crash_type == "user")
1890 IncrementPrefValue(prefs::kStabilityOtherUserCrashCount);
1891 else if (crash_type == "kernel")
1892 IncrementPrefValue(prefs::kStabilityKernelCrashCount);
1893 else if (crash_type == "uncleanshutdown")
1894 IncrementPrefValue(prefs::kStabilitySystemUncleanShutdownCount);
1895 else
1896 NOTREACHED() << "Unexpected Chrome OS crash type " << crash_type;
1897 // Wake up metrics logs sending if necessary now that new
1898 // log data is available.
1899 HandleIdleSinceLastTransmission(false);
1900}
1901#endif // OS_CHROMEOS
1902
brettw@chromium.org650b2d52013-02-10 03:41:451903void MetricsService::LogPluginLoadingError(const base::FilePath& plugin_path) {
jam@chromium.orgd7bd3e52013-07-21 04:29:201904 content::WebPluginInfo plugin;
bauerb@chromium.orgcd937072012-07-02 09:00:291905 bool success =
1906 content::PluginService::GetInstance()->GetPluginInfoByPath(plugin_path,
1907 &plugin);
1908 DCHECK(success);
1909 ChildProcessStats& stats = child_process_stats_buffer_[plugin.name];
1910 // Initialize the type if this entry is new.
1911 if (stats.process_type == content::PROCESS_TYPE_UNKNOWN) {
1912 // The plug-in process might not actually of type PLUGIN (which means
1913 // NPAPI), but we only care that it is *a* plug-in process.
1914 stats.process_type = content::PROCESS_TYPE_PLUGIN;
1915 } else {
1916 DCHECK(IsPluginProcess(stats.process_type));
1917 }
1918 stats.loading_errors++;
1919}
1920
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:401921MetricsService::ChildProcessStats& MetricsService::GetChildProcessStats(
1922 const content::ChildProcessData& data) {
brettw@chromium.org439f1e32013-12-09 20:09:091923 const base::string16& child_name = data.name;
jam@chromium.orgf3b357692013-03-22 05:16:131924 if (!ContainsKey(child_process_stats_buffer_, child_name)) {
1925 child_process_stats_buffer_[child_name] =
1926 ChildProcessStats(data.process_type);
1927 }
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:401928 return child_process_stats_buffer_[child_name];
initial.commit09911bf2008-07-26 23:55:291929}
1930
initial.commit09911bf2008-07-26 23:55:291931void MetricsService::RecordPluginChanges(PrefService* pref) {
battre@chromium.orgf8628c22011-04-05 12:10:181932 ListPrefUpdate update(pref, prefs::kStabilityPluginStats);
avi@chromium.orgcb1078de2013-12-23 20:04:221933 base::ListValue* plugins = update.Get();
initial.commit09911bf2008-07-26 23:55:291934 DCHECK(plugins);
1935
avi@chromium.orgcb1078de2013-12-23 20:04:221936 for (base::ListValue::iterator value_iter = plugins->begin();
initial.commit09911bf2008-07-26 23:55:291937 value_iter != plugins->end(); ++value_iter) {
avi@chromium.orgcb1078de2013-12-23 20:04:221938 if (!(*value_iter)->IsType(base::Value::TYPE_DICTIONARY)) {
jar@chromium.orga063c102010-07-22 22:20:191939 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291940 continue;
1941 }
1942
avi@chromium.orgcb1078de2013-12-23 20:04:221943 base::DictionaryValue* plugin_dict =
1944 static_cast<base::DictionaryValue*>(*value_iter);
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511945 std::string plugin_name;
nsylvain@chromium.org8e50b602009-03-03 22:59:431946 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
nsylvain@chromium.org6470ee8f2009-03-03 20:46:401947 if (plugin_name.empty()) {
jar@chromium.orga063c102010-07-22 22:20:191948 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291949 continue;
1950 }
1951
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511952 // TODO(viettrungluu): remove conversions
avi@chromium.org6778fed2013-12-24 20:09:371953 base::string16 name16 = base::UTF8ToUTF16(plugin_name);
evan@chromium.org68b9e72b2011-08-05 23:08:221954 if (child_process_stats_buffer_.find(name16) ==
1955 child_process_stats_buffer_.end()) {
initial.commit09911bf2008-07-26 23:55:291956 continue;
evan@chromium.org68b9e72b2011-08-05 23:08:221957 }
initial.commit09911bf2008-07-26 23:55:291958
evan@chromium.org68b9e72b2011-08-05 23:08:221959 ChildProcessStats stats = child_process_stats_buffer_[name16];
initial.commit09911bf2008-07-26 23:55:291960 if (stats.process_launches) {
1961 int launches = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431962 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291963 launches += stats.process_launches;
nsylvain@chromium.org8e50b602009-03-03 22:59:431964 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291965 }
1966 if (stats.process_crashes) {
1967 int crashes = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431968 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291969 crashes += stats.process_crashes;
nsylvain@chromium.org8e50b602009-03-03 22:59:431970 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291971 }
1972 if (stats.instances) {
1973 int instances = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431974 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291975 instances += stats.instances;
nsylvain@chromium.org8e50b602009-03-03 22:59:431976 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291977 }
bauerb@chromium.orgcd937072012-07-02 09:00:291978 if (stats.loading_errors) {
1979 int loading_errors = 0;
1980 plugin_dict->GetInteger(prefs::kStabilityPluginLoadingErrors,
1981 &loading_errors);
1982 loading_errors += stats.loading_errors;
1983 plugin_dict->SetInteger(prefs::kStabilityPluginLoadingErrors,
1984 loading_errors);
1985 }
initial.commit09911bf2008-07-26 23:55:291986
evan@chromium.org68b9e72b2011-08-05 23:08:221987 child_process_stats_buffer_.erase(name16);
initial.commit09911bf2008-07-26 23:55:291988 }
1989
1990 // Now go through and add dictionaries for plugins that didn't already have
1991 // reports in Local State.
brettw@chromium.orgd2065e062013-12-12 23:49:521992 for (std::map<base::string16, ChildProcessStats>::iterator cache_iter =
jam@chromium.orga27a9382009-02-11 23:55:101993 child_process_stats_buffer_.begin();
1994 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
jam@chromium.orga27a9382009-02-11 23:55:101995 ChildProcessStats stats = cache_iter->second;
gregoryd@google.com0d84c5d2009-10-09 01:10:421996
1997 // Insert only plugins information into the plugins list.
petkov@chromium.org8d5f1dae2011-11-11 14:30:411998 if (!IsPluginProcess(stats.process_type))
gregoryd@google.com0d84c5d2009-10-09 01:10:421999 continue;
2000
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:512001 // TODO(viettrungluu): remove conversion
avi@chromium.org6778fed2013-12-24 20:09:372002 std::string plugin_name = base::UTF16ToUTF8(cache_iter->first);
gregoryd@google.com0d84c5d2009-10-09 01:10:422003
avi@chromium.orgcb1078de2013-12-23 20:04:222004 base::DictionaryValue* plugin_dict = new base::DictionaryValue;
initial.commit09911bf2008-07-26 23:55:292005
nsylvain@chromium.org8e50b602009-03-03 22:59:432006 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
2007 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:292008 stats.process_launches);
nsylvain@chromium.org8e50b602009-03-03 22:59:432009 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:292010 stats.process_crashes);
nsylvain@chromium.org8e50b602009-03-03 22:59:432011 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:292012 stats.instances);
bauerb@chromium.orgcd937072012-07-02 09:00:292013 plugin_dict->SetInteger(prefs::kStabilityPluginLoadingErrors,
2014 stats.loading_errors);
initial.commit09911bf2008-07-26 23:55:292015 plugins->Append(plugin_dict);
2016 }
jam@chromium.orga27a9382009-02-11 23:55:102017 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:292018}
2019
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:042020bool MetricsService::ShouldLogEvents() {
2021 // We simply don't log events to UMA if there is a single incognito
initial.commit09911bf2008-07-26 23:55:292022 // session visible. The problem is that we always notify using the orginal
2023 // profile in order to simplify notification processing.
tfarina@chromium.orge764e582012-08-01 03:01:292024 return !chrome::IsOffTheRecordSessionActive();
initial.commit09911bf2008-07-26 23:55:292025}
2026
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:512027void MetricsService::RecordBooleanPrefValue(const char* path, bool value) {
initial.commit09911bf2008-07-26 23:55:292028 DCHECK(IsSingleThreaded());
2029
2030 PrefService* pref = g_browser_process->local_state();
2031 DCHECK(pref);
2032
2033 pref->SetBoolean(path, value);
2034 RecordCurrentState(pref);
2035}
2036
2037void MetricsService::RecordCurrentState(PrefService* pref) {
robertshield@google.com0bb1a622009-03-04 03:22:322038 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:292039
2040 RecordPluginChanges(pref);
2041}
2042
petkov@chromium.org8d5f1dae2011-11-11 14:30:412043// static
jam@chromium.orgf3b357692013-03-22 05:16:132044bool MetricsService::IsPluginProcess(int process_type) {
2045 return (process_type == content::PROCESS_TYPE_PLUGIN ||
2046 process_type == content::PROCESS_TYPE_PPAPI_PLUGIN ||
2047 process_type == content::PROCESS_TYPE_PPAPI_BROKER);
petkov@chromium.org8d5f1dae2011-11-11 14:30:412048}
2049
rvargas@google.com5ccaa412009-11-13 22:00:162050#if defined(OS_CHROMEOS)
sky@chromium.org29cf16772010-04-21 15:13:472051void MetricsService::StartExternalMetrics() {
rvargas@google.com5ccaa412009-11-13 22:00:162052 external_metrics_ = new chromeos::ExternalMetrics;
sky@chromium.org29cf16772010-04-21 15:13:472053 external_metrics_->Start();
rvargas@google.com5ccaa412009-11-13 22:00:162054}
2055#endif
sreeram@chromium.org3819f2ee2011-08-21 09:44:382056
2057// static
2058bool MetricsServiceHelper::IsMetricsReportingEnabled() {
2059 bool result = false;
2060 const PrefService* local_state = g_browser_process->local_state();
2061 if (local_state) {
2062 const PrefService::Preference* uma_pref =
2063 local_state->FindPreference(prefs::kMetricsReportingEnabled);
2064 if (uma_pref) {
2065 bool success = uma_pref->GetValue()->GetAsBoolean(&result);
2066 DCHECK(success);
2067 }
2068 }
2069 return result;
2070}