blob: 1c1e37b3aa93c7705535f032860294342bec4b5b [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"
brettw@chromium.org835d7c82010-10-14 04:38:38171#include "base/metrics/histogram.h"
eroman@chromium.org1026afd2013-03-20 14:28:54172#include "base/metrics/sparse_histogram.h"
kaiwang@chromium.org567d30e2012-07-13 21:48:29173#include "base/metrics/statistics_recorder.h"
joi@chromium.org3853a4c2013-02-11 17:15:57174#include "base/prefs/pref_registry_simple.h"
175#include "base/prefs/pref_service.h"
derat@chromium.org9eec53fe2013-10-30 20:21:17176#include "base/prefs/scoped_user_pref_update.h"
brettw@chromium.org3ea1b182013-02-08 22:38:41177#include "base/strings/string_number_conversions.h"
avi@chromium.org112158af2013-06-07 23:46:18178#include "base/strings/utf_string_conversions.h"
brettw@chromium.orgce072a72010-12-31 20:02:16179#include "base/threading/platform_thread.h"
tfarina@chromium.orgb3841c502011-03-09 01:21:31180#include "base/threading/thread.h"
jam@chromium.org3a7b66d2012-04-26 16:34:16181#include "base/threading/thread_restrictions.h"
isherman@chromium.orged0fd002012-04-25 23:10:34182#include "base/tracked_objects.h"
erg@google.com679082052010-07-21 21:30:13183#include "base/values.h"
initial.commit09911bf2008-07-26 23:55:29184#include "chrome/browser/browser_process.h"
jam@chromium.org9ea0cd32013-07-12 01:50:36185#include "chrome/browser/chrome_notification_types.h"
isherman@chromium.orgb8ddb052012-04-19 02:36:06186#include "chrome/browser/io_thread.h"
sail@chromium.org84c988a2011-04-19 17:56:33187#include "chrome/browser/memory_details.h"
asharif@chromium.org537c638d2013-07-04 00:49:19188#include "chrome/browser/metrics/compression_utils.h"
erg@google.com679082052010-07-21 21:30:13189#include "chrome/browser/metrics/metrics_log.h"
miu@chromium.org39076642014-05-05 20:32:55190#include "chrome/browser/metrics/metrics_state_manager.h"
simonjam@chromium.orgaa312812013-04-30 19:46:05191#include "chrome/browser/metrics/time_ticks_experiment_win.h"
isherman@chromium.orged0fd002012-04-25 23:10:34192#include "chrome/browser/metrics/tracking_synchronizer.h"
simonjam@chromium.orgadbb3762012-03-09 22:20:08193#include "chrome/browser/net/http_pipelining_compatibility_client.h"
rtenneti@chromium.orgd67d1052011-06-09 05:11:41194#include "chrome/browser/net/network_stats.h"
tfarina@chromium.org0fafc8d2013-06-01 00:09:50195#include "chrome/browser/omnibox/omnibox_log.h"
dtrainor@chromium.org10b132b02012-07-27 20:46:18196#include "chrome/browser/ui/browser_otr_state.h"
rogerm@chromium.org261ab7c2013-08-19 15:04:58197#include "chrome/common/chrome_constants.h"
jar@chromium.org92745242009-06-12 16:52:21198#include "chrome/common/chrome_switches.h"
rsesek@chromium.org264c0acac2013-10-01 13:33:30199#include "chrome/common/crash_keys.h"
motek@chromium.org14bb46692014-05-20 17:16:45200#include "chrome/common/metrics/variations/variations_util.h"
simonjam@chromium.orgb4a72d842012-03-22 20:09:09201#include "chrome/common/net/test_server_locations.h"
initial.commit09911bf2008-07-26 23:55:29202#include "chrome/common/pref_names.h"
jam@chromium.orge09ba552009-02-05 03:26:29203#include "chrome/common/render_messages.h"
bsimonnet@chromium.org064107e2014-05-02 00:59:06204#include "components/metrics/metrics_log_manager.h"
holte@chromium.org7f07db62014-05-15 01:12:45205#include "components/metrics/metrics_pref_names.h"
motek@chromium.org14bb46692014-05-20 17:16:45206#include "components/metrics/metrics_reporting_scheduler.h"
asvitkine@chromium.org50ae9f12013-08-29 18:03:22207#include "components/variations/entropy_provider.h"
bengr@chromium.org60677562013-11-17 15:52:55208#include "components/variations/metrics_util.h"
jam@chromium.org4967f792012-01-20 22:14:40209#include "content/public/browser/child_process_data.h"
rtenneti@google.com83ab4a282012-07-12 18:19:45210#include "content/public/browser/histogram_fetcher.h"
tfarina@chromium.org09d31d52012-03-11 22:30:27211#include "content/public/browser/load_notification_details.h"
jam@chromium.orgad50def52011-10-19 23:17:07212#include "content/public/browser/notification_service.h"
jam@chromium.org3a5180ae2011-12-21 02:39:38213#include "content/public/browser/plugin_service.h"
ananta@chromium.orgf3b1a082011-11-18 00:34:30214#include "content/public/browser/render_process_host.h"
mpearson@chromium.org5d490e42012-08-30 05:16:43215#include "content/public/browser/user_metrics.h"
avi@chromium.org459f3502012-09-17 17:08:12216#include "content/public/browser/web_contents.h"
yael.aharon@intel.comd5d383252013-07-04 14:44:32217#include "content/public/common/process_type.h"
jam@chromium.orgd7bd3e52013-07-21 04:29:20218#include "content/public/common/webplugininfo.h"
benwells@chromium.org50de9aa22013-11-14 06:30:34219#include "extensions/browser/process_map.h"
isherman@chromium.orgfe58acc22012-02-29 01:29:58220#include "net/base/load_flags.h"
akalin@chromium.org3dc1bc42012-06-19 08:20:53221#include "net/url_request/url_fetcher.h"
initial.commit09911bf2008-07-26 23:55:29222
phajdan.jr@chromium.orge06131d2010-02-10 18:40:33223// TODO(port): port browser_distribution.h.
224#if !defined(OS_POSIX)
kuchhal@chromium.org79bf0b72009-04-27 21:30:55225#include "chrome/installer/util/browser_distribution.h"
paul@chromium.orgdc6f4962009-02-13 01:25:50226#endif
227
rvargas@google.com5ccaa412009-11-13 22:00:16228#if defined(OS_CHROMEOS)
elijahtaylor@chromium.org1ef13cf2014-03-21 22:44:01229#include "chrome/browser/chromeos/settings/cros_settings.h"
stevenjb@chromium.org279690f82013-10-09 08:23:52230#include "chromeos/system/statistics_provider.h"
rvargas@google.com5ccaa412009-11-13 22:00:16231#endif
232
eroman@chromium.orgd7c1fa62012-06-15 23:35:30233#if defined(OS_WIN)
234#include <windows.h> // Needed for STATUS_* codes
rogerm@chromium.org261ab7c2013-08-19 15:04:58235#include "base/win/registry.h"
eroman@chromium.orgd7c1fa62012-06-15 23:35:30236#endif
237
vitalybuka@chromium.orga3079832013-10-24 20:29:36238#if !defined(OS_ANDROID)
jianli@chromium.orgcbf160aa2013-11-05 17:54:55239#include "chrome/browser/service_process/service_process_control.h"
vitalybuka@chromium.orga3079832013-10-24 20:29:36240#endif
241
dsh@google.come1acf6f2008-10-27 20:43:33242using base::Time;
joi@chromium.org631bb742011-11-02 11:29:39243using content::BrowserThread;
jam@chromium.org4967f792012-01-20 22:14:40244using content::ChildProcessData;
tfarina@chromium.org09d31d52012-03-11 22:30:27245using content::LoadNotificationDetails;
jam@chromium.org3a5180ae2011-12-21 02:39:38246using content::PluginService;
bsimonnet@chromium.org064107e2014-05-02 00:59:06247using metrics::MetricsLogManager;
dsh@google.come1acf6f2008-10-27 20:43:33248
isherman@chromium.orgfe58acc22012-02-29 01:29:58249namespace {
isherman@chromium.orgb2a4812d2012-02-28 05:31:31250
isherman@chromium.orgfe58acc22012-02-29 01:29:58251// Check to see that we're being called on only one thread.
252bool IsSingleThreaded() {
253 static base::PlatformThreadId thread_id = 0;
254 if (!thread_id)
255 thread_id = base::PlatformThread::CurrentId();
256 return base::PlatformThread::CurrentId() == thread_id;
257}
258
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16259// The delay, in seconds, after starting recording before doing expensive
260// initialization work.
dfalcantara@chromium.org12180f82012-10-10 21:13:30261#if defined(OS_ANDROID) || defined(OS_IOS)
262// On mobile devices, a significant portion of sessions last less than a minute.
263// Use a shorter timer on these platforms to avoid losing data.
264// TODO(dfalcantara): To avoid delaying startup, tighten up initialization so
265// that it occurs after the user gets their initial page.
266const int kInitializationDelaySeconds = 5;
267#else
isherman@chromium.orgfe58acc22012-02-29 01:29:58268const int kInitializationDelaySeconds = 30;
dfalcantara@chromium.org12180f82012-10-10 21:13:30269#endif
petersont@google.com252873ef2008-08-04 21:59:45270
jar@chromium.orgc9a3ef82009-05-28 22:02:46271// This specifies the amount of time to wait for all renderers to send their
272// data.
isherman@chromium.orgfe58acc22012-02-29 01:29:58273const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
jar@chromium.orgc9a3ef82009-05-28 22:02:46274
stuartmorgan@chromium.org54702c92011-04-15 15:06:43275// The maximum number of events in a log uploaded to the UMA server.
isherman@chromium.orgfe58acc22012-02-29 01:29:58276const int kEventLimit = 2400;
jar@google.com68475e602008-08-22 03:21:15277
278// If an upload fails, and the transmission was over this byte count, then we
279// will discard the log, and not try to retransmit it. We also don't persist
280// the log to the prefs for transmission during the next chrome session if this
281// limit is exceeded.
isherman@chromium.orgfe58acc22012-02-29 01:29:58282const size_t kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29283
tedvessenes@gmail.comfc4252a72012-01-12 21:58:47284// Interval, in minutes, between state saves.
isherman@chromium.orgfe58acc22012-02-29 01:29:58285const int kSaveStateIntervalMinutes = 5;
286
isherman@chromium.org4266def22012-05-17 01:02:40287enum ResponseStatus {
288 UNKNOWN_FAILURE,
289 SUCCESS,
290 BAD_REQUEST, // Invalid syntax or log too large.
isherman@chromium.org9f5c1ce82012-05-23 23:11:28291 NO_RESPONSE,
isherman@chromium.org4266def22012-05-17 01:02:40292 NUM_RESPONSE_STATUSES
293};
294
295ResponseStatus ResponseCodeToStatus(int response_code) {
296 switch (response_code) {
297 case 200:
298 return SUCCESS;
299 case 400:
300 return BAD_REQUEST;
isherman@chromium.org9f5c1ce82012-05-23 23:11:28301 case net::URLFetcher::RESPONSE_CODE_INVALID:
302 return NO_RESPONSE;
isherman@chromium.org4266def22012-05-17 01:02:40303 default:
304 return UNKNOWN_FAILURE;
305 }
306}
307
eroman@chromium.orgd7c1fa62012-06-15 23:35:30308// Converts an exit code into something that can be inserted into our
309// histograms (which expect non-negative numbers less than MAX_INT).
310int MapCrashExitCodeForHistogram(int exit_code) {
311#if defined(OS_WIN)
312 // Since |abs(STATUS_GUARD_PAGE_VIOLATION) == MAX_INT| it causes problems in
313 // histograms.cc. Solve this by remapping it to a smaller value, which
314 // hopefully doesn't conflict with other codes.
315 if (exit_code == STATUS_GUARD_PAGE_VIOLATION)
316 return 0x1FCF7EC3; // Randomly picked number.
317#endif
318
319 return std::abs(exit_code);
320}
321
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19322void MarkAppCleanShutdownAndCommit() {
323 PrefService* pref = g_browser_process->local_state();
324 pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19325 pref->SetInteger(prefs::kStabilityExecutionPhase,
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21326 MetricsService::SHUTDOWN_COMPLETE);
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19327 // Start writing right away (write happens on a different thread).
328 pref->CommitPendingWrite();
329}
330
asvitkine@chromium.org20f999b52012-08-24 22:32:59331} // namespace
initial.commit09911bf2008-07-26 23:55:29332
bengr@chromium.org60677562013-11-17 15:52:55333
asvitkine@chromium.org7a5c07812014-02-26 11:45:41334SyntheticTrialGroup::SyntheticTrialGroup(uint32 trial, uint32 group) {
bengr@chromium.org60677562013-11-17 15:52:55335 id.name = trial;
336 id.group = group;
337}
338
339SyntheticTrialGroup::~SyntheticTrialGroup() {
340}
341
jar@chromium.orgc0c55e92011-09-10 18:47:30342// static
343MetricsService::ShutdownCleanliness MetricsService::clean_shutdown_status_ =
344 MetricsService::CLEANLY_SHUTDOWN;
345
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19346MetricsService::ExecutionPhase MetricsService::execution_phase_ =
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21347 MetricsService::UNINITIALIZED_PHASE;
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19348
erg@google.com679082052010-07-21 21:30:13349// This is used to quickly log stats from child process related notifications in
350// MetricsService::child_stats_buffer_. The buffer's contents are transferred
351// out when Local State is periodically saved. The information is then
352// reported to the UMA server on next launch.
353struct MetricsService::ChildProcessStats {
354 public:
jam@chromium.orgf3b357692013-03-22 05:16:13355 explicit ChildProcessStats(int process_type)
erg@google.com679082052010-07-21 21:30:13356 : process_launches(0),
357 process_crashes(0),
358 instances(0),
bauerb@chromium.orgcd937072012-07-02 09:00:29359 loading_errors(0),
jam@chromium.orgf3b357692013-03-22 05:16:13360 process_type(process_type) {}
erg@google.com679082052010-07-21 21:30:13361
362 // This constructor is only used by the map to return some default value for
363 // an index for which no value has been assigned.
364 ChildProcessStats()
365 : process_launches(0),
pkasting@chromium.orgd88bf0a2011-08-30 23:55:57366 process_crashes(0),
367 instances(0),
bauerb@chromium.orgcd937072012-07-02 09:00:29368 loading_errors(0),
jam@chromium.orgbd5d6cf2011-12-01 00:39:12369 process_type(content::PROCESS_TYPE_UNKNOWN) {}
erg@google.com679082052010-07-21 21:30:13370
371 // The number of times that the given child process has been launched
372 int process_launches;
373
374 // The number of times that the given child process has crashed
375 int process_crashes;
376
377 // The number of instances of this child process that have been created.
378 // An instance is a DOM object rendered by this child process during a page
379 // load.
380 int instances;
381
bauerb@chromium.orgcd937072012-07-02 09:00:29382 // The number of times there was an error loading an instance of this child
383 // process.
384 int loading_errors;
385
jam@chromium.orgf3b357692013-03-22 05:16:13386 int process_type;
erg@google.com679082052010-07-21 21:30:13387};
initial.commit09911bf2008-07-26 23:55:29388
sail@chromium.org84c988a2011-04-19 17:56:33389// Handles asynchronous fetching of memory details.
390// Will run the provided task after finished.
391class MetricsMemoryDetails : public MemoryDetails {
392 public:
dcheng@chromium.org2226c222011-11-22 00:08:40393 explicit MetricsMemoryDetails(const base::Closure& callback)
394 : callback_(callback) {}
sail@chromium.org84c988a2011-04-19 17:56:33395
rsleevi@chromium.orgb94584a2013-02-07 03:02:08396 virtual void OnDetailsAvailable() OVERRIDE {
xhwang@chromium.orgb3a25092013-05-28 22:08:16397 base::MessageLoop::current()->PostTask(FROM_HERE, callback_);
sail@chromium.org84c988a2011-04-19 17:56:33398 }
399
400 private:
rsleevi@chromium.orgb94584a2013-02-07 03:02:08401 virtual ~MetricsMemoryDetails() {}
sail@chromium.org84c988a2011-04-19 17:56:33402
dcheng@chromium.org2226c222011-11-22 00:08:40403 base::Closure callback_;
sail@chromium.org84c988a2011-04-19 17:56:33404 DISALLOW_COPY_AND_ASSIGN(MetricsMemoryDetails);
405};
406
initial.commit09911bf2008-07-26 23:55:29407// static
joi@chromium.orgb1de2c72013-02-06 02:45:47408void MetricsService::RegisterPrefs(PrefRegistrySimple* registry) {
initial.commit09911bf2008-07-26 23:55:29409 DCHECK(IsSingleThreaded());
miu@chromium.org39076642014-05-05 20:32:55410 metrics::MetricsStateManager::RegisterPrefs(registry);
411
joi@chromium.orgb1de2c72013-02-06 02:45:47412 registry->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
413 registry->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
dcheng@chromium.org007b3f82013-04-09 08:46:45414 registry->RegisterStringPref(prefs::kStabilityStatsVersion, std::string());
joi@chromium.orgb1de2c72013-02-06 02:45:47415 registry->RegisterInt64Pref(prefs::kStabilityStatsBuildTime, 0);
416 registry->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19417 registry->RegisterIntegerPref(prefs::kStabilityExecutionPhase,
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21418 UNINITIALIZED_PHASE);
joi@chromium.orgb1de2c72013-02-06 02:45:47419 registry->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
420 registry->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
421 registry->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
422 registry->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
423 registry->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount, 0);
424 registry->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
425 registry->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
426 registry->RegisterIntegerPref(prefs::kStabilityExtensionRendererCrashCount,
427 0);
428 registry->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
429 registry->RegisterIntegerPref(prefs::kStabilityChildProcessCrashCount, 0);
430 registry->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail, 0);
431 registry->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
432 0);
433 registry->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
434 registry->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
petkov@chromium.orgc1834a92011-01-21 18:21:03435#if defined(OS_CHROMEOS)
joi@chromium.orgb1de2c72013-02-06 02:45:47436 registry->RegisterIntegerPref(prefs::kStabilityOtherUserCrashCount, 0);
437 registry->RegisterIntegerPref(prefs::kStabilityKernelCrashCount, 0);
438 registry->RegisterIntegerPref(prefs::kStabilitySystemUncleanShutdownCount, 0);
petkov@chromium.orgc1834a92011-01-21 18:21:03439#endif // OS_CHROMEOS
cpu@google.come73c01972008-08-13 00:18:24440
asvitkine@chromium.org0f2f7792013-11-28 16:09:14441 registry->RegisterStringPref(prefs::kStabilitySavedSystemProfile,
442 std::string());
443 registry->RegisterStringPref(prefs::kStabilitySavedSystemProfileHash,
444 std::string());
445
holte@chromium.org7f07db62014-05-15 01:12:45446 registry->RegisterListPref(metrics::prefs::kMetricsInitialLogs);
447 registry->RegisterListPref(metrics::prefs::kMetricsOngoingLogs);
robertshield@google.com0bb1a622009-03-04 03:22:32448
isherman@chromium.org5c181552013-02-07 09:12:52449 registry->RegisterInt64Pref(prefs::kInstallDate, 0);
joi@chromium.orgb1de2c72013-02-06 02:45:47450 registry->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
451 registry->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
joi@chromium.orgb1de2c72013-02-06 02:45:47452 registry->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
453 registry->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
454 registry->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
kkimlabs@chromium.orgc778687a2014-02-11 14:46:45455
456#if defined(OS_ANDROID)
457 RegisterPrefsAndroid(registry);
458#endif // defined(OS_ANDROID)
initial.commit09911bf2008-07-26 23:55:29459}
460
isherman@chromium.org728de072014-05-21 09:20:32461MetricsService::MetricsService(metrics::MetricsStateManager* state_manager,
462 metrics::MetricsServiceClient* client)
holte@chromium.org7f07db62014-05-15 01:12:45463 : MetricsServiceBase(g_browser_process->local_state(),
464 kUploadLogAvoidRetransmitSize),
465 state_manager_(state_manager),
isherman@chromium.org728de072014-05-21 09:20:32466 client_(client),
jwd@chromium.org37d4709a2014-03-29 03:07:40467 recording_active_(false),
petersont@google.comd01b8732008-10-16 02:18:07468 reporting_active_(false),
stuartmorgan@chromium.org410938e02012-10-24 16:33:59469 test_mode_active_(false),
petersont@google.comd01b8732008-10-16 02:18:07470 state_(INITIALIZED),
asvitkine@chromium.org80a8f312013-12-16 18:00:30471 has_initial_stability_log_(false),
petersont@google.comd01b8732008-10-16 02:18:07472 idle_since_last_transmission_(false),
asvitkine@chromium.org80a8f312013-12-16 18:00:30473 session_id_(-1),
initial.commit09911bf2008-07-26 23:55:29474 next_window_id_(0),
tfarina@chromium.org9c009092013-05-01 03:14:09475 self_ptr_factory_(this),
476 state_saver_factory_(this),
stevet@chromium.orge5354322012-08-09 23:07:37477 waiting_for_asynchronous_reporting_step_(false),
miu@chromium.org39076642014-05-05 20:32:55478 num_async_histogram_fetches_in_progress_(0) {
initial.commit09911bf2008-07-26 23:55:29479 DCHECK(IsSingleThreaded());
miu@chromium.org39076642014-05-05 20:32:55480 DCHECK(state_manager_);
isherman@chromium.org728de072014-05-21 09:20:32481 DCHECK(client_);
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16482
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:40483 BrowserChildProcessObserver::Add(this);
initial.commit09911bf2008-07-26 23:55:29484}
485
486MetricsService::~MetricsService() {
stuartmorgan@chromium.org410938e02012-10-24 16:33:59487 DisableRecording();
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:40488
489 BrowserChildProcessObserver::Remove(this);
initial.commit09911bf2008-07-26 23:55:29490}
491
miu@chromium.org39076642014-05-05 20:32:55492void MetricsService::InitializeMetricsRecordingState() {
493 InitializeMetricsState();
asvitkine@chromium.org80a8f312013-12-16 18:00:30494
495 base::Closure callback = base::Bind(&MetricsService::StartScheduledUpload,
496 self_ptr_factory_.GetWeakPtr());
497 scheduler_.reset(new MetricsReportingScheduler(callback));
498}
499
petersont@google.comd01b8732008-10-16 02:18:07500void MetricsService::Start() {
stuartmorgan@chromium.orgb1c8dc02011-04-13 18:32:04501 HandleIdleSinceLastTransmission(false);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59502 EnableRecording();
503 EnableReporting();
petersont@google.comd01b8732008-10-16 02:18:07504}
505
miu@chromium.org39076642014-05-05 20:32:55506bool MetricsService::StartIfMetricsReportingEnabled() {
507 const bool enabled = state_manager_->IsMetricsReportingEnabled();
508 if (enabled)
509 Start();
510 return enabled;
511}
512
stuartmorgan@chromium.org410938e02012-10-24 16:33:59513void MetricsService::StartRecordingForTests() {
514 test_mode_active_ = true;
515 EnableRecording();
516 DisableReporting();
petersont@google.comd01b8732008-10-16 02:18:07517}
518
519void MetricsService::Stop() {
stuartmorgan@chromium.orgb1c8dc02011-04-13 18:32:04520 HandleIdleSinceLastTransmission(false);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59521 DisableReporting();
522 DisableRecording();
523}
524
525void MetricsService::EnableReporting() {
526 if (reporting_active_)
527 return;
528 reporting_active_ = true;
529 StartSchedulerIfNecessary();
530}
531
532void MetricsService::DisableReporting() {
533 reporting_active_ = false;
petersont@google.comd01b8732008-10-16 02:18:07534}
535
joi@chromium.orgedafd4c2011-05-10 17:18:53536std::string MetricsService::GetClientId() {
miu@chromium.org39076642014-05-05 20:32:55537 return state_manager_->client_id();
joi@chromium.orgedafd4c2011-05-10 17:18:53538}
539
asvitkine@chromium.org20f999b52012-08-24 22:32:59540scoped_ptr<const base::FieldTrial::EntropyProvider>
miu@chromium.org39076642014-05-05 20:32:55541MetricsService::CreateEntropyProvider() {
542 // TODO(asvitkine): Refactor the code so that MetricsService does not expose
543 // this method.
544 return state_manager_->CreateEntropyProvider();
jam@chromium.org5cbeeef72012-02-08 02:05:18545}
546
stuartmorgan@chromium.org410938e02012-10-24 16:33:59547void MetricsService::EnableRecording() {
initial.commit09911bf2008-07-26 23:55:29548 DCHECK(IsSingleThreaded());
549
stuartmorgan@chromium.org410938e02012-10-24 16:33:59550 if (recording_active_)
initial.commit09911bf2008-07-26 23:55:29551 return;
stuartmorgan@chromium.org410938e02012-10-24 16:33:59552 recording_active_ = true;
initial.commit09911bf2008-07-26 23:55:29553
miu@chromium.org39076642014-05-05 20:32:55554 state_manager_->ForceClientIdCreation();
555 crash_keys::SetClientID(state_manager_->client_id());
stuartmorgan@chromium.org410938e02012-10-24 16:33:59556 if (!log_manager_.current_log())
557 OpenNewLog();
pkasting@chromium.org005ef3e2009-05-22 20:55:46558
asvitkine@chromium.org85791b0b2014-05-20 15:18:58559 for (size_t i = 0; i < metrics_providers_.size(); ++i)
560 metrics_providers_[i]->OnRecordingEnabled();
561
stuartmorgan@chromium.org410938e02012-10-24 16:33:59562 SetUpNotifications(&registrar_, this);
ben@chromium.orge6e30ac2014-01-13 21:24:39563 base::RemoveActionCallback(action_callback_);
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:22564 action_callback_ = base::Bind(&MetricsService::OnUserAction,
565 base::Unretained(this));
ben@chromium.orge6e30ac2014-01-13 21:24:39566 base::AddActionCallback(action_callback_);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59567}
568
569void MetricsService::DisableRecording() {
570 DCHECK(IsSingleThreaded());
571
572 if (!recording_active_)
573 return;
574 recording_active_ = false;
575
ben@chromium.orge6e30ac2014-01-13 21:24:39576 base::RemoveActionCallback(action_callback_);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59577 registrar_.RemoveAll();
asvitkine@chromium.org85791b0b2014-05-20 15:18:58578
579 for (size_t i = 0; i < metrics_providers_.size(); ++i)
580 metrics_providers_[i]->OnRecordingDisabled();
581
stuartmorgan@chromium.org410938e02012-10-24 16:33:59582 PushPendingLogsToPersistentStorage();
583 DCHECK(!log_manager_.has_staged_log());
initial.commit09911bf2008-07-26 23:55:29584}
585
petersont@google.comd01b8732008-10-16 02:18:07586bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29587 DCHECK(IsSingleThreaded());
petersont@google.comd01b8732008-10-16 02:18:07588 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29589}
590
petersont@google.comd01b8732008-10-16 02:18:07591bool MetricsService::reporting_active() const {
592 DCHECK(IsSingleThreaded());
593 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29594}
595
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15596// static
jam@chromium.org6c2381d2011-10-19 02:52:53597void MetricsService::SetUpNotifications(
598 content::NotificationRegistrar* registrar,
599 content::NotificationObserver* observer) {
600 registrar->Add(observer, chrome::NOTIFICATION_BROWSER_OPENED,
jam@chromium.orgad50def52011-10-19 23:17:07601 content::NotificationService::AllBrowserContextsAndSources());
jam@chromium.org6c2381d2011-10-19 02:52:53602 registrar->Add(observer, chrome::NOTIFICATION_BROWSER_CLOSED,
jam@chromium.orgad50def52011-10-19 23:17:07603 content::NotificationService::AllSources());
avi@chromium.org884033e2012-04-16 19:38:42604 registrar->Add(observer, chrome::NOTIFICATION_TAB_PARENTED,
jam@chromium.orgad50def52011-10-19 23:17:07605 content::NotificationService::AllSources());
avi@chromium.org884033e2012-04-16 19:38:42606 registrar->Add(observer, chrome::NOTIFICATION_TAB_CLOSING,
jam@chromium.orgad50def52011-10-19 23:17:07607 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53608 registrar->Add(observer, content::NOTIFICATION_LOAD_START,
jam@chromium.orgad50def52011-10-19 23:17:07609 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53610 registrar->Add(observer, content::NOTIFICATION_LOAD_STOP,
jam@chromium.orgad50def52011-10-19 23:17:07611 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53612 registrar->Add(observer, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
jam@chromium.orgad50def52011-10-19 23:17:07613 content::NotificationService::AllSources());
avi@chromium.org42d8d7582013-11-09 01:24:38614 registrar->Add(observer, content::NOTIFICATION_RENDER_WIDGET_HOST_HANG,
jam@chromium.orgad50def52011-10-19 23:17:07615 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53616 registrar->Add(observer, chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
jam@chromium.orgad50def52011-10-19 23:17:07617 content::NotificationService::AllSources());
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15618}
619
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:40620void MetricsService::BrowserChildProcessHostConnected(
621 const content::ChildProcessData& data) {
622 GetChildProcessStats(data).process_launches++;
623}
624
625void MetricsService::BrowserChildProcessCrashed(
626 const content::ChildProcessData& data) {
627 GetChildProcessStats(data).process_crashes++;
628 // Exclude plugin crashes from the count below because we report them via
629 // a separate UMA metric.
jam@chromium.orgf3b357692013-03-22 05:16:13630 if (!IsPluginProcess(data.process_type))
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:40631 IncrementPrefValue(prefs::kStabilityChildProcessCrashCount);
632}
633
634void MetricsService::BrowserChildProcessInstanceCreated(
635 const content::ChildProcessData& data) {
636 GetChildProcessStats(data).instances++;
637}
638
ananta@chromium.org432115822011-07-10 15:52:27639void MetricsService::Observe(int type,
jam@chromium.org6c2381d2011-10-19 02:52:53640 const content::NotificationSource& source,
641 const content::NotificationDetails& details) {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10642 DCHECK(log_manager_.current_log());
initial.commit09911bf2008-07-26 23:55:29643 DCHECK(IsSingleThreaded());
644
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04645 // Check for notifications related to core stability metrics, or that are
646 // just triggers to end idle mode. Anything else should be added in the later
647 // switch statement, where they take effect only if general metrics should be
648 // logged.
649 bool handled = false;
ananta@chromium.org432115822011-07-10 15:52:27650 switch (type) {
ananta@chromium.org432115822011-07-10 15:52:27651 case chrome::NOTIFICATION_BROWSER_OPENED:
isherman@chromium.org46a0efc2013-07-17 15:40:47652 case chrome::NOTIFICATION_BROWSER_CLOSED:
653 case chrome::NOTIFICATION_TAB_PARENTED:
654 case chrome::NOTIFICATION_TAB_CLOSING:
ananta@chromium.org432115822011-07-10 15:52:27655 case content::NOTIFICATION_LOAD_STOP:
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04656 // These notifications are used only to break out of idle mode.
657 handled = true;
initial.commit09911bf2008-07-26 23:55:29658 break;
659
rlp@chromium.org752a5262013-06-23 14:53:42660 case content::NOTIFICATION_LOAD_START: {
661 content::NavigationController* controller =
662 content::Source<content::NavigationController>(source).ptr();
663 content::WebContents* web_contents = controller->GetWebContents();
664 LogLoadStarted(web_contents);
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04665 handled = true;
initial.commit09911bf2008-07-26 23:55:29666 break;
rlp@chromium.org752a5262013-06-23 14:53:42667 }
initial.commit09911bf2008-07-26 23:55:29668
ananta@chromium.org432115822011-07-10 15:52:27669 case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: {
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04670 content::RenderProcessHost::RendererClosedDetails* process_details =
671 content::Details<
672 content::RenderProcessHost::RendererClosedDetails>(
673 details).ptr();
674 content::RenderProcessHost* host =
675 content::Source<content::RenderProcessHost>(source).ptr();
676 LogRendererCrash(
677 host, process_details->status, process_details->exit_code);
678 handled = true;
initial.commit09911bf2008-07-26 23:55:29679 break;
ananta@chromium.org1226abb2010-06-10 18:01:28680 }
initial.commit09911bf2008-07-26 23:55:29681
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04682 case content::NOTIFICATION_RENDER_WIDGET_HOST_HANG:
683 LogRendererHang();
684 handled = true;
initial.commit09911bf2008-07-26 23:55:29685 break;
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04686
687 default:
688 // Everything else is handled after the early return check below.
689 break;
690 }
691
692 // If it wasn't one of the stability-related notifications, and event
693 // logging isn't suppressed, handle it.
694 if (!handled && ShouldLogEvents()) {
695 switch (type) {
696 case chrome::NOTIFICATION_OMNIBOX_OPENED_URL: {
697 MetricsLog* current_log =
698 static_cast<MetricsLog*>(log_manager_.current_log());
699 DCHECK(current_log);
700 current_log->RecordOmniboxOpenedURL(
701 *content::Details<OmniboxLog>(details).ptr());
702 break;
703 }
704
705 default:
706 NOTREACHED();
707 break;
708 }
initial.commit09911bf2008-07-26 23:55:29709 }
petersont@google.comd01b8732008-10-16 02:18:07710
711 HandleIdleSinceLastTransmission(false);
petersont@google.comd01b8732008-10-16 02:18:07712}
713
714void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
715 // If there wasn't a lot of action, maybe the computer was asleep, in which
716 // case, the log transmissions should have stopped. Here we start them up
717 // again.
pkasting@chromium.orgcac78842008-11-27 01:02:20718 if (!in_idle && idle_since_last_transmission_)
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16719 StartSchedulerIfNecessary();
pkasting@chromium.orgcac78842008-11-27 01:02:20720 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29721}
722
initial.commit09911bf2008-07-26 23:55:29723void MetricsService::RecordStartOfSessionEnd() {
stuartmorgan@chromium.org466f3c12011-03-23 21:20:38724 LogCleanShutdown();
initial.commit09911bf2008-07-26 23:55:29725 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
726}
727
728void MetricsService::RecordCompletedSessionEnd() {
stuartmorgan@chromium.org466f3c12011-03-23 21:20:38729 LogCleanShutdown();
initial.commit09911bf2008-07-26 23:55:29730 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
731}
732
stuartmorgan@chromium.org410938e02012-10-24 16:33:59733#if defined(OS_ANDROID) || defined(OS_IOS)
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39734void MetricsService::OnAppEnterBackground() {
735 scheduler_->Stop();
736
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19737 MarkAppCleanShutdownAndCommit();
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39738
739 // At this point, there's no way of knowing when the process will be
740 // killed, so this has to be treated similar to a shutdown, closing and
741 // persisting all logs. Unlinke a shutdown, the state is primed to be ready
742 // to continue logging and uploading if the process does return.
asvitkine@chromium.org80a8f312013-12-16 18:00:30743 if (recording_active() && state_ >= SENDING_INITIAL_STABILITY_LOG) {
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39744 PushPendingLogsToPersistentStorage();
stuartmorgan@chromium.org410938e02012-10-24 16:33:59745 // Persisting logs closes the current log, so start recording a new log
746 // immediately to capture any background work that might be done before the
747 // process is killed.
748 OpenNewLog();
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39749 }
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39750}
751
752void MetricsService::OnAppEnterForeground() {
753 PrefService* pref = g_browser_process->local_state();
754 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
755
756 StartSchedulerIfNecessary();
757}
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19758#else
759void MetricsService::LogNeedForCleanShutdown() {
760 PrefService* pref = g_browser_process->local_state();
761 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
762 // Redundant setting to be sure we call for a clean shutdown.
763 clean_shutdown_status_ = NEED_TO_SHUTDOWN;
764}
765#endif // defined(OS_ANDROID) || defined(OS_IOS)
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39766
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21767// static
768void MetricsService::SetExecutionPhase(ExecutionPhase execution_phase) {
769 execution_phase_ = execution_phase;
770 PrefService* pref = g_browser_process->local_state();
771 pref->SetInteger(prefs::kStabilityExecutionPhase, execution_phase_);
772}
773
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16774void MetricsService::RecordBreakpadRegistration(bool success) {
jar@google.com68475e602008-08-22 03:21:15775 if (!success)
cpu@google.come73c01972008-08-13 00:18:24776 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
777 else
778 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
779}
780
781void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
782 if (!has_debugger)
783 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
784 else
jar@google.com68475e602008-08-22 03:21:15785 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
cpu@google.come73c01972008-08-13 00:18:24786}
787
rogerm@chromium.org261ab7c2013-08-19 15:04:58788#if defined(OS_WIN)
789void MetricsService::CountBrowserCrashDumpAttempts() {
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45790 // Open the registry key for iteration.
rogerm@chromium.org261ab7c2013-08-19 15:04:58791 base::win::RegKey regkey;
792 if (regkey.Open(HKEY_CURRENT_USER,
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45793 chrome::kBrowserCrashDumpAttemptsRegistryPath,
rogerm@chromium.org261ab7c2013-08-19 15:04:58794 KEY_ALL_ACCESS) != ERROR_SUCCESS) {
795 return;
796 }
797
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45798 // The values we're interested in counting are all prefixed with the version.
799 base::string16 chrome_version(base::ASCIIToUTF16(chrome::kChromeVersion));
800
801 // Track a list of values to delete. We don't modify the registry key while
802 // we're iterating over its values.
803 typedef std::vector<base::string16> StringVector;
804 StringVector to_delete;
805
806 // Iterate over the values in the key counting dumps with and without crashes.
807 // We directly walk the values instead of using RegistryValueIterator in order
808 // to read all of the values as DWORDS instead of strings.
809 base::string16 name;
810 DWORD value = 0;
811 int dumps_with_crash = 0;
812 int dumps_with_no_crash = 0;
rogerm@chromium.org261ab7c2013-08-19 15:04:58813 for (int i = regkey.GetValueCount() - 1; i >= 0; --i) {
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45814 if (regkey.GetValueNameAt(i, &name) == ERROR_SUCCESS &&
815 StartsWith(name, chrome_version, false) &&
816 regkey.ReadValueDW(name.c_str(), &value) == ERROR_SUCCESS) {
817 to_delete.push_back(name);
818 if (value == 0)
819 ++dumps_with_no_crash;
820 else
821 ++dumps_with_crash;
rogerm@chromium.org261ab7c2013-08-19 15:04:58822 }
823 }
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45824
825 // Delete the registry keys we've just counted.
826 for (StringVector::iterator i = to_delete.begin(); i != to_delete.end(); ++i)
827 regkey.DeleteValue(i->c_str());
828
829 // Capture the histogram samples.
830 if (dumps_with_crash != 0)
831 UMA_HISTOGRAM_COUNTS("Chrome.BrowserDumpsWithCrash", dumps_with_crash);
832 if (dumps_with_no_crash != 0)
833 UMA_HISTOGRAM_COUNTS("Chrome.BrowserDumpsWithNoCrash", dumps_with_no_crash);
834 int total_dumps = dumps_with_crash + dumps_with_no_crash;
835 if (total_dumps != 0)
836 UMA_HISTOGRAM_COUNTS("Chrome.BrowserCrashDumpAttempts", total_dumps);
rogerm@chromium.org261ab7c2013-08-19 15:04:58837}
838#endif // defined(OS_WIN)
839
initial.commit09911bf2008-07-26 23:55:29840//------------------------------------------------------------------------------
841// private methods
842//------------------------------------------------------------------------------
843
844
845//------------------------------------------------------------------------------
846// Initialization methods
847
miu@chromium.org39076642014-05-05 20:32:55848void MetricsService::InitializeMetricsState() {
kuchhal@chromium.org79bf0b72009-04-27 21:30:55849#if defined(OS_POSIX)
simonjam@chromium.orgb4a72d842012-03-22 20:09:09850 network_stats_server_ = chrome_common_net::kEchoTestServerLocation;
851 http_pipelining_test_server_ = chrome_common_net::kPipelineTestServerBaseUrl;
kuchhal@chromium.org79bf0b72009-04-27 21:30:55852#else
853 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
rtenneti@chromium.orgd67d1052011-06-09 05:11:41854 network_stats_server_ = dist->GetNetworkStatsServer();
simonjam@chromium.orgadbb3762012-03-09 22:20:08855 http_pipelining_test_server_ = dist->GetHttpPipeliningTestServer();
kuchhal@chromium.org79bf0b72009-04-27 21:30:55856#endif
857
initial.commit09911bf2008-07-26 23:55:29858 PrefService* pref = g_browser_process->local_state();
859 DCHECK(pref);
860
asvitkine@chromium.orgb58b8b22014-04-08 22:40:33861 pref->SetString(prefs::kStabilityStatsVersion,
862 MetricsLog::GetVersionString());
863 pref->SetInt64(prefs::kStabilityStatsBuildTime, MetricsLog::GetBuildTime());
jar@chromium.org541f77922009-02-23 21:14:38864
initial.commit09911bf2008-07-26 23:55:29865 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
initial.commit09911bf2008-07-26 23:55:29866
kkimlabs@chromium.orgc778687a2014-02-11 14:46:45867#if defined(OS_ANDROID)
868 LogAndroidStabilityToPrefs(pref);
869#endif // defined(OS_ANDROID)
870
cpu@google.come73c01972008-08-13 00:18:24871 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
872 IncrementPrefValue(prefs::kStabilityCrashCount);
jar@chromium.orgc0c55e92011-09-10 18:47:30873 // Reset flag, and wait until we call LogNeedForCleanShutdown() before
874 // monitoring.
875 pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19876
877 // TODO(rtenneti): On windows, consider saving/getting execution_phase from
878 // the registry.
879 int execution_phase = pref->GetInteger(prefs::kStabilityExecutionPhase);
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21880 UMA_HISTOGRAM_SPARSE_SLOWLY("Chrome.Browser.CrashedExecutionPhase",
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19881 execution_phase);
asvitkine@chromium.org80a8f312013-12-16 18:00:30882
883 // If the previous session didn't exit cleanly, then prepare an initial
884 // stability log if UMA is enabled.
miu@chromium.org39076642014-05-05 20:32:55885 if (state_manager_->IsMetricsReportingEnabled())
asvitkine@chromium.org80a8f312013-12-16 18:00:30886 PrepareInitialStabilityLog();
initial.commit09911bf2008-07-26 23:55:29887 }
asvitkine@chromium.org80a8f312013-12-16 18:00:30888
889 // Update session ID.
890 ++session_id_;
891 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
892
893 // Stability bookkeeping
894 IncrementPrefValue(prefs::kStabilityLaunchCount);
895
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21896 DCHECK_EQ(UNINITIALIZED_PHASE, execution_phase_);
897 SetExecutionPhase(START_METRICS_RECORDING);
cpu@google.come73c01972008-08-13 00:18:24898
rogerm@chromium.org261ab7c2013-08-19 15:04:58899#if defined(OS_WIN)
900 CountBrowserCrashDumpAttempts();
901#endif // defined(OS_WIN)
902
cpu@google.come73c01972008-08-13 00:18:24903 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
904 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
jar@chromium.orgc9abf242009-07-18 06:00:38905 // This is marked false when we get a WM_ENDSESSION.
906 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
initial.commit09911bf2008-07-26 23:55:29907 }
initial.commit09911bf2008-07-26 23:55:29908
mpearson@chromium.org076961c2014-03-12 22:23:56909 // Call GetUptimes() for the first time, thus allowing all later calls
910 // to record incremental uptimes accurately.
911 base::TimeDelta ignored_uptime_parameter;
912 base::TimeDelta startup_uptime;
913 GetUptimes(pref, &startup_uptime, &ignored_uptime_parameter);
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36914 DCHECK_EQ(0, startup_uptime.InMicroseconds());
jar@chromium.org9165f742010-03-10 22:55:01915 // For backwards compatibility, leave this intact in case Omaha is checking
916 // them. prefs::kStabilityLastTimestampSec may also be useless now.
917 // TODO(jar): Delete these if they have no uses.
robertshield@google.com0bb1a622009-03-04 03:22:32918 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
919
920 // Bookkeeping for the uninstall metrics.
921 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29922
jar@chromium.org92745242009-06-12 16:52:21923 // Get stats on use of command line.
924 const CommandLine* command_line(CommandLine::ForCurrentProcess());
925 size_t common_commands = 0;
926 if (command_line->HasSwitch(switches::kUserDataDir)) {
927 ++common_commands;
928 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
929 }
930
931 if (command_line->HasSwitch(switches::kApp)) {
932 ++common_commands;
933 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
934 }
935
msw@chromium.org62b4e522011-07-13 21:46:32936 size_t switch_count = command_line->GetSwitches().size();
937 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount", switch_count);
jar@chromium.org92745242009-06-12 16:52:21938 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
msw@chromium.org62b4e522011-07-13 21:46:32939 switch_count - common_commands);
jar@chromium.org92745242009-06-12 16:52:21940
initial.commit09911bf2008-07-26 23:55:29941 // Kick off the process of saving the state (so the uptime numbers keep
942 // getting updated) every n minutes.
943 ScheduleNextStateSave();
944}
945
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40946// static
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56947void MetricsService::InitTaskGetHardwareClass(
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40948 base::WeakPtr<MetricsService> self,
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56949 base::MessageLoopProxy* target_loop) {
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56950 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
951
952 std::string hardware_class;
953#if defined(OS_CHROMEOS)
954 chromeos::system::StatisticsProvider::GetInstance()->GetMachineStatistic(
955 "hardware_class", &hardware_class);
956#endif // OS_CHROMEOS
957
958 target_loop->PostTask(FROM_HERE,
959 base::Bind(&MetricsService::OnInitTaskGotHardwareClass,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40960 self, hardware_class));
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56961}
962
963void MetricsService::OnInitTaskGotHardwareClass(
964 const std::string& hardware_class) {
isherman@chromium.orged0fd002012-04-25 23:10:34965 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
zelidrag@chromium.org85ed9d42010-06-08 22:37:44966 hardware_class_ = hardware_class;
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56967
nileshagrawal@chromium.orgebd71962012-12-20 02:56:55968#if defined(ENABLE_PLUGINS)
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56969 // Start the next part of the init task: loading plugin information.
970 PluginService::GetInstance()->GetPlugins(
971 base::Bind(&MetricsService::OnInitTaskGotPluginInfo,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40972 self_ptr_factory_.GetWeakPtr()));
nileshagrawal@chromium.orgebd71962012-12-20 02:56:55973#else
jam@chromium.orgd7bd3e52013-07-21 04:29:20974 std::vector<content::WebPluginInfo> plugin_list_empty;
nileshagrawal@chromium.orgebd71962012-12-20 02:56:55975 OnInitTaskGotPluginInfo(plugin_list_empty);
976#endif // defined(ENABLE_PLUGINS)
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56977}
978
979void MetricsService::OnInitTaskGotPluginInfo(
jam@chromium.orgd7bd3e52013-07-21 04:29:20980 const std::vector<content::WebPluginInfo>& plugins) {
isherman@chromium.orged0fd002012-04-25 23:10:34981 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
jam@chromium.org35fa6a22009-08-15 00:04:01982 plugins_ = plugins;
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56983
ryanmyers@chromium.org197c0772012-05-14 23:50:51984 // Schedules a task on a blocking pool thread to gather Google Update
985 // statistics (requires Registry reads).
986 BrowserThread::PostBlockingPoolTask(
987 FROM_HERE,
988 base::Bind(&MetricsService::InitTaskGetGoogleUpdateData,
989 self_ptr_factory_.GetWeakPtr(),
xhwang@chromium.orgb3a25092013-05-28 22:08:16990 base::MessageLoop::current()->message_loop_proxy()));
ryanmyers@chromium.org197c0772012-05-14 23:50:51991}
992
993// static
994void MetricsService::InitTaskGetGoogleUpdateData(
995 base::WeakPtr<MetricsService> self,
996 base::MessageLoopProxy* target_loop) {
997 GoogleUpdateMetrics google_update_metrics;
998
999#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
1000 const bool system_install = GoogleUpdateSettings::IsSystemInstall();
1001
1002 google_update_metrics.is_system_install = system_install;
1003 google_update_metrics.last_started_au =
1004 GoogleUpdateSettings::GetGoogleUpdateLastStartedAU(system_install);
1005 google_update_metrics.last_checked =
1006 GoogleUpdateSettings::GetGoogleUpdateLastChecked(system_install);
1007 GoogleUpdateSettings::GetUpdateDetailForGoogleUpdate(
1008 system_install,
1009 &google_update_metrics.google_update_data);
1010 GoogleUpdateSettings::GetUpdateDetail(
1011 system_install,
1012 &google_update_metrics.product_data);
1013#endif // defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
1014
1015 target_loop->PostTask(FROM_HERE,
1016 base::Bind(&MetricsService::OnInitTaskGotGoogleUpdateData,
1017 self, google_update_metrics));
1018}
1019
1020void MetricsService::OnInitTaskGotGoogleUpdateData(
1021 const GoogleUpdateMetrics& google_update_metrics) {
1022 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
1023
1024 google_update_metrics_ = google_update_metrics;
1025
isherman@chromium.orged0fd002012-04-25 23:10:341026 // Start the next part of the init task: fetching performance data. This will
1027 // call into |FinishedReceivingProfilerData()| when the task completes.
1028 chrome_browser_metrics::TrackingSynchronizer::FetchProfilerDataAsynchronously(
1029 self_ptr_factory_.GetWeakPtr());
1030}
1031
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:221032void MetricsService::OnUserAction(const std::string& action) {
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:041033 if (!ShouldLogEvents())
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:221034 return;
1035
isherman@chromium.org4426d2d2014-04-09 12:33:001036 log_manager_.current_log()->RecordUserAction(action);
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:221037 HandleIdleSinceLastTransmission(false);
1038}
1039
isherman@chromium.orged0fd002012-04-25 23:10:341040void MetricsService::ReceivedProfilerData(
1041 const tracked_objects::ProcessDataSnapshot& process_data,
jam@chromium.orgf3b357692013-03-22 05:16:131042 int process_type) {
isherman@chromium.orged0fd002012-04-25 23:10:341043 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
1044
1045 // Upon the first callback, create the initial log so that we can immediately
1046 // save the profiler data.
asvitkine@chromium.org9eae4032014-04-09 19:15:191047 if (!initial_metrics_log_.get()) {
1048 initial_metrics_log_.reset(
miu@chromium.org39076642014-05-05 20:32:551049 new MetricsLog(state_manager_->client_id(), session_id_,
1050 MetricsLog::ONGOING_LOG));
bolian@chromium.org2a321de32014-05-10 19:59:061051 NotifyOnDidCreateMetricsLog();
asvitkine@chromium.org9eae4032014-04-09 19:15:191052 }
isherman@chromium.orged0fd002012-04-25 23:10:341053
asvitkine@chromium.org80a8f312013-12-16 18:00:301054 initial_metrics_log_->RecordProfilerData(process_data, process_type);
isherman@chromium.orged0fd002012-04-25 23:10:341055}
1056
1057void MetricsService::FinishedReceivingProfilerData() {
1058 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361059 state_ = INIT_TASK_DONE;
asvitkine@chromium.org70886cd2013-12-04 05:53:421060 scheduler_->InitTaskComplete();
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361061}
1062
mpearson@chromium.org076961c2014-03-12 22:23:561063void MetricsService::GetUptimes(PrefService* pref,
1064 base::TimeDelta* incremental_uptime,
1065 base::TimeDelta* uptime) {
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361066 base::TimeTicks now = base::TimeTicks::Now();
mpearson@chromium.org076961c2014-03-12 22:23:561067 // If this is the first call, init |first_updated_time_| and
1068 // |last_updated_time_|.
1069 if (last_updated_time_.is_null()) {
1070 first_updated_time_ = now;
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361071 last_updated_time_ = now;
mpearson@chromium.org076961c2014-03-12 22:23:561072 }
1073 *incremental_uptime = now - last_updated_time_;
1074 *uptime = now - first_updated_time_;
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361075 last_updated_time_ = now;
1076
mpearson@chromium.org076961c2014-03-12 22:23:561077 const int64 incremental_time_secs = incremental_uptime->InSeconds();
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361078 if (incremental_time_secs > 0) {
1079 int64 metrics_uptime = pref->GetInt64(prefs::kUninstallMetricsUptimeSec);
1080 metrics_uptime += incremental_time_secs;
1081 pref->SetInt64(prefs::kUninstallMetricsUptimeSec, metrics_uptime);
1082 }
initial.commit09911bf2008-07-26 23:55:291083}
1084
bolian@chromium.org2a321de32014-05-10 19:59:061085void MetricsService::AddObserver(MetricsServiceObserver* observer) {
1086 DCHECK(thread_checker_.CalledOnValidThread());
1087 observers_.AddObserver(observer);
1088}
1089
1090void MetricsService::RemoveObserver(MetricsServiceObserver* observer) {
1091 DCHECK(thread_checker_.CalledOnValidThread());
1092 observers_.RemoveObserver(observer);
1093}
1094
1095void MetricsService::NotifyOnDidCreateMetricsLog() {
1096 DCHECK(thread_checker_.CalledOnValidThread());
1097 FOR_EACH_OBSERVER(
1098 MetricsServiceObserver, observers_, OnDidCreateMetricsLog());
1099}
1100
initial.commit09911bf2008-07-26 23:55:291101//------------------------------------------------------------------------------
1102// State save methods
1103
1104void MetricsService::ScheduleNextStateSave() {
isherman@chromium.org8454aeb2011-11-19 23:38:201105 state_saver_factory_.InvalidateWeakPtrs();
initial.commit09911bf2008-07-26 23:55:291106
xhwang@chromium.orgb3a25092013-05-28 22:08:161107 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
isherman@chromium.org8454aeb2011-11-19 23:38:201108 base::Bind(&MetricsService::SaveLocalState,
1109 state_saver_factory_.GetWeakPtr()),
tedvessenes@gmail.comfc4252a72012-01-12 21:58:471110 base::TimeDelta::FromMinutes(kSaveStateIntervalMinutes));
initial.commit09911bf2008-07-26 23:55:291111}
1112
1113void MetricsService::SaveLocalState() {
1114 PrefService* pref = g_browser_process->local_state();
1115 if (!pref) {
jar@chromium.orga063c102010-07-22 22:20:191116 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291117 return;
1118 }
1119
1120 RecordCurrentState(pref);
initial.commit09911bf2008-07-26 23:55:291121
tedvessenes@gmail.comfc4252a72012-01-12 21:58:471122 // TODO(jar):110021 Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:291123 ScheduleNextStateSave();
1124}
1125
1126
1127//------------------------------------------------------------------------------
1128// Recording control methods
1129
stuartmorgan@chromium.org410938e02012-10-24 16:33:591130void MetricsService::OpenNewLog() {
1131 DCHECK(!log_manager_.current_log());
initial.commit09911bf2008-07-26 23:55:291132
asvitkine@chromium.org9eae4032014-04-09 19:15:191133 log_manager_.BeginLoggingWithLog(
miu@chromium.org39076642014-05-05 20:32:551134 new MetricsLog(state_manager_->client_id(), session_id_,
1135 MetricsLog::ONGOING_LOG));
bolian@chromium.org2a321de32014-05-10 19:59:061136 NotifyOnDidCreateMetricsLog();
initial.commit09911bf2008-07-26 23:55:291137 if (state_ == INITIALIZED) {
1138 // We only need to schedule that run once.
zelidrag@chromium.org85ed9d42010-06-08 22:37:441139 state_ = INIT_TASK_SCHEDULED;
initial.commit09911bf2008-07-26 23:55:291140
zelidrag@chromium.org85ed9d42010-06-08 22:37:441141 // Schedules a task on the file thread for execution of slower
1142 // initialization steps (such as plugin list generation) necessary
1143 // for sending the initial log. This avoids blocking the main UI
1144 // thread.
joi@chromium.orged10dd12011-12-07 12:03:421145 BrowserThread::PostDelayedTask(
1146 BrowserThread::FILE,
1147 FROM_HERE,
rsesek@chromium.orgd33e7cc2011-09-23 01:43:561148 base::Bind(&MetricsService::InitTaskGetHardwareClass,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401149 self_ptr_factory_.GetWeakPtr(),
xhwang@chromium.orgb3a25092013-05-28 22:08:161150 base::MessageLoop::current()->message_loop_proxy()),
tedvessenes@gmail.com7e560102012-03-08 20:58:421151 base::TimeDelta::FromSeconds(kInitializationDelaySeconds));
initial.commit09911bf2008-07-26 23:55:291152 }
1153}
1154
stuartmorgan@chromium.org410938e02012-10-24 16:33:591155void MetricsService::CloseCurrentLog() {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101156 if (!log_manager_.current_log())
initial.commit09911bf2008-07-26 23:55:291157 return;
1158
jar@google.com68475e602008-08-22 03:21:151159 // TODO(jar): Integrate bounds on log recording more consistently, so that we
1160 // can stop recording logs that are too big much sooner.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101161 if (log_manager_.current_log()->num_events() > kEventLimit) {
dsh@google.com553dba62009-02-24 19:08:231162 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101163 log_manager_.current_log()->num_events());
1164 log_manager_.DiscardCurrentLog();
stuartmorgan@chromium.org410938e02012-10-24 16:33:591165 OpenNewLog(); // Start trivial log to hold our histograms.
jar@google.com68475e602008-08-22 03:21:151166 }
1167
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101168 // Adds to ongoing logs.
1169 log_manager_.current_log()->set_hardware_class(hardware_class_);
jar@chromium.orgaccdfa62011-09-20 01:56:521170
jar@google.com0b33f80b2008-12-17 21:34:361171 // Put incremental data (histogram deltas, and realtime stats deltas) at the
jar@google.com147bbc0b2009-01-06 19:37:401172 // end of all log transmissions (initial log handles this separately).
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:381173 // RecordIncrementalStabilityElements only exists on the derived
1174 // MetricsLog class.
isherman@chromium.org279703f2012-01-20 22:23:261175 MetricsLog* current_log =
1176 static_cast<MetricsLog*>(log_manager_.current_log());
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:381177 DCHECK(current_log);
asvitkine@chromium.orgb3610d42014-05-19 18:07:231178 std::vector<variations::ActiveGroupId> synthetic_trials;
bengr@chromium.org60677562013-11-17 15:52:551179 GetCurrentSyntheticFieldTrials(&synthetic_trials);
asvitkine@chromium.org85791b0b2014-05-20 15:18:581180 current_log->RecordEnvironment(metrics_providers_.get(), plugins_,
1181 google_update_metrics_, synthetic_trials);
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361182 PrefService* pref = g_browser_process->local_state();
mpearson@chromium.org076961c2014-03-12 22:23:561183 base::TimeDelta incremental_uptime;
1184 base::TimeDelta uptime;
1185 GetUptimes(pref, &incremental_uptime, &uptime);
asvitkine@chromium.org85791b0b2014-05-20 15:18:581186 current_log->RecordStabilityMetrics(metrics_providers_.get(),
1187 incremental_uptime, uptime);
bengr@chromium.org60677562013-11-17 15:52:551188
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:381189 RecordCurrentHistograms();
asvitkine@chromium.org85791b0b2014-05-20 15:18:581190 current_log->RecordGeneralMetrics(metrics_providers_.get());
initial.commit09911bf2008-07-26 23:55:291191
stuartmorgan@chromium.org29948262012-03-01 12:15:081192 log_manager_.FinishCurrentLog();
initial.commit09911bf2008-07-26 23:55:291193}
1194
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101195void MetricsService::PushPendingLogsToPersistentStorage() {
asvitkine@chromium.org80a8f312013-12-16 18:00:301196 if (state_ < SENDING_INITIAL_STABILITY_LOG)
avi@google.com28ab7f92009-01-06 21:39:041197 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:291198
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101199 if (log_manager_.has_staged_log()) {
stuartmorgan@chromium.org7d41ae6d2012-06-26 08:53:031200 // We may race here, and send second copy of the log later.
holte@chromium.org7f07db62014-05-15 01:12:451201 metrics::PersistedLogs::StoreType store_type;
isherman@chromium.orge3eb0c42013-04-18 06:18:581202 if (current_fetch_.get())
holte@chromium.org7f07db62014-05-15 01:12:451203 store_type = metrics::PersistedLogs::PROVISIONAL_STORE;
isherman@chromium.orgdc61fe92012-06-12 00:13:501204 else
holte@chromium.org7f07db62014-05-15 01:12:451205 store_type = metrics::PersistedLogs::NORMAL_STORE;
stuartmorgan@chromium.orge7508d82012-05-03 15:59:531206 log_manager_.StoreStagedLogAsUnsent(store_type);
initial.commit09911bf2008-07-26 23:55:291207 }
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101208 DCHECK(!log_manager_.has_staged_log());
stuartmorgan@chromium.org410938e02012-10-24 16:33:591209 CloseCurrentLog();
asvitkine@chromium.org80a8f312013-12-16 18:00:301210 log_manager_.PersistUnsentLogs();
stuartmorgan@chromium.org7d41ae6d2012-06-26 08:53:031211
1212 // If there was a staged and/or current log, then there is now at least one
1213 // log waiting to be uploaded.
1214 if (log_manager_.has_unsent_logs())
1215 state_ = SENDING_OLD_LOGS;
initial.commit09911bf2008-07-26 23:55:291216}
1217
1218//------------------------------------------------------------------------------
1219// Transmission of logs methods
1220
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161221void MetricsService::StartSchedulerIfNecessary() {
stuartmorgan@chromium.org410938e02012-10-24 16:33:591222 // Never schedule cutting or uploading of logs in test mode.
1223 if (test_mode_active_)
1224 return;
1225
1226 // Even if reporting is disabled, the scheduler is needed to trigger the
1227 // creation of the initial log, which must be done in order for any logs to be
1228 // persisted on shutdown or backgrounding.
asvitkine@chromium.org80a8f312013-12-16 18:00:301229 if (recording_active() &&
1230 (reporting_active() || state_ < SENDING_INITIAL_STABILITY_LOG)) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161231 scheduler_->Start();
asvitkine@chromium.org80a8f312013-12-16 18:00:301232 }
initial.commit09911bf2008-07-26 23:55:291233}
1234
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161235void MetricsService::StartScheduledUpload() {
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471236 // If we're getting no notifications, then the log won't have much in it, and
1237 // it's possible the computer is about to go to sleep, so don't upload and
1238 // stop the scheduler.
stuartmorgan@chromium.org410938e02012-10-24 16:33:591239 // If recording has been turned off, the scheduler doesn't need to run.
1240 // If reporting is off, proceed if the initial log hasn't been created, since
1241 // that has to happen in order for logs to be cut and stored when persisting.
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471242 // TODO(stuartmorgan): Call Stop() on the schedule when reporting and/or
1243 // recording are turned off instead of letting it fire and then aborting.
1244 if (idle_since_last_transmission_ ||
stuartmorgan@chromium.org410938e02012-10-24 16:33:591245 !recording_active() ||
asvitkine@chromium.org80a8f312013-12-16 18:00:301246 (!reporting_active() && state_ >= SENDING_INITIAL_STABILITY_LOG)) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161247 scheduler_->Stop();
1248 scheduler_->UploadCancelled();
1249 return;
1250 }
1251
stuartmorgan@chromium.orgc15faf372012-07-11 06:01:341252 // If the callback was to upload an old log, but there no longer is one,
1253 // just report success back to the scheduler to begin the ongoing log
1254 // callbacks.
1255 // TODO(stuartmorgan): Consider removing the distinction between
1256 // SENDING_OLD_LOGS and SENDING_CURRENT_LOGS to simplify the state machine
1257 // now that the log upload flow is the same for both modes.
1258 if (state_ == SENDING_OLD_LOGS && !log_manager_.has_unsent_logs()) {
1259 state_ = SENDING_CURRENT_LOGS;
1260 scheduler_->UploadFinished(true /* healthy */, false /* no unsent logs */);
1261 return;
1262 }
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471263 // If there are unsent logs, send the next one. If not, start the asynchronous
1264 // process of finalizing the current log for upload.
1265 if (state_ == SENDING_OLD_LOGS) {
1266 DCHECK(log_manager_.has_unsent_logs());
1267 log_manager_.StageNextLogForUpload();
1268 SendStagedLog();
1269 } else {
1270 StartFinalLogInfoCollection();
1271 }
stuartmorgan@chromium.org29948262012-03-01 12:15:081272}
1273
1274void MetricsService::StartFinalLogInfoCollection() {
1275 // Begin the multi-step process of collecting memory usage histograms:
1276 // First spawn a task to collect the memory details; when that task is
1277 // finished, it will call OnMemoryDetailCollectionDone. That will in turn
1278 // call HistogramSynchronization to collect histograms from all renderers and
1279 // then call OnHistogramSynchronizationDone to continue processing.
isherman@chromium.orgd119f222012-06-08 02:33:271280 DCHECK(!waiting_for_asynchronous_reporting_step_);
1281 waiting_for_asynchronous_reporting_step_ = true;
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161282
dcheng@chromium.org2226c222011-11-22 00:08:401283 base::Closure callback =
1284 base::Bind(&MetricsService::OnMemoryDetailCollectionDone,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401285 self_ptr_factory_.GetWeakPtr());
sail@chromium.org84c988a2011-04-19 17:56:331286
dcheng@chromium.org2226c222011-11-22 00:08:401287 scoped_refptr<MetricsMemoryDetails> details(
1288 new MetricsMemoryDetails(callback));
jamescook@chromium.org4306df72012-04-20 18:58:571289 details->StartFetch(MemoryDetails::UPDATE_USER_METRICS);
sail@chromium.org84c988a2011-04-19 17:56:331290
1291 // Collect WebCore cache information to put into a histogram.
ananta@chromium.orgf3b1a082011-11-18 00:34:301292 for (content::RenderProcessHost::iterator i(
1293 content::RenderProcessHost::AllHostsIterator());
sail@chromium.org84c988a2011-04-19 17:56:331294 !i.IsAtEnd(); i.Advance())
ananta@chromium.org2ccf45c2011-08-19 23:35:501295 i.GetCurrentValue()->Send(new ChromeViewMsg_GetCacheResourceStats());
sail@chromium.org84c988a2011-04-19 17:56:331296}
1297
1298void MetricsService::OnMemoryDetailCollectionDone() {
jar@chromium.orgc9a3ef82009-05-28 22:02:461299 DCHECK(IsSingleThreaded());
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161300 // This function should only be called as the callback from an ansynchronous
1301 // step.
isherman@chromium.orgd119f222012-06-08 02:33:271302 DCHECK(waiting_for_asynchronous_reporting_step_);
jar@chromium.orgc9a3ef82009-05-28 22:02:461303
jar@chromium.orgc9a3ef82009-05-28 22:02:461304 // Create a callback_task for OnHistogramSynchronizationDone.
dcheng@chromium.org2226c222011-11-22 00:08:401305 base::Closure callback = base::Bind(
1306 &MetricsService::OnHistogramSynchronizationDone,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401307 self_ptr_factory_.GetWeakPtr());
jar@chromium.orgc9a3ef82009-05-28 22:02:461308
vitalybuka@chromium.orga3079832013-10-24 20:29:361309 base::TimeDelta timeout =
1310 base::TimeDelta::FromMilliseconds(kMaxHistogramGatheringWaitDuration);
1311
1312 DCHECK_EQ(num_async_histogram_fetches_in_progress_, 0);
1313
1314#if defined(OS_ANDROID)
1315 // Android has no service process.
1316 num_async_histogram_fetches_in_progress_ = 1;
1317#else // OS_ANDROID
1318 num_async_histogram_fetches_in_progress_ = 2;
1319 // Run requests to service and content in parallel.
1320 if (!ServiceProcessControl::GetInstance()->GetHistograms(callback, timeout)) {
1321 // Assume |num_async_histogram_fetches_in_progress_| is not changed by
1322 // |GetHistograms()|.
1323 DCHECK_EQ(num_async_histogram_fetches_in_progress_, 2);
1324 // Assign |num_async_histogram_fetches_in_progress_| above and decrement it
1325 // here to make code work even if |GetHistograms()| fired |callback|.
1326 --num_async_histogram_fetches_in_progress_;
1327 }
1328#endif // OS_ANDROID
1329
jar@chromium.orgc9a3ef82009-05-28 22:02:461330 // Set up the callback to task to call after we receive histograms from all
rtenneti@google.com83ab4a282012-07-12 18:19:451331 // child processes. Wait time specifies how long to wait before absolutely
jar@chromium.orgc9a3ef82009-05-28 22:02:461332 // calling us back on the task.
vitalybuka@chromium.orga3079832013-10-24 20:29:361333 content::FetchHistogramsAsynchronously(base::MessageLoop::current(), callback,
1334 timeout);
jar@chromium.orgc9a3ef82009-05-28 22:02:461335}
1336
1337void MetricsService::OnHistogramSynchronizationDone() {
initial.commit09911bf2008-07-26 23:55:291338 DCHECK(IsSingleThreaded());
stuartmorgan@chromium.org29948262012-03-01 12:15:081339 // This function should only be called as the callback from an ansynchronous
1340 // step.
isherman@chromium.orgd119f222012-06-08 02:33:271341 DCHECK(waiting_for_asynchronous_reporting_step_);
vitalybuka@chromium.orga3079832013-10-24 20:29:361342 DCHECK_GT(num_async_histogram_fetches_in_progress_, 0);
1343
1344 // Check if all expected requests finished.
1345 if (--num_async_histogram_fetches_in_progress_ > 0)
1346 return;
initial.commit09911bf2008-07-26 23:55:291347
isherman@chromium.orgd119f222012-06-08 02:33:271348 waiting_for_asynchronous_reporting_step_ = false;
stuartmorgan@chromium.org29948262012-03-01 12:15:081349 OnFinalLogInfoCollectionDone();
1350}
1351
1352void MetricsService::OnFinalLogInfoCollectionDone() {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161353 // If somehow there is a fetch in progress, we return and hope things work
1354 // out. The scheduler isn't informed since if this happens, the scheduler
1355 // will get a response from the upload.
isherman@chromium.orge3eb0c42013-04-18 06:18:581356 DCHECK(!current_fetch_.get());
1357 if (current_fetch_.get())
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161358 return;
1359
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471360 // Abort if metrics were turned off during the final info gathering.
stuartmorgan@chromium.org410938e02012-10-24 16:33:591361 if (!recording_active()) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161362 scheduler_->Stop();
1363 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:071364 return;
1365 }
1366
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471367 StageNewLog();
stuartmorgan@chromium.org410938e02012-10-24 16:33:591368
1369 // If logs shouldn't be uploaded, stop here. It's important that this check
1370 // be after StageNewLog(), otherwise the previous logs will never be loaded,
1371 // and thus the open log won't be persisted.
1372 // TODO(stuartmorgan): This is unnecessarily complicated; restructure loading
1373 // of previous logs to not require running part of the upload logic.
1374 // http://crbug.com/157337
1375 if (!reporting_active()) {
1376 scheduler_->Stop();
1377 scheduler_->UploadCancelled();
1378 return;
1379 }
1380
stuartmorgan@chromium.org29948262012-03-01 12:15:081381 SendStagedLog();
1382}
1383
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471384void MetricsService::StageNewLog() {
stuartmorgan@chromium.org29948262012-03-01 12:15:081385 if (log_manager_.has_staged_log())
1386 return;
1387
1388 switch (state_) {
1389 case INITIALIZED:
1390 case INIT_TASK_SCHEDULED: // We should be further along by now.
isherman@chromium.orgdc61fe92012-06-12 00:13:501391 NOTREACHED();
stuartmorgan@chromium.org29948262012-03-01 12:15:081392 return;
1393
1394 case INIT_TASK_DONE:
asvitkine@chromium.org80a8f312013-12-16 18:00:301395 if (has_initial_stability_log_) {
1396 // There's an initial stability log, ready to send.
1397 log_manager_.StageNextLogForUpload();
1398 has_initial_stability_log_ = false;
asvitkine@chromium.orgf61eb842014-01-22 10:59:131399 // Note: No need to call LoadPersistedUnsentLogs() here because unsent
1400 // logs have already been loaded by PrepareInitialStabilityLog().
asvitkine@chromium.org80a8f312013-12-16 18:00:301401 state_ = SENDING_INITIAL_STABILITY_LOG;
1402 } else {
asvitkine@chromium.orgb58b8b22014-04-08 22:40:331403 PrepareInitialMetricsLog();
asvitkine@chromium.orgf61eb842014-01-22 10:59:131404 // Load unsent logs (if any) from local state.
1405 log_manager_.LoadPersistedUnsentLogs();
asvitkine@chromium.org80a8f312013-12-16 18:00:301406 state_ = SENDING_INITIAL_METRICS_LOG;
1407 }
stuartmorgan@chromium.org29948262012-03-01 12:15:081408 break;
1409
1410 case SENDING_OLD_LOGS:
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471411 NOTREACHED(); // Shouldn't be staging a new log during old log sending.
1412 return;
stuartmorgan@chromium.org29948262012-03-01 12:15:081413
1414 case SENDING_CURRENT_LOGS:
stuartmorgan@chromium.org410938e02012-10-24 16:33:591415 CloseCurrentLog();
1416 OpenNewLog();
stuartmorgan@chromium.org29948262012-03-01 12:15:081417 log_manager_.StageNextLogForUpload();
1418 break;
1419
1420 default:
1421 NOTREACHED();
1422 return;
1423 }
1424
1425 DCHECK(log_manager_.has_staged_log());
1426}
1427
asvitkine@chromium.org80a8f312013-12-16 18:00:301428void MetricsService::PrepareInitialStabilityLog() {
1429 DCHECK_EQ(INITIALIZED, state_);
1430 PrefService* pref = g_browser_process->local_state();
1431 DCHECK_NE(0, pref->GetInteger(prefs::kStabilityCrashCount));
stuartmorgan@chromium.org29948262012-03-01 12:15:081432
asvitkine@chromium.org80a8f312013-12-16 18:00:301433 scoped_ptr<MetricsLog> initial_stability_log(
miu@chromium.org39076642014-05-05 20:32:551434 new MetricsLog(state_manager_->client_id(), session_id_,
asvitkine@chromium.org9eae4032014-04-09 19:15:191435 MetricsLog::INITIAL_STABILITY_LOG));
bolian@chromium.org2a321de32014-05-10 19:59:061436
1437 // Do not call NotifyOnDidCreateMetricsLog here because the stability
1438 // log describes stats from the _previous_ session.
1439
asvitkine@chromium.org80a8f312013-12-16 18:00:301440 if (!initial_stability_log->LoadSavedEnvironmentFromPrefs())
1441 return;
asvitkine@chromium.org85791b0b2014-05-20 15:18:581442
asvitkine@chromium.org80a8f312013-12-16 18:00:301443 log_manager_.LoadPersistedUnsentLogs();
1444
1445 log_manager_.PauseCurrentLog();
asvitkine@chromium.org9eae4032014-04-09 19:15:191446 log_manager_.BeginLoggingWithLog(initial_stability_log.release());
asvitkine@chromium.org85791b0b2014-05-20 15:18:581447
1448 // Note: Some stability providers may record stability stats via histograms,
1449 // so this call has to be after BeginLoggingWithLog().
1450 MetricsLog* current_log =
1451 static_cast<MetricsLog*>(log_manager_.current_log());
1452 current_log->RecordStabilityMetrics(metrics_providers_.get(),
1453 base::TimeDelta(), base::TimeDelta());
1454
kkimlabs@chromium.orgc778687a2014-02-11 14:46:451455#if defined(OS_ANDROID)
1456 ConvertAndroidStabilityPrefsToHistograms(pref);
1457 RecordCurrentStabilityHistograms();
1458#endif // defined(OS_ANDROID)
asvitkine@chromium.org85791b0b2014-05-20 15:18:581459
1460 // Note: RecordGeneralMetrics() intentionally not called since this log is for
1461 // stability stats from a previous session only.
1462
asvitkine@chromium.org80a8f312013-12-16 18:00:301463 log_manager_.FinishCurrentLog();
1464 log_manager_.ResumePausedLog();
1465
1466 // Store unsent logs, including the stability log that was just saved, so
1467 // that they're not lost in case of a crash before upload time.
1468 log_manager_.PersistUnsentLogs();
1469
1470 has_initial_stability_log_ = true;
1471}
1472
asvitkine@chromium.orgb58b8b22014-04-08 22:40:331473void MetricsService::PrepareInitialMetricsLog() {
asvitkine@chromium.org80a8f312013-12-16 18:00:301474 DCHECK(state_ == INIT_TASK_DONE || state_ == SENDING_INITIAL_STABILITY_LOG);
1475 initial_metrics_log_->set_hardware_class(hardware_class_);
asvitkine@chromium.org0edf8762013-11-21 18:33:301476
asvitkine@chromium.orgb3610d42014-05-19 18:07:231477 std::vector<variations::ActiveGroupId> synthetic_trials;
bengr@chromium.org60677562013-11-17 15:52:551478 GetCurrentSyntheticFieldTrials(&synthetic_trials);
asvitkine@chromium.org85791b0b2014-05-20 15:18:581479 initial_metrics_log_->RecordEnvironment(metrics_providers_.get(), plugins_,
1480 google_update_metrics_,
asvitkine@chromium.org80a8f312013-12-16 18:00:301481 synthetic_trials);
asvitkine@chromium.org0edf8762013-11-21 18:33:301482 PrefService* pref = g_browser_process->local_state();
mpearson@chromium.org076961c2014-03-12 22:23:561483 base::TimeDelta incremental_uptime;
1484 base::TimeDelta uptime;
1485 GetUptimes(pref, &incremental_uptime, &uptime);
stuartmorgan@chromium.org29948262012-03-01 12:15:081486
1487 // Histograms only get written to the current log, so make the new log current
1488 // before writing them.
1489 log_manager_.PauseCurrentLog();
asvitkine@chromium.org9eae4032014-04-09 19:15:191490 log_manager_.BeginLoggingWithLog(initial_metrics_log_.release());
asvitkine@chromium.org85791b0b2014-05-20 15:18:581491
1492 // Note: Some stability providers may record stability stats via histograms,
1493 // so this call has to be after BeginLoggingWithLog().
1494 MetricsLog* current_log =
1495 static_cast<MetricsLog*>(log_manager_.current_log());
1496 current_log->RecordStabilityMetrics(metrics_providers_.get(),
1497 base::TimeDelta(), base::TimeDelta());
1498
kkimlabs@chromium.orgc778687a2014-02-11 14:46:451499#if defined(OS_ANDROID)
1500 ConvertAndroidStabilityPrefsToHistograms(pref);
1501#endif // defined(OS_ANDROID)
stuartmorgan@chromium.org29948262012-03-01 12:15:081502 RecordCurrentHistograms();
asvitkine@chromium.org85791b0b2014-05-20 15:18:581503
1504 current_log->RecordGeneralMetrics(metrics_providers_.get());
1505
stuartmorgan@chromium.org29948262012-03-01 12:15:081506 log_manager_.FinishCurrentLog();
1507 log_manager_.ResumePausedLog();
1508
1509 DCHECK(!log_manager_.has_staged_log());
1510 log_manager_.StageNextLogForUpload();
1511}
1512
stuartmorgan@chromium.org29948262012-03-01 12:15:081513void MetricsService::SendStagedLog() {
1514 DCHECK(log_manager_.has_staged_log());
1515
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101516 PrepareFetchWithStagedLog();
petersont@google.comd01b8732008-10-16 02:18:071517
isherman@chromium.orge3eb0c42013-04-18 06:18:581518 bool upload_created = (current_fetch_.get() != NULL);
isherman@chromium.orgd6bebb92012-06-13 23:14:551519 UMA_HISTOGRAM_BOOLEAN("UMA.UploadCreation", upload_created);
1520 if (!upload_created) {
petersont@google.comd01b8732008-10-16 02:18:071521 // Compression failed, and log discarded :-/.
isherman@chromium.orgdc61fe92012-06-12 00:13:501522 // Skip this upload and hope things work out next time.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101523 log_manager_.DiscardStagedLog();
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161524 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:071525 return;
1526 }
1527
isherman@chromium.orgd119f222012-06-08 02:33:271528 DCHECK(!waiting_for_asynchronous_reporting_step_);
isherman@chromium.orgd119f222012-06-08 02:33:271529 waiting_for_asynchronous_reporting_step_ = true;
isherman@chromium.orgdc61fe92012-06-12 00:13:501530
isherman@chromium.orge3eb0c42013-04-18 06:18:581531 current_fetch_->Start();
petersont@google.comd01b8732008-10-16 02:18:071532
1533 HandleIdleSinceLastTransmission(true);
1534}
1535
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101536void MetricsService::PrepareFetchWithStagedLog() {
isherman@chromium.orgdc61fe92012-06-12 00:13:501537 DCHECK(log_manager_.has_staged_log());
pkasting@chromium.orgcac78842008-11-27 01:02:201538
isherman@chromium.orgfe58acc22012-02-29 01:29:581539 // Prepare the protobuf version.
isherman@chromium.orge3eb0c42013-04-18 06:18:581540 DCHECK(!current_fetch_.get());
isherman@chromium.org5f3e1642013-05-05 03:37:341541 if (log_manager_.has_staged_log()) {
isherman@chromium.orge3eb0c42013-04-18 06:18:581542 current_fetch_.reset(net::URLFetcher::Create(
isherman@chromium.org5f3e1642013-05-05 03:37:341543 GURL(kServerUrl), net::URLFetcher::POST, this));
isherman@chromium.orge3eb0c42013-04-18 06:18:581544 current_fetch_->SetRequestContext(
isherman@chromium.orgfe58acc22012-02-29 01:29:581545 g_browser_process->system_request_context());
asharif@chromium.org537c638d2013-07-04 00:49:191546
holte@chromium.org7f07db62014-05-15 01:12:451547 std::string log_text = log_manager_.staged_log();
asharif@chromium.org8df71322013-09-13 18:40:001548 std::string compressed_log_text;
1549 bool compression_successful = chrome::GzipCompress(log_text,
1550 &compressed_log_text);
1551 DCHECK(compression_successful);
1552 if (compression_successful) {
1553 current_fetch_->SetUploadData(kMimeType, compressed_log_text);
1554 // Tell the server that we're uploading gzipped protobufs.
1555 current_fetch_->SetExtraRequestHeaders("content-encoding: gzip");
asvitkine@chromium.orgcfee9aa52013-10-19 17:53:051556 const std::string hash =
1557 base::HexEncode(log_manager_.staged_log_hash().data(),
1558 log_manager_.staged_log_hash().size());
1559 DCHECK(!hash.empty());
1560 current_fetch_->AddExtraRequestHeader("X-Chrome-UMA-Log-SHA1: " + hash);
asharif@chromium.org8df71322013-09-13 18:40:001561 UMA_HISTOGRAM_PERCENTAGE(
1562 "UMA.ProtoCompressionRatio",
1563 100 * compressed_log_text.size() / log_text.size());
1564 UMA_HISTOGRAM_CUSTOM_COUNTS(
1565 "UMA.ProtoGzippedKBSaved",
1566 (log_text.size() - compressed_log_text.size()) / 1024,
1567 1, 2000, 50);
asharif@chromium.org537c638d2013-07-04 00:49:191568 }
asharif@chromium.org537c638d2013-07-04 00:49:191569
isherman@chromium.orgfe58acc22012-02-29 01:29:581570 // We already drop cookies server-side, but we might as well strip them out
1571 // client-side as well.
isherman@chromium.orge3eb0c42013-04-18 06:18:581572 current_fetch_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES |
1573 net::LOAD_DO_NOT_SEND_COOKIES);
isherman@chromium.orgfe58acc22012-02-29 01:29:581574 }
initial.commit09911bf2008-07-26 23:55:291575}
1576
akalin@chromium.org10c2d692012-05-11 05:32:231577void MetricsService::OnURLFetchComplete(const net::URLFetcher* source) {
isherman@chromium.orgd119f222012-06-08 02:33:271578 DCHECK(waiting_for_asynchronous_reporting_step_);
isherman@chromium.orgfe58acc22012-02-29 01:29:581579
1580 // We're not allowed to re-use the existing |URLFetcher|s, so free them here.
isherman@chromium.orge3eb0c42013-04-18 06:18:581581 // Note however that |source| is aliased to the fetcher, so we should be
isherman@chromium.org4266def22012-05-17 01:02:401582 // careful not to delete it too early.
isherman@chromium.orge3eb0c42013-04-18 06:18:581583 DCHECK_EQ(current_fetch_.get(), source);
1584 scoped_ptr<net::URLFetcher> s(current_fetch_.Pass());
isherman@chromium.orgfe58acc22012-02-29 01:29:581585
isherman@chromium.orgdc61fe92012-06-12 00:13:501586 int response_code = source->GetResponseCode();
isherman@chromium.orgfe58acc22012-02-29 01:29:581587
isherman@chromium.orgdc61fe92012-06-12 00:13:501588 // Log a histogram to track response success vs. failure rates.
isherman@chromium.orge3eb0c42013-04-18 06:18:581589 UMA_HISTOGRAM_ENUMERATION("UMA.UploadResponseStatus.Protobuf",
1590 ResponseCodeToStatus(response_code),
1591 NUM_RESPONSE_STATUSES);
isherman@chromium.orgfe58acc22012-02-29 01:29:581592
stuartmorgan@chromium.orge7508d82012-05-03 15:59:531593 // If the upload was provisionally stored, drop it now that the upload is
1594 // known to have gone through.
1595 log_manager_.DiscardLastProvisionalStore();
initial.commit09911bf2008-07-26 23:55:291596
isherman@chromium.orgdc61fe92012-06-12 00:13:501597 bool upload_succeeded = response_code == 200;
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161598
jar@chromium.org0eb34fee2009-01-21 08:04:381599 // Provide boolean for error recovery (allow us to ignore response_code).
paul@chromium.orgdc6f4962009-02-13 01:25:501600 bool discard_log = false;
holte@chromium.org7f07db62014-05-15 01:12:451601 const size_t log_size = log_manager_.staged_log().length();
isherman@chromium.orgdc61fe92012-06-12 00:13:501602 if (!upload_succeeded && log_size > kUploadLogAvoidRetransmitSize) {
1603 UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
1604 static_cast<int>(log_size));
jar@chromium.org0eb34fee2009-01-21 08:04:381605 discard_log = true;
isherman@chromium.orgdc61fe92012-06-12 00:13:501606 } else if (response_code == 400) {
jar@chromium.org0eb34fee2009-01-21 08:04:381607 // Bad syntax. Retransmission won't work.
jar@chromium.org0eb34fee2009-01-21 08:04:381608 discard_log = true;
jar@google.com68475e602008-08-22 03:21:151609 }
1610
isherman@chromium.orge3eb0c42013-04-18 06:18:581611 if (upload_succeeded || discard_log)
isherman@chromium.org5f3e1642013-05-05 03:37:341612 log_manager_.DiscardStagedLog();
isherman@chromium.orgdc61fe92012-06-12 00:13:501613
1614 waiting_for_asynchronous_reporting_step_ = false;
1615
1616 if (!log_manager_.has_staged_log()) {
initial.commit09911bf2008-07-26 23:55:291617 switch (state_) {
asvitkine@chromium.org80a8f312013-12-16 18:00:301618 case SENDING_INITIAL_STABILITY_LOG:
1619 // Store the updated list to disk now that the removed log is uploaded.
1620 log_manager_.PersistUnsentLogs();
asvitkine@chromium.orgb58b8b22014-04-08 22:40:331621 PrepareInitialMetricsLog();
asvitkine@chromium.org80a8f312013-12-16 18:00:301622 SendStagedLog();
1623 state_ = SENDING_INITIAL_METRICS_LOG;
1624 break;
1625
1626 case SENDING_INITIAL_METRICS_LOG:
1627 // The initial metrics log never gets persisted to local state, so it's
1628 // not necessary to call log_manager_.PersistUnsentLogs() here.
1629 // TODO(asvitkine): It should be persisted like the initial stability
1630 // log and old unsent logs. http://crbug.com/328417
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471631 state_ = log_manager_.has_unsent_logs() ? SENDING_OLD_LOGS
1632 : SENDING_CURRENT_LOGS;
initial.commit09911bf2008-07-26 23:55:291633 break;
1634
initial.commit09911bf2008-07-26 23:55:291635 case SENDING_OLD_LOGS:
stuartmorgan@chromium.orgd53e2232011-06-30 15:54:571636 // Store the updated list to disk now that the removed log is uploaded.
asvitkine@chromium.org80a8f312013-12-16 18:00:301637 log_manager_.PersistUnsentLogs();
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471638 if (!log_manager_.has_unsent_logs())
1639 state_ = SENDING_CURRENT_LOGS;
initial.commit09911bf2008-07-26 23:55:291640 break;
1641
1642 case SENDING_CURRENT_LOGS:
1643 break;
1644
1645 default:
jar@chromium.orga063c102010-07-22 22:20:191646 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291647 break;
1648 }
petersont@google.comd01b8732008-10-16 02:18:071649
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101650 if (log_manager_.has_unsent_logs())
isherman@chromium.orged0fd002012-04-25 23:10:341651 DCHECK_LT(state_, SENDING_CURRENT_LOGS);
initial.commit09911bf2008-07-26 23:55:291652 }
petersont@google.com252873ef2008-08-04 21:59:451653
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161654 // Error 400 indicates a problem with the log, not with the server, so
1655 // don't consider that a sign that the server is in trouble.
isherman@chromium.orgdc61fe92012-06-12 00:13:501656 bool server_is_healthy = upload_succeeded || response_code == 400;
asvitkine@chromium.org80a8f312013-12-16 18:00:301657 // Don't notify the scheduler that the upload is finished if we've only sent
1658 // the initial stability log, but not yet the initial metrics log (treat the
1659 // two as a single unit of work as far as the scheduler is concerned).
1660 if (state_ != SENDING_INITIAL_METRICS_LOG) {
1661 scheduler_->UploadFinished(server_is_healthy,
1662 log_manager_.has_unsent_logs());
1663 }
rtenneti@chromium.orgd67d1052011-06-09 05:11:411664
1665 // Collect network stats if UMA upload succeeded.
isherman@chromium.orgb8ddb052012-04-19 02:36:061666 IOThread* io_thread = g_browser_process->io_thread();
1667 if (server_is_healthy && io_thread) {
1668 chrome_browser_net::CollectNetworkStats(network_stats_server_, io_thread);
simonjam@chromium.orgadbb3762012-03-09 22:20:081669 chrome_browser_net::CollectPipeliningCapabilityStatsOnUIThread(
isherman@chromium.orgb8ddb052012-04-19 02:36:061670 http_pipelining_test_server_, io_thread);
simonjam@chromium.orgaa312812013-04-30 19:46:051671#if defined(OS_WIN)
1672 chrome::CollectTimeTicksStats();
1673#endif
simonjam@chromium.orgadbb3762012-03-09 22:20:081674 }
initial.commit09911bf2008-07-26 23:55:291675}
1676
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511677void MetricsService::IncrementPrefValue(const char* path) {
cpu@google.come73c01972008-08-13 00:18:241678 PrefService* pref = g_browser_process->local_state();
1679 DCHECK(pref);
1680 int value = pref->GetInteger(path);
1681 pref->SetInteger(path, value + 1);
1682}
1683
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511684void MetricsService::IncrementLongPrefsValue(const char* path) {
robertshield@google.com0bb1a622009-03-04 03:22:321685 PrefService* pref = g_browser_process->local_state();
1686 DCHECK(pref);
1687 int64 value = pref->GetInt64(path);
jar@chromium.orgb42c5e42010-06-03 20:43:251688 pref->SetInt64(path, value + 1);
robertshield@google.com0bb1a622009-03-04 03:22:321689}
1690
rlp@chromium.org752a5262013-06-23 14:53:421691void MetricsService::LogLoadStarted(content::WebContents* web_contents) {
ben@chromium.orge6e30ac2014-01-13 21:24:391692 content::RecordAction(base::UserMetricsAction("PageLoad"));
jar@chromium.orgdd8d12a2011-09-02 02:10:151693 HISTOGRAM_ENUMERATION("Chrome.UmaPageloadCounter", 1, 2);
cpu@google.come73c01972008-08-13 00:18:241694 IncrementPrefValue(prefs::kStabilityPageLoadCount);
robertshield@google.com0bb1a622009-03-04 03:22:321695 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
jar@google.com0b33f80b2008-12-17 21:34:361696 // We need to save the prefs, as page load count is a critical stat, and it
1697 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291698}
1699
jar@chromium.orgc3721482012-03-23 16:21:481700void MetricsService::LogRendererCrash(content::RenderProcessHost* host,
1701 base::TerminationStatus status,
jam@chromium.orgf1675202012-07-09 15:18:001702 int exit_code) {
aa@chromium.org6f371442011-11-09 06:45:461703 bool was_extension_process =
jamescook@chromium.orgfafdc842014-01-17 18:09:081704 extensions::ProcessMap::Get(host->GetBrowserContext())
1705 ->Contains(host->GetID());
jar@chromium.orgc3721482012-03-23 16:21:481706 if (status == base::TERMINATION_STATUS_PROCESS_CRASHED ||
1707 status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
eroman@chromium.orgd7c1fa62012-06-15 23:35:301708 if (was_extension_process) {
jochen@chromium.org718eab62011-10-05 21:16:521709 IncrementPrefValue(prefs::kStabilityExtensionRendererCrashCount);
eroman@chromium.orgd7c1fa62012-06-15 23:35:301710
eroman@chromium.org1026afd2013-03-20 14:28:541711 UMA_HISTOGRAM_SPARSE_SLOWLY("CrashExitCodes.Extension",
1712 MapCrashExitCodeForHistogram(exit_code));
eroman@chromium.orgd7c1fa62012-06-15 23:35:301713 } else {
jochen@chromium.org718eab62011-10-05 21:16:521714 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291715
eroman@chromium.org1026afd2013-03-20 14:28:541716 UMA_HISTOGRAM_SPARSE_SLOWLY("CrashExitCodes.Renderer",
1717 MapCrashExitCodeForHistogram(exit_code));
eroman@chromium.orgd7c1fa62012-06-15 23:35:301718 }
1719
jochen@chromium.org718eab62011-10-05 21:16:521720 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildCrashes",
1721 was_extension_process ? 2 : 1);
jar@chromium.orgc3721482012-03-23 16:21:481722 } else if (status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED) {
jochen@chromium.org718eab62011-10-05 21:16:521723 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildKills",
1724 was_extension_process ? 2 : 1);
jam@chromium.orgf1675202012-07-09 15:18:001725 } else if (status == base::TERMINATION_STATUS_STILL_RUNNING) {
1726 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.DisconnectedAlive",
jochen@chromium.org718eab62011-10-05 21:16:521727 was_extension_process ? 2 : 1);
jochen@chromium.org718eab62011-10-05 21:16:521728 }
asvitkine@chromium.org80a8f312013-12-16 18:00:301729}
asargent@chromium.org1f085622009-12-04 05:33:451730
initial.commit09911bf2008-07-26 23:55:291731void MetricsService::LogRendererHang() {
cpu@google.come73c01972008-08-13 00:18:241732 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291733}
1734
jar@chromium.orgc0c55e92011-09-10 18:47:301735bool MetricsService::UmaMetricsProperlyShutdown() {
1736 CHECK(clean_shutdown_status_ == CLEANLY_SHUTDOWN ||
1737 clean_shutdown_status_ == NEED_TO_SHUTDOWN);
1738 return clean_shutdown_status_ == CLEANLY_SHUTDOWN;
1739}
1740
bengr@chromium.org60677562013-11-17 15:52:551741void MetricsService::RegisterSyntheticFieldTrial(
1742 const SyntheticTrialGroup& trial) {
1743 for (size_t i = 0; i < synthetic_trial_groups_.size(); ++i) {
1744 if (synthetic_trial_groups_[i].id.name == trial.id.name) {
1745 if (synthetic_trial_groups_[i].id.group != trial.id.group) {
1746 synthetic_trial_groups_[i].id.group = trial.id.group;
asvitkine@chromium.org7a5c07812014-02-26 11:45:411747 synthetic_trial_groups_[i].start_time = base::TimeTicks::Now();
bengr@chromium.org60677562013-11-17 15:52:551748 }
1749 return;
1750 }
1751 }
1752
asvitkine@chromium.org7a5c07812014-02-26 11:45:411753 SyntheticTrialGroup trial_group = trial;
1754 trial_group.start_time = base::TimeTicks::Now();
bengr@chromium.org60677562013-11-17 15:52:551755 synthetic_trial_groups_.push_back(trial_group);
1756}
1757
asvitkine@chromium.org85791b0b2014-05-20 15:18:581758void MetricsService::RegisterMetricsProvider(
1759 scoped_ptr<metrics::MetricsProvider> provider) {
1760 DCHECK_EQ(INITIALIZED, state_);
1761 metrics_providers_.push_back(provider.release());
1762}
1763
blundell@chromium.org61b0d482014-05-20 14:49:101764void MetricsService::CheckForClonedInstall(
1765 scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
1766 state_manager_->CheckForClonedInstall(task_runner);
jwd@chromium.org99c892d2014-03-24 18:11:211767}
1768
bengr@chromium.org60677562013-11-17 15:52:551769void MetricsService::GetCurrentSyntheticFieldTrials(
asvitkine@chromium.orgb3610d42014-05-19 18:07:231770 std::vector<variations::ActiveGroupId>* synthetic_trials) {
bengr@chromium.org60677562013-11-17 15:52:551771 DCHECK(synthetic_trials);
1772 synthetic_trials->clear();
1773 const MetricsLog* current_log =
1774 static_cast<const MetricsLog*>(log_manager_.current_log());
1775 for (size_t i = 0; i < synthetic_trial_groups_.size(); ++i) {
1776 if (synthetic_trial_groups_[i].start_time <= current_log->creation_time())
1777 synthetic_trials->push_back(synthetic_trial_groups_[i].id);
1778 }
1779}
1780
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381781void MetricsService::LogCleanShutdown() {
jar@chromium.orgacd55b32011-09-05 17:35:311782 // Redundant hack to write pref ASAP.
nileshagrawal@chromium.org84c384e2013-03-01 23:20:191783 MarkAppCleanShutdownAndCommit();
1784
jar@chromium.orgc0c55e92011-09-10 18:47:301785 // Redundant setting to assure that we always reset this value at shutdown
1786 // (and that we don't use some alternate path, and not call LogCleanShutdown).
1787 clean_shutdown_status_ = CLEANLY_SHUTDOWN;
jar@chromium.orgacd55b32011-09-05 17:35:311788
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381789 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6a6d0d12013-10-28 15:58:191790 PrefService* pref = g_browser_process->local_state();
1791 pref->SetInteger(prefs::kStabilityExecutionPhase,
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:211792 MetricsService::SHUTDOWN_COMPLETE);
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381793}
1794
petkov@chromium.orgc1834a92011-01-21 18:21:031795#if defined(OS_CHROMEOS)
1796void MetricsService::LogChromeOSCrash(const std::string &crash_type) {
1797 if (crash_type == "user")
1798 IncrementPrefValue(prefs::kStabilityOtherUserCrashCount);
1799 else if (crash_type == "kernel")
1800 IncrementPrefValue(prefs::kStabilityKernelCrashCount);
1801 else if (crash_type == "uncleanshutdown")
1802 IncrementPrefValue(prefs::kStabilitySystemUncleanShutdownCount);
1803 else
1804 NOTREACHED() << "Unexpected Chrome OS crash type " << crash_type;
1805 // Wake up metrics logs sending if necessary now that new
1806 // log data is available.
1807 HandleIdleSinceLastTransmission(false);
1808}
1809#endif // OS_CHROMEOS
1810
brettw@chromium.org650b2d52013-02-10 03:41:451811void MetricsService::LogPluginLoadingError(const base::FilePath& plugin_path) {
jam@chromium.orgd7bd3e52013-07-21 04:29:201812 content::WebPluginInfo plugin;
bauerb@chromium.orgcd937072012-07-02 09:00:291813 bool success =
1814 content::PluginService::GetInstance()->GetPluginInfoByPath(plugin_path,
1815 &plugin);
1816 DCHECK(success);
1817 ChildProcessStats& stats = child_process_stats_buffer_[plugin.name];
1818 // Initialize the type if this entry is new.
1819 if (stats.process_type == content::PROCESS_TYPE_UNKNOWN) {
1820 // The plug-in process might not actually of type PLUGIN (which means
1821 // NPAPI), but we only care that it is *a* plug-in process.
1822 stats.process_type = content::PROCESS_TYPE_PLUGIN;
1823 } else {
1824 DCHECK(IsPluginProcess(stats.process_type));
1825 }
1826 stats.loading_errors++;
1827}
1828
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:401829MetricsService::ChildProcessStats& MetricsService::GetChildProcessStats(
1830 const content::ChildProcessData& data) {
brettw@chromium.org439f1e32013-12-09 20:09:091831 const base::string16& child_name = data.name;
jam@chromium.orgf3b357692013-03-22 05:16:131832 if (!ContainsKey(child_process_stats_buffer_, child_name)) {
1833 child_process_stats_buffer_[child_name] =
1834 ChildProcessStats(data.process_type);
1835 }
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:401836 return child_process_stats_buffer_[child_name];
initial.commit09911bf2008-07-26 23:55:291837}
1838
initial.commit09911bf2008-07-26 23:55:291839void MetricsService::RecordPluginChanges(PrefService* pref) {
battre@chromium.orgf8628c22011-04-05 12:10:181840 ListPrefUpdate update(pref, prefs::kStabilityPluginStats);
avi@chromium.orgcb1078de2013-12-23 20:04:221841 base::ListValue* plugins = update.Get();
initial.commit09911bf2008-07-26 23:55:291842 DCHECK(plugins);
1843
avi@chromium.orgcb1078de2013-12-23 20:04:221844 for (base::ListValue::iterator value_iter = plugins->begin();
initial.commit09911bf2008-07-26 23:55:291845 value_iter != plugins->end(); ++value_iter) {
avi@chromium.orgcb1078de2013-12-23 20:04:221846 if (!(*value_iter)->IsType(base::Value::TYPE_DICTIONARY)) {
jar@chromium.orga063c102010-07-22 22:20:191847 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291848 continue;
1849 }
1850
avi@chromium.orgcb1078de2013-12-23 20:04:221851 base::DictionaryValue* plugin_dict =
1852 static_cast<base::DictionaryValue*>(*value_iter);
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511853 std::string plugin_name;
nsylvain@chromium.org8e50b602009-03-03 22:59:431854 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
nsylvain@chromium.org6470ee8f2009-03-03 20:46:401855 if (plugin_name.empty()) {
jar@chromium.orga063c102010-07-22 22:20:191856 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291857 continue;
1858 }
1859
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511860 // TODO(viettrungluu): remove conversions
avi@chromium.org6778fed2013-12-24 20:09:371861 base::string16 name16 = base::UTF8ToUTF16(plugin_name);
evan@chromium.org68b9e72b2011-08-05 23:08:221862 if (child_process_stats_buffer_.find(name16) ==
1863 child_process_stats_buffer_.end()) {
initial.commit09911bf2008-07-26 23:55:291864 continue;
evan@chromium.org68b9e72b2011-08-05 23:08:221865 }
initial.commit09911bf2008-07-26 23:55:291866
evan@chromium.org68b9e72b2011-08-05 23:08:221867 ChildProcessStats stats = child_process_stats_buffer_[name16];
initial.commit09911bf2008-07-26 23:55:291868 if (stats.process_launches) {
1869 int launches = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431870 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291871 launches += stats.process_launches;
nsylvain@chromium.org8e50b602009-03-03 22:59:431872 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291873 }
1874 if (stats.process_crashes) {
1875 int crashes = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431876 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291877 crashes += stats.process_crashes;
nsylvain@chromium.org8e50b602009-03-03 22:59:431878 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291879 }
1880 if (stats.instances) {
1881 int instances = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431882 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291883 instances += stats.instances;
nsylvain@chromium.org8e50b602009-03-03 22:59:431884 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291885 }
bauerb@chromium.orgcd937072012-07-02 09:00:291886 if (stats.loading_errors) {
1887 int loading_errors = 0;
1888 plugin_dict->GetInteger(prefs::kStabilityPluginLoadingErrors,
1889 &loading_errors);
1890 loading_errors += stats.loading_errors;
1891 plugin_dict->SetInteger(prefs::kStabilityPluginLoadingErrors,
1892 loading_errors);
1893 }
initial.commit09911bf2008-07-26 23:55:291894
evan@chromium.org68b9e72b2011-08-05 23:08:221895 child_process_stats_buffer_.erase(name16);
initial.commit09911bf2008-07-26 23:55:291896 }
1897
1898 // Now go through and add dictionaries for plugins that didn't already have
1899 // reports in Local State.
brettw@chromium.orgd2065e062013-12-12 23:49:521900 for (std::map<base::string16, ChildProcessStats>::iterator cache_iter =
jam@chromium.orga27a9382009-02-11 23:55:101901 child_process_stats_buffer_.begin();
1902 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
jam@chromium.orga27a9382009-02-11 23:55:101903 ChildProcessStats stats = cache_iter->second;
gregoryd@google.com0d84c5d2009-10-09 01:10:421904
1905 // Insert only plugins information into the plugins list.
petkov@chromium.org8d5f1dae2011-11-11 14:30:411906 if (!IsPluginProcess(stats.process_type))
gregoryd@google.com0d84c5d2009-10-09 01:10:421907 continue;
1908
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511909 // TODO(viettrungluu): remove conversion
avi@chromium.org6778fed2013-12-24 20:09:371910 std::string plugin_name = base::UTF16ToUTF8(cache_iter->first);
gregoryd@google.com0d84c5d2009-10-09 01:10:421911
avi@chromium.orgcb1078de2013-12-23 20:04:221912 base::DictionaryValue* plugin_dict = new base::DictionaryValue;
initial.commit09911bf2008-07-26 23:55:291913
nsylvain@chromium.org8e50b602009-03-03 22:59:431914 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
1915 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:291916 stats.process_launches);
nsylvain@chromium.org8e50b602009-03-03 22:59:431917 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:291918 stats.process_crashes);
nsylvain@chromium.org8e50b602009-03-03 22:59:431919 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:291920 stats.instances);
bauerb@chromium.orgcd937072012-07-02 09:00:291921 plugin_dict->SetInteger(prefs::kStabilityPluginLoadingErrors,
1922 stats.loading_errors);
initial.commit09911bf2008-07-26 23:55:291923 plugins->Append(plugin_dict);
1924 }
jam@chromium.orga27a9382009-02-11 23:55:101925 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291926}
1927
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:041928bool MetricsService::ShouldLogEvents() {
1929 // We simply don't log events to UMA if there is a single incognito
initial.commit09911bf2008-07-26 23:55:291930 // session visible. The problem is that we always notify using the orginal
1931 // profile in order to simplify notification processing.
tfarina@chromium.orge764e582012-08-01 03:01:291932 return !chrome::IsOffTheRecordSessionActive();
initial.commit09911bf2008-07-26 23:55:291933}
1934
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511935void MetricsService::RecordBooleanPrefValue(const char* path, bool value) {
initial.commit09911bf2008-07-26 23:55:291936 DCHECK(IsSingleThreaded());
1937
1938 PrefService* pref = g_browser_process->local_state();
1939 DCHECK(pref);
1940
1941 pref->SetBoolean(path, value);
1942 RecordCurrentState(pref);
1943}
1944
1945void MetricsService::RecordCurrentState(PrefService* pref) {
robertshield@google.com0bb1a622009-03-04 03:22:321946 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291947
1948 RecordPluginChanges(pref);
1949}
1950
petkov@chromium.org8d5f1dae2011-11-11 14:30:411951// static
jam@chromium.orgf3b357692013-03-22 05:16:131952bool MetricsService::IsPluginProcess(int process_type) {
1953 return (process_type == content::PROCESS_TYPE_PLUGIN ||
1954 process_type == content::PROCESS_TYPE_PPAPI_PLUGIN ||
1955 process_type == content::PROCESS_TYPE_PPAPI_BROKER);
petkov@chromium.org8d5f1dae2011-11-11 14:30:411956}
1957
sreeram@chromium.org3819f2ee2011-08-21 09:44:381958// static
1959bool MetricsServiceHelper::IsMetricsReportingEnabled() {
1960 bool result = false;
1961 const PrefService* local_state = g_browser_process->local_state();
1962 if (local_state) {
1963 const PrefService::Preference* uma_pref =
1964 local_state->FindPreference(prefs::kMetricsReportingEnabled);
1965 if (uma_pref) {
1966 bool success = uma_pref->GetValue()->GetAsBoolean(&result);
1967 DCHECK(success);
1968 }
1969 }
1970 return result;
1971}
elijahtaylor@chromium.org1ef13cf2014-03-21 22:44:011972
1973bool MetricsServiceHelper::IsCrashReportingEnabled() {
1974#if defined(GOOGLE_CHROME_BUILD)
1975#if defined(OS_CHROMEOS)
1976 bool reporting_enabled = false;
1977 chromeos::CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref,
1978 &reporting_enabled);
1979 return reporting_enabled;
1980#elif defined(OS_ANDROID)
1981 // Android has its own settings for metrics / crash uploading.
1982 const PrefService* prefs = g_browser_process->local_state();
1983 return prefs->GetBoolean(prefs::kCrashReportingEnabled);
1984#else
1985 return MetricsServiceHelper::IsMetricsReportingEnabled();
1986#endif
1987#else
1988 return false;
1989#endif
1990}
bolian@chromium.org2a321de32014-05-10 19:59:061991
1992void MetricsServiceHelper::AddMetricsServiceObserver(
1993 MetricsServiceObserver* observer) {
1994 MetricsService* metrics_service = g_browser_process->metrics_service();
1995 if (metrics_service)
1996 metrics_service->AddObserver(observer);
1997}
1998
1999void MetricsServiceHelper::RemoveMetricsServiceObserver(
2000 MetricsServiceObserver* observer) {
2001 MetricsService* metrics_service = g_browser_process->metrics_service();
2002 if (metrics_service)
2003 metrics_service->RemoveObserver(observer);
2004}