blob: 55b9f074448ef95e89dbf79093db0ff210c69443 [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"
asvitkine@chromium.orgcf4dc612014-05-21 12:33:43191#include "chrome/browser/metrics/omnibox_metrics_provider.h"
isherman@chromium.orged0fd002012-04-25 23:10:34192#include "chrome/browser/metrics/tracking_synchronizer.h"
dtrainor@chromium.org10b132b02012-07-27 20:46:18193#include "chrome/browser/ui/browser_otr_state.h"
rogerm@chromium.org261ab7c2013-08-19 15:04:58194#include "chrome/common/chrome_constants.h"
jar@chromium.org92745242009-06-12 16:52:21195#include "chrome/common/chrome_switches.h"
rsesek@chromium.org264c0acac2013-10-01 13:33:30196#include "chrome/common/crash_keys.h"
initial.commit09911bf2008-07-26 23:55:29197#include "chrome/common/pref_names.h"
jam@chromium.orge09ba552009-02-05 03:26:29198#include "chrome/common/render_messages.h"
motek@chromium.orgcffb2002014-05-22 03:58:39199#include "chrome/common/variations/variations_util.h"
isherman@chromium.org09dee82d2014-05-22 14:00:53200#include "components/metrics/metrics_log_base.h"
bsimonnet@chromium.org064107e2014-05-02 00:59:06201#include "components/metrics/metrics_log_manager.h"
holte@chromium.org7f07db62014-05-15 01:12:45202#include "components/metrics/metrics_pref_names.h"
motek@chromium.org14bb46692014-05-20 17:16:45203#include "components/metrics/metrics_reporting_scheduler.h"
asvitkine@chromium.org73929422014-05-22 08:19:05204#include "components/metrics/metrics_service_client.h"
asvitkine@chromium.org50ae9f12013-08-29 18:03:22205#include "components/variations/entropy_provider.h"
bengr@chromium.org60677562013-11-17 15:52:55206#include "components/variations/metrics_util.h"
jam@chromium.org4967f792012-01-20 22:14:40207#include "content/public/browser/child_process_data.h"
rtenneti@google.com83ab4a282012-07-12 18:19:45208#include "content/public/browser/histogram_fetcher.h"
tfarina@chromium.org09d31d52012-03-11 22:30:27209#include "content/public/browser/load_notification_details.h"
jam@chromium.orgad50def52011-10-19 23:17:07210#include "content/public/browser/notification_service.h"
jam@chromium.org3a5180ae2011-12-21 02:39:38211#include "content/public/browser/plugin_service.h"
ananta@chromium.orgf3b1a082011-11-18 00:34:30212#include "content/public/browser/render_process_host.h"
mpearson@chromium.org5d490e42012-08-30 05:16:43213#include "content/public/browser/user_metrics.h"
avi@chromium.org459f3502012-09-17 17:08:12214#include "content/public/browser/web_contents.h"
yael.aharon@intel.comd5d383252013-07-04 14:44:32215#include "content/public/common/process_type.h"
jam@chromium.orgd7bd3e52013-07-21 04:29:20216#include "content/public/common/webplugininfo.h"
benwells@chromium.org50de9aa22013-11-14 06:30:34217#include "extensions/browser/process_map.h"
isherman@chromium.orgfe58acc22012-02-29 01:29:58218#include "net/base/load_flags.h"
akalin@chromium.org3dc1bc42012-06-19 08:20:53219#include "net/url_request/url_fetcher.h"
initial.commit09911bf2008-07-26 23:55:29220
rvargas@google.com5ccaa412009-11-13 22:00:16221#if defined(OS_CHROMEOS)
elijahtaylor@chromium.org1ef13cf2014-03-21 22:44:01222#include "chrome/browser/chromeos/settings/cros_settings.h"
stevenjb@chromium.org279690f82013-10-09 08:23:52223#include "chromeos/system/statistics_provider.h"
rvargas@google.com5ccaa412009-11-13 22:00:16224#endif
225
eroman@chromium.orgd7c1fa62012-06-15 23:35:30226#if defined(OS_WIN)
227#include <windows.h> // Needed for STATUS_* codes
rogerm@chromium.org261ab7c2013-08-19 15:04:58228#include "base/win/registry.h"
asvitkine@chromium.org68e679232014-05-22 07:49:15229#include "chrome/browser/metrics/google_update_metrics_provider_win.h"
eroman@chromium.orgd7c1fa62012-06-15 23:35:30230#endif
231
asvitkine@chromium.org6ba11eb2014-05-22 08:17:46232#if defined(OS_ANDROID)
233// TODO(asvitkine): Move this out of MetricsService.
234#include "chrome/browser/metrics/android_metrics_provider.h"
235#else
jianli@chromium.orgcbf160aa2013-11-05 17:54:55236#include "chrome/browser/service_process/service_process_control.h"
vitalybuka@chromium.orga3079832013-10-24 20:29:36237#endif
238
dsh@google.come1acf6f2008-10-27 20:43:33239using base::Time;
joi@chromium.org631bb742011-11-02 11:29:39240using content::BrowserThread;
jam@chromium.org4967f792012-01-20 22:14:40241using content::ChildProcessData;
tfarina@chromium.org09d31d52012-03-11 22:30:27242using content::LoadNotificationDetails;
jam@chromium.org3a5180ae2011-12-21 02:39:38243using content::PluginService;
bsimonnet@chromium.org064107e2014-05-02 00:59:06244using metrics::MetricsLogManager;
dsh@google.come1acf6f2008-10-27 20:43:33245
isherman@chromium.orgfe58acc22012-02-29 01:29:58246namespace {
isherman@chromium.orgb2a4812d2012-02-28 05:31:31247
isherman@chromium.orgfe58acc22012-02-29 01:29:58248// Check to see that we're being called on only one thread.
249bool IsSingleThreaded() {
250 static base::PlatformThreadId thread_id = 0;
251 if (!thread_id)
252 thread_id = base::PlatformThread::CurrentId();
253 return base::PlatformThread::CurrentId() == thread_id;
254}
255
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16256// The delay, in seconds, after starting recording before doing expensive
257// initialization work.
dfalcantara@chromium.org12180f82012-10-10 21:13:30258#if defined(OS_ANDROID) || defined(OS_IOS)
259// On mobile devices, a significant portion of sessions last less than a minute.
260// Use a shorter timer on these platforms to avoid losing data.
261// TODO(dfalcantara): To avoid delaying startup, tighten up initialization so
262// that it occurs after the user gets their initial page.
263const int kInitializationDelaySeconds = 5;
264#else
isherman@chromium.orgfe58acc22012-02-29 01:29:58265const int kInitializationDelaySeconds = 30;
dfalcantara@chromium.org12180f82012-10-10 21:13:30266#endif
petersont@google.com252873ef2008-08-04 21:59:45267
jar@chromium.orgc9a3ef82009-05-28 22:02:46268// This specifies the amount of time to wait for all renderers to send their
269// data.
isherman@chromium.orgfe58acc22012-02-29 01:29:58270const int kMaxHistogramGatheringWaitDuration = 60000; // 60 seconds.
jar@chromium.orgc9a3ef82009-05-28 22:02:46271
stuartmorgan@chromium.org54702c92011-04-15 15:06:43272// The maximum number of events in a log uploaded to the UMA server.
isherman@chromium.orgfe58acc22012-02-29 01:29:58273const int kEventLimit = 2400;
jar@google.com68475e602008-08-22 03:21:15274
275// If an upload fails, and the transmission was over this byte count, then we
276// will discard the log, and not try to retransmit it. We also don't persist
277// the log to the prefs for transmission during the next chrome session if this
278// limit is exceeded.
isherman@chromium.orgfe58acc22012-02-29 01:29:58279const size_t kUploadLogAvoidRetransmitSize = 50000;
initial.commit09911bf2008-07-26 23:55:29280
tedvessenes@gmail.comfc4252a72012-01-12 21:58:47281// Interval, in minutes, between state saves.
isherman@chromium.orgfe58acc22012-02-29 01:29:58282const int kSaveStateIntervalMinutes = 5;
283
isherman@chromium.org4266def22012-05-17 01:02:40284enum ResponseStatus {
285 UNKNOWN_FAILURE,
286 SUCCESS,
287 BAD_REQUEST, // Invalid syntax or log too large.
isherman@chromium.org9f5c1ce82012-05-23 23:11:28288 NO_RESPONSE,
isherman@chromium.org4266def22012-05-17 01:02:40289 NUM_RESPONSE_STATUSES
290};
291
292ResponseStatus ResponseCodeToStatus(int response_code) {
293 switch (response_code) {
294 case 200:
295 return SUCCESS;
296 case 400:
297 return BAD_REQUEST;
isherman@chromium.org9f5c1ce82012-05-23 23:11:28298 case net::URLFetcher::RESPONSE_CODE_INVALID:
299 return NO_RESPONSE;
isherman@chromium.org4266def22012-05-17 01:02:40300 default:
301 return UNKNOWN_FAILURE;
302 }
303}
304
eroman@chromium.orgd7c1fa62012-06-15 23:35:30305// Converts an exit code into something that can be inserted into our
306// histograms (which expect non-negative numbers less than MAX_INT).
307int MapCrashExitCodeForHistogram(int exit_code) {
308#if defined(OS_WIN)
309 // Since |abs(STATUS_GUARD_PAGE_VIOLATION) == MAX_INT| it causes problems in
310 // histograms.cc. Solve this by remapping it to a smaller value, which
311 // hopefully doesn't conflict with other codes.
312 if (exit_code == STATUS_GUARD_PAGE_VIOLATION)
313 return 0x1FCF7EC3; // Randomly picked number.
314#endif
315
316 return std::abs(exit_code);
317}
318
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19319void MarkAppCleanShutdownAndCommit() {
320 PrefService* pref = g_browser_process->local_state();
321 pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19322 pref->SetInteger(prefs::kStabilityExecutionPhase,
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21323 MetricsService::SHUTDOWN_COMPLETE);
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19324 // Start writing right away (write happens on a different thread).
325 pref->CommitPendingWrite();
326}
327
asvitkine@chromium.org20f999b52012-08-24 22:32:59328} // namespace
initial.commit09911bf2008-07-26 23:55:29329
bengr@chromium.org60677562013-11-17 15:52:55330
asvitkine@chromium.org7a5c07812014-02-26 11:45:41331SyntheticTrialGroup::SyntheticTrialGroup(uint32 trial, uint32 group) {
bengr@chromium.org60677562013-11-17 15:52:55332 id.name = trial;
333 id.group = group;
334}
335
336SyntheticTrialGroup::~SyntheticTrialGroup() {
337}
338
jar@chromium.orgc0c55e92011-09-10 18:47:30339// static
340MetricsService::ShutdownCleanliness MetricsService::clean_shutdown_status_ =
341 MetricsService::CLEANLY_SHUTDOWN;
342
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19343MetricsService::ExecutionPhase MetricsService::execution_phase_ =
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21344 MetricsService::UNINITIALIZED_PHASE;
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19345
erg@google.com679082052010-07-21 21:30:13346// This is used to quickly log stats from child process related notifications in
347// MetricsService::child_stats_buffer_. The buffer's contents are transferred
348// out when Local State is periodically saved. The information is then
349// reported to the UMA server on next launch.
350struct MetricsService::ChildProcessStats {
351 public:
jam@chromium.orgf3b357692013-03-22 05:16:13352 explicit ChildProcessStats(int process_type)
erg@google.com679082052010-07-21 21:30:13353 : process_launches(0),
354 process_crashes(0),
355 instances(0),
bauerb@chromium.orgcd937072012-07-02 09:00:29356 loading_errors(0),
jam@chromium.orgf3b357692013-03-22 05:16:13357 process_type(process_type) {}
erg@google.com679082052010-07-21 21:30:13358
359 // This constructor is only used by the map to return some default value for
360 // an index for which no value has been assigned.
361 ChildProcessStats()
362 : process_launches(0),
pkasting@chromium.orgd88bf0a2011-08-30 23:55:57363 process_crashes(0),
364 instances(0),
bauerb@chromium.orgcd937072012-07-02 09:00:29365 loading_errors(0),
jam@chromium.orgbd5d6cf2011-12-01 00:39:12366 process_type(content::PROCESS_TYPE_UNKNOWN) {}
erg@google.com679082052010-07-21 21:30:13367
368 // The number of times that the given child process has been launched
369 int process_launches;
370
371 // The number of times that the given child process has crashed
372 int process_crashes;
373
374 // The number of instances of this child process that have been created.
375 // An instance is a DOM object rendered by this child process during a page
376 // load.
377 int instances;
378
bauerb@chromium.orgcd937072012-07-02 09:00:29379 // The number of times there was an error loading an instance of this child
380 // process.
381 int loading_errors;
382
jam@chromium.orgf3b357692013-03-22 05:16:13383 int process_type;
erg@google.com679082052010-07-21 21:30:13384};
initial.commit09911bf2008-07-26 23:55:29385
sail@chromium.org84c988a2011-04-19 17:56:33386// Handles asynchronous fetching of memory details.
387// Will run the provided task after finished.
388class MetricsMemoryDetails : public MemoryDetails {
389 public:
dcheng@chromium.org2226c222011-11-22 00:08:40390 explicit MetricsMemoryDetails(const base::Closure& callback)
391 : callback_(callback) {}
sail@chromium.org84c988a2011-04-19 17:56:33392
rsleevi@chromium.orgb94584a2013-02-07 03:02:08393 virtual void OnDetailsAvailable() OVERRIDE {
xhwang@chromium.orgb3a25092013-05-28 22:08:16394 base::MessageLoop::current()->PostTask(FROM_HERE, callback_);
sail@chromium.org84c988a2011-04-19 17:56:33395 }
396
397 private:
rsleevi@chromium.orgb94584a2013-02-07 03:02:08398 virtual ~MetricsMemoryDetails() {}
sail@chromium.org84c988a2011-04-19 17:56:33399
dcheng@chromium.org2226c222011-11-22 00:08:40400 base::Closure callback_;
sail@chromium.org84c988a2011-04-19 17:56:33401 DISALLOW_COPY_AND_ASSIGN(MetricsMemoryDetails);
402};
403
initial.commit09911bf2008-07-26 23:55:29404// static
joi@chromium.orgb1de2c72013-02-06 02:45:47405void MetricsService::RegisterPrefs(PrefRegistrySimple* registry) {
initial.commit09911bf2008-07-26 23:55:29406 DCHECK(IsSingleThreaded());
miu@chromium.org39076642014-05-05 20:32:55407 metrics::MetricsStateManager::RegisterPrefs(registry);
408
joi@chromium.orgb1de2c72013-02-06 02:45:47409 registry->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
410 registry->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
dcheng@chromium.org007b3f82013-04-09 08:46:45411 registry->RegisterStringPref(prefs::kStabilityStatsVersion, std::string());
joi@chromium.orgb1de2c72013-02-06 02:45:47412 registry->RegisterInt64Pref(prefs::kStabilityStatsBuildTime, 0);
413 registry->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19414 registry->RegisterIntegerPref(prefs::kStabilityExecutionPhase,
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21415 UNINITIALIZED_PHASE);
joi@chromium.orgb1de2c72013-02-06 02:45:47416 registry->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
417 registry->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
418 registry->RegisterIntegerPref(prefs::kStabilityLaunchCount, 0);
419 registry->RegisterIntegerPref(prefs::kStabilityCrashCount, 0);
420 registry->RegisterIntegerPref(prefs::kStabilityIncompleteSessionEndCount, 0);
421 registry->RegisterIntegerPref(prefs::kStabilityPageLoadCount, 0);
422 registry->RegisterIntegerPref(prefs::kStabilityRendererCrashCount, 0);
423 registry->RegisterIntegerPref(prefs::kStabilityExtensionRendererCrashCount,
424 0);
425 registry->RegisterIntegerPref(prefs::kStabilityRendererHangCount, 0);
426 registry->RegisterIntegerPref(prefs::kStabilityChildProcessCrashCount, 0);
427 registry->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationFail, 0);
428 registry->RegisterIntegerPref(prefs::kStabilityBreakpadRegistrationSuccess,
429 0);
430 registry->RegisterIntegerPref(prefs::kStabilityDebuggerPresent, 0);
431 registry->RegisterIntegerPref(prefs::kStabilityDebuggerNotPresent, 0);
petkov@chromium.orgc1834a92011-01-21 18:21:03432#if defined(OS_CHROMEOS)
joi@chromium.orgb1de2c72013-02-06 02:45:47433 registry->RegisterIntegerPref(prefs::kStabilityOtherUserCrashCount, 0);
434 registry->RegisterIntegerPref(prefs::kStabilityKernelCrashCount, 0);
435 registry->RegisterIntegerPref(prefs::kStabilitySystemUncleanShutdownCount, 0);
petkov@chromium.orgc1834a92011-01-21 18:21:03436#endif // OS_CHROMEOS
cpu@google.come73c01972008-08-13 00:18:24437
asvitkine@chromium.org0f2f7792013-11-28 16:09:14438 registry->RegisterStringPref(prefs::kStabilitySavedSystemProfile,
439 std::string());
440 registry->RegisterStringPref(prefs::kStabilitySavedSystemProfileHash,
441 std::string());
442
holte@chromium.org7f07db62014-05-15 01:12:45443 registry->RegisterListPref(metrics::prefs::kMetricsInitialLogs);
444 registry->RegisterListPref(metrics::prefs::kMetricsOngoingLogs);
robertshield@google.com0bb1a622009-03-04 03:22:32445
isherman@chromium.org5c181552013-02-07 09:12:52446 registry->RegisterInt64Pref(prefs::kInstallDate, 0);
joi@chromium.orgb1de2c72013-02-06 02:45:47447 registry->RegisterInt64Pref(prefs::kUninstallMetricsPageLoadCount, 0);
448 registry->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
joi@chromium.orgb1de2c72013-02-06 02:45:47449 registry->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
450 registry->RegisterInt64Pref(prefs::kUninstallLastLaunchTimeSec, 0);
451 registry->RegisterInt64Pref(prefs::kUninstallLastObservedRunTimeSec, 0);
kkimlabs@chromium.orgc778687a2014-02-11 14:46:45452
453#if defined(OS_ANDROID)
asvitkine@chromium.org6ba11eb2014-05-22 08:17:46454 // TODO(asvitkine): Move this out of here.
455 AndroidMetricsProvider::RegisterPrefs(registry);
kkimlabs@chromium.orgc778687a2014-02-11 14:46:45456#endif // defined(OS_ANDROID)
initial.commit09911bf2008-07-26 23:55:29457}
458
isherman@chromium.org728de072014-05-21 09:20:32459MetricsService::MetricsService(metrics::MetricsStateManager* state_manager,
460 metrics::MetricsServiceClient* client)
holte@chromium.org7f07db62014-05-15 01:12:45461 : MetricsServiceBase(g_browser_process->local_state(),
462 kUploadLogAvoidRetransmitSize),
463 state_manager_(state_manager),
isherman@chromium.org728de072014-05-21 09:20:32464 client_(client),
jwd@chromium.org37d4709a2014-03-29 03:07:40465 recording_active_(false),
petersont@google.comd01b8732008-10-16 02:18:07466 reporting_active_(false),
stuartmorgan@chromium.org410938e02012-10-24 16:33:59467 test_mode_active_(false),
petersont@google.comd01b8732008-10-16 02:18:07468 state_(INITIALIZED),
asvitkine@chromium.org80a8f312013-12-16 18:00:30469 has_initial_stability_log_(false),
petersont@google.comd01b8732008-10-16 02:18:07470 idle_since_last_transmission_(false),
asvitkine@chromium.org80a8f312013-12-16 18:00:30471 session_id_(-1),
initial.commit09911bf2008-07-26 23:55:29472 next_window_id_(0),
tfarina@chromium.org9c009092013-05-01 03:14:09473 self_ptr_factory_(this),
474 state_saver_factory_(this),
stevet@chromium.orge5354322012-08-09 23:07:37475 waiting_for_asynchronous_reporting_step_(false),
miu@chromium.org39076642014-05-05 20:32:55476 num_async_histogram_fetches_in_progress_(0) {
initial.commit09911bf2008-07-26 23:55:29477 DCHECK(IsSingleThreaded());
miu@chromium.org39076642014-05-05 20:32:55478 DCHECK(state_manager_);
isherman@chromium.org728de072014-05-21 09:20:32479 DCHECK(client_);
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16480
asvitkine@chromium.org6ba11eb2014-05-22 08:17:46481#if defined(OS_ANDROID)
482 // TODO(asvitkine): Move this out of MetricsService.
483 RegisterMetricsProvider(
484 scoped_ptr<metrics::MetricsProvider>(new AndroidMetricsProvider(
485 g_browser_process->local_state())));
486#endif // defined(OS_ANDROID)
487
asvitkine@chromium.orgcf4dc612014-05-21 12:33:43488 // TODO(asvitkine): Move this out of MetricsService.
489 RegisterMetricsProvider(
490 scoped_ptr<metrics::MetricsProvider>(new OmniboxMetricsProvider));
491
asvitkine@chromium.org68e679232014-05-22 07:49:15492#if defined(OS_WIN)
493 google_update_metrics_provider_ = new GoogleUpdateMetricsProviderWin;
494 RegisterMetricsProvider(scoped_ptr<metrics::MetricsProvider>(
495 google_update_metrics_provider_));
496#endif
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:40497 BrowserChildProcessObserver::Add(this);
initial.commit09911bf2008-07-26 23:55:29498}
499
500MetricsService::~MetricsService() {
stuartmorgan@chromium.org410938e02012-10-24 16:33:59501 DisableRecording();
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:40502
503 BrowserChildProcessObserver::Remove(this);
initial.commit09911bf2008-07-26 23:55:29504}
505
miu@chromium.org39076642014-05-05 20:32:55506void MetricsService::InitializeMetricsRecordingState() {
507 InitializeMetricsState();
asvitkine@chromium.org80a8f312013-12-16 18:00:30508
509 base::Closure callback = base::Bind(&MetricsService::StartScheduledUpload,
510 self_ptr_factory_.GetWeakPtr());
511 scheduler_.reset(new MetricsReportingScheduler(callback));
512}
513
petersont@google.comd01b8732008-10-16 02:18:07514void MetricsService::Start() {
stuartmorgan@chromium.orgb1c8dc02011-04-13 18:32:04515 HandleIdleSinceLastTransmission(false);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59516 EnableRecording();
517 EnableReporting();
petersont@google.comd01b8732008-10-16 02:18:07518}
519
miu@chromium.org39076642014-05-05 20:32:55520bool MetricsService::StartIfMetricsReportingEnabled() {
521 const bool enabled = state_manager_->IsMetricsReportingEnabled();
522 if (enabled)
523 Start();
524 return enabled;
525}
526
stuartmorgan@chromium.org410938e02012-10-24 16:33:59527void MetricsService::StartRecordingForTests() {
528 test_mode_active_ = true;
529 EnableRecording();
530 DisableReporting();
petersont@google.comd01b8732008-10-16 02:18:07531}
532
533void MetricsService::Stop() {
stuartmorgan@chromium.orgb1c8dc02011-04-13 18:32:04534 HandleIdleSinceLastTransmission(false);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59535 DisableReporting();
536 DisableRecording();
537}
538
539void MetricsService::EnableReporting() {
540 if (reporting_active_)
541 return;
542 reporting_active_ = true;
543 StartSchedulerIfNecessary();
544}
545
546void MetricsService::DisableReporting() {
547 reporting_active_ = false;
petersont@google.comd01b8732008-10-16 02:18:07548}
549
joi@chromium.orgedafd4c2011-05-10 17:18:53550std::string MetricsService::GetClientId() {
miu@chromium.org39076642014-05-05 20:32:55551 return state_manager_->client_id();
joi@chromium.orgedafd4c2011-05-10 17:18:53552}
553
asvitkine@chromium.org20f999b52012-08-24 22:32:59554scoped_ptr<const base::FieldTrial::EntropyProvider>
miu@chromium.org39076642014-05-05 20:32:55555MetricsService::CreateEntropyProvider() {
556 // TODO(asvitkine): Refactor the code so that MetricsService does not expose
557 // this method.
558 return state_manager_->CreateEntropyProvider();
jam@chromium.org5cbeeef72012-02-08 02:05:18559}
560
stuartmorgan@chromium.org410938e02012-10-24 16:33:59561void MetricsService::EnableRecording() {
initial.commit09911bf2008-07-26 23:55:29562 DCHECK(IsSingleThreaded());
563
stuartmorgan@chromium.org410938e02012-10-24 16:33:59564 if (recording_active_)
initial.commit09911bf2008-07-26 23:55:29565 return;
stuartmorgan@chromium.org410938e02012-10-24 16:33:59566 recording_active_ = true;
initial.commit09911bf2008-07-26 23:55:29567
miu@chromium.org39076642014-05-05 20:32:55568 state_manager_->ForceClientIdCreation();
569 crash_keys::SetClientID(state_manager_->client_id());
stuartmorgan@chromium.org410938e02012-10-24 16:33:59570 if (!log_manager_.current_log())
571 OpenNewLog();
pkasting@chromium.org005ef3e2009-05-22 20:55:46572
asvitkine@chromium.org85791b0b2014-05-20 15:18:58573 for (size_t i = 0; i < metrics_providers_.size(); ++i)
574 metrics_providers_[i]->OnRecordingEnabled();
575
stuartmorgan@chromium.org410938e02012-10-24 16:33:59576 SetUpNotifications(&registrar_, this);
ben@chromium.orge6e30ac2014-01-13 21:24:39577 base::RemoveActionCallback(action_callback_);
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:22578 action_callback_ = base::Bind(&MetricsService::OnUserAction,
579 base::Unretained(this));
ben@chromium.orge6e30ac2014-01-13 21:24:39580 base::AddActionCallback(action_callback_);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59581}
582
583void MetricsService::DisableRecording() {
584 DCHECK(IsSingleThreaded());
585
586 if (!recording_active_)
587 return;
588 recording_active_ = false;
589
ben@chromium.orge6e30ac2014-01-13 21:24:39590 base::RemoveActionCallback(action_callback_);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59591 registrar_.RemoveAll();
asvitkine@chromium.org85791b0b2014-05-20 15:18:58592
593 for (size_t i = 0; i < metrics_providers_.size(); ++i)
594 metrics_providers_[i]->OnRecordingDisabled();
595
stuartmorgan@chromium.org410938e02012-10-24 16:33:59596 PushPendingLogsToPersistentStorage();
597 DCHECK(!log_manager_.has_staged_log());
initial.commit09911bf2008-07-26 23:55:29598}
599
petersont@google.comd01b8732008-10-16 02:18:07600bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29601 DCHECK(IsSingleThreaded());
petersont@google.comd01b8732008-10-16 02:18:07602 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29603}
604
petersont@google.comd01b8732008-10-16 02:18:07605bool MetricsService::reporting_active() const {
606 DCHECK(IsSingleThreaded());
607 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29608}
609
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15610// static
jam@chromium.org6c2381d2011-10-19 02:52:53611void MetricsService::SetUpNotifications(
612 content::NotificationRegistrar* registrar,
613 content::NotificationObserver* observer) {
jam@chromium.org6c2381d2011-10-19 02:52:53614 registrar->Add(observer, content::NOTIFICATION_LOAD_START,
jam@chromium.orgad50def52011-10-19 23:17:07615 content::NotificationService::AllSources());
jam@chromium.org6c2381d2011-10-19 02:52:53616 registrar->Add(observer, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
jam@chromium.orgad50def52011-10-19 23:17:07617 content::NotificationService::AllSources());
avi@chromium.org42d8d7582013-11-09 01:24:38618 registrar->Add(observer, content::NOTIFICATION_RENDER_WIDGET_HOST_HANG,
jam@chromium.orgad50def52011-10-19 23:17:07619 content::NotificationService::AllSources());
rtenneti@chromium.org87ef9ea2011-02-26 03:15:15620}
621
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:40622void MetricsService::BrowserChildProcessHostConnected(
623 const content::ChildProcessData& data) {
624 GetChildProcessStats(data).process_launches++;
625}
626
627void MetricsService::BrowserChildProcessCrashed(
628 const content::ChildProcessData& data) {
629 GetChildProcessStats(data).process_crashes++;
630 // Exclude plugin crashes from the count below because we report them via
631 // a separate UMA metric.
jam@chromium.orgf3b357692013-03-22 05:16:13632 if (!IsPluginProcess(data.process_type))
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:40633 IncrementPrefValue(prefs::kStabilityChildProcessCrashCount);
634}
635
636void MetricsService::BrowserChildProcessInstanceCreated(
637 const content::ChildProcessData& data) {
638 GetChildProcessStats(data).instances++;
639}
640
ananta@chromium.org432115822011-07-10 15:52:27641void MetricsService::Observe(int type,
jam@chromium.org6c2381d2011-10-19 02:52:53642 const content::NotificationSource& source,
643 const content::NotificationDetails& details) {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10644 DCHECK(log_manager_.current_log());
initial.commit09911bf2008-07-26 23:55:29645 DCHECK(IsSingleThreaded());
646
ananta@chromium.org432115822011-07-10 15:52:27647 switch (type) {
rlp@chromium.org752a5262013-06-23 14:53:42648 case content::NOTIFICATION_LOAD_START: {
649 content::NavigationController* controller =
650 content::Source<content::NavigationController>(source).ptr();
651 content::WebContents* web_contents = controller->GetWebContents();
652 LogLoadStarted(web_contents);
initial.commit09911bf2008-07-26 23:55:29653 break;
rlp@chromium.org752a5262013-06-23 14:53:42654 }
initial.commit09911bf2008-07-26 23:55:29655
ananta@chromium.org432115822011-07-10 15:52:27656 case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: {
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04657 content::RenderProcessHost::RendererClosedDetails* process_details =
658 content::Details<
659 content::RenderProcessHost::RendererClosedDetails>(
660 details).ptr();
661 content::RenderProcessHost* host =
662 content::Source<content::RenderProcessHost>(source).ptr();
663 LogRendererCrash(
664 host, process_details->status, process_details->exit_code);
initial.commit09911bf2008-07-26 23:55:29665 break;
ananta@chromium.org1226abb2010-06-10 18:01:28666 }
initial.commit09911bf2008-07-26 23:55:29667
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04668 case content::NOTIFICATION_RENDER_WIDGET_HOST_HANG:
669 LogRendererHang();
initial.commit09911bf2008-07-26 23:55:29670 break;
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04671
672 default:
asvitkine@chromium.orgcf4dc612014-05-21 12:33:43673 NOTREACHED();
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04674 }
petersont@google.comd01b8732008-10-16 02:18:07675}
676
677void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
678 // If there wasn't a lot of action, maybe the computer was asleep, in which
679 // case, the log transmissions should have stopped. Here we start them up
680 // again.
pkasting@chromium.orgcac78842008-11-27 01:02:20681 if (!in_idle && idle_since_last_transmission_)
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16682 StartSchedulerIfNecessary();
pkasting@chromium.orgcac78842008-11-27 01:02:20683 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29684}
685
isherman@chromium.orgd7ea39e2014-05-22 03:59:18686void MetricsService::OnApplicationNotIdle() {
687 if (recording_active_)
688 HandleIdleSinceLastTransmission(false);
689}
690
initial.commit09911bf2008-07-26 23:55:29691void MetricsService::RecordStartOfSessionEnd() {
stuartmorgan@chromium.org466f3c12011-03-23 21:20:38692 LogCleanShutdown();
initial.commit09911bf2008-07-26 23:55:29693 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
694}
695
696void MetricsService::RecordCompletedSessionEnd() {
stuartmorgan@chromium.org466f3c12011-03-23 21:20:38697 LogCleanShutdown();
initial.commit09911bf2008-07-26 23:55:29698 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
699}
700
stuartmorgan@chromium.org410938e02012-10-24 16:33:59701#if defined(OS_ANDROID) || defined(OS_IOS)
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39702void MetricsService::OnAppEnterBackground() {
703 scheduler_->Stop();
704
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19705 MarkAppCleanShutdownAndCommit();
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39706
707 // At this point, there's no way of knowing when the process will be
708 // killed, so this has to be treated similar to a shutdown, closing and
709 // persisting all logs. Unlinke a shutdown, the state is primed to be ready
710 // to continue logging and uploading if the process does return.
asvitkine@chromium.org80a8f312013-12-16 18:00:30711 if (recording_active() && state_ >= SENDING_INITIAL_STABILITY_LOG) {
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39712 PushPendingLogsToPersistentStorage();
stuartmorgan@chromium.org410938e02012-10-24 16:33:59713 // Persisting logs closes the current log, so start recording a new log
714 // immediately to capture any background work that might be done before the
715 // process is killed.
716 OpenNewLog();
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39717 }
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39718}
719
720void MetricsService::OnAppEnterForeground() {
721 PrefService* pref = g_browser_process->local_state();
722 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
723
724 StartSchedulerIfNecessary();
725}
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19726#else
727void MetricsService::LogNeedForCleanShutdown() {
728 PrefService* pref = g_browser_process->local_state();
729 pref->SetBoolean(prefs::kStabilityExitedCleanly, false);
730 // Redundant setting to be sure we call for a clean shutdown.
731 clean_shutdown_status_ = NEED_TO_SHUTDOWN;
732}
733#endif // defined(OS_ANDROID) || defined(OS_IOS)
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39734
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21735// static
736void MetricsService::SetExecutionPhase(ExecutionPhase execution_phase) {
737 execution_phase_ = execution_phase;
738 PrefService* pref = g_browser_process->local_state();
739 pref->SetInteger(prefs::kStabilityExecutionPhase, execution_phase_);
740}
741
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16742void MetricsService::RecordBreakpadRegistration(bool success) {
jar@google.com68475e602008-08-22 03:21:15743 if (!success)
cpu@google.come73c01972008-08-13 00:18:24744 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
745 else
746 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
747}
748
749void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
750 if (!has_debugger)
751 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
752 else
jar@google.com68475e602008-08-22 03:21:15753 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
cpu@google.come73c01972008-08-13 00:18:24754}
755
rogerm@chromium.org261ab7c2013-08-19 15:04:58756#if defined(OS_WIN)
757void MetricsService::CountBrowserCrashDumpAttempts() {
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45758 // Open the registry key for iteration.
rogerm@chromium.org261ab7c2013-08-19 15:04:58759 base::win::RegKey regkey;
760 if (regkey.Open(HKEY_CURRENT_USER,
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45761 chrome::kBrowserCrashDumpAttemptsRegistryPath,
rogerm@chromium.org261ab7c2013-08-19 15:04:58762 KEY_ALL_ACCESS) != ERROR_SUCCESS) {
763 return;
764 }
765
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45766 // The values we're interested in counting are all prefixed with the version.
767 base::string16 chrome_version(base::ASCIIToUTF16(chrome::kChromeVersion));
768
769 // Track a list of values to delete. We don't modify the registry key while
770 // we're iterating over its values.
771 typedef std::vector<base::string16> StringVector;
772 StringVector to_delete;
773
774 // Iterate over the values in the key counting dumps with and without crashes.
775 // We directly walk the values instead of using RegistryValueIterator in order
776 // to read all of the values as DWORDS instead of strings.
777 base::string16 name;
778 DWORD value = 0;
779 int dumps_with_crash = 0;
780 int dumps_with_no_crash = 0;
rogerm@chromium.org261ab7c2013-08-19 15:04:58781 for (int i = regkey.GetValueCount() - 1; i >= 0; --i) {
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45782 if (regkey.GetValueNameAt(i, &name) == ERROR_SUCCESS &&
783 StartsWith(name, chrome_version, false) &&
784 regkey.ReadValueDW(name.c_str(), &value) == ERROR_SUCCESS) {
785 to_delete.push_back(name);
786 if (value == 0)
787 ++dumps_with_no_crash;
788 else
789 ++dumps_with_crash;
rogerm@chromium.org261ab7c2013-08-19 15:04:58790 }
791 }
rogerm@chromium.orga5e0fe5e2013-09-16 06:15:45792
793 // Delete the registry keys we've just counted.
794 for (StringVector::iterator i = to_delete.begin(); i != to_delete.end(); ++i)
795 regkey.DeleteValue(i->c_str());
796
797 // Capture the histogram samples.
798 if (dumps_with_crash != 0)
799 UMA_HISTOGRAM_COUNTS("Chrome.BrowserDumpsWithCrash", dumps_with_crash);
800 if (dumps_with_no_crash != 0)
801 UMA_HISTOGRAM_COUNTS("Chrome.BrowserDumpsWithNoCrash", dumps_with_no_crash);
802 int total_dumps = dumps_with_crash + dumps_with_no_crash;
803 if (total_dumps != 0)
804 UMA_HISTOGRAM_COUNTS("Chrome.BrowserCrashDumpAttempts", total_dumps);
rogerm@chromium.org261ab7c2013-08-19 15:04:58805}
806#endif // defined(OS_WIN)
807
initial.commit09911bf2008-07-26 23:55:29808//------------------------------------------------------------------------------
809// private methods
810//------------------------------------------------------------------------------
811
812
813//------------------------------------------------------------------------------
814// Initialization methods
815
miu@chromium.org39076642014-05-05 20:32:55816void MetricsService::InitializeMetricsState() {
initial.commit09911bf2008-07-26 23:55:29817 PrefService* pref = g_browser_process->local_state();
818 DCHECK(pref);
819
isherman@chromium.org09dee82d2014-05-22 14:00:53820 pref->SetString(prefs::kStabilityStatsVersion, client_->GetVersionString());
asvitkine@chromium.orgb58b8b22014-04-08 22:40:33821 pref->SetInt64(prefs::kStabilityStatsBuildTime, MetricsLog::GetBuildTime());
jar@chromium.org541f77922009-02-23 21:14:38822
initial.commit09911bf2008-07-26 23:55:29823 session_id_ = pref->GetInteger(prefs::kMetricsSessionID);
initial.commit09911bf2008-07-26 23:55:29824
cpu@google.come73c01972008-08-13 00:18:24825 if (!pref->GetBoolean(prefs::kStabilityExitedCleanly)) {
826 IncrementPrefValue(prefs::kStabilityCrashCount);
jar@chromium.orgc0c55e92011-09-10 18:47:30827 // Reset flag, and wait until we call LogNeedForCleanShutdown() before
828 // monitoring.
829 pref->SetBoolean(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19830
831 // TODO(rtenneti): On windows, consider saving/getting execution_phase from
832 // the registry.
833 int execution_phase = pref->GetInteger(prefs::kStabilityExecutionPhase);
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21834 UMA_HISTOGRAM_SPARSE_SLOWLY("Chrome.Browser.CrashedExecutionPhase",
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19835 execution_phase);
asvitkine@chromium.org80a8f312013-12-16 18:00:30836
837 // If the previous session didn't exit cleanly, then prepare an initial
838 // stability log if UMA is enabled.
miu@chromium.org39076642014-05-05 20:32:55839 if (state_manager_->IsMetricsReportingEnabled())
asvitkine@chromium.org80a8f312013-12-16 18:00:30840 PrepareInitialStabilityLog();
initial.commit09911bf2008-07-26 23:55:29841 }
asvitkine@chromium.org80a8f312013-12-16 18:00:30842
843 // Update session ID.
844 ++session_id_;
845 pref->SetInteger(prefs::kMetricsSessionID, session_id_);
846
847 // Stability bookkeeping
848 IncrementPrefValue(prefs::kStabilityLaunchCount);
849
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21850 DCHECK_EQ(UNINITIALIZED_PHASE, execution_phase_);
851 SetExecutionPhase(START_METRICS_RECORDING);
cpu@google.come73c01972008-08-13 00:18:24852
rogerm@chromium.org261ab7c2013-08-19 15:04:58853#if defined(OS_WIN)
854 CountBrowserCrashDumpAttempts();
855#endif // defined(OS_WIN)
856
cpu@google.come73c01972008-08-13 00:18:24857 if (!pref->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
858 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
jar@chromium.orgc9abf242009-07-18 06:00:38859 // This is marked false when we get a WM_ENDSESSION.
860 pref->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
initial.commit09911bf2008-07-26 23:55:29861 }
initial.commit09911bf2008-07-26 23:55:29862
mpearson@chromium.org076961c2014-03-12 22:23:56863 // Call GetUptimes() for the first time, thus allowing all later calls
864 // to record incremental uptimes accurately.
865 base::TimeDelta ignored_uptime_parameter;
866 base::TimeDelta startup_uptime;
867 GetUptimes(pref, &startup_uptime, &ignored_uptime_parameter);
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36868 DCHECK_EQ(0, startup_uptime.InMicroseconds());
jar@chromium.org9165f742010-03-10 22:55:01869 // For backwards compatibility, leave this intact in case Omaha is checking
870 // them. prefs::kStabilityLastTimestampSec may also be useless now.
871 // TODO(jar): Delete these if they have no uses.
robertshield@google.com0bb1a622009-03-04 03:22:32872 pref->SetInt64(prefs::kStabilityLaunchTimeSec, Time::Now().ToTimeT());
873
874 // Bookkeeping for the uninstall metrics.
875 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29876
jar@chromium.org92745242009-06-12 16:52:21877 // Get stats on use of command line.
878 const CommandLine* command_line(CommandLine::ForCurrentProcess());
879 size_t common_commands = 0;
880 if (command_line->HasSwitch(switches::kUserDataDir)) {
881 ++common_commands;
882 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineDatDirCount", 1);
883 }
884
885 if (command_line->HasSwitch(switches::kApp)) {
886 ++common_commands;
887 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineAppModeCount", 1);
888 }
889
msw@chromium.org62b4e522011-07-13 21:46:32890 size_t switch_count = command_line->GetSwitches().size();
891 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineFlagCount", switch_count);
jar@chromium.org92745242009-06-12 16:52:21892 UMA_HISTOGRAM_COUNTS_100("Chrome.CommandLineUncommonFlagCount",
msw@chromium.org62b4e522011-07-13 21:46:32893 switch_count - common_commands);
jar@chromium.org92745242009-06-12 16:52:21894
initial.commit09911bf2008-07-26 23:55:29895 // Kick off the process of saving the state (so the uptime numbers keep
896 // getting updated) every n minutes.
897 ScheduleNextStateSave();
898}
899
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40900// static
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56901void MetricsService::InitTaskGetHardwareClass(
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40902 base::WeakPtr<MetricsService> self,
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56903 base::MessageLoopProxy* target_loop) {
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56904 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
905
906 std::string hardware_class;
907#if defined(OS_CHROMEOS)
908 chromeos::system::StatisticsProvider::GetInstance()->GetMachineStatistic(
909 "hardware_class", &hardware_class);
910#endif // OS_CHROMEOS
911
912 target_loop->PostTask(FROM_HERE,
913 base::Bind(&MetricsService::OnInitTaskGotHardwareClass,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40914 self, hardware_class));
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56915}
916
917void MetricsService::OnInitTaskGotHardwareClass(
918 const std::string& hardware_class) {
isherman@chromium.orged0fd002012-04-25 23:10:34919 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
zelidrag@chromium.org85ed9d42010-06-08 22:37:44920 hardware_class_ = hardware_class;
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56921
nileshagrawal@chromium.orgebd71962012-12-20 02:56:55922#if defined(ENABLE_PLUGINS)
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56923 // Start the next part of the init task: loading plugin information.
924 PluginService::GetInstance()->GetPlugins(
925 base::Bind(&MetricsService::OnInitTaskGotPluginInfo,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:40926 self_ptr_factory_.GetWeakPtr()));
nileshagrawal@chromium.orgebd71962012-12-20 02:56:55927#else
jam@chromium.orgd7bd3e52013-07-21 04:29:20928 std::vector<content::WebPluginInfo> plugin_list_empty;
nileshagrawal@chromium.orgebd71962012-12-20 02:56:55929 OnInitTaskGotPluginInfo(plugin_list_empty);
930#endif // defined(ENABLE_PLUGINS)
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56931}
932
933void MetricsService::OnInitTaskGotPluginInfo(
jam@chromium.orgd7bd3e52013-07-21 04:29:20934 const std::vector<content::WebPluginInfo>& plugins) {
isherman@chromium.orged0fd002012-04-25 23:10:34935 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
jam@chromium.org35fa6a22009-08-15 00:04:01936 plugins_ = plugins;
rsesek@chromium.orgd33e7cc2011-09-23 01:43:56937
asvitkine@chromium.org68e679232014-05-22 07:49:15938 const base::Closure got_metrics_callback =
939 base::Bind(&MetricsService::OnInitTaskGotGoogleUpdateData,
940 self_ptr_factory_.GetWeakPtr());
ryanmyers@chromium.org197c0772012-05-14 23:50:51941
942#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
asvitkine@chromium.org68e679232014-05-22 07:49:15943 google_update_metrics_provider_->GetGoogleUpdateData(got_metrics_callback);
944#else
945 got_metrics_callback.Run();
946#endif
ryanmyers@chromium.org197c0772012-05-14 23:50:51947}
948
asvitkine@chromium.org68e679232014-05-22 07:49:15949void MetricsService::OnInitTaskGotGoogleUpdateData() {
ryanmyers@chromium.org197c0772012-05-14 23:50:51950 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
951
isherman@chromium.orged0fd002012-04-25 23:10:34952 // Start the next part of the init task: fetching performance data. This will
953 // call into |FinishedReceivingProfilerData()| when the task completes.
954 chrome_browser_metrics::TrackingSynchronizer::FetchProfilerDataAsynchronously(
955 self_ptr_factory_.GetWeakPtr());
956}
957
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:22958void MetricsService::OnUserAction(const std::string& action) {
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04959 if (!ShouldLogEvents())
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:22960 return;
961
isherman@chromium.org4426d2d2014-04-09 12:33:00962 log_manager_.current_log()->RecordUserAction(action);
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:22963 HandleIdleSinceLastTransmission(false);
964}
965
isherman@chromium.orged0fd002012-04-25 23:10:34966void MetricsService::ReceivedProfilerData(
967 const tracked_objects::ProcessDataSnapshot& process_data,
jam@chromium.orgf3b357692013-03-22 05:16:13968 int process_type) {
isherman@chromium.orged0fd002012-04-25 23:10:34969 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
970
971 // Upon the first callback, create the initial log so that we can immediately
972 // save the profiler data.
asvitkine@chromium.org9eae4032014-04-09 19:15:19973 if (!initial_metrics_log_.get()) {
isherman@chromium.org09dee82d2014-05-22 14:00:53974 initial_metrics_log_ = CreateLog(MetricsLog::ONGOING_LOG);
bolian@chromium.org2a321de32014-05-10 19:59:06975 NotifyOnDidCreateMetricsLog();
asvitkine@chromium.org9eae4032014-04-09 19:15:19976 }
isherman@chromium.orged0fd002012-04-25 23:10:34977
asvitkine@chromium.org80a8f312013-12-16 18:00:30978 initial_metrics_log_->RecordProfilerData(process_data, process_type);
isherman@chromium.orged0fd002012-04-25 23:10:34979}
980
981void MetricsService::FinishedReceivingProfilerData() {
982 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36983 state_ = INIT_TASK_DONE;
asvitkine@chromium.org70886cd2013-12-04 05:53:42984 scheduler_->InitTaskComplete();
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36985}
986
mpearson@chromium.org076961c2014-03-12 22:23:56987void MetricsService::GetUptimes(PrefService* pref,
988 base::TimeDelta* incremental_uptime,
989 base::TimeDelta* uptime) {
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36990 base::TimeTicks now = base::TimeTicks::Now();
mpearson@chromium.org076961c2014-03-12 22:23:56991 // If this is the first call, init |first_updated_time_| and
992 // |last_updated_time_|.
993 if (last_updated_time_.is_null()) {
994 first_updated_time_ = now;
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36995 last_updated_time_ = now;
mpearson@chromium.org076961c2014-03-12 22:23:56996 }
997 *incremental_uptime = now - last_updated_time_;
998 *uptime = now - first_updated_time_;
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36999 last_updated_time_ = now;
1000
mpearson@chromium.org076961c2014-03-12 22:23:561001 const int64 incremental_time_secs = incremental_uptime->InSeconds();
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361002 if (incremental_time_secs > 0) {
1003 int64 metrics_uptime = pref->GetInt64(prefs::kUninstallMetricsUptimeSec);
1004 metrics_uptime += incremental_time_secs;
1005 pref->SetInt64(prefs::kUninstallMetricsUptimeSec, metrics_uptime);
1006 }
initial.commit09911bf2008-07-26 23:55:291007}
1008
bolian@chromium.org2a321de32014-05-10 19:59:061009void MetricsService::AddObserver(MetricsServiceObserver* observer) {
1010 DCHECK(thread_checker_.CalledOnValidThread());
1011 observers_.AddObserver(observer);
1012}
1013
1014void MetricsService::RemoveObserver(MetricsServiceObserver* observer) {
1015 DCHECK(thread_checker_.CalledOnValidThread());
1016 observers_.RemoveObserver(observer);
1017}
1018
1019void MetricsService::NotifyOnDidCreateMetricsLog() {
1020 DCHECK(thread_checker_.CalledOnValidThread());
1021 FOR_EACH_OBSERVER(
1022 MetricsServiceObserver, observers_, OnDidCreateMetricsLog());
1023}
1024
initial.commit09911bf2008-07-26 23:55:291025//------------------------------------------------------------------------------
1026// State save methods
1027
1028void MetricsService::ScheduleNextStateSave() {
isherman@chromium.org8454aeb2011-11-19 23:38:201029 state_saver_factory_.InvalidateWeakPtrs();
initial.commit09911bf2008-07-26 23:55:291030
xhwang@chromium.orgb3a25092013-05-28 22:08:161031 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
isherman@chromium.org8454aeb2011-11-19 23:38:201032 base::Bind(&MetricsService::SaveLocalState,
1033 state_saver_factory_.GetWeakPtr()),
tedvessenes@gmail.comfc4252a72012-01-12 21:58:471034 base::TimeDelta::FromMinutes(kSaveStateIntervalMinutes));
initial.commit09911bf2008-07-26 23:55:291035}
1036
1037void MetricsService::SaveLocalState() {
1038 PrefService* pref = g_browser_process->local_state();
1039 if (!pref) {
jar@chromium.orga063c102010-07-22 22:20:191040 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291041 return;
1042 }
1043
1044 RecordCurrentState(pref);
initial.commit09911bf2008-07-26 23:55:291045
tedvessenes@gmail.comfc4252a72012-01-12 21:58:471046 // TODO(jar):110021 Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:291047 ScheduleNextStateSave();
1048}
1049
1050
1051//------------------------------------------------------------------------------
1052// Recording control methods
1053
stuartmorgan@chromium.org410938e02012-10-24 16:33:591054void MetricsService::OpenNewLog() {
1055 DCHECK(!log_manager_.current_log());
initial.commit09911bf2008-07-26 23:55:291056
asvitkine@chromium.org9eae4032014-04-09 19:15:191057 log_manager_.BeginLoggingWithLog(
isherman@chromium.org09dee82d2014-05-22 14:00:531058 CreateLog(MetricsLog::ONGOING_LOG).PassAs<metrics::MetricsLogBase>());
bolian@chromium.org2a321de32014-05-10 19:59:061059 NotifyOnDidCreateMetricsLog();
initial.commit09911bf2008-07-26 23:55:291060 if (state_ == INITIALIZED) {
1061 // We only need to schedule that run once.
zelidrag@chromium.org85ed9d42010-06-08 22:37:441062 state_ = INIT_TASK_SCHEDULED;
initial.commit09911bf2008-07-26 23:55:291063
zelidrag@chromium.org85ed9d42010-06-08 22:37:441064 // Schedules a task on the file thread for execution of slower
1065 // initialization steps (such as plugin list generation) necessary
1066 // for sending the initial log. This avoids blocking the main UI
1067 // thread.
joi@chromium.orged10dd12011-12-07 12:03:421068 BrowserThread::PostDelayedTask(
1069 BrowserThread::FILE,
1070 FROM_HERE,
rsesek@chromium.orgd33e7cc2011-09-23 01:43:561071 base::Bind(&MetricsService::InitTaskGetHardwareClass,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401072 self_ptr_factory_.GetWeakPtr(),
xhwang@chromium.orgb3a25092013-05-28 22:08:161073 base::MessageLoop::current()->message_loop_proxy()),
tedvessenes@gmail.com7e560102012-03-08 20:58:421074 base::TimeDelta::FromSeconds(kInitializationDelaySeconds));
initial.commit09911bf2008-07-26 23:55:291075 }
1076}
1077
stuartmorgan@chromium.org410938e02012-10-24 16:33:591078void MetricsService::CloseCurrentLog() {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101079 if (!log_manager_.current_log())
initial.commit09911bf2008-07-26 23:55:291080 return;
1081
jar@google.com68475e602008-08-22 03:21:151082 // TODO(jar): Integrate bounds on log recording more consistently, so that we
1083 // can stop recording logs that are too big much sooner.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101084 if (log_manager_.current_log()->num_events() > kEventLimit) {
dsh@google.com553dba62009-02-24 19:08:231085 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101086 log_manager_.current_log()->num_events());
1087 log_manager_.DiscardCurrentLog();
stuartmorgan@chromium.org410938e02012-10-24 16:33:591088 OpenNewLog(); // Start trivial log to hold our histograms.
jar@google.com68475e602008-08-22 03:21:151089 }
1090
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101091 // Adds to ongoing logs.
1092 log_manager_.current_log()->set_hardware_class(hardware_class_);
jar@chromium.orgaccdfa62011-09-20 01:56:521093
jar@google.com0b33f80b2008-12-17 21:34:361094 // Put incremental data (histogram deltas, and realtime stats deltas) at the
jar@google.com147bbc0b2009-01-06 19:37:401095 // end of all log transmissions (initial log handles this separately).
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:381096 // RecordIncrementalStabilityElements only exists on the derived
1097 // MetricsLog class.
isherman@chromium.org279703f2012-01-20 22:23:261098 MetricsLog* current_log =
1099 static_cast<MetricsLog*>(log_manager_.current_log());
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:381100 DCHECK(current_log);
asvitkine@chromium.orgb3610d42014-05-19 18:07:231101 std::vector<variations::ActiveGroupId> synthetic_trials;
bengr@chromium.org60677562013-11-17 15:52:551102 GetCurrentSyntheticFieldTrials(&synthetic_trials);
asvitkine@chromium.org85791b0b2014-05-20 15:18:581103 current_log->RecordEnvironment(metrics_providers_.get(), plugins_,
asvitkine@chromium.org68e679232014-05-22 07:49:151104 synthetic_trials);
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:361105 PrefService* pref = g_browser_process->local_state();
mpearson@chromium.org076961c2014-03-12 22:23:561106 base::TimeDelta incremental_uptime;
1107 base::TimeDelta uptime;
1108 GetUptimes(pref, &incremental_uptime, &uptime);
asvitkine@chromium.org85791b0b2014-05-20 15:18:581109 current_log->RecordStabilityMetrics(metrics_providers_.get(),
1110 incremental_uptime, uptime);
bengr@chromium.org60677562013-11-17 15:52:551111
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:381112 RecordCurrentHistograms();
asvitkine@chromium.org85791b0b2014-05-20 15:18:581113 current_log->RecordGeneralMetrics(metrics_providers_.get());
initial.commit09911bf2008-07-26 23:55:291114
stuartmorgan@chromium.org29948262012-03-01 12:15:081115 log_manager_.FinishCurrentLog();
initial.commit09911bf2008-07-26 23:55:291116}
1117
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101118void MetricsService::PushPendingLogsToPersistentStorage() {
asvitkine@chromium.org80a8f312013-12-16 18:00:301119 if (state_ < SENDING_INITIAL_STABILITY_LOG)
avi@google.com28ab7f92009-01-06 21:39:041120 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:291121
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101122 if (log_manager_.has_staged_log()) {
stuartmorgan@chromium.org7d41ae6d2012-06-26 08:53:031123 // We may race here, and send second copy of the log later.
holte@chromium.org7f07db62014-05-15 01:12:451124 metrics::PersistedLogs::StoreType store_type;
isherman@chromium.orge3eb0c42013-04-18 06:18:581125 if (current_fetch_.get())
holte@chromium.org7f07db62014-05-15 01:12:451126 store_type = metrics::PersistedLogs::PROVISIONAL_STORE;
isherman@chromium.orgdc61fe92012-06-12 00:13:501127 else
holte@chromium.org7f07db62014-05-15 01:12:451128 store_type = metrics::PersistedLogs::NORMAL_STORE;
stuartmorgan@chromium.orge7508d82012-05-03 15:59:531129 log_manager_.StoreStagedLogAsUnsent(store_type);
initial.commit09911bf2008-07-26 23:55:291130 }
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101131 DCHECK(!log_manager_.has_staged_log());
stuartmorgan@chromium.org410938e02012-10-24 16:33:591132 CloseCurrentLog();
asvitkine@chromium.org80a8f312013-12-16 18:00:301133 log_manager_.PersistUnsentLogs();
stuartmorgan@chromium.org7d41ae6d2012-06-26 08:53:031134
1135 // If there was a staged and/or current log, then there is now at least one
1136 // log waiting to be uploaded.
1137 if (log_manager_.has_unsent_logs())
1138 state_ = SENDING_OLD_LOGS;
initial.commit09911bf2008-07-26 23:55:291139}
1140
1141//------------------------------------------------------------------------------
1142// Transmission of logs methods
1143
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161144void MetricsService::StartSchedulerIfNecessary() {
stuartmorgan@chromium.org410938e02012-10-24 16:33:591145 // Never schedule cutting or uploading of logs in test mode.
1146 if (test_mode_active_)
1147 return;
1148
1149 // Even if reporting is disabled, the scheduler is needed to trigger the
1150 // creation of the initial log, which must be done in order for any logs to be
1151 // persisted on shutdown or backgrounding.
asvitkine@chromium.org80a8f312013-12-16 18:00:301152 if (recording_active() &&
1153 (reporting_active() || state_ < SENDING_INITIAL_STABILITY_LOG)) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161154 scheduler_->Start();
asvitkine@chromium.org80a8f312013-12-16 18:00:301155 }
initial.commit09911bf2008-07-26 23:55:291156}
1157
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161158void MetricsService::StartScheduledUpload() {
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471159 // If we're getting no notifications, then the log won't have much in it, and
1160 // it's possible the computer is about to go to sleep, so don't upload and
1161 // stop the scheduler.
stuartmorgan@chromium.org410938e02012-10-24 16:33:591162 // If recording has been turned off, the scheduler doesn't need to run.
1163 // If reporting is off, proceed if the initial log hasn't been created, since
1164 // that has to happen in order for logs to be cut and stored when persisting.
isherman@chromium.orgd7ea39e2014-05-22 03:59:181165 // TODO(stuartmorgan): Call Stop() on the scheduler when reporting and/or
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471166 // recording are turned off instead of letting it fire and then aborting.
1167 if (idle_since_last_transmission_ ||
stuartmorgan@chromium.org410938e02012-10-24 16:33:591168 !recording_active() ||
asvitkine@chromium.org80a8f312013-12-16 18:00:301169 (!reporting_active() && state_ >= SENDING_INITIAL_STABILITY_LOG)) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161170 scheduler_->Stop();
1171 scheduler_->UploadCancelled();
1172 return;
1173 }
1174
stuartmorgan@chromium.orgc15faf372012-07-11 06:01:341175 // If the callback was to upload an old log, but there no longer is one,
1176 // just report success back to the scheduler to begin the ongoing log
1177 // callbacks.
1178 // TODO(stuartmorgan): Consider removing the distinction between
1179 // SENDING_OLD_LOGS and SENDING_CURRENT_LOGS to simplify the state machine
1180 // now that the log upload flow is the same for both modes.
1181 if (state_ == SENDING_OLD_LOGS && !log_manager_.has_unsent_logs()) {
1182 state_ = SENDING_CURRENT_LOGS;
1183 scheduler_->UploadFinished(true /* healthy */, false /* no unsent logs */);
1184 return;
1185 }
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471186 // If there are unsent logs, send the next one. If not, start the asynchronous
1187 // process of finalizing the current log for upload.
1188 if (state_ == SENDING_OLD_LOGS) {
1189 DCHECK(log_manager_.has_unsent_logs());
1190 log_manager_.StageNextLogForUpload();
1191 SendStagedLog();
1192 } else {
1193 StartFinalLogInfoCollection();
1194 }
stuartmorgan@chromium.org29948262012-03-01 12:15:081195}
1196
1197void MetricsService::StartFinalLogInfoCollection() {
1198 // Begin the multi-step process of collecting memory usage histograms:
1199 // First spawn a task to collect the memory details; when that task is
1200 // finished, it will call OnMemoryDetailCollectionDone. That will in turn
1201 // call HistogramSynchronization to collect histograms from all renderers and
1202 // then call OnHistogramSynchronizationDone to continue processing.
isherman@chromium.orgd119f222012-06-08 02:33:271203 DCHECK(!waiting_for_asynchronous_reporting_step_);
1204 waiting_for_asynchronous_reporting_step_ = true;
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161205
dcheng@chromium.org2226c222011-11-22 00:08:401206 base::Closure callback =
1207 base::Bind(&MetricsService::OnMemoryDetailCollectionDone,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401208 self_ptr_factory_.GetWeakPtr());
sail@chromium.org84c988a2011-04-19 17:56:331209
dcheng@chromium.org2226c222011-11-22 00:08:401210 scoped_refptr<MetricsMemoryDetails> details(
1211 new MetricsMemoryDetails(callback));
jamescook@chromium.org4306df72012-04-20 18:58:571212 details->StartFetch(MemoryDetails::UPDATE_USER_METRICS);
sail@chromium.org84c988a2011-04-19 17:56:331213
1214 // Collect WebCore cache information to put into a histogram.
ananta@chromium.orgf3b1a082011-11-18 00:34:301215 for (content::RenderProcessHost::iterator i(
1216 content::RenderProcessHost::AllHostsIterator());
sail@chromium.org84c988a2011-04-19 17:56:331217 !i.IsAtEnd(); i.Advance())
ananta@chromium.org2ccf45c2011-08-19 23:35:501218 i.GetCurrentValue()->Send(new ChromeViewMsg_GetCacheResourceStats());
sail@chromium.org84c988a2011-04-19 17:56:331219}
1220
1221void MetricsService::OnMemoryDetailCollectionDone() {
jar@chromium.orgc9a3ef82009-05-28 22:02:461222 DCHECK(IsSingleThreaded());
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161223 // This function should only be called as the callback from an ansynchronous
1224 // step.
isherman@chromium.orgd119f222012-06-08 02:33:271225 DCHECK(waiting_for_asynchronous_reporting_step_);
jar@chromium.orgc9a3ef82009-05-28 22:02:461226
jar@chromium.orgc9a3ef82009-05-28 22:02:461227 // Create a callback_task for OnHistogramSynchronizationDone.
dcheng@chromium.org2226c222011-11-22 00:08:401228 base::Closure callback = base::Bind(
1229 &MetricsService::OnHistogramSynchronizationDone,
dpolukhin@chromium.orgc94d7382012-02-28 08:43:401230 self_ptr_factory_.GetWeakPtr());
jar@chromium.orgc9a3ef82009-05-28 22:02:461231
vitalybuka@chromium.orga3079832013-10-24 20:29:361232 base::TimeDelta timeout =
1233 base::TimeDelta::FromMilliseconds(kMaxHistogramGatheringWaitDuration);
1234
1235 DCHECK_EQ(num_async_histogram_fetches_in_progress_, 0);
1236
1237#if defined(OS_ANDROID)
1238 // Android has no service process.
1239 num_async_histogram_fetches_in_progress_ = 1;
1240#else // OS_ANDROID
1241 num_async_histogram_fetches_in_progress_ = 2;
1242 // Run requests to service and content in parallel.
1243 if (!ServiceProcessControl::GetInstance()->GetHistograms(callback, timeout)) {
1244 // Assume |num_async_histogram_fetches_in_progress_| is not changed by
1245 // |GetHistograms()|.
1246 DCHECK_EQ(num_async_histogram_fetches_in_progress_, 2);
1247 // Assign |num_async_histogram_fetches_in_progress_| above and decrement it
1248 // here to make code work even if |GetHistograms()| fired |callback|.
1249 --num_async_histogram_fetches_in_progress_;
1250 }
1251#endif // OS_ANDROID
1252
jar@chromium.orgc9a3ef82009-05-28 22:02:461253 // Set up the callback to task to call after we receive histograms from all
rtenneti@google.com83ab4a282012-07-12 18:19:451254 // child processes. Wait time specifies how long to wait before absolutely
jar@chromium.orgc9a3ef82009-05-28 22:02:461255 // calling us back on the task.
vitalybuka@chromium.orga3079832013-10-24 20:29:361256 content::FetchHistogramsAsynchronously(base::MessageLoop::current(), callback,
1257 timeout);
jar@chromium.orgc9a3ef82009-05-28 22:02:461258}
1259
1260void MetricsService::OnHistogramSynchronizationDone() {
initial.commit09911bf2008-07-26 23:55:291261 DCHECK(IsSingleThreaded());
stuartmorgan@chromium.org29948262012-03-01 12:15:081262 // This function should only be called as the callback from an ansynchronous
1263 // step.
isherman@chromium.orgd119f222012-06-08 02:33:271264 DCHECK(waiting_for_asynchronous_reporting_step_);
vitalybuka@chromium.orga3079832013-10-24 20:29:361265 DCHECK_GT(num_async_histogram_fetches_in_progress_, 0);
1266
1267 // Check if all expected requests finished.
1268 if (--num_async_histogram_fetches_in_progress_ > 0)
1269 return;
initial.commit09911bf2008-07-26 23:55:291270
isherman@chromium.orgd119f222012-06-08 02:33:271271 waiting_for_asynchronous_reporting_step_ = false;
stuartmorgan@chromium.org29948262012-03-01 12:15:081272 OnFinalLogInfoCollectionDone();
1273}
1274
1275void MetricsService::OnFinalLogInfoCollectionDone() {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161276 // If somehow there is a fetch in progress, we return and hope things work
1277 // out. The scheduler isn't informed since if this happens, the scheduler
1278 // will get a response from the upload.
isherman@chromium.orge3eb0c42013-04-18 06:18:581279 DCHECK(!current_fetch_.get());
1280 if (current_fetch_.get())
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161281 return;
1282
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471283 // Abort if metrics were turned off during the final info gathering.
stuartmorgan@chromium.org410938e02012-10-24 16:33:591284 if (!recording_active()) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161285 scheduler_->Stop();
1286 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:071287 return;
1288 }
1289
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471290 StageNewLog();
stuartmorgan@chromium.org410938e02012-10-24 16:33:591291
1292 // If logs shouldn't be uploaded, stop here. It's important that this check
1293 // be after StageNewLog(), otherwise the previous logs will never be loaded,
1294 // and thus the open log won't be persisted.
1295 // TODO(stuartmorgan): This is unnecessarily complicated; restructure loading
1296 // of previous logs to not require running part of the upload logic.
1297 // http://crbug.com/157337
1298 if (!reporting_active()) {
1299 scheduler_->Stop();
1300 scheduler_->UploadCancelled();
1301 return;
1302 }
1303
stuartmorgan@chromium.org29948262012-03-01 12:15:081304 SendStagedLog();
1305}
1306
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471307void MetricsService::StageNewLog() {
stuartmorgan@chromium.org29948262012-03-01 12:15:081308 if (log_manager_.has_staged_log())
1309 return;
1310
1311 switch (state_) {
1312 case INITIALIZED:
1313 case INIT_TASK_SCHEDULED: // We should be further along by now.
isherman@chromium.orgdc61fe92012-06-12 00:13:501314 NOTREACHED();
stuartmorgan@chromium.org29948262012-03-01 12:15:081315 return;
1316
1317 case INIT_TASK_DONE:
asvitkine@chromium.org80a8f312013-12-16 18:00:301318 if (has_initial_stability_log_) {
1319 // There's an initial stability log, ready to send.
1320 log_manager_.StageNextLogForUpload();
1321 has_initial_stability_log_ = false;
asvitkine@chromium.orgf61eb842014-01-22 10:59:131322 // Note: No need to call LoadPersistedUnsentLogs() here because unsent
1323 // logs have already been loaded by PrepareInitialStabilityLog().
asvitkine@chromium.org80a8f312013-12-16 18:00:301324 state_ = SENDING_INITIAL_STABILITY_LOG;
1325 } else {
asvitkine@chromium.orgb58b8b22014-04-08 22:40:331326 PrepareInitialMetricsLog();
asvitkine@chromium.orgf61eb842014-01-22 10:59:131327 // Load unsent logs (if any) from local state.
1328 log_manager_.LoadPersistedUnsentLogs();
asvitkine@chromium.org80a8f312013-12-16 18:00:301329 state_ = SENDING_INITIAL_METRICS_LOG;
1330 }
stuartmorgan@chromium.org29948262012-03-01 12:15:081331 break;
1332
1333 case SENDING_OLD_LOGS:
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471334 NOTREACHED(); // Shouldn't be staging a new log during old log sending.
1335 return;
stuartmorgan@chromium.org29948262012-03-01 12:15:081336
1337 case SENDING_CURRENT_LOGS:
stuartmorgan@chromium.org410938e02012-10-24 16:33:591338 CloseCurrentLog();
1339 OpenNewLog();
stuartmorgan@chromium.org29948262012-03-01 12:15:081340 log_manager_.StageNextLogForUpload();
1341 break;
1342
1343 default:
1344 NOTREACHED();
1345 return;
1346 }
1347
1348 DCHECK(log_manager_.has_staged_log());
1349}
1350
asvitkine@chromium.org80a8f312013-12-16 18:00:301351void MetricsService::PrepareInitialStabilityLog() {
1352 DCHECK_EQ(INITIALIZED, state_);
1353 PrefService* pref = g_browser_process->local_state();
1354 DCHECK_NE(0, pref->GetInteger(prefs::kStabilityCrashCount));
stuartmorgan@chromium.org29948262012-03-01 12:15:081355
asvitkine@chromium.org80a8f312013-12-16 18:00:301356 scoped_ptr<MetricsLog> initial_stability_log(
isherman@chromium.org09dee82d2014-05-22 14:00:531357 CreateLog(MetricsLog::INITIAL_STABILITY_LOG));
bolian@chromium.org2a321de32014-05-10 19:59:061358
1359 // Do not call NotifyOnDidCreateMetricsLog here because the stability
1360 // log describes stats from the _previous_ session.
1361
asvitkine@chromium.org80a8f312013-12-16 18:00:301362 if (!initial_stability_log->LoadSavedEnvironmentFromPrefs())
1363 return;
asvitkine@chromium.org85791b0b2014-05-20 15:18:581364
asvitkine@chromium.org80a8f312013-12-16 18:00:301365 log_manager_.LoadPersistedUnsentLogs();
1366
1367 log_manager_.PauseCurrentLog();
isherman@chromium.org09dee82d2014-05-22 14:00:531368 log_manager_.BeginLoggingWithLog(
1369 initial_stability_log.PassAs<metrics::MetricsLogBase>());
asvitkine@chromium.org85791b0b2014-05-20 15:18:581370
1371 // Note: Some stability providers may record stability stats via histograms,
1372 // so this call has to be after BeginLoggingWithLog().
1373 MetricsLog* current_log =
1374 static_cast<MetricsLog*>(log_manager_.current_log());
1375 current_log->RecordStabilityMetrics(metrics_providers_.get(),
1376 base::TimeDelta(), base::TimeDelta());
kkimlabs@chromium.orgc778687a2014-02-11 14:46:451377 RecordCurrentStabilityHistograms();
asvitkine@chromium.org85791b0b2014-05-20 15:18:581378
1379 // Note: RecordGeneralMetrics() intentionally not called since this log is for
1380 // stability stats from a previous session only.
1381
asvitkine@chromium.org80a8f312013-12-16 18:00:301382 log_manager_.FinishCurrentLog();
1383 log_manager_.ResumePausedLog();
1384
1385 // Store unsent logs, including the stability log that was just saved, so
1386 // that they're not lost in case of a crash before upload time.
1387 log_manager_.PersistUnsentLogs();
1388
1389 has_initial_stability_log_ = true;
1390}
1391
asvitkine@chromium.orgb58b8b22014-04-08 22:40:331392void MetricsService::PrepareInitialMetricsLog() {
asvitkine@chromium.org80a8f312013-12-16 18:00:301393 DCHECK(state_ == INIT_TASK_DONE || state_ == SENDING_INITIAL_STABILITY_LOG);
1394 initial_metrics_log_->set_hardware_class(hardware_class_);
asvitkine@chromium.org0edf8762013-11-21 18:33:301395
asvitkine@chromium.orgb3610d42014-05-19 18:07:231396 std::vector<variations::ActiveGroupId> synthetic_trials;
bengr@chromium.org60677562013-11-17 15:52:551397 GetCurrentSyntheticFieldTrials(&synthetic_trials);
asvitkine@chromium.org85791b0b2014-05-20 15:18:581398 initial_metrics_log_->RecordEnvironment(metrics_providers_.get(), plugins_,
asvitkine@chromium.org80a8f312013-12-16 18:00:301399 synthetic_trials);
asvitkine@chromium.org0edf8762013-11-21 18:33:301400 PrefService* pref = g_browser_process->local_state();
mpearson@chromium.org076961c2014-03-12 22:23:561401 base::TimeDelta incremental_uptime;
1402 base::TimeDelta uptime;
1403 GetUptimes(pref, &incremental_uptime, &uptime);
stuartmorgan@chromium.org29948262012-03-01 12:15:081404
1405 // Histograms only get written to the current log, so make the new log current
1406 // before writing them.
1407 log_manager_.PauseCurrentLog();
isherman@chromium.org09dee82d2014-05-22 14:00:531408 log_manager_.BeginLoggingWithLog(
1409 initial_metrics_log_.PassAs<metrics::MetricsLogBase>());
asvitkine@chromium.org85791b0b2014-05-20 15:18:581410
1411 // Note: Some stability providers may record stability stats via histograms,
1412 // so this call has to be after BeginLoggingWithLog().
1413 MetricsLog* current_log =
1414 static_cast<MetricsLog*>(log_manager_.current_log());
1415 current_log->RecordStabilityMetrics(metrics_providers_.get(),
1416 base::TimeDelta(), base::TimeDelta());
stuartmorgan@chromium.org29948262012-03-01 12:15:081417 RecordCurrentHistograms();
asvitkine@chromium.org85791b0b2014-05-20 15:18:581418
1419 current_log->RecordGeneralMetrics(metrics_providers_.get());
1420
stuartmorgan@chromium.org29948262012-03-01 12:15:081421 log_manager_.FinishCurrentLog();
1422 log_manager_.ResumePausedLog();
1423
1424 DCHECK(!log_manager_.has_staged_log());
1425 log_manager_.StageNextLogForUpload();
1426}
1427
stuartmorgan@chromium.org29948262012-03-01 12:15:081428void MetricsService::SendStagedLog() {
1429 DCHECK(log_manager_.has_staged_log());
1430
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101431 PrepareFetchWithStagedLog();
petersont@google.comd01b8732008-10-16 02:18:071432
isherman@chromium.orge3eb0c42013-04-18 06:18:581433 bool upload_created = (current_fetch_.get() != NULL);
isherman@chromium.orgd6bebb92012-06-13 23:14:551434 UMA_HISTOGRAM_BOOLEAN("UMA.UploadCreation", upload_created);
1435 if (!upload_created) {
petersont@google.comd01b8732008-10-16 02:18:071436 // Compression failed, and log discarded :-/.
isherman@chromium.orgdc61fe92012-06-12 00:13:501437 // Skip this upload and hope things work out next time.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101438 log_manager_.DiscardStagedLog();
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161439 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:071440 return;
1441 }
1442
isherman@chromium.orgd119f222012-06-08 02:33:271443 DCHECK(!waiting_for_asynchronous_reporting_step_);
isherman@chromium.orgd119f222012-06-08 02:33:271444 waiting_for_asynchronous_reporting_step_ = true;
isherman@chromium.orgdc61fe92012-06-12 00:13:501445
isherman@chromium.orge3eb0c42013-04-18 06:18:581446 current_fetch_->Start();
petersont@google.comd01b8732008-10-16 02:18:071447
1448 HandleIdleSinceLastTransmission(true);
1449}
1450
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101451void MetricsService::PrepareFetchWithStagedLog() {
isherman@chromium.orgdc61fe92012-06-12 00:13:501452 DCHECK(log_manager_.has_staged_log());
pkasting@chromium.orgcac78842008-11-27 01:02:201453
isherman@chromium.orgfe58acc22012-02-29 01:29:581454 // Prepare the protobuf version.
isherman@chromium.orge3eb0c42013-04-18 06:18:581455 DCHECK(!current_fetch_.get());
isherman@chromium.org5f3e1642013-05-05 03:37:341456 if (log_manager_.has_staged_log()) {
isherman@chromium.orge3eb0c42013-04-18 06:18:581457 current_fetch_.reset(net::URLFetcher::Create(
isherman@chromium.org5f3e1642013-05-05 03:37:341458 GURL(kServerUrl), net::URLFetcher::POST, this));
isherman@chromium.orge3eb0c42013-04-18 06:18:581459 current_fetch_->SetRequestContext(
isherman@chromium.orgfe58acc22012-02-29 01:29:581460 g_browser_process->system_request_context());
asharif@chromium.org537c638d2013-07-04 00:49:191461
holte@chromium.org7f07db62014-05-15 01:12:451462 std::string log_text = log_manager_.staged_log();
asharif@chromium.org8df71322013-09-13 18:40:001463 std::string compressed_log_text;
1464 bool compression_successful = chrome::GzipCompress(log_text,
1465 &compressed_log_text);
1466 DCHECK(compression_successful);
1467 if (compression_successful) {
1468 current_fetch_->SetUploadData(kMimeType, compressed_log_text);
1469 // Tell the server that we're uploading gzipped protobufs.
1470 current_fetch_->SetExtraRequestHeaders("content-encoding: gzip");
asvitkine@chromium.orgcfee9aa52013-10-19 17:53:051471 const std::string hash =
1472 base::HexEncode(log_manager_.staged_log_hash().data(),
1473 log_manager_.staged_log_hash().size());
1474 DCHECK(!hash.empty());
1475 current_fetch_->AddExtraRequestHeader("X-Chrome-UMA-Log-SHA1: " + hash);
asharif@chromium.org8df71322013-09-13 18:40:001476 UMA_HISTOGRAM_PERCENTAGE(
1477 "UMA.ProtoCompressionRatio",
1478 100 * compressed_log_text.size() / log_text.size());
1479 UMA_HISTOGRAM_CUSTOM_COUNTS(
1480 "UMA.ProtoGzippedKBSaved",
1481 (log_text.size() - compressed_log_text.size()) / 1024,
1482 1, 2000, 50);
asharif@chromium.org537c638d2013-07-04 00:49:191483 }
asharif@chromium.org537c638d2013-07-04 00:49:191484
isherman@chromium.orgfe58acc22012-02-29 01:29:581485 // We already drop cookies server-side, but we might as well strip them out
1486 // client-side as well.
isherman@chromium.orge3eb0c42013-04-18 06:18:581487 current_fetch_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES |
1488 net::LOAD_DO_NOT_SEND_COOKIES);
isherman@chromium.orgfe58acc22012-02-29 01:29:581489 }
initial.commit09911bf2008-07-26 23:55:291490}
1491
akalin@chromium.org10c2d692012-05-11 05:32:231492void MetricsService::OnURLFetchComplete(const net::URLFetcher* source) {
isherman@chromium.orgd119f222012-06-08 02:33:271493 DCHECK(waiting_for_asynchronous_reporting_step_);
isherman@chromium.orgfe58acc22012-02-29 01:29:581494
1495 // We're not allowed to re-use the existing |URLFetcher|s, so free them here.
isherman@chromium.orge3eb0c42013-04-18 06:18:581496 // Note however that |source| is aliased to the fetcher, so we should be
isherman@chromium.org4266def22012-05-17 01:02:401497 // careful not to delete it too early.
isherman@chromium.orge3eb0c42013-04-18 06:18:581498 DCHECK_EQ(current_fetch_.get(), source);
1499 scoped_ptr<net::URLFetcher> s(current_fetch_.Pass());
isherman@chromium.orgfe58acc22012-02-29 01:29:581500
isherman@chromium.orgdc61fe92012-06-12 00:13:501501 int response_code = source->GetResponseCode();
isherman@chromium.orgfe58acc22012-02-29 01:29:581502
isherman@chromium.orgdc61fe92012-06-12 00:13:501503 // Log a histogram to track response success vs. failure rates.
isherman@chromium.orge3eb0c42013-04-18 06:18:581504 UMA_HISTOGRAM_ENUMERATION("UMA.UploadResponseStatus.Protobuf",
1505 ResponseCodeToStatus(response_code),
1506 NUM_RESPONSE_STATUSES);
isherman@chromium.orgfe58acc22012-02-29 01:29:581507
stuartmorgan@chromium.orge7508d82012-05-03 15:59:531508 // If the upload was provisionally stored, drop it now that the upload is
1509 // known to have gone through.
1510 log_manager_.DiscardLastProvisionalStore();
initial.commit09911bf2008-07-26 23:55:291511
isherman@chromium.orgdc61fe92012-06-12 00:13:501512 bool upload_succeeded = response_code == 200;
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161513
jar@chromium.org0eb34fee2009-01-21 08:04:381514 // Provide boolean for error recovery (allow us to ignore response_code).
paul@chromium.orgdc6f4962009-02-13 01:25:501515 bool discard_log = false;
holte@chromium.org7f07db62014-05-15 01:12:451516 const size_t log_size = log_manager_.staged_log().length();
isherman@chromium.orgdc61fe92012-06-12 00:13:501517 if (!upload_succeeded && log_size > kUploadLogAvoidRetransmitSize) {
1518 UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
1519 static_cast<int>(log_size));
jar@chromium.org0eb34fee2009-01-21 08:04:381520 discard_log = true;
isherman@chromium.orgdc61fe92012-06-12 00:13:501521 } else if (response_code == 400) {
jar@chromium.org0eb34fee2009-01-21 08:04:381522 // Bad syntax. Retransmission won't work.
jar@chromium.org0eb34fee2009-01-21 08:04:381523 discard_log = true;
jar@google.com68475e602008-08-22 03:21:151524 }
1525
isherman@chromium.orge3eb0c42013-04-18 06:18:581526 if (upload_succeeded || discard_log)
isherman@chromium.org5f3e1642013-05-05 03:37:341527 log_manager_.DiscardStagedLog();
isherman@chromium.orgdc61fe92012-06-12 00:13:501528
1529 waiting_for_asynchronous_reporting_step_ = false;
1530
1531 if (!log_manager_.has_staged_log()) {
initial.commit09911bf2008-07-26 23:55:291532 switch (state_) {
asvitkine@chromium.org80a8f312013-12-16 18:00:301533 case SENDING_INITIAL_STABILITY_LOG:
1534 // Store the updated list to disk now that the removed log is uploaded.
1535 log_manager_.PersistUnsentLogs();
asvitkine@chromium.orgb58b8b22014-04-08 22:40:331536 PrepareInitialMetricsLog();
asvitkine@chromium.org80a8f312013-12-16 18:00:301537 SendStagedLog();
1538 state_ = SENDING_INITIAL_METRICS_LOG;
1539 break;
1540
1541 case SENDING_INITIAL_METRICS_LOG:
1542 // The initial metrics log never gets persisted to local state, so it's
1543 // not necessary to call log_manager_.PersistUnsentLogs() here.
1544 // TODO(asvitkine): It should be persisted like the initial stability
1545 // log and old unsent logs. http://crbug.com/328417
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471546 state_ = log_manager_.has_unsent_logs() ? SENDING_OLD_LOGS
1547 : SENDING_CURRENT_LOGS;
initial.commit09911bf2008-07-26 23:55:291548 break;
1549
initial.commit09911bf2008-07-26 23:55:291550 case SENDING_OLD_LOGS:
stuartmorgan@chromium.orgd53e2232011-06-30 15:54:571551 // Store the updated list to disk now that the removed log is uploaded.
asvitkine@chromium.org80a8f312013-12-16 18:00:301552 log_manager_.PersistUnsentLogs();
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471553 if (!log_manager_.has_unsent_logs())
1554 state_ = SENDING_CURRENT_LOGS;
initial.commit09911bf2008-07-26 23:55:291555 break;
1556
1557 case SENDING_CURRENT_LOGS:
1558 break;
1559
1560 default:
jar@chromium.orga063c102010-07-22 22:20:191561 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291562 break;
1563 }
petersont@google.comd01b8732008-10-16 02:18:071564
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101565 if (log_manager_.has_unsent_logs())
isherman@chromium.orged0fd002012-04-25 23:10:341566 DCHECK_LT(state_, SENDING_CURRENT_LOGS);
initial.commit09911bf2008-07-26 23:55:291567 }
petersont@google.com252873ef2008-08-04 21:59:451568
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161569 // Error 400 indicates a problem with the log, not with the server, so
1570 // don't consider that a sign that the server is in trouble.
isherman@chromium.orgdc61fe92012-06-12 00:13:501571 bool server_is_healthy = upload_succeeded || response_code == 400;
asvitkine@chromium.org80a8f312013-12-16 18:00:301572 // Don't notify the scheduler that the upload is finished if we've only sent
1573 // the initial stability log, but not yet the initial metrics log (treat the
1574 // two as a single unit of work as far as the scheduler is concerned).
1575 if (state_ != SENDING_INITIAL_METRICS_LOG) {
1576 scheduler_->UploadFinished(server_is_healthy,
1577 log_manager_.has_unsent_logs());
1578 }
rtenneti@chromium.orgd67d1052011-06-09 05:11:411579
asvitkine@chromium.org73929422014-05-22 08:19:051580 if (server_is_healthy)
1581 client_->OnLogUploadComplete();
initial.commit09911bf2008-07-26 23:55:291582}
1583
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511584void MetricsService::IncrementPrefValue(const char* path) {
cpu@google.come73c01972008-08-13 00:18:241585 PrefService* pref = g_browser_process->local_state();
1586 DCHECK(pref);
1587 int value = pref->GetInteger(path);
1588 pref->SetInteger(path, value + 1);
1589}
1590
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511591void MetricsService::IncrementLongPrefsValue(const char* path) {
robertshield@google.com0bb1a622009-03-04 03:22:321592 PrefService* pref = g_browser_process->local_state();
1593 DCHECK(pref);
1594 int64 value = pref->GetInt64(path);
jar@chromium.orgb42c5e42010-06-03 20:43:251595 pref->SetInt64(path, value + 1);
robertshield@google.com0bb1a622009-03-04 03:22:321596}
1597
rlp@chromium.org752a5262013-06-23 14:53:421598void MetricsService::LogLoadStarted(content::WebContents* web_contents) {
ben@chromium.orge6e30ac2014-01-13 21:24:391599 content::RecordAction(base::UserMetricsAction("PageLoad"));
jar@chromium.orgdd8d12a2011-09-02 02:10:151600 HISTOGRAM_ENUMERATION("Chrome.UmaPageloadCounter", 1, 2);
cpu@google.come73c01972008-08-13 00:18:241601 IncrementPrefValue(prefs::kStabilityPageLoadCount);
robertshield@google.com0bb1a622009-03-04 03:22:321602 IncrementLongPrefsValue(prefs::kUninstallMetricsPageLoadCount);
jar@google.com0b33f80b2008-12-17 21:34:361603 // We need to save the prefs, as page load count is a critical stat, and it
1604 // might be lost due to a crash :-(.
initial.commit09911bf2008-07-26 23:55:291605}
1606
jar@chromium.orgc3721482012-03-23 16:21:481607void MetricsService::LogRendererCrash(content::RenderProcessHost* host,
1608 base::TerminationStatus status,
jam@chromium.orgf1675202012-07-09 15:18:001609 int exit_code) {
aa@chromium.org6f371442011-11-09 06:45:461610 bool was_extension_process =
jamescook@chromium.orgfafdc842014-01-17 18:09:081611 extensions::ProcessMap::Get(host->GetBrowserContext())
1612 ->Contains(host->GetID());
jar@chromium.orgc3721482012-03-23 16:21:481613 if (status == base::TERMINATION_STATUS_PROCESS_CRASHED ||
1614 status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
eroman@chromium.orgd7c1fa62012-06-15 23:35:301615 if (was_extension_process) {
jochen@chromium.org718eab62011-10-05 21:16:521616 IncrementPrefValue(prefs::kStabilityExtensionRendererCrashCount);
eroman@chromium.orgd7c1fa62012-06-15 23:35:301617
eroman@chromium.org1026afd2013-03-20 14:28:541618 UMA_HISTOGRAM_SPARSE_SLOWLY("CrashExitCodes.Extension",
1619 MapCrashExitCodeForHistogram(exit_code));
eroman@chromium.orgd7c1fa62012-06-15 23:35:301620 } else {
jochen@chromium.org718eab62011-10-05 21:16:521621 IncrementPrefValue(prefs::kStabilityRendererCrashCount);
initial.commit09911bf2008-07-26 23:55:291622
eroman@chromium.org1026afd2013-03-20 14:28:541623 UMA_HISTOGRAM_SPARSE_SLOWLY("CrashExitCodes.Renderer",
1624 MapCrashExitCodeForHistogram(exit_code));
eroman@chromium.orgd7c1fa62012-06-15 23:35:301625 }
1626
jochen@chromium.org718eab62011-10-05 21:16:521627 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildCrashes",
1628 was_extension_process ? 2 : 1);
jar@chromium.orgc3721482012-03-23 16:21:481629 } else if (status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED) {
jochen@chromium.org718eab62011-10-05 21:16:521630 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildKills",
1631 was_extension_process ? 2 : 1);
jam@chromium.orgf1675202012-07-09 15:18:001632 } else if (status == base::TERMINATION_STATUS_STILL_RUNNING) {
1633 UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.DisconnectedAlive",
jochen@chromium.org718eab62011-10-05 21:16:521634 was_extension_process ? 2 : 1);
jochen@chromium.org718eab62011-10-05 21:16:521635 }
asvitkine@chromium.org80a8f312013-12-16 18:00:301636}
asargent@chromium.org1f085622009-12-04 05:33:451637
initial.commit09911bf2008-07-26 23:55:291638void MetricsService::LogRendererHang() {
cpu@google.come73c01972008-08-13 00:18:241639 IncrementPrefValue(prefs::kStabilityRendererHangCount);
initial.commit09911bf2008-07-26 23:55:291640}
1641
jar@chromium.orgc0c55e92011-09-10 18:47:301642bool MetricsService::UmaMetricsProperlyShutdown() {
1643 CHECK(clean_shutdown_status_ == CLEANLY_SHUTDOWN ||
1644 clean_shutdown_status_ == NEED_TO_SHUTDOWN);
1645 return clean_shutdown_status_ == CLEANLY_SHUTDOWN;
1646}
1647
bengr@chromium.org60677562013-11-17 15:52:551648void MetricsService::RegisterSyntheticFieldTrial(
1649 const SyntheticTrialGroup& trial) {
1650 for (size_t i = 0; i < synthetic_trial_groups_.size(); ++i) {
1651 if (synthetic_trial_groups_[i].id.name == trial.id.name) {
1652 if (synthetic_trial_groups_[i].id.group != trial.id.group) {
1653 synthetic_trial_groups_[i].id.group = trial.id.group;
asvitkine@chromium.org7a5c07812014-02-26 11:45:411654 synthetic_trial_groups_[i].start_time = base::TimeTicks::Now();
bengr@chromium.org60677562013-11-17 15:52:551655 }
1656 return;
1657 }
1658 }
1659
asvitkine@chromium.org7a5c07812014-02-26 11:45:411660 SyntheticTrialGroup trial_group = trial;
1661 trial_group.start_time = base::TimeTicks::Now();
bengr@chromium.org60677562013-11-17 15:52:551662 synthetic_trial_groups_.push_back(trial_group);
1663}
1664
asvitkine@chromium.org85791b0b2014-05-20 15:18:581665void MetricsService::RegisterMetricsProvider(
1666 scoped_ptr<metrics::MetricsProvider> provider) {
1667 DCHECK_EQ(INITIALIZED, state_);
1668 metrics_providers_.push_back(provider.release());
1669}
1670
blundell@chromium.org61b0d482014-05-20 14:49:101671void MetricsService::CheckForClonedInstall(
1672 scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
1673 state_manager_->CheckForClonedInstall(task_runner);
jwd@chromium.org99c892d2014-03-24 18:11:211674}
1675
bengr@chromium.org60677562013-11-17 15:52:551676void MetricsService::GetCurrentSyntheticFieldTrials(
asvitkine@chromium.orgb3610d42014-05-19 18:07:231677 std::vector<variations::ActiveGroupId>* synthetic_trials) {
bengr@chromium.org60677562013-11-17 15:52:551678 DCHECK(synthetic_trials);
1679 synthetic_trials->clear();
1680 const MetricsLog* current_log =
1681 static_cast<const MetricsLog*>(log_manager_.current_log());
1682 for (size_t i = 0; i < synthetic_trial_groups_.size(); ++i) {
1683 if (synthetic_trial_groups_[i].start_time <= current_log->creation_time())
1684 synthetic_trials->push_back(synthetic_trial_groups_[i].id);
1685 }
1686}
1687
isherman@chromium.org09dee82d2014-05-22 14:00:531688scoped_ptr<MetricsLog> MetricsService::CreateLog(MetricsLog::LogType log_type) {
1689 return make_scoped_ptr(new MetricsLog(
1690 state_manager_->client_id(), session_id_, log_type, client_));
1691}
1692
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381693void MetricsService::LogCleanShutdown() {
jar@chromium.orgacd55b32011-09-05 17:35:311694 // Redundant hack to write pref ASAP.
nileshagrawal@chromium.org84c384e2013-03-01 23:20:191695 MarkAppCleanShutdownAndCommit();
1696
jar@chromium.orgc0c55e92011-09-10 18:47:301697 // Redundant setting to assure that we always reset this value at shutdown
1698 // (and that we don't use some alternate path, and not call LogCleanShutdown).
1699 clean_shutdown_status_ = CLEANLY_SHUTDOWN;
jar@chromium.orgacd55b32011-09-05 17:35:311700
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381701 RecordBooleanPrefValue(prefs::kStabilityExitedCleanly, true);
rtenneti@chromium.org6a6d0d12013-10-28 15:58:191702 PrefService* pref = g_browser_process->local_state();
1703 pref->SetInteger(prefs::kStabilityExecutionPhase,
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:211704 MetricsService::SHUTDOWN_COMPLETE);
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381705}
1706
petkov@chromium.orgc1834a92011-01-21 18:21:031707#if defined(OS_CHROMEOS)
1708void MetricsService::LogChromeOSCrash(const std::string &crash_type) {
1709 if (crash_type == "user")
1710 IncrementPrefValue(prefs::kStabilityOtherUserCrashCount);
1711 else if (crash_type == "kernel")
1712 IncrementPrefValue(prefs::kStabilityKernelCrashCount);
1713 else if (crash_type == "uncleanshutdown")
1714 IncrementPrefValue(prefs::kStabilitySystemUncleanShutdownCount);
1715 else
1716 NOTREACHED() << "Unexpected Chrome OS crash type " << crash_type;
1717 // Wake up metrics logs sending if necessary now that new
1718 // log data is available.
1719 HandleIdleSinceLastTransmission(false);
1720}
1721#endif // OS_CHROMEOS
1722
brettw@chromium.org650b2d52013-02-10 03:41:451723void MetricsService::LogPluginLoadingError(const base::FilePath& plugin_path) {
jam@chromium.orgd7bd3e52013-07-21 04:29:201724 content::WebPluginInfo plugin;
bauerb@chromium.orgcd937072012-07-02 09:00:291725 bool success =
1726 content::PluginService::GetInstance()->GetPluginInfoByPath(plugin_path,
1727 &plugin);
1728 DCHECK(success);
1729 ChildProcessStats& stats = child_process_stats_buffer_[plugin.name];
1730 // Initialize the type if this entry is new.
1731 if (stats.process_type == content::PROCESS_TYPE_UNKNOWN) {
1732 // The plug-in process might not actually of type PLUGIN (which means
1733 // NPAPI), but we only care that it is *a* plug-in process.
1734 stats.process_type = content::PROCESS_TYPE_PLUGIN;
1735 } else {
1736 DCHECK(IsPluginProcess(stats.process_type));
1737 }
1738 stats.loading_errors++;
1739}
1740
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:401741MetricsService::ChildProcessStats& MetricsService::GetChildProcessStats(
1742 const content::ChildProcessData& data) {
brettw@chromium.org439f1e32013-12-09 20:09:091743 const base::string16& child_name = data.name;
jam@chromium.orgf3b357692013-03-22 05:16:131744 if (!ContainsKey(child_process_stats_buffer_, child_name)) {
1745 child_process_stats_buffer_[child_name] =
1746 ChildProcessStats(data.process_type);
1747 }
phajdan.jr@chromium.orgf4eaf7b92013-02-28 22:00:401748 return child_process_stats_buffer_[child_name];
initial.commit09911bf2008-07-26 23:55:291749}
1750
initial.commit09911bf2008-07-26 23:55:291751void MetricsService::RecordPluginChanges(PrefService* pref) {
battre@chromium.orgf8628c22011-04-05 12:10:181752 ListPrefUpdate update(pref, prefs::kStabilityPluginStats);
avi@chromium.orgcb1078de2013-12-23 20:04:221753 base::ListValue* plugins = update.Get();
initial.commit09911bf2008-07-26 23:55:291754 DCHECK(plugins);
1755
avi@chromium.orgcb1078de2013-12-23 20:04:221756 for (base::ListValue::iterator value_iter = plugins->begin();
initial.commit09911bf2008-07-26 23:55:291757 value_iter != plugins->end(); ++value_iter) {
avi@chromium.orgcb1078de2013-12-23 20:04:221758 if (!(*value_iter)->IsType(base::Value::TYPE_DICTIONARY)) {
jar@chromium.orga063c102010-07-22 22:20:191759 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291760 continue;
1761 }
1762
avi@chromium.orgcb1078de2013-12-23 20:04:221763 base::DictionaryValue* plugin_dict =
1764 static_cast<base::DictionaryValue*>(*value_iter);
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511765 std::string plugin_name;
nsylvain@chromium.org8e50b602009-03-03 22:59:431766 plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);
nsylvain@chromium.org6470ee8f2009-03-03 20:46:401767 if (plugin_name.empty()) {
jar@chromium.orga063c102010-07-22 22:20:191768 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291769 continue;
1770 }
1771
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511772 // TODO(viettrungluu): remove conversions
avi@chromium.org6778fed2013-12-24 20:09:371773 base::string16 name16 = base::UTF8ToUTF16(plugin_name);
evan@chromium.org68b9e72b2011-08-05 23:08:221774 if (child_process_stats_buffer_.find(name16) ==
1775 child_process_stats_buffer_.end()) {
initial.commit09911bf2008-07-26 23:55:291776 continue;
evan@chromium.org68b9e72b2011-08-05 23:08:221777 }
initial.commit09911bf2008-07-26 23:55:291778
evan@chromium.org68b9e72b2011-08-05 23:08:221779 ChildProcessStats stats = child_process_stats_buffer_[name16];
initial.commit09911bf2008-07-26 23:55:291780 if (stats.process_launches) {
1781 int launches = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431782 plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
initial.commit09911bf2008-07-26 23:55:291783 launches += stats.process_launches;
nsylvain@chromium.org8e50b602009-03-03 22:59:431784 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches, launches);
initial.commit09911bf2008-07-26 23:55:291785 }
1786 if (stats.process_crashes) {
1787 int crashes = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431788 plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
initial.commit09911bf2008-07-26 23:55:291789 crashes += stats.process_crashes;
nsylvain@chromium.org8e50b602009-03-03 22:59:431790 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes, crashes);
initial.commit09911bf2008-07-26 23:55:291791 }
1792 if (stats.instances) {
1793 int instances = 0;
nsylvain@chromium.org8e50b602009-03-03 22:59:431794 plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
initial.commit09911bf2008-07-26 23:55:291795 instances += stats.instances;
nsylvain@chromium.org8e50b602009-03-03 22:59:431796 plugin_dict->SetInteger(prefs::kStabilityPluginInstances, instances);
initial.commit09911bf2008-07-26 23:55:291797 }
bauerb@chromium.orgcd937072012-07-02 09:00:291798 if (stats.loading_errors) {
1799 int loading_errors = 0;
1800 plugin_dict->GetInteger(prefs::kStabilityPluginLoadingErrors,
1801 &loading_errors);
1802 loading_errors += stats.loading_errors;
1803 plugin_dict->SetInteger(prefs::kStabilityPluginLoadingErrors,
1804 loading_errors);
1805 }
initial.commit09911bf2008-07-26 23:55:291806
evan@chromium.org68b9e72b2011-08-05 23:08:221807 child_process_stats_buffer_.erase(name16);
initial.commit09911bf2008-07-26 23:55:291808 }
1809
1810 // Now go through and add dictionaries for plugins that didn't already have
1811 // reports in Local State.
brettw@chromium.orgd2065e062013-12-12 23:49:521812 for (std::map<base::string16, ChildProcessStats>::iterator cache_iter =
jam@chromium.orga27a9382009-02-11 23:55:101813 child_process_stats_buffer_.begin();
1814 cache_iter != child_process_stats_buffer_.end(); ++cache_iter) {
jam@chromium.orga27a9382009-02-11 23:55:101815 ChildProcessStats stats = cache_iter->second;
gregoryd@google.com0d84c5d2009-10-09 01:10:421816
1817 // Insert only plugins information into the plugins list.
petkov@chromium.org8d5f1dae2011-11-11 14:30:411818 if (!IsPluginProcess(stats.process_type))
gregoryd@google.com0d84c5d2009-10-09 01:10:421819 continue;
1820
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511821 // TODO(viettrungluu): remove conversion
avi@chromium.org6778fed2013-12-24 20:09:371822 std::string plugin_name = base::UTF16ToUTF8(cache_iter->first);
gregoryd@google.com0d84c5d2009-10-09 01:10:421823
avi@chromium.orgcb1078de2013-12-23 20:04:221824 base::DictionaryValue* plugin_dict = new base::DictionaryValue;
initial.commit09911bf2008-07-26 23:55:291825
nsylvain@chromium.org8e50b602009-03-03 22:59:431826 plugin_dict->SetString(prefs::kStabilityPluginName, plugin_name);
1827 plugin_dict->SetInteger(prefs::kStabilityPluginLaunches,
initial.commit09911bf2008-07-26 23:55:291828 stats.process_launches);
nsylvain@chromium.org8e50b602009-03-03 22:59:431829 plugin_dict->SetInteger(prefs::kStabilityPluginCrashes,
initial.commit09911bf2008-07-26 23:55:291830 stats.process_crashes);
nsylvain@chromium.org8e50b602009-03-03 22:59:431831 plugin_dict->SetInteger(prefs::kStabilityPluginInstances,
initial.commit09911bf2008-07-26 23:55:291832 stats.instances);
bauerb@chromium.orgcd937072012-07-02 09:00:291833 plugin_dict->SetInteger(prefs::kStabilityPluginLoadingErrors,
1834 stats.loading_errors);
initial.commit09911bf2008-07-26 23:55:291835 plugins->Append(plugin_dict);
1836 }
jam@chromium.orga27a9382009-02-11 23:55:101837 child_process_stats_buffer_.clear();
initial.commit09911bf2008-07-26 23:55:291838}
1839
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:041840bool MetricsService::ShouldLogEvents() {
1841 // We simply don't log events to UMA if there is a single incognito
initial.commit09911bf2008-07-26 23:55:291842 // session visible. The problem is that we always notify using the orginal
1843 // profile in order to simplify notification processing.
tfarina@chromium.orge764e582012-08-01 03:01:291844 return !chrome::IsOffTheRecordSessionActive();
initial.commit09911bf2008-07-26 23:55:291845}
1846
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511847void MetricsService::RecordBooleanPrefValue(const char* path, bool value) {
initial.commit09911bf2008-07-26 23:55:291848 DCHECK(IsSingleThreaded());
1849
1850 PrefService* pref = g_browser_process->local_state();
1851 DCHECK(pref);
1852
1853 pref->SetBoolean(path, value);
1854 RecordCurrentState(pref);
1855}
1856
1857void MetricsService::RecordCurrentState(PrefService* pref) {
robertshield@google.com0bb1a622009-03-04 03:22:321858 pref->SetInt64(prefs::kStabilityLastTimestampSec, Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291859
1860 RecordPluginChanges(pref);
1861}
1862
petkov@chromium.org8d5f1dae2011-11-11 14:30:411863// static
jam@chromium.orgf3b357692013-03-22 05:16:131864bool MetricsService::IsPluginProcess(int process_type) {
1865 return (process_type == content::PROCESS_TYPE_PLUGIN ||
1866 process_type == content::PROCESS_TYPE_PPAPI_PLUGIN ||
1867 process_type == content::PROCESS_TYPE_PPAPI_BROKER);
petkov@chromium.org8d5f1dae2011-11-11 14:30:411868}
1869
sreeram@chromium.org3819f2ee2011-08-21 09:44:381870// static
1871bool MetricsServiceHelper::IsMetricsReportingEnabled() {
1872 bool result = false;
1873 const PrefService* local_state = g_browser_process->local_state();
1874 if (local_state) {
1875 const PrefService::Preference* uma_pref =
1876 local_state->FindPreference(prefs::kMetricsReportingEnabled);
1877 if (uma_pref) {
1878 bool success = uma_pref->GetValue()->GetAsBoolean(&result);
1879 DCHECK(success);
1880 }
1881 }
1882 return result;
1883}
elijahtaylor@chromium.org1ef13cf2014-03-21 22:44:011884
1885bool MetricsServiceHelper::IsCrashReportingEnabled() {
1886#if defined(GOOGLE_CHROME_BUILD)
1887#if defined(OS_CHROMEOS)
1888 bool reporting_enabled = false;
1889 chromeos::CrosSettings::Get()->GetBoolean(chromeos::kStatsReportingPref,
1890 &reporting_enabled);
1891 return reporting_enabled;
1892#elif defined(OS_ANDROID)
1893 // Android has its own settings for metrics / crash uploading.
1894 const PrefService* prefs = g_browser_process->local_state();
1895 return prefs->GetBoolean(prefs::kCrashReportingEnabled);
1896#else
1897 return MetricsServiceHelper::IsMetricsReportingEnabled();
1898#endif
1899#else
1900 return false;
1901#endif
1902}
bolian@chromium.org2a321de32014-05-10 19:59:061903
1904void MetricsServiceHelper::AddMetricsServiceObserver(
1905 MetricsServiceObserver* observer) {
1906 MetricsService* metrics_service = g_browser_process->metrics_service();
1907 if (metrics_service)
1908 metrics_service->AddObserver(observer);
1909}
1910
1911void MetricsServiceHelper::RemoveMetricsServiceObserver(
1912 MetricsServiceObserver* observer) {
1913 MetricsService* metrics_service = g_browser_process->metrics_service();
1914 if (metrics_service)
1915 metrics_service->RemoveObserver(observer);
1916}