blob: 54e4deb73c6a2f5af67a2139d72af6869bd5a4e3 [file] [log] [blame]
blundell@chromium.orgd6147bd2014-06-11 01:58:191// Copyright 2014 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
blundell@chromium.orgd6147bd2014-06-11 01:58:19164#include "components/metrics/metrics_service.h"
maruel@chromium.org40bcc302009-03-02 20:50:39165
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"
brettw@chromium.org835d7c82010-10-14 04:38:38170#include "base/metrics/histogram.h"
isherman@chromium.orgacc2ce5512014-05-22 18:29:13171#include "base/metrics/histogram_base.h"
172#include "base/metrics/histogram_samples.h"
eroman@chromium.org1026afd2013-03-20 14:28:54173#include "base/metrics/sparse_histogram.h"
kaiwang@chromium.org567d30e2012-07-13 21:48:29174#include "base/metrics/statistics_recorder.h"
joi@chromium.org3853a4c2013-02-11 17:15:57175#include "base/prefs/pref_registry_simple.h"
176#include "base/prefs/pref_service.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"
gab@chromium.org64b8652c2014-07-16 19:14:28182#include "base/time/time.h"
isherman@chromium.orged0fd002012-04-25 23:10:34183#include "base/tracked_objects.h"
erg@google.com679082052010-07-21 21:30:13184#include "base/values.h"
blundell@chromium.org91b1d912014-06-05 10:52:08185#include "components/metrics/metrics_log.h"
bsimonnet@chromium.org064107e2014-05-02 00:59:06186#include "components/metrics/metrics_log_manager.h"
asvitkine@chromium.org0d5a61a82014-05-31 22:28:34187#include "components/metrics/metrics_log_uploader.h"
holte@chromium.org7f07db62014-05-15 01:12:45188#include "components/metrics/metrics_pref_names.h"
motek@chromium.org14bb46692014-05-20 17:16:45189#include "components/metrics/metrics_reporting_scheduler.h"
asvitkine@chromium.org73929422014-05-22 08:19:05190#include "components/metrics/metrics_service_client.h"
blundell@chromium.org16a30912014-06-04 00:20:04191#include "components/metrics/metrics_state_manager.h"
asvitkine@chromium.org50ae9f12013-08-29 18:03:22192#include "components/variations/entropy_provider.h"
initial.commit09911bf2008-07-26 23:55:29193
asvitkinecbd420732014-08-26 22:15:40194namespace metrics {
dsh@google.come1acf6f2008-10-27 20:43:33195
isherman@chromium.orgfe58acc22012-02-29 01:29:58196namespace {
isherman@chromium.orgb2a4812d2012-02-28 05:31:31197
isherman@chromium.orgfe58acc22012-02-29 01:29:58198// Check to see that we're being called on only one thread.
199bool IsSingleThreaded() {
200 static base::PlatformThreadId thread_id = 0;
201 if (!thread_id)
202 thread_id = base::PlatformThread::CurrentId();
203 return base::PlatformThread::CurrentId() == thread_id;
204}
205
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16206// The delay, in seconds, after starting recording before doing expensive
207// initialization work.
dfalcantara@chromium.org12180f82012-10-10 21:13:30208#if defined(OS_ANDROID) || defined(OS_IOS)
209// On mobile devices, a significant portion of sessions last less than a minute.
210// Use a shorter timer on these platforms to avoid losing data.
211// TODO(dfalcantara): To avoid delaying startup, tighten up initialization so
212// that it occurs after the user gets their initial page.
213const int kInitializationDelaySeconds = 5;
214#else
isherman@chromium.orgfe58acc22012-02-29 01:29:58215const int kInitializationDelaySeconds = 30;
dfalcantara@chromium.org12180f82012-10-10 21:13:30216#endif
petersont@google.com252873ef2008-08-04 21:59:45217
stuartmorgan@chromium.org54702c92011-04-15 15:06:43218// The maximum number of events in a log uploaded to the UMA server.
isherman@chromium.orgfe58acc22012-02-29 01:29:58219const int kEventLimit = 2400;
jar@google.com68475e602008-08-22 03:21:15220
221// If an upload fails, and the transmission was over this byte count, then we
222// will discard the log, and not try to retransmit it. We also don't persist
223// the log to the prefs for transmission during the next chrome session if this
224// limit is exceeded.
asvitkine@chromium.orga63006e2014-06-20 05:22:32225const size_t kUploadLogAvoidRetransmitSize = 100 * 1024;
initial.commit09911bf2008-07-26 23:55:29226
tedvessenes@gmail.comfc4252a72012-01-12 21:58:47227// Interval, in minutes, between state saves.
isherman@chromium.orgfe58acc22012-02-29 01:29:58228const int kSaveStateIntervalMinutes = 5;
229
isherman@chromium.org4266def22012-05-17 01:02:40230enum ResponseStatus {
231 UNKNOWN_FAILURE,
232 SUCCESS,
233 BAD_REQUEST, // Invalid syntax or log too large.
isherman@chromium.org9f5c1ce82012-05-23 23:11:28234 NO_RESPONSE,
isherman@chromium.org4266def22012-05-17 01:02:40235 NUM_RESPONSE_STATUSES
236};
237
238ResponseStatus ResponseCodeToStatus(int response_code) {
239 switch (response_code) {
asvitkine@chromium.org0d5a61a82014-05-31 22:28:34240 case -1:
241 return NO_RESPONSE;
isherman@chromium.org4266def22012-05-17 01:02:40242 case 200:
243 return SUCCESS;
244 case 400:
245 return BAD_REQUEST;
246 default:
247 return UNKNOWN_FAILURE;
248 }
249}
250
erikwright65b58df2014-09-12 00:05:28251void MarkAppCleanShutdownAndCommit(CleanExitBeacon* clean_exit_beacon,
252 PrefService* local_state) {
253 clean_exit_beacon->WriteBeaconValue(true);
asvitkinea63d19e2014-10-24 16:19:39254 local_state->SetInteger(prefs::kStabilityExecutionPhase,
blundell@chromium.org24f81ca2014-05-26 15:59:34255 MetricsService::SHUTDOWN_COMPLETE);
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19256 // Start writing right away (write happens on a different thread).
blundell@chromium.org24f81ca2014-05-26 15:59:34257 local_state->CommitPendingWrite();
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19258}
259
asvitkine@chromium.org20f999b52012-08-24 22:32:59260} // namespace
initial.commit09911bf2008-07-26 23:55:29261
bengr@chromium.org60677562013-11-17 15:52:55262
asvitkine@chromium.org7a5c07812014-02-26 11:45:41263SyntheticTrialGroup::SyntheticTrialGroup(uint32 trial, uint32 group) {
bengr@chromium.org60677562013-11-17 15:52:55264 id.name = trial;
265 id.group = group;
266}
267
268SyntheticTrialGroup::~SyntheticTrialGroup() {
269}
270
jar@chromium.orgc0c55e92011-09-10 18:47:30271// static
272MetricsService::ShutdownCleanliness MetricsService::clean_shutdown_status_ =
273 MetricsService::CLEANLY_SHUTDOWN;
274
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19275MetricsService::ExecutionPhase MetricsService::execution_phase_ =
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21276 MetricsService::UNINITIALIZED_PHASE;
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19277
initial.commit09911bf2008-07-26 23:55:29278// static
joi@chromium.orgb1de2c72013-02-06 02:45:47279void MetricsService::RegisterPrefs(PrefRegistrySimple* registry) {
initial.commit09911bf2008-07-26 23:55:29280 DCHECK(IsSingleThreaded());
asvitkinea63d19e2014-10-24 16:19:39281 MetricsStateManager::RegisterPrefs(registry);
blundell@chromium.org91b1d912014-06-05 10:52:08282 MetricsLog::RegisterPrefs(registry);
miu@chromium.org39076642014-05-05 20:32:55283
asvitkinea63d19e2014-10-24 16:19:39284 registry->RegisterInt64Pref(prefs::kInstallDate, 0);
gab@chromium.org65801452014-07-09 05:42:41285
asvitkinea63d19e2014-10-24 16:19:39286 registry->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
287 registry->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
288 registry->RegisterStringPref(prefs::kStabilityStatsVersion, std::string());
289 registry->RegisterInt64Pref(prefs::kStabilityStatsBuildTime, 0);
290 registry->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
291 registry->RegisterIntegerPref(prefs::kStabilityExecutionPhase,
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21292 UNINITIALIZED_PHASE);
asvitkinea63d19e2014-10-24 16:19:39293 registry->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
294 registry->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
asvitkine@chromium.org0f2f7792013-11-28 16:09:14295
asvitkinea63d19e2014-10-24 16:19:39296 registry->RegisterListPref(prefs::kMetricsInitialLogs);
297 registry->RegisterListPref(prefs::kMetricsOngoingLogs);
robertshield@google.com0bb1a622009-03-04 03:22:32298
asvitkinea63d19e2014-10-24 16:19:39299 registry->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
300 registry->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
initial.commit09911bf2008-07-26 23:55:29301}
302
asvitkinea63d19e2014-10-24 16:19:39303MetricsService::MetricsService(MetricsStateManager* state_manager,
304 MetricsServiceClient* client,
blundell@chromium.org24f81ca2014-05-26 15:59:34305 PrefService* local_state)
306 : log_manager_(local_state, kUploadLogAvoidRetransmitSize),
isherman@chromium.orgacc2ce5512014-05-22 18:29:13307 histogram_snapshot_manager_(this),
holte@chromium.org7f07db62014-05-15 01:12:45308 state_manager_(state_manager),
isherman@chromium.org728de072014-05-21 09:20:32309 client_(client),
blundell@chromium.org24f81ca2014-05-26 15:59:34310 local_state_(local_state),
erikwright65b58df2014-09-12 00:05:28311 clean_exit_beacon_(client->GetRegistryBackupKey(), local_state),
jwd@chromium.org37d4709a2014-03-29 03:07:40312 recording_active_(false),
petersont@google.comd01b8732008-10-16 02:18:07313 reporting_active_(false),
stuartmorgan@chromium.org410938e02012-10-24 16:33:59314 test_mode_active_(false),
petersont@google.comd01b8732008-10-16 02:18:07315 state_(INITIALIZED),
asvitkine@chromium.org80a8f312013-12-16 18:00:30316 has_initial_stability_log_(false),
asvitkine@chromium.org0d5a61a82014-05-31 22:28:34317 log_upload_in_progress_(false),
petersont@google.comd01b8732008-10-16 02:18:07318 idle_since_last_transmission_(false),
asvitkine@chromium.org80a8f312013-12-16 18:00:30319 session_id_(-1),
tfarina@chromium.org9c009092013-05-01 03:14:09320 self_ptr_factory_(this),
asvitkine@chromium.org0d5a61a82014-05-31 22:28:34321 state_saver_factory_(this) {
initial.commit09911bf2008-07-26 23:55:29322 DCHECK(IsSingleThreaded());
miu@chromium.org39076642014-05-05 20:32:55323 DCHECK(state_manager_);
isherman@chromium.org728de072014-05-21 09:20:32324 DCHECK(client_);
blundell@chromium.org24f81ca2014-05-26 15:59:34325 DCHECK(local_state_);
gab@chromium.org64b8652c2014-07-16 19:14:28326
327 // Set the install date if this is our first run.
asvitkinea63d19e2014-10-24 16:19:39328 int64 install_date = local_state_->GetInt64(prefs::kInstallDate);
329 if (install_date == 0)
330 local_state_->SetInt64(prefs::kInstallDate, base::Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:29331}
332
333MetricsService::~MetricsService() {
stuartmorgan@chromium.org410938e02012-10-24 16:33:59334 DisableRecording();
initial.commit09911bf2008-07-26 23:55:29335}
336
miu@chromium.org39076642014-05-05 20:32:55337void MetricsService::InitializeMetricsRecordingState() {
338 InitializeMetricsState();
asvitkine@chromium.org80a8f312013-12-16 18:00:30339
gayaned52ca402015-02-23 21:23:06340 base::Closure upload_callback =
341 base::Bind(&MetricsService::StartScheduledUpload,
342 self_ptr_factory_.GetWeakPtr());
343 scheduler_.reset(
344 new MetricsReportingScheduler(upload_callback, is_cellular_callback_));
asvitkine@chromium.org80a8f312013-12-16 18:00:30345}
346
petersont@google.comd01b8732008-10-16 02:18:07347void MetricsService::Start() {
stuartmorgan@chromium.orgb1c8dc02011-04-13 18:32:04348 HandleIdleSinceLastTransmission(false);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59349 EnableRecording();
350 EnableReporting();
petersont@google.comd01b8732008-10-16 02:18:07351}
352
miu@chromium.org39076642014-05-05 20:32:55353bool MetricsService::StartIfMetricsReportingEnabled() {
354 const bool enabled = state_manager_->IsMetricsReportingEnabled();
355 if (enabled)
356 Start();
357 return enabled;
358}
359
stuartmorgan@chromium.org410938e02012-10-24 16:33:59360void MetricsService::StartRecordingForTests() {
361 test_mode_active_ = true;
362 EnableRecording();
363 DisableReporting();
petersont@google.comd01b8732008-10-16 02:18:07364}
365
366void MetricsService::Stop() {
stuartmorgan@chromium.orgb1c8dc02011-04-13 18:32:04367 HandleIdleSinceLastTransmission(false);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59368 DisableReporting();
369 DisableRecording();
370}
371
372void MetricsService::EnableReporting() {
373 if (reporting_active_)
374 return;
375 reporting_active_ = true;
376 StartSchedulerIfNecessary();
377}
378
379void MetricsService::DisableReporting() {
380 reporting_active_ = false;
petersont@google.comd01b8732008-10-16 02:18:07381}
382
joi@chromium.orgedafd4c2011-05-10 17:18:53383std::string MetricsService::GetClientId() {
miu@chromium.org39076642014-05-05 20:32:55384 return state_manager_->client_id();
joi@chromium.orgedafd4c2011-05-10 17:18:53385}
386
gab@chromium.org65801452014-07-09 05:42:41387int64 MetricsService::GetInstallDate() {
asvitkinea63d19e2014-10-24 16:19:39388 return local_state_->GetInt64(prefs::kInstallDate);
gab@chromium.org65801452014-07-09 05:42:41389}
390
asvitkine@chromium.org20f999b52012-08-24 22:32:59391scoped_ptr<const base::FieldTrial::EntropyProvider>
miu@chromium.org39076642014-05-05 20:32:55392MetricsService::CreateEntropyProvider() {
393 // TODO(asvitkine): Refactor the code so that MetricsService does not expose
394 // this method.
395 return state_manager_->CreateEntropyProvider();
jam@chromium.org5cbeeef72012-02-08 02:05:18396}
397
stuartmorgan@chromium.org410938e02012-10-24 16:33:59398void MetricsService::EnableRecording() {
initial.commit09911bf2008-07-26 23:55:29399 DCHECK(IsSingleThreaded());
400
stuartmorgan@chromium.org410938e02012-10-24 16:33:59401 if (recording_active_)
initial.commit09911bf2008-07-26 23:55:29402 return;
stuartmorgan@chromium.org410938e02012-10-24 16:33:59403 recording_active_ = true;
initial.commit09911bf2008-07-26 23:55:29404
miu@chromium.org39076642014-05-05 20:32:55405 state_manager_->ForceClientIdCreation();
gab@chromium.org9d1b0152014-07-09 18:53:22406 client_->SetMetricsClientId(state_manager_->client_id());
stuartmorgan@chromium.org410938e02012-10-24 16:33:59407 if (!log_manager_.current_log())
408 OpenNewLog();
pkasting@chromium.org005ef3e2009-05-22 20:55:46409
asvitkine@chromium.org85791b0b2014-05-20 15:18:58410 for (size_t i = 0; i < metrics_providers_.size(); ++i)
411 metrics_providers_[i]->OnRecordingEnabled();
412
ben@chromium.orge6e30ac2014-01-13 21:24:39413 base::RemoveActionCallback(action_callback_);
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:22414 action_callback_ = base::Bind(&MetricsService::OnUserAction,
415 base::Unretained(this));
ben@chromium.orge6e30ac2014-01-13 21:24:39416 base::AddActionCallback(action_callback_);
stuartmorgan@chromium.org410938e02012-10-24 16:33:59417}
418
419void MetricsService::DisableRecording() {
420 DCHECK(IsSingleThreaded());
421
422 if (!recording_active_)
423 return;
424 recording_active_ = false;
425
ben@chromium.orge6e30ac2014-01-13 21:24:39426 base::RemoveActionCallback(action_callback_);
asvitkine@chromium.org85791b0b2014-05-20 15:18:58427
428 for (size_t i = 0; i < metrics_providers_.size(); ++i)
429 metrics_providers_[i]->OnRecordingDisabled();
430
stuartmorgan@chromium.org410938e02012-10-24 16:33:59431 PushPendingLogsToPersistentStorage();
initial.commit09911bf2008-07-26 23:55:29432}
433
petersont@google.comd01b8732008-10-16 02:18:07434bool MetricsService::recording_active() const {
initial.commit09911bf2008-07-26 23:55:29435 DCHECK(IsSingleThreaded());
petersont@google.comd01b8732008-10-16 02:18:07436 return recording_active_;
initial.commit09911bf2008-07-26 23:55:29437}
438
petersont@google.comd01b8732008-10-16 02:18:07439bool MetricsService::reporting_active() const {
440 DCHECK(IsSingleThreaded());
441 return reporting_active_;
initial.commit09911bf2008-07-26 23:55:29442}
443
isherman@chromium.orgacc2ce5512014-05-22 18:29:13444void MetricsService::RecordDelta(const base::HistogramBase& histogram,
445 const base::HistogramSamples& snapshot) {
446 log_manager_.current_log()->RecordHistogramDelta(histogram.histogram_name(),
447 snapshot);
448}
449
450void MetricsService::InconsistencyDetected(
451 base::HistogramBase::Inconsistency problem) {
452 UMA_HISTOGRAM_ENUMERATION("Histogram.InconsistenciesBrowser",
453 problem, base::HistogramBase::NEVER_EXCEEDED_VALUE);
454}
455
456void MetricsService::UniqueInconsistencyDetected(
457 base::HistogramBase::Inconsistency problem) {
458 UMA_HISTOGRAM_ENUMERATION("Histogram.InconsistenciesBrowserUnique",
459 problem, base::HistogramBase::NEVER_EXCEEDED_VALUE);
460}
461
462void MetricsService::InconsistencyDetectedInLoggedCount(int amount) {
463 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentSnapshotBrowser",
464 std::abs(amount));
465}
466
petersont@google.comd01b8732008-10-16 02:18:07467void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
468 // If there wasn't a lot of action, maybe the computer was asleep, in which
469 // case, the log transmissions should have stopped. Here we start them up
470 // again.
pkasting@chromium.orgcac78842008-11-27 01:02:20471 if (!in_idle && idle_since_last_transmission_)
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16472 StartSchedulerIfNecessary();
pkasting@chromium.orgcac78842008-11-27 01:02:20473 idle_since_last_transmission_ = in_idle;
initial.commit09911bf2008-07-26 23:55:29474}
475
isherman@chromium.orgd7ea39e2014-05-22 03:59:18476void MetricsService::OnApplicationNotIdle() {
477 if (recording_active_)
478 HandleIdleSinceLastTransmission(false);
479}
480
initial.commit09911bf2008-07-26 23:55:29481void MetricsService::RecordStartOfSessionEnd() {
stuartmorgan@chromium.org466f3c12011-03-23 21:20:38482 LogCleanShutdown();
asvitkinea63d19e2014-10-24 16:19:39483 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
initial.commit09911bf2008-07-26 23:55:29484}
485
486void MetricsService::RecordCompletedSessionEnd() {
stuartmorgan@chromium.org466f3c12011-03-23 21:20:38487 LogCleanShutdown();
asvitkinea63d19e2014-10-24 16:19:39488 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
initial.commit09911bf2008-07-26 23:55:29489}
490
stuartmorgan@chromium.org410938e02012-10-24 16:33:59491#if defined(OS_ANDROID) || defined(OS_IOS)
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39492void MetricsService::OnAppEnterBackground() {
493 scheduler_->Stop();
494
erikwright65b58df2014-09-12 00:05:28495 MarkAppCleanShutdownAndCommit(&clean_exit_beacon_, local_state_);
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39496
497 // At this point, there's no way of knowing when the process will be
498 // killed, so this has to be treated similar to a shutdown, closing and
499 // persisting all logs. Unlinke a shutdown, the state is primed to be ready
500 // to continue logging and uploading if the process does return.
asvitkine@chromium.org80a8f312013-12-16 18:00:30501 if (recording_active() && state_ >= SENDING_INITIAL_STABILITY_LOG) {
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39502 PushPendingLogsToPersistentStorage();
stuartmorgan@chromium.org410938e02012-10-24 16:33:59503 // Persisting logs closes the current log, so start recording a new log
504 // immediately to capture any background work that might be done before the
505 // process is killed.
506 OpenNewLog();
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39507 }
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39508}
509
510void MetricsService::OnAppEnterForeground() {
erikwright65b58df2014-09-12 00:05:28511 clean_exit_beacon_.WriteBeaconValue(false);
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39512 StartSchedulerIfNecessary();
513}
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19514#else
erikwrightcc98a7e02014-09-09 22:05:12515void MetricsService::LogNeedForCleanShutdown() {
erikwright65b58df2014-09-12 00:05:28516 clean_exit_beacon_.WriteBeaconValue(false);
nileshagrawal@chromium.org84c384e2013-03-01 23:20:19517 // Redundant setting to be sure we call for a clean shutdown.
518 clean_shutdown_status_ = NEED_TO_SHUTDOWN;
519}
520#endif // defined(OS_ANDROID) || defined(OS_IOS)
dfalcantara@chromium.org117fbdf22012-06-26 18:36:39521
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21522// static
blundell@chromium.org24f81ca2014-05-26 15:59:34523void MetricsService::SetExecutionPhase(ExecutionPhase execution_phase,
524 PrefService* local_state) {
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21525 execution_phase_ = execution_phase;
asvitkinea63d19e2014-10-24 16:19:39526 local_state->SetInteger(prefs::kStabilityExecutionPhase, execution_phase_);
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21527}
528
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16529void MetricsService::RecordBreakpadRegistration(bool success) {
jar@google.com68475e602008-08-22 03:21:15530 if (!success)
asvitkinea63d19e2014-10-24 16:19:39531 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
cpu@google.come73c01972008-08-13 00:18:24532 else
asvitkinea63d19e2014-10-24 16:19:39533 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
cpu@google.come73c01972008-08-13 00:18:24534}
535
536void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
537 if (!has_debugger)
asvitkinea63d19e2014-10-24 16:19:39538 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
cpu@google.come73c01972008-08-13 00:18:24539 else
asvitkinea63d19e2014-10-24 16:19:39540 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
cpu@google.come73c01972008-08-13 00:18:24541}
542
yiyaoliu14ef3ead2014-11-19 02:36:50543void MetricsService::ClearSavedStabilityMetrics() {
544 for (size_t i = 0; i < metrics_providers_.size(); ++i)
545 metrics_providers_[i]->ClearSavedStabilityMetrics();
546
547 // Reset the prefs that are managed by MetricsService/MetricsLog directly.
548 local_state_->SetInteger(prefs::kStabilityCrashCount, 0);
549 local_state_->SetInteger(prefs::kStabilityExecutionPhase,
550 UNINITIALIZED_PHASE);
551 local_state_->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
552 local_state_->SetInteger(prefs::kStabilityLaunchCount, 0);
553 local_state_->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
554}
555
initial.commit09911bf2008-07-26 23:55:29556//------------------------------------------------------------------------------
557// private methods
558//------------------------------------------------------------------------------
559
560
561//------------------------------------------------------------------------------
562// Initialization methods
563
miu@chromium.org39076642014-05-05 20:32:55564void MetricsService::InitializeMetricsState() {
asvitkineff3e2a62014-09-18 22:01:49565 const int64 buildtime = MetricsLog::GetBuildTime();
566 const std::string version = client_->GetVersionString();
567 bool version_changed = false;
568 if (local_state_->GetInt64(prefs::kStabilityStatsBuildTime) != buildtime ||
569 local_state_->GetString(prefs::kStabilityStatsVersion) != version) {
asvitkinea63d19e2014-10-24 16:19:39570 local_state_->SetString(prefs::kStabilityStatsVersion, version);
571 local_state_->SetInt64(prefs::kStabilityStatsBuildTime, buildtime);
asvitkineff3e2a62014-09-18 22:01:49572 version_changed = true;
573 }
initial.commit09911bf2008-07-26 23:55:29574
holte@chromium.org94dce122014-07-16 04:20:12575 log_manager_.LoadPersistedUnsentLogs();
576
asvitkinea63d19e2014-10-24 16:19:39577 session_id_ = local_state_->GetInteger(prefs::kMetricsSessionID);
erikwright65b58df2014-09-12 00:05:28578
579 if (!clean_exit_beacon_.exited_cleanly()) {
asvitkinea63d19e2014-10-24 16:19:39580 IncrementPrefValue(prefs::kStabilityCrashCount);
jar@chromium.orgc0c55e92011-09-10 18:47:30581 // Reset flag, and wait until we call LogNeedForCleanShutdown() before
582 // monitoring.
erikwright65b58df2014-09-12 00:05:28583 clean_exit_beacon_.WriteBeaconValue(true);
siggic179dd062014-09-10 17:02:31584 }
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19585
erikwright65b58df2014-09-12 00:05:28586 if (!clean_exit_beacon_.exited_cleanly() || ProvidersHaveStabilityMetrics()) {
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19587 // TODO(rtenneti): On windows, consider saving/getting execution_phase from
588 // the registry.
blundell@chromium.org24f81ca2014-05-26 15:59:34589 int execution_phase =
asvitkinea63d19e2014-10-24 16:19:39590 local_state_->GetInteger(prefs::kStabilityExecutionPhase);
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21591 UMA_HISTOGRAM_SPARSE_SLOWLY("Chrome.Browser.CrashedExecutionPhase",
rtenneti@chromium.org6a6d0d12013-10-28 15:58:19592 execution_phase);
asvitkine@chromium.org80a8f312013-12-16 18:00:30593
siggic179dd062014-09-10 17:02:31594 // If the previous session didn't exit cleanly, or if any provider
595 // explicitly requests it, prepare an initial stability log -
596 // provided UMA is enabled.
miu@chromium.org39076642014-05-05 20:32:55597 if (state_manager_->IsMetricsReportingEnabled())
asvitkine@chromium.org80a8f312013-12-16 18:00:30598 PrepareInitialStabilityLog();
initial.commit09911bf2008-07-26 23:55:29599 }
asvitkine@chromium.org80a8f312013-12-16 18:00:30600
asvitkineff3e2a62014-09-18 22:01:49601 // If no initial stability log was generated and there was a version upgrade,
602 // clear the stability stats from the previous version (so that they don't get
603 // attributed to the current version). This could otherwise happen due to a
604 // number of different edge cases, such as if the last version crashed before
605 // it could save off a system profile or if UMA reporting is disabled (which
606 // normally results in stats being accumulated).
yiyaoliu14ef3ead2014-11-19 02:36:50607 if (!has_initial_stability_log_ && version_changed)
608 ClearSavedStabilityMetrics();
asvitkineff3e2a62014-09-18 22:01:49609
asvitkine@chromium.org80a8f312013-12-16 18:00:30610 // Update session ID.
611 ++session_id_;
asvitkinea63d19e2014-10-24 16:19:39612 local_state_->SetInteger(prefs::kMetricsSessionID, session_id_);
asvitkine@chromium.org80a8f312013-12-16 18:00:30613
614 // Stability bookkeeping
asvitkinea63d19e2014-10-24 16:19:39615 IncrementPrefValue(prefs::kStabilityLaunchCount);
asvitkine@chromium.org80a8f312013-12-16 18:00:30616
rtenneti@chromium.org6d67ea0d2013-11-14 11:02:21617 DCHECK_EQ(UNINITIALIZED_PHASE, execution_phase_);
blundell@chromium.org24f81ca2014-05-26 15:59:34618 SetExecutionPhase(START_METRICS_RECORDING, local_state_);
cpu@google.come73c01972008-08-13 00:18:24619
asvitkinea63d19e2014-10-24 16:19:39620 if (!local_state_->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
621 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
jar@chromium.orgc9abf242009-07-18 06:00:38622 // This is marked false when we get a WM_ENDSESSION.
asvitkinea63d19e2014-10-24 16:19:39623 local_state_->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
initial.commit09911bf2008-07-26 23:55:29624 }
initial.commit09911bf2008-07-26 23:55:29625
mpearson@chromium.org076961c2014-03-12 22:23:56626 // Call GetUptimes() for the first time, thus allowing all later calls
627 // to record incremental uptimes accurately.
628 base::TimeDelta ignored_uptime_parameter;
629 base::TimeDelta startup_uptime;
blundell@chromium.org24f81ca2014-05-26 15:59:34630 GetUptimes(local_state_, &startup_uptime, &ignored_uptime_parameter);
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36631 DCHECK_EQ(0, startup_uptime.InMicroseconds());
jar@chromium.org9165f742010-03-10 22:55:01632 // For backwards compatibility, leave this intact in case Omaha is checking
asvitkinea63d19e2014-10-24 16:19:39633 // them. prefs::kStabilityLastTimestampSec may also be useless now.
jar@chromium.org9165f742010-03-10 22:55:01634 // TODO(jar): Delete these if they have no uses.
asvitkinea63d19e2014-10-24 16:19:39635 local_state_->SetInt64(prefs::kStabilityLaunchTimeSec,
asvitkinecbd420732014-08-26 22:15:40636 base::Time::Now().ToTimeT());
robertshield@google.com0bb1a622009-03-04 03:22:32637
638 // Bookkeeping for the uninstall metrics.
asvitkinea63d19e2014-10-24 16:19:39639 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
initial.commit09911bf2008-07-26 23:55:29640
initial.commit09911bf2008-07-26 23:55:29641 // Kick off the process of saving the state (so the uptime numbers keep
642 // getting updated) every n minutes.
643 ScheduleNextStateSave();
644}
645
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:22646void MetricsService::OnUserAction(const std::string& action) {
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:04647 if (!ShouldLogEvents())
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:22648 return;
649
isherman@chromium.org4426d2d2014-04-09 12:33:00650 log_manager_.current_log()->RecordUserAction(action);
phajdan.jr@chromium.orgdd98f392013-02-04 13:03:22651 HandleIdleSinceLastTransmission(false);
652}
653
blundell@chromium.org4a55a712014-06-08 16:50:34654void MetricsService::FinishedGatheringInitialMetrics() {
isherman@chromium.orged0fd002012-04-25 23:10:34655 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36656 state_ = INIT_TASK_DONE;
blundell@chromium.org83d09f92014-06-03 14:58:26657
658 // Create the initial log.
659 if (!initial_metrics_log_.get()) {
660 initial_metrics_log_ = CreateLog(MetricsLog::ONGOING_LOG);
661 NotifyOnDidCreateMetricsLog();
662 }
663
asvitkine@chromium.org70886cd2013-12-04 05:53:42664 scheduler_->InitTaskComplete();
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36665}
666
mpearson@chromium.org076961c2014-03-12 22:23:56667void MetricsService::GetUptimes(PrefService* pref,
668 base::TimeDelta* incremental_uptime,
669 base::TimeDelta* uptime) {
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36670 base::TimeTicks now = base::TimeTicks::Now();
mpearson@chromium.org076961c2014-03-12 22:23:56671 // If this is the first call, init |first_updated_time_| and
672 // |last_updated_time_|.
673 if (last_updated_time_.is_null()) {
674 first_updated_time_ = now;
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36675 last_updated_time_ = now;
mpearson@chromium.org076961c2014-03-12 22:23:56676 }
677 *incremental_uptime = now - last_updated_time_;
678 *uptime = now - first_updated_time_;
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36679 last_updated_time_ = now;
680
mpearson@chromium.org076961c2014-03-12 22:23:56681 const int64 incremental_time_secs = incremental_uptime->InSeconds();
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36682 if (incremental_time_secs > 0) {
asvitkinea63d19e2014-10-24 16:19:39683 int64 metrics_uptime = pref->GetInt64(prefs::kUninstallMetricsUptimeSec);
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36684 metrics_uptime += incremental_time_secs;
asvitkinea63d19e2014-10-24 16:19:39685 pref->SetInt64(prefs::kUninstallMetricsUptimeSec, metrics_uptime);
asvitkine@chromium.orgc68a2b9b2013-10-09 18:16:36686 }
initial.commit09911bf2008-07-26 23:55:29687}
688
bolian@chromium.org2a321de32014-05-10 19:59:06689void MetricsService::NotifyOnDidCreateMetricsLog() {
asvitkinebbde62b2014-09-03 16:33:21690 DCHECK(IsSingleThreaded());
blundell@chromium.org8304f61a2014-05-24 12:17:33691 for (size_t i = 0; i < metrics_providers_.size(); ++i)
692 metrics_providers_[i]->OnDidCreateMetricsLog();
bolian@chromium.org2a321de32014-05-10 19:59:06693}
694
initial.commit09911bf2008-07-26 23:55:29695//------------------------------------------------------------------------------
696// State save methods
697
698void MetricsService::ScheduleNextStateSave() {
isherman@chromium.org8454aeb2011-11-19 23:38:20699 state_saver_factory_.InvalidateWeakPtrs();
initial.commit09911bf2008-07-26 23:55:29700
xhwang@chromium.orgb3a25092013-05-28 22:08:16701 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
isherman@chromium.org8454aeb2011-11-19 23:38:20702 base::Bind(&MetricsService::SaveLocalState,
703 state_saver_factory_.GetWeakPtr()),
tedvessenes@gmail.comfc4252a72012-01-12 21:58:47704 base::TimeDelta::FromMinutes(kSaveStateIntervalMinutes));
initial.commit09911bf2008-07-26 23:55:29705}
706
707void MetricsService::SaveLocalState() {
blundell@chromium.org24f81ca2014-05-26 15:59:34708 RecordCurrentState(local_state_);
initial.commit09911bf2008-07-26 23:55:29709
tedvessenes@gmail.comfc4252a72012-01-12 21:58:47710 // TODO(jar):110021 Does this run down the batteries????
initial.commit09911bf2008-07-26 23:55:29711 ScheduleNextStateSave();
712}
713
714
715//------------------------------------------------------------------------------
716// Recording control methods
717
stuartmorgan@chromium.org410938e02012-10-24 16:33:59718void MetricsService::OpenNewLog() {
719 DCHECK(!log_manager_.current_log());
initial.commit09911bf2008-07-26 23:55:29720
asvitkine@chromium.orgbfb77b52014-06-07 01:54:01721 log_manager_.BeginLoggingWithLog(CreateLog(MetricsLog::ONGOING_LOG));
bolian@chromium.org2a321de32014-05-10 19:59:06722 NotifyOnDidCreateMetricsLog();
initial.commit09911bf2008-07-26 23:55:29723 if (state_ == INITIALIZED) {
724 // We only need to schedule that run once.
zelidrag@chromium.org85ed9d42010-06-08 22:37:44725 state_ = INIT_TASK_SCHEDULED;
initial.commit09911bf2008-07-26 23:55:29726
blundell@chromium.orgd6147bd2014-06-11 01:58:19727 base::MessageLoop::current()->PostDelayedTask(
joi@chromium.orged10dd12011-12-07 12:03:42728 FROM_HERE,
blundell@chromium.org51994b22014-05-30 13:24:21729 base::Bind(&MetricsService::StartGatheringMetrics,
730 self_ptr_factory_.GetWeakPtr()),
tedvessenes@gmail.com7e560102012-03-08 20:58:42731 base::TimeDelta::FromSeconds(kInitializationDelaySeconds));
initial.commit09911bf2008-07-26 23:55:29732 }
733}
734
blundell@chromium.org51994b22014-05-30 13:24:21735void MetricsService::StartGatheringMetrics() {
blundell@chromium.org51994b22014-05-30 13:24:21736 client_->StartGatheringMetrics(
blundell@chromium.org4a55a712014-06-08 16:50:34737 base::Bind(&MetricsService::FinishedGatheringInitialMetrics,
blundell@chromium.org51994b22014-05-30 13:24:21738 self_ptr_factory_.GetWeakPtr()));
739}
740
stuartmorgan@chromium.org410938e02012-10-24 16:33:59741void MetricsService::CloseCurrentLog() {
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10742 if (!log_manager_.current_log())
initial.commit09911bf2008-07-26 23:55:29743 return;
744
jar@google.com68475e602008-08-22 03:21:15745 // TODO(jar): Integrate bounds on log recording more consistently, so that we
746 // can stop recording logs that are too big much sooner.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10747 if (log_manager_.current_log()->num_events() > kEventLimit) {
dsh@google.com553dba62009-02-24 19:08:23748 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10749 log_manager_.current_log()->num_events());
750 log_manager_.DiscardCurrentLog();
stuartmorgan@chromium.org410938e02012-10-24 16:33:59751 OpenNewLog(); // Start trivial log to hold our histograms.
jar@google.com68475e602008-08-22 03:21:15752 }
753
jar@google.com0b33f80b2008-12-17 21:34:36754 // Put incremental data (histogram deltas, and realtime stats deltas) at the
jar@google.com147bbc0b2009-01-06 19:37:40755 // end of all log transmissions (initial log handles this separately).
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:38756 // RecordIncrementalStabilityElements only exists on the derived
757 // MetricsLog class.
holte@chromium.org94dce122014-07-16 04:20:12758 MetricsLog* current_log = log_manager_.current_log();
stuartmorgan@chromium.org024b5cd2011-05-27 03:29:38759 DCHECK(current_log);
asvitkine88aa9332014-09-29 23:29:17760 RecordCurrentEnvironment(current_log);
mpearson@chromium.org076961c2014-03-12 22:23:56761 base::TimeDelta incremental_uptime;
762 base::TimeDelta uptime;
blundell@chromium.org24f81ca2014-05-26 15:59:34763 GetUptimes(local_state_, &incremental_uptime, &uptime);
asvitkine@chromium.org85791b0b2014-05-20 15:18:58764 current_log->RecordStabilityMetrics(metrics_providers_.get(),
765 incremental_uptime, uptime);
bengr@chromium.org60677562013-11-17 15:52:55766
asvitkine@chromium.org85791b0b2014-05-20 15:18:58767 current_log->RecordGeneralMetrics(metrics_providers_.get());
mariakhomenko191028982014-10-20 23:22:56768 RecordCurrentHistograms();
initial.commit09911bf2008-07-26 23:55:29769
stuartmorgan@chromium.org29948262012-03-01 12:15:08770 log_manager_.FinishCurrentLog();
initial.commit09911bf2008-07-26 23:55:29771}
772
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:10773void MetricsService::PushPendingLogsToPersistentStorage() {
asvitkine@chromium.org80a8f312013-12-16 18:00:30774 if (state_ < SENDING_INITIAL_STABILITY_LOG)
avi@google.com28ab7f92009-01-06 21:39:04775 return; // We didn't and still don't have time to get plugin list etc.
initial.commit09911bf2008-07-26 23:55:29776
stuartmorgan@chromium.org410938e02012-10-24 16:33:59777 CloseCurrentLog();
asvitkine@chromium.org80a8f312013-12-16 18:00:30778 log_manager_.PersistUnsentLogs();
stuartmorgan@chromium.org7d41ae6d2012-06-26 08:53:03779
780 // If there was a staged and/or current log, then there is now at least one
781 // log waiting to be uploaded.
782 if (log_manager_.has_unsent_logs())
783 state_ = SENDING_OLD_LOGS;
initial.commit09911bf2008-07-26 23:55:29784}
785
786//------------------------------------------------------------------------------
787// Transmission of logs methods
788
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16789void MetricsService::StartSchedulerIfNecessary() {
stuartmorgan@chromium.org410938e02012-10-24 16:33:59790 // Never schedule cutting or uploading of logs in test mode.
791 if (test_mode_active_)
792 return;
793
794 // Even if reporting is disabled, the scheduler is needed to trigger the
795 // creation of the initial log, which must be done in order for any logs to be
796 // persisted on shutdown or backgrounding.
asvitkine@chromium.org80a8f312013-12-16 18:00:30797 if (recording_active() &&
798 (reporting_active() || state_ < SENDING_INITIAL_STABILITY_LOG)) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16799 scheduler_->Start();
asvitkine@chromium.org80a8f312013-12-16 18:00:30800 }
initial.commit09911bf2008-07-26 23:55:29801}
802
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16803void MetricsService::StartScheduledUpload() {
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:47804 // If we're getting no notifications, then the log won't have much in it, and
805 // it's possible the computer is about to go to sleep, so don't upload and
806 // stop the scheduler.
stuartmorgan@chromium.org410938e02012-10-24 16:33:59807 // If recording has been turned off, the scheduler doesn't need to run.
808 // If reporting is off, proceed if the initial log hasn't been created, since
809 // that has to happen in order for logs to be cut and stored when persisting.
isherman@chromium.orgd7ea39e2014-05-22 03:59:18810 // TODO(stuartmorgan): Call Stop() on the scheduler when reporting and/or
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:47811 // recording are turned off instead of letting it fire and then aborting.
812 if (idle_since_last_transmission_ ||
stuartmorgan@chromium.org410938e02012-10-24 16:33:59813 !recording_active() ||
asvitkine@chromium.org80a8f312013-12-16 18:00:30814 (!reporting_active() && state_ >= SENDING_INITIAL_STABILITY_LOG)) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16815 scheduler_->Stop();
816 scheduler_->UploadCancelled();
817 return;
818 }
819
stuartmorgan@chromium.orgc15faf372012-07-11 06:01:34820 // If the callback was to upload an old log, but there no longer is one,
821 // just report success back to the scheduler to begin the ongoing log
822 // callbacks.
823 // TODO(stuartmorgan): Consider removing the distinction between
824 // SENDING_OLD_LOGS and SENDING_CURRENT_LOGS to simplify the state machine
825 // now that the log upload flow is the same for both modes.
826 if (state_ == SENDING_OLD_LOGS && !log_manager_.has_unsent_logs()) {
827 state_ = SENDING_CURRENT_LOGS;
828 scheduler_->UploadFinished(true /* healthy */, false /* no unsent logs */);
829 return;
830 }
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:47831 // If there are unsent logs, send the next one. If not, start the asynchronous
832 // process of finalizing the current log for upload.
833 if (state_ == SENDING_OLD_LOGS) {
834 DCHECK(log_manager_.has_unsent_logs());
835 log_manager_.StageNextLogForUpload();
836 SendStagedLog();
837 } else {
asvitkine@chromium.org4b4892b2014-05-22 15:06:15838 client_->CollectFinalMetrics(
839 base::Bind(&MetricsService::OnFinalLogInfoCollectionDone,
840 self_ptr_factory_.GetWeakPtr()));
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:47841 }
stuartmorgan@chromium.org29948262012-03-01 12:15:08842}
843
stuartmorgan@chromium.org29948262012-03-01 12:15:08844void MetricsService::OnFinalLogInfoCollectionDone() {
asvitkine@chromium.org0d5a61a82014-05-31 22:28:34845 // If somehow there is a log upload in progress, we return and hope things
846 // work out. The scheduler isn't informed since if this happens, the scheduler
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16847 // will get a response from the upload.
asvitkine@chromium.org0d5a61a82014-05-31 22:28:34848 DCHECK(!log_upload_in_progress_);
849 if (log_upload_in_progress_)
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16850 return;
851
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:47852 // Abort if metrics were turned off during the final info gathering.
stuartmorgan@chromium.org410938e02012-10-24 16:33:59853 if (!recording_active()) {
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:16854 scheduler_->Stop();
855 scheduler_->UploadCancelled();
petersont@google.comd01b8732008-10-16 02:18:07856 return;
857 }
858
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:47859 StageNewLog();
stuartmorgan@chromium.org410938e02012-10-24 16:33:59860
861 // If logs shouldn't be uploaded, stop here. It's important that this check
862 // be after StageNewLog(), otherwise the previous logs will never be loaded,
863 // and thus the open log won't be persisted.
864 // TODO(stuartmorgan): This is unnecessarily complicated; restructure loading
865 // of previous logs to not require running part of the upload logic.
866 // http://crbug.com/157337
867 if (!reporting_active()) {
868 scheduler_->Stop();
869 scheduler_->UploadCancelled();
870 return;
871 }
872
stuartmorgan@chromium.org29948262012-03-01 12:15:08873 SendStagedLog();
874}
875
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:47876void MetricsService::StageNewLog() {
stuartmorgan@chromium.org29948262012-03-01 12:15:08877 if (log_manager_.has_staged_log())
878 return;
879
880 switch (state_) {
881 case INITIALIZED:
882 case INIT_TASK_SCHEDULED: // We should be further along by now.
isherman@chromium.orgdc61fe92012-06-12 00:13:50883 NOTREACHED();
stuartmorgan@chromium.org29948262012-03-01 12:15:08884 return;
885
886 case INIT_TASK_DONE:
holtea29872a2015-03-02 22:44:17887 PrepareInitialMetricsLog();
888 // Stage the first log, which could be a stability log (either one
889 // for created in this session or from a previous session) or the
890 // initial metrics log that was just created.
891 log_manager_.StageNextLogForUpload();
892 if (has_initial_stability_log_) {
893 // The initial stability log was just staged.
894 has_initial_stability_log_ = false;
895 state_ = SENDING_INITIAL_STABILITY_LOG;
holted1843d42014-10-09 18:38:52896 } else {
holtea29872a2015-03-02 22:44:17897 state_ = SENDING_INITIAL_METRICS_LOG;
asvitkine@chromium.org80a8f312013-12-16 18:00:30898 }
stuartmorgan@chromium.org29948262012-03-01 12:15:08899 break;
900
901 case SENDING_OLD_LOGS:
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:47902 NOTREACHED(); // Shouldn't be staging a new log during old log sending.
903 return;
stuartmorgan@chromium.org29948262012-03-01 12:15:08904
905 case SENDING_CURRENT_LOGS:
stuartmorgan@chromium.org410938e02012-10-24 16:33:59906 CloseCurrentLog();
907 OpenNewLog();
stuartmorgan@chromium.org29948262012-03-01 12:15:08908 log_manager_.StageNextLogForUpload();
909 break;
910
911 default:
912 NOTREACHED();
913 return;
914 }
915
916 DCHECK(log_manager_.has_staged_log());
917}
918
siggic179dd062014-09-10 17:02:31919bool MetricsService::ProvidersHaveStabilityMetrics() {
920 // Check whether any metrics provider has stability metrics.
921 for (size_t i = 0; i < metrics_providers_.size(); ++i) {
922 if (metrics_providers_[i]->HasStabilityMetrics())
923 return true;
924 }
925
926 return false;
927}
928
asvitkine@chromium.org80a8f312013-12-16 18:00:30929void MetricsService::PrepareInitialStabilityLog() {
930 DCHECK_EQ(INITIALIZED, state_);
stuartmorgan@chromium.org29948262012-03-01 12:15:08931
asvitkine@chromium.org80a8f312013-12-16 18:00:30932 scoped_ptr<MetricsLog> initial_stability_log(
isherman@chromium.org09dee82d2014-05-22 14:00:53933 CreateLog(MetricsLog::INITIAL_STABILITY_LOG));
bolian@chromium.org2a321de32014-05-10 19:59:06934
935 // Do not call NotifyOnDidCreateMetricsLog here because the stability
936 // log describes stats from the _previous_ session.
937
asvitkine@chromium.org80a8f312013-12-16 18:00:30938 if (!initial_stability_log->LoadSavedEnvironmentFromPrefs())
939 return;
asvitkine@chromium.org85791b0b2014-05-20 15:18:58940
asvitkine@chromium.org80a8f312013-12-16 18:00:30941 log_manager_.PauseCurrentLog();
asvitkine@chromium.orgbfb77b52014-06-07 01:54:01942 log_manager_.BeginLoggingWithLog(initial_stability_log.Pass());
asvitkine@chromium.org85791b0b2014-05-20 15:18:58943
944 // Note: Some stability providers may record stability stats via histograms,
945 // so this call has to be after BeginLoggingWithLog().
asvitkine@chromium.orgbfb77b52014-06-07 01:54:01946 log_manager_.current_log()->RecordStabilityMetrics(
947 metrics_providers_.get(), base::TimeDelta(), base::TimeDelta());
kkimlabs@chromium.orgc778687a2014-02-11 14:46:45948 RecordCurrentStabilityHistograms();
asvitkine@chromium.org85791b0b2014-05-20 15:18:58949
950 // Note: RecordGeneralMetrics() intentionally not called since this log is for
951 // stability stats from a previous session only.
952
asvitkine@chromium.org80a8f312013-12-16 18:00:30953 log_manager_.FinishCurrentLog();
954 log_manager_.ResumePausedLog();
955
956 // Store unsent logs, including the stability log that was just saved, so
957 // that they're not lost in case of a crash before upload time.
958 log_manager_.PersistUnsentLogs();
959
960 has_initial_stability_log_ = true;
961}
962
asvitkine@chromium.orgb58b8b22014-04-08 22:40:33963void MetricsService::PrepareInitialMetricsLog() {
asvitkine@chromium.org80a8f312013-12-16 18:00:30964 DCHECK(state_ == INIT_TASK_DONE || state_ == SENDING_INITIAL_STABILITY_LOG);
asvitkine@chromium.org0edf8762013-11-21 18:33:30965
asvitkine88aa9332014-09-29 23:29:17966 RecordCurrentEnvironment(initial_metrics_log_.get());
mpearson@chromium.org076961c2014-03-12 22:23:56967 base::TimeDelta incremental_uptime;
968 base::TimeDelta uptime;
blundell@chromium.org24f81ca2014-05-26 15:59:34969 GetUptimes(local_state_, &incremental_uptime, &uptime);
stuartmorgan@chromium.org29948262012-03-01 12:15:08970
971 // Histograms only get written to the current log, so make the new log current
972 // before writing them.
973 log_manager_.PauseCurrentLog();
asvitkine@chromium.orgbfb77b52014-06-07 01:54:01974 log_manager_.BeginLoggingWithLog(initial_metrics_log_.Pass());
asvitkine@chromium.org85791b0b2014-05-20 15:18:58975
976 // Note: Some stability providers may record stability stats via histograms,
977 // so this call has to be after BeginLoggingWithLog().
holte@chromium.org94dce122014-07-16 04:20:12978 MetricsLog* current_log = log_manager_.current_log();
asvitkine@chromium.org85791b0b2014-05-20 15:18:58979 current_log->RecordStabilityMetrics(metrics_providers_.get(),
980 base::TimeDelta(), base::TimeDelta());
asvitkine@chromium.org85791b0b2014-05-20 15:18:58981 current_log->RecordGeneralMetrics(metrics_providers_.get());
mariakhomenko191028982014-10-20 23:22:56982 RecordCurrentHistograms();
asvitkine@chromium.org85791b0b2014-05-20 15:18:58983
stuartmorgan@chromium.org29948262012-03-01 12:15:08984 log_manager_.FinishCurrentLog();
985 log_manager_.ResumePausedLog();
986
holte@chromium.org94dce122014-07-16 04:20:12987 // Store unsent logs, including the initial log that was just saved, so
988 // that they're not lost in case of a crash before upload time.
989 log_manager_.PersistUnsentLogs();
stuartmorgan@chromium.org29948262012-03-01 12:15:08990}
991
stuartmorgan@chromium.org29948262012-03-01 12:15:08992void MetricsService::SendStagedLog() {
993 DCHECK(log_manager_.has_staged_log());
asvitkine@chromium.org0d5a61a82014-05-31 22:28:34994 if (!log_manager_.has_staged_log())
995 return;
stuartmorgan@chromium.org29948262012-03-01 12:15:08996
asvitkine@chromium.org0d5a61a82014-05-31 22:28:34997 DCHECK(!log_upload_in_progress_);
998 log_upload_in_progress_ = true;
petersont@google.comd01b8732008-10-16 02:18:07999
asvitkine@chromium.org0d5a61a82014-05-31 22:28:341000 if (!log_uploader_) {
1001 log_uploader_ = client_->CreateUploader(
asvitkine@chromium.org0d5a61a82014-05-31 22:28:341002 base::Bind(&MetricsService::OnLogUploadComplete,
1003 self_ptr_factory_.GetWeakPtr()));
1004 }
1005
1006 const std::string hash =
1007 base::HexEncode(log_manager_.staged_log_hash().data(),
1008 log_manager_.staged_log_hash().size());
1009 bool success = log_uploader_->UploadLog(log_manager_.staged_log(), hash);
1010 UMA_HISTOGRAM_BOOLEAN("UMA.UploadCreation", success);
1011 if (!success) {
isherman@chromium.orgdc61fe92012-06-12 00:13:501012 // Skip this upload and hope things work out next time.
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101013 log_manager_.DiscardStagedLog();
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161014 scheduler_->UploadCancelled();
asvitkine@chromium.org0d5a61a82014-05-31 22:28:341015 log_upload_in_progress_ = false;
petersont@google.comd01b8732008-10-16 02:18:071016 return;
1017 }
1018
petersont@google.comd01b8732008-10-16 02:18:071019 HandleIdleSinceLastTransmission(true);
1020}
1021
pkasting@chromium.orgcac78842008-11-27 01:02:201022
asvitkine@chromium.org0d5a61a82014-05-31 22:28:341023void MetricsService::OnLogUploadComplete(int response_code) {
1024 DCHECK(log_upload_in_progress_);
1025 log_upload_in_progress_ = false;
isherman@chromium.orgfe58acc22012-02-29 01:29:581026
isherman@chromium.orgdc61fe92012-06-12 00:13:501027 // Log a histogram to track response success vs. failure rates.
isherman@chromium.orge3eb0c42013-04-18 06:18:581028 UMA_HISTOGRAM_ENUMERATION("UMA.UploadResponseStatus.Protobuf",
1029 ResponseCodeToStatus(response_code),
1030 NUM_RESPONSE_STATUSES);
isherman@chromium.orgfe58acc22012-02-29 01:29:581031
isherman@chromium.orgdc61fe92012-06-12 00:13:501032 bool upload_succeeded = response_code == 200;
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161033
jar@chromium.org0eb34fee2009-01-21 08:04:381034 // Provide boolean for error recovery (allow us to ignore response_code).
paul@chromium.orgdc6f4962009-02-13 01:25:501035 bool discard_log = false;
holte@chromium.org7f07db62014-05-15 01:12:451036 const size_t log_size = log_manager_.staged_log().length();
asvitkined80ebf6c2014-09-02 22:29:111037 if (upload_succeeded) {
1038 UMA_HISTOGRAM_COUNTS_10000("UMA.LogSize.OnSuccess", log_size / 1024);
1039 } else if (log_size > kUploadLogAvoidRetransmitSize) {
isherman@chromium.orgdc61fe92012-06-12 00:13:501040 UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
1041 static_cast<int>(log_size));
jar@chromium.org0eb34fee2009-01-21 08:04:381042 discard_log = true;
isherman@chromium.orgdc61fe92012-06-12 00:13:501043 } else if (response_code == 400) {
jar@chromium.org0eb34fee2009-01-21 08:04:381044 // Bad syntax. Retransmission won't work.
jar@chromium.org0eb34fee2009-01-21 08:04:381045 discard_log = true;
jar@google.com68475e602008-08-22 03:21:151046 }
1047
holte@chromium.org94dce122014-07-16 04:20:121048 if (upload_succeeded || discard_log) {
isherman@chromium.org5f3e1642013-05-05 03:37:341049 log_manager_.DiscardStagedLog();
holte@chromium.org94dce122014-07-16 04:20:121050 // Store the updated list to disk now that the removed log is uploaded.
1051 log_manager_.PersistUnsentLogs();
1052 }
isherman@chromium.orgdc61fe92012-06-12 00:13:501053
isherman@chromium.orgdc61fe92012-06-12 00:13:501054 if (!log_manager_.has_staged_log()) {
initial.commit09911bf2008-07-26 23:55:291055 switch (state_) {
asvitkine@chromium.org80a8f312013-12-16 18:00:301056 case SENDING_INITIAL_STABILITY_LOG:
holtea29872a2015-03-02 22:44:171057 // The initial metrics log is already in the queue of unsent logs.
1058 state_ = SENDING_OLD_LOGS;
asvitkine@chromium.org80a8f312013-12-16 18:00:301059 break;
1060
1061 case SENDING_INITIAL_METRICS_LOG:
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471062 state_ = log_manager_.has_unsent_logs() ? SENDING_OLD_LOGS
1063 : SENDING_CURRENT_LOGS;
initial.commit09911bf2008-07-26 23:55:291064 break;
1065
initial.commit09911bf2008-07-26 23:55:291066 case SENDING_OLD_LOGS:
stuartmorgan@chromium.orgcd1ac712012-06-26 08:26:471067 if (!log_manager_.has_unsent_logs())
1068 state_ = SENDING_CURRENT_LOGS;
initial.commit09911bf2008-07-26 23:55:291069 break;
1070
1071 case SENDING_CURRENT_LOGS:
1072 break;
1073
1074 default:
jar@chromium.orga063c102010-07-22 22:20:191075 NOTREACHED();
initial.commit09911bf2008-07-26 23:55:291076 break;
1077 }
petersont@google.comd01b8732008-10-16 02:18:071078
stuartmorgan@chromium.orgcac267c2011-09-29 15:18:101079 if (log_manager_.has_unsent_logs())
isherman@chromium.orged0fd002012-04-25 23:10:341080 DCHECK_LT(state_, SENDING_CURRENT_LOGS);
initial.commit09911bf2008-07-26 23:55:291081 }
petersont@google.com252873ef2008-08-04 21:59:451082
stuartmorgan@chromium.org7f7f1962011-04-20 15:58:161083 // Error 400 indicates a problem with the log, not with the server, so
1084 // don't consider that a sign that the server is in trouble.
isherman@chromium.orgdc61fe92012-06-12 00:13:501085 bool server_is_healthy = upload_succeeded || response_code == 400;
holtea29872a2015-03-02 22:44:171086 scheduler_->UploadFinished(server_is_healthy, log_manager_.has_unsent_logs());
rtenneti@chromium.orgd67d1052011-06-09 05:11:411087
asvitkine@chromium.org73929422014-05-22 08:19:051088 if (server_is_healthy)
1089 client_->OnLogUploadComplete();
initial.commit09911bf2008-07-26 23:55:291090}
1091
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511092void MetricsService::IncrementPrefValue(const char* path) {
blundell@chromium.org24f81ca2014-05-26 15:59:341093 int value = local_state_->GetInteger(path);
1094 local_state_->SetInteger(path, value + 1);
cpu@google.come73c01972008-08-13 00:18:241095}
1096
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511097void MetricsService::IncrementLongPrefsValue(const char* path) {
blundell@chromium.org24f81ca2014-05-26 15:59:341098 int64 value = local_state_->GetInt64(path);
1099 local_state_->SetInt64(path, value + 1);
robertshield@google.com0bb1a622009-03-04 03:22:321100}
1101
jar@chromium.orgc0c55e92011-09-10 18:47:301102bool MetricsService::UmaMetricsProperlyShutdown() {
1103 CHECK(clean_shutdown_status_ == CLEANLY_SHUTDOWN ||
1104 clean_shutdown_status_ == NEED_TO_SHUTDOWN);
1105 return clean_shutdown_status_ == CLEANLY_SHUTDOWN;
1106}
1107
asvitkinee0dbdbe2014-10-31 21:59:571108void MetricsService::AddSyntheticTrialObserver(
1109 SyntheticTrialObserver* observer) {
1110 synthetic_trial_observer_list_.AddObserver(observer);
1111 if (!synthetic_trial_groups_.empty())
1112 observer->OnSyntheticTrialsChanged(synthetic_trial_groups_);
1113}
1114
1115void MetricsService::RemoveSyntheticTrialObserver(
1116 SyntheticTrialObserver* observer) {
1117 synthetic_trial_observer_list_.RemoveObserver(observer);
1118}
1119
bengr@chromium.org60677562013-11-17 15:52:551120void MetricsService::RegisterSyntheticFieldTrial(
1121 const SyntheticTrialGroup& trial) {
1122 for (size_t i = 0; i < synthetic_trial_groups_.size(); ++i) {
1123 if (synthetic_trial_groups_[i].id.name == trial.id.name) {
1124 if (synthetic_trial_groups_[i].id.group != trial.id.group) {
1125 synthetic_trial_groups_[i].id.group = trial.id.group;
asvitkine@chromium.org7a5c07812014-02-26 11:45:411126 synthetic_trial_groups_[i].start_time = base::TimeTicks::Now();
asvitkinee0dbdbe2014-10-31 21:59:571127 NotifySyntheticTrialObservers();
bengr@chromium.org60677562013-11-17 15:52:551128 }
1129 return;
1130 }
1131 }
1132
asvitkine@chromium.org7a5c07812014-02-26 11:45:411133 SyntheticTrialGroup trial_group = trial;
1134 trial_group.start_time = base::TimeTicks::Now();
bengr@chromium.org60677562013-11-17 15:52:551135 synthetic_trial_groups_.push_back(trial_group);
asvitkinee0dbdbe2014-10-31 21:59:571136 NotifySyntheticTrialObservers();
bengr@chromium.org60677562013-11-17 15:52:551137}
1138
asvitkine@chromium.org85791b0b2014-05-20 15:18:581139void MetricsService::RegisterMetricsProvider(
asvitkinea63d19e2014-10-24 16:19:391140 scoped_ptr<MetricsProvider> provider) {
asvitkine@chromium.org85791b0b2014-05-20 15:18:581141 DCHECK_EQ(INITIALIZED, state_);
1142 metrics_providers_.push_back(provider.release());
1143}
1144
blundell@chromium.org61b0d482014-05-20 14:49:101145void MetricsService::CheckForClonedInstall(
1146 scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
1147 state_manager_->CheckForClonedInstall(task_runner);
jwd@chromium.org99c892d2014-03-24 18:11:211148}
1149
asvitkinee0dbdbe2014-10-31 21:59:571150void MetricsService::NotifySyntheticTrialObservers() {
1151 FOR_EACH_OBSERVER(SyntheticTrialObserver, synthetic_trial_observer_list_,
1152 OnSyntheticTrialsChanged(synthetic_trial_groups_));
1153}
1154
bengr@chromium.org60677562013-11-17 15:52:551155void MetricsService::GetCurrentSyntheticFieldTrials(
asvitkine@chromium.orgb3610d42014-05-19 18:07:231156 std::vector<variations::ActiveGroupId>* synthetic_trials) {
bengr@chromium.org60677562013-11-17 15:52:551157 DCHECK(synthetic_trials);
1158 synthetic_trials->clear();
holte@chromium.org94dce122014-07-16 04:20:121159 const MetricsLog* current_log = log_manager_.current_log();
bengr@chromium.org60677562013-11-17 15:52:551160 for (size_t i = 0; i < synthetic_trial_groups_.size(); ++i) {
1161 if (synthetic_trial_groups_[i].start_time <= current_log->creation_time())
1162 synthetic_trials->push_back(synthetic_trial_groups_[i].id);
1163 }
1164}
1165
isherman@chromium.org09dee82d2014-05-22 14:00:531166scoped_ptr<MetricsLog> MetricsService::CreateLog(MetricsLog::LogType log_type) {
blundell@chromium.org24f81ca2014-05-26 15:59:341167 return make_scoped_ptr(new MetricsLog(state_manager_->client_id(),
1168 session_id_,
1169 log_type,
1170 client_,
1171 local_state_));
isherman@chromium.org09dee82d2014-05-22 14:00:531172}
1173
asvitkine88aa9332014-09-29 23:29:171174void MetricsService::RecordCurrentEnvironment(MetricsLog* log) {
1175 std::vector<variations::ActiveGroupId> synthetic_trials;
1176 GetCurrentSyntheticFieldTrials(&synthetic_trials);
1177 log->RecordEnvironment(metrics_providers_.get(), synthetic_trials,
1178 GetInstallDate());
1179 UMA_HISTOGRAM_COUNTS_100("UMA.SyntheticTrials.Count",
1180 synthetic_trials.size());
1181}
1182
isherman@chromium.orgacc2ce5512014-05-22 18:29:131183void MetricsService::RecordCurrentHistograms() {
1184 DCHECK(log_manager_.current_log());
1185 histogram_snapshot_manager_.PrepareDeltas(
1186 base::Histogram::kNoFlags, base::Histogram::kUmaTargetedHistogramFlag);
1187}
1188
1189void MetricsService::RecordCurrentStabilityHistograms() {
1190 DCHECK(log_manager_.current_log());
1191 histogram_snapshot_manager_.PrepareDeltas(
1192 base::Histogram::kNoFlags, base::Histogram::kUmaStabilityHistogramFlag);
1193}
1194
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381195void MetricsService::LogCleanShutdown() {
jar@chromium.orgacd55b32011-09-05 17:35:311196 // Redundant hack to write pref ASAP.
erikwright65b58df2014-09-12 00:05:281197 MarkAppCleanShutdownAndCommit(&clean_exit_beacon_, local_state_);
nileshagrawal@chromium.org84c384e2013-03-01 23:20:191198
jar@chromium.orgc0c55e92011-09-10 18:47:301199 // Redundant setting to assure that we always reset this value at shutdown
1200 // (and that we don't use some alternate path, and not call LogCleanShutdown).
1201 clean_shutdown_status_ = CLEANLY_SHUTDOWN;
jar@chromium.orgacd55b32011-09-05 17:35:311202
erikwright65b58df2014-09-12 00:05:281203 clean_exit_beacon_.WriteBeaconValue(true);
1204 RecordCurrentState(local_state_);
asvitkinea63d19e2014-10-24 16:19:391205 local_state_->SetInteger(prefs::kStabilityExecutionPhase,
blundell@chromium.org24f81ca2014-05-26 15:59:341206 MetricsService::SHUTDOWN_COMPLETE);
stuartmorgan@chromium.org466f3c12011-03-23 21:20:381207}
1208
stuartmorgan@chromium.orge5ad60a2014-03-11 03:54:041209bool MetricsService::ShouldLogEvents() {
1210 // We simply don't log events to UMA if there is a single incognito
initial.commit09911bf2008-07-26 23:55:291211 // session visible. The problem is that we always notify using the orginal
1212 // profile in order to simplify notification processing.
isherman@chromium.org7d000322014-05-23 07:16:021213 return !client_->IsOffTheRecordSessionActive();
initial.commit09911bf2008-07-26 23:55:291214}
1215
viettrungluu@chromium.org57ecc4b2010-08-11 03:02:511216void MetricsService::RecordBooleanPrefValue(const char* path, bool value) {
initial.commit09911bf2008-07-26 23:55:291217 DCHECK(IsSingleThreaded());
blundell@chromium.org24f81ca2014-05-26 15:59:341218 local_state_->SetBoolean(path, value);
1219 RecordCurrentState(local_state_);
initial.commit09911bf2008-07-26 23:55:291220}
1221
1222void MetricsService::RecordCurrentState(PrefService* pref) {
asvitkinea63d19e2014-10-24 16:19:391223 pref->SetInt64(prefs::kStabilityLastTimestampSec,
asvitkinecbd420732014-08-26 22:15:401224 base::Time::Now().ToTimeT());
initial.commit09911bf2008-07-26 23:55:291225}
asvitkinecbd420732014-08-26 22:15:401226
gayaned52ca402015-02-23 21:23:061227void MetricsService::SetConnectionTypeCallback(
1228 base::Callback<void(bool*)> is_cellular_callback) {
1229 DCHECK(!scheduler_);
1230 is_cellular_callback_ = is_cellular_callback;
1231}
1232
asvitkinecbd420732014-08-26 22:15:401233} // namespace metrics