Work on Windows GN component build.
[chromium-blink-merge.git] / components / metrics / metrics_service.cc
blob60a3f309a48e1f870afff2a03f51b7c6e99eb06d
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 //------------------------------------------------------------------------------
6 // Description of the life cycle of a instance of MetricsService.
7 //
8 // OVERVIEW
9 //
10 // A MetricsService instance is typically created at application startup. It is
11 // the central controller for the acquisition of log data, and the automatic
12 // 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,
16 // 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.
24 // Logs fall into one of two categories: "initial logs," and "ongoing logs."
25 // There is at most one initial log sent for each complete run of 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.
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)
39 // is 30 minutes. That time period starts when the first user action causes a
40 // logging event. This means that if there is no user action, there may be long
41 // periods without any (ongoing) log transmissions. Ongoing logs typically
42 // 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
48 // to the UMA server. The finalization also acquires the most recent number
49 // of page loads, along with any counts of renderer or plugin crashes.
51 // When the browser shuts down, there will typically be a fragment of an ongoing
52 // log that has not yet been transmitted. At shutdown time, that fragment is
53 // closed (including snapshotting histograms), and persisted, for potential
54 // transmission during a future run of the product.
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.
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).
75 // With the above overview, we can now describe the state machine's various
76 // states, based on the State enum specified in the state_ member. Those states
77 // are:
79 // 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_LOGS, // Sending logs and creating new ones when we run out.
84 // In more detail, we have:
86 // INITIALIZED, // Constructor was called.
87 // The MS has been constructed, but has taken no actions to compose the
88 // initial log.
90 // INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to finish.
91 // Typically about 30 seconds after startup, a task is sent to a second thread
92 // (the file thread) to perform deferred (lower priority and slower)
93 // initialization steps such as getting the list of plugins. That task will
94 // (when complete) make an async callback (via a Task) to indicate the
95 // completion.
97 // INIT_TASK_DONE, // Waiting for timer to send initial log.
98 // The callback has arrived, and it is now possible for an initial log to be
99 // created. This callback typically arrives back less than one second after
100 // the deferred init task is dispatched.
102 // SENDING_LOGS, // Sending logs an creating new ones when we run out.
103 // Logs from previous sessions have been loaded, and initial logs have been
104 // created (an optional stability log and the first metrics log). We will
105 // send all of these logs, and when run out, we will start cutting new logs
106 // to send. We will also cut a new log if we expect a shutdown.
108 // The progression through the above states is simple, and sequential.
109 // States proceed from INITIAL to SENDING_LOGS, and remain in the latter until
110 // shutdown.
112 // Also note that whenever we successfully send a log, we mirror the list
113 // of logs into the PrefService. This ensures that IF we crash, we won't start
114 // up and retransmit our old logs again.
116 // Due to race conditions, it is always possible that a log file could be sent
117 // twice. For example, if a log file is sent, but not yet acknowledged by
118 // the external server, and the user shuts down, then a copy of the log may be
119 // saved for re-transmission. These duplicates could be filtered out server
120 // side, but are not expected to be a significant problem.
123 //------------------------------------------------------------------------------
125 #include "components/metrics/metrics_service.h"
127 #include <algorithm>
129 #include "base/bind.h"
130 #include "base/callback.h"
131 #include "base/metrics/histogram.h"
132 #include "base/metrics/histogram_base.h"
133 #include "base/metrics/histogram_samples.h"
134 #include "base/metrics/sparse_histogram.h"
135 #include "base/metrics/statistics_recorder.h"
136 #include "base/prefs/pref_registry_simple.h"
137 #include "base/prefs/pref_service.h"
138 #include "base/strings/string_number_conversions.h"
139 #include "base/strings/utf_string_conversions.h"
140 #include "base/threading/platform_thread.h"
141 #include "base/threading/thread.h"
142 #include "base/threading/thread_restrictions.h"
143 #include "base/time/time.h"
144 #include "base/tracked_objects.h"
145 #include "base/values.h"
146 #include "components/metrics/metrics_log.h"
147 #include "components/metrics/metrics_log_manager.h"
148 #include "components/metrics/metrics_log_uploader.h"
149 #include "components/metrics/metrics_pref_names.h"
150 #include "components/metrics/metrics_reporting_scheduler.h"
151 #include "components/metrics/metrics_service_client.h"
152 #include "components/metrics/metrics_state_manager.h"
153 #include "components/variations/entropy_provider.h"
155 namespace metrics {
157 namespace {
159 // Check to see that we're being called on only one thread.
160 bool IsSingleThreaded() {
161 static base::PlatformThreadId thread_id = 0;
162 if (!thread_id)
163 thread_id = base::PlatformThread::CurrentId();
164 return base::PlatformThread::CurrentId() == thread_id;
167 // The delay, in seconds, after starting recording before doing expensive
168 // initialization work.
169 #if defined(OS_ANDROID) || defined(OS_IOS)
170 // On mobile devices, a significant portion of sessions last less than a minute.
171 // Use a shorter timer on these platforms to avoid losing data.
172 // TODO(dfalcantara): To avoid delaying startup, tighten up initialization so
173 // that it occurs after the user gets their initial page.
174 const int kInitializationDelaySeconds = 5;
175 #else
176 const int kInitializationDelaySeconds = 30;
177 #endif
179 // The maximum number of events in a log uploaded to the UMA server.
180 const int kEventLimit = 2400;
182 // If an upload fails, and the transmission was over this byte count, then we
183 // will discard the log, and not try to retransmit it. We also don't persist
184 // the log to the prefs for transmission during the next chrome session if this
185 // limit is exceeded.
186 const size_t kUploadLogAvoidRetransmitSize = 100 * 1024;
188 // Interval, in minutes, between state saves.
189 const int kSaveStateIntervalMinutes = 5;
191 enum ResponseStatus {
192 UNKNOWN_FAILURE,
193 SUCCESS,
194 BAD_REQUEST, // Invalid syntax or log too large.
195 NO_RESPONSE,
196 NUM_RESPONSE_STATUSES
199 ResponseStatus ResponseCodeToStatus(int response_code) {
200 switch (response_code) {
201 case -1:
202 return NO_RESPONSE;
203 case 200:
204 return SUCCESS;
205 case 400:
206 return BAD_REQUEST;
207 default:
208 return UNKNOWN_FAILURE;
212 #if defined(OS_ANDROID) || defined(OS_IOS)
213 void MarkAppCleanShutdownAndCommit(CleanExitBeacon* clean_exit_beacon,
214 PrefService* local_state) {
215 clean_exit_beacon->WriteBeaconValue(true);
216 local_state->SetInteger(prefs::kStabilityExecutionPhase,
217 MetricsService::SHUTDOWN_COMPLETE);
218 // Start writing right away (write happens on a different thread).
219 local_state->CommitPendingWrite();
221 #endif // defined(OS_ANDROID) || defined(OS_IOS)
223 } // namespace
226 SyntheticTrialGroup::SyntheticTrialGroup(uint32 trial, uint32 group) {
227 id.name = trial;
228 id.group = group;
231 SyntheticTrialGroup::~SyntheticTrialGroup() {
234 // static
235 MetricsService::ShutdownCleanliness MetricsService::clean_shutdown_status_ =
236 MetricsService::CLEANLY_SHUTDOWN;
238 MetricsService::ExecutionPhase MetricsService::execution_phase_ =
239 MetricsService::UNINITIALIZED_PHASE;
241 // static
242 void MetricsService::RegisterPrefs(PrefRegistrySimple* registry) {
243 DCHECK(IsSingleThreaded());
244 MetricsStateManager::RegisterPrefs(registry);
245 MetricsLog::RegisterPrefs(registry);
247 registry->RegisterInt64Pref(prefs::kInstallDate, 0);
249 registry->RegisterInt64Pref(prefs::kStabilityLaunchTimeSec, 0);
250 registry->RegisterInt64Pref(prefs::kStabilityLastTimestampSec, 0);
251 registry->RegisterStringPref(prefs::kStabilityStatsVersion, std::string());
252 registry->RegisterInt64Pref(prefs::kStabilityStatsBuildTime, 0);
253 registry->RegisterBooleanPref(prefs::kStabilityExitedCleanly, true);
254 registry->RegisterIntegerPref(prefs::kStabilityExecutionPhase,
255 UNINITIALIZED_PHASE);
256 registry->RegisterBooleanPref(prefs::kStabilitySessionEndCompleted, true);
257 registry->RegisterIntegerPref(prefs::kMetricsSessionID, -1);
259 registry->RegisterListPref(prefs::kMetricsInitialLogs);
260 registry->RegisterListPref(prefs::kMetricsOngoingLogs);
262 registry->RegisterInt64Pref(prefs::kUninstallLaunchCount, 0);
263 registry->RegisterInt64Pref(prefs::kUninstallMetricsUptimeSec, 0);
266 MetricsService::MetricsService(MetricsStateManager* state_manager,
267 MetricsServiceClient* client,
268 PrefService* local_state)
269 : log_manager_(local_state, kUploadLogAvoidRetransmitSize),
270 histogram_snapshot_manager_(this),
271 state_manager_(state_manager),
272 client_(client),
273 local_state_(local_state),
274 clean_exit_beacon_(client->GetRegistryBackupKey(), local_state),
275 recording_active_(false),
276 reporting_active_(false),
277 test_mode_active_(false),
278 state_(INITIALIZED),
279 log_upload_in_progress_(false),
280 idle_since_last_transmission_(false),
281 session_id_(-1),
282 self_ptr_factory_(this),
283 state_saver_factory_(this) {
284 DCHECK(IsSingleThreaded());
285 DCHECK(state_manager_);
286 DCHECK(client_);
287 DCHECK(local_state_);
289 // Set the install date if this is our first run.
290 int64 install_date = local_state_->GetInt64(prefs::kInstallDate);
291 if (install_date == 0)
292 local_state_->SetInt64(prefs::kInstallDate, base::Time::Now().ToTimeT());
295 MetricsService::~MetricsService() {
296 DisableRecording();
299 void MetricsService::InitializeMetricsRecordingState() {
300 InitializeMetricsState();
302 base::Closure upload_callback =
303 base::Bind(&MetricsService::StartScheduledUpload,
304 self_ptr_factory_.GetWeakPtr());
305 scheduler_.reset(
306 new MetricsReportingScheduler(
307 upload_callback,
308 // MetricsServiceClient outlives MetricsService, and
309 // MetricsReportingScheduler is tied to the lifetime of |this|.
310 base::Bind(&MetricsServiceClient::GetStandardUploadInterval,
311 base::Unretained(client_))));
314 void MetricsService::Start() {
315 HandleIdleSinceLastTransmission(false);
316 EnableRecording();
317 EnableReporting();
320 bool MetricsService::StartIfMetricsReportingEnabled() {
321 const bool enabled = state_manager_->IsMetricsReportingEnabled();
322 if (enabled)
323 Start();
324 return enabled;
327 void MetricsService::StartRecordingForTests() {
328 test_mode_active_ = true;
329 EnableRecording();
330 DisableReporting();
333 void MetricsService::Stop() {
334 HandleIdleSinceLastTransmission(false);
335 DisableReporting();
336 DisableRecording();
339 void MetricsService::EnableReporting() {
340 if (reporting_active_)
341 return;
342 reporting_active_ = true;
343 StartSchedulerIfNecessary();
346 void MetricsService::DisableReporting() {
347 reporting_active_ = false;
350 std::string MetricsService::GetClientId() {
351 return state_manager_->client_id();
354 int64 MetricsService::GetInstallDate() {
355 return local_state_->GetInt64(prefs::kInstallDate);
358 scoped_ptr<const base::FieldTrial::EntropyProvider>
359 MetricsService::CreateEntropyProvider() {
360 // TODO(asvitkine): Refactor the code so that MetricsService does not expose
361 // this method.
362 return state_manager_->CreateEntropyProvider();
365 void MetricsService::EnableRecording() {
366 DCHECK(IsSingleThreaded());
368 if (recording_active_)
369 return;
370 recording_active_ = true;
372 state_manager_->ForceClientIdCreation();
373 client_->SetMetricsClientId(state_manager_->client_id());
374 if (!log_manager_.current_log())
375 OpenNewLog();
377 for (size_t i = 0; i < metrics_providers_.size(); ++i)
378 metrics_providers_[i]->OnRecordingEnabled();
380 base::RemoveActionCallback(action_callback_);
381 action_callback_ = base::Bind(&MetricsService::OnUserAction,
382 base::Unretained(this));
383 base::AddActionCallback(action_callback_);
386 void MetricsService::DisableRecording() {
387 DCHECK(IsSingleThreaded());
389 if (!recording_active_)
390 return;
391 recording_active_ = false;
393 client_->OnRecordingDisabled();
395 base::RemoveActionCallback(action_callback_);
397 for (size_t i = 0; i < metrics_providers_.size(); ++i)
398 metrics_providers_[i]->OnRecordingDisabled();
400 PushPendingLogsToPersistentStorage();
403 bool MetricsService::recording_active() const {
404 DCHECK(IsSingleThreaded());
405 return recording_active_;
408 bool MetricsService::reporting_active() const {
409 DCHECK(IsSingleThreaded());
410 return reporting_active_;
413 void MetricsService::RecordDelta(const base::HistogramBase& histogram,
414 const base::HistogramSamples& snapshot) {
415 log_manager_.current_log()->RecordHistogramDelta(histogram.histogram_name(),
416 snapshot);
419 void MetricsService::InconsistencyDetected(
420 base::HistogramBase::Inconsistency problem) {
421 UMA_HISTOGRAM_ENUMERATION("Histogram.InconsistenciesBrowser",
422 problem, base::HistogramBase::NEVER_EXCEEDED_VALUE);
425 void MetricsService::UniqueInconsistencyDetected(
426 base::HistogramBase::Inconsistency problem) {
427 UMA_HISTOGRAM_ENUMERATION("Histogram.InconsistenciesBrowserUnique",
428 problem, base::HistogramBase::NEVER_EXCEEDED_VALUE);
431 void MetricsService::InconsistencyDetectedInLoggedCount(int amount) {
432 UMA_HISTOGRAM_COUNTS("Histogram.InconsistentSnapshotBrowser",
433 std::abs(amount));
436 void MetricsService::HandleIdleSinceLastTransmission(bool in_idle) {
437 // If there wasn't a lot of action, maybe the computer was asleep, in which
438 // case, the log transmissions should have stopped. Here we start them up
439 // again.
440 if (!in_idle && idle_since_last_transmission_)
441 StartSchedulerIfNecessary();
442 idle_since_last_transmission_ = in_idle;
445 void MetricsService::OnApplicationNotIdle() {
446 if (recording_active_)
447 HandleIdleSinceLastTransmission(false);
450 void MetricsService::RecordStartOfSessionEnd() {
451 LogCleanShutdown();
452 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, false);
455 void MetricsService::RecordCompletedSessionEnd() {
456 LogCleanShutdown();
457 RecordBooleanPrefValue(prefs::kStabilitySessionEndCompleted, true);
460 #if defined(OS_ANDROID) || defined(OS_IOS)
461 void MetricsService::OnAppEnterBackground() {
462 scheduler_->Stop();
464 MarkAppCleanShutdownAndCommit(&clean_exit_beacon_, local_state_);
466 // At this point, there's no way of knowing when the process will be
467 // killed, so this has to be treated similar to a shutdown, closing and
468 // persisting all logs. Unlinke a shutdown, the state is primed to be ready
469 // to continue logging and uploading if the process does return.
470 if (recording_active() && state_ >= SENDING_LOGS) {
471 PushPendingLogsToPersistentStorage();
472 // Persisting logs closes the current log, so start recording a new log
473 // immediately to capture any background work that might be done before the
474 // process is killed.
475 OpenNewLog();
479 void MetricsService::OnAppEnterForeground() {
480 clean_exit_beacon_.WriteBeaconValue(false);
481 StartSchedulerIfNecessary();
483 #else
484 void MetricsService::LogNeedForCleanShutdown() {
485 clean_exit_beacon_.WriteBeaconValue(false);
486 // Redundant setting to be sure we call for a clean shutdown.
487 clean_shutdown_status_ = NEED_TO_SHUTDOWN;
489 #endif // defined(OS_ANDROID) || defined(OS_IOS)
491 // static
492 void MetricsService::SetExecutionPhase(ExecutionPhase execution_phase,
493 PrefService* local_state) {
494 execution_phase_ = execution_phase;
495 local_state->SetInteger(prefs::kStabilityExecutionPhase, execution_phase_);
498 void MetricsService::RecordBreakpadRegistration(bool success) {
499 if (!success)
500 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationFail);
501 else
502 IncrementPrefValue(prefs::kStabilityBreakpadRegistrationSuccess);
505 void MetricsService::RecordBreakpadHasDebugger(bool has_debugger) {
506 if (!has_debugger)
507 IncrementPrefValue(prefs::kStabilityDebuggerNotPresent);
508 else
509 IncrementPrefValue(prefs::kStabilityDebuggerPresent);
512 void MetricsService::ClearSavedStabilityMetrics() {
513 for (size_t i = 0; i < metrics_providers_.size(); ++i)
514 metrics_providers_[i]->ClearSavedStabilityMetrics();
516 // Reset the prefs that are managed by MetricsService/MetricsLog directly.
517 local_state_->SetInteger(prefs::kStabilityCrashCount, 0);
518 local_state_->SetInteger(prefs::kStabilityExecutionPhase,
519 UNINITIALIZED_PHASE);
520 local_state_->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);
521 local_state_->SetInteger(prefs::kStabilityLaunchCount, 0);
522 local_state_->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
525 //------------------------------------------------------------------------------
526 // private methods
527 //------------------------------------------------------------------------------
530 //------------------------------------------------------------------------------
531 // Initialization methods
533 void MetricsService::InitializeMetricsState() {
534 const int64 buildtime = MetricsLog::GetBuildTime();
535 const std::string version = client_->GetVersionString();
536 bool version_changed = false;
537 if (local_state_->GetInt64(prefs::kStabilityStatsBuildTime) != buildtime ||
538 local_state_->GetString(prefs::kStabilityStatsVersion) != version) {
539 local_state_->SetString(prefs::kStabilityStatsVersion, version);
540 local_state_->SetInt64(prefs::kStabilityStatsBuildTime, buildtime);
541 version_changed = true;
544 log_manager_.LoadPersistedUnsentLogs();
546 session_id_ = local_state_->GetInteger(prefs::kMetricsSessionID);
548 if (!clean_exit_beacon_.exited_cleanly()) {
549 IncrementPrefValue(prefs::kStabilityCrashCount);
550 // Reset flag, and wait until we call LogNeedForCleanShutdown() before
551 // monitoring.
552 clean_exit_beacon_.WriteBeaconValue(true);
555 bool has_initial_stability_log = false;
556 if (!clean_exit_beacon_.exited_cleanly() || ProvidersHaveStabilityMetrics()) {
557 // TODO(rtenneti): On windows, consider saving/getting execution_phase from
558 // the registry.
559 int execution_phase =
560 local_state_->GetInteger(prefs::kStabilityExecutionPhase);
561 UMA_HISTOGRAM_SPARSE_SLOWLY("Chrome.Browser.CrashedExecutionPhase",
562 execution_phase);
564 // If the previous session didn't exit cleanly, or if any provider
565 // explicitly requests it, prepare an initial stability log -
566 // provided UMA is enabled.
567 if (state_manager_->IsMetricsReportingEnabled())
568 has_initial_stability_log = PrepareInitialStabilityLog();
571 // If no initial stability log was generated and there was a version upgrade,
572 // clear the stability stats from the previous version (so that they don't get
573 // attributed to the current version). This could otherwise happen due to a
574 // number of different edge cases, such as if the last version crashed before
575 // it could save off a system profile or if UMA reporting is disabled (which
576 // normally results in stats being accumulated).
577 if (!has_initial_stability_log && version_changed)
578 ClearSavedStabilityMetrics();
580 // Update session ID.
581 ++session_id_;
582 local_state_->SetInteger(prefs::kMetricsSessionID, session_id_);
584 // Stability bookkeeping
585 IncrementPrefValue(prefs::kStabilityLaunchCount);
587 DCHECK_EQ(UNINITIALIZED_PHASE, execution_phase_);
588 SetExecutionPhase(START_METRICS_RECORDING, local_state_);
590 if (!local_state_->GetBoolean(prefs::kStabilitySessionEndCompleted)) {
591 IncrementPrefValue(prefs::kStabilityIncompleteSessionEndCount);
592 // This is marked false when we get a WM_ENDSESSION.
593 local_state_->SetBoolean(prefs::kStabilitySessionEndCompleted, true);
596 // Call GetUptimes() for the first time, thus allowing all later calls
597 // to record incremental uptimes accurately.
598 base::TimeDelta ignored_uptime_parameter;
599 base::TimeDelta startup_uptime;
600 GetUptimes(local_state_, &startup_uptime, &ignored_uptime_parameter);
601 DCHECK_EQ(0, startup_uptime.InMicroseconds());
602 // For backwards compatibility, leave this intact in case Omaha is checking
603 // them. prefs::kStabilityLastTimestampSec may also be useless now.
604 // TODO(jar): Delete these if they have no uses.
605 local_state_->SetInt64(prefs::kStabilityLaunchTimeSec,
606 base::Time::Now().ToTimeT());
608 // Bookkeeping for the uninstall metrics.
609 IncrementLongPrefsValue(prefs::kUninstallLaunchCount);
611 // Kick off the process of saving the state (so the uptime numbers keep
612 // getting updated) every n minutes.
613 ScheduleNextStateSave();
616 void MetricsService::OnUserAction(const std::string& action) {
617 if (!ShouldLogEvents())
618 return;
620 log_manager_.current_log()->RecordUserAction(action);
621 HandleIdleSinceLastTransmission(false);
624 void MetricsService::FinishedGatheringInitialMetrics() {
625 DCHECK_EQ(INIT_TASK_SCHEDULED, state_);
626 state_ = INIT_TASK_DONE;
628 // Create the initial log.
629 if (!initial_metrics_log_.get()) {
630 initial_metrics_log_ = CreateLog(MetricsLog::ONGOING_LOG);
631 NotifyOnDidCreateMetricsLog();
634 scheduler_->InitTaskComplete();
637 void MetricsService::GetUptimes(PrefService* pref,
638 base::TimeDelta* incremental_uptime,
639 base::TimeDelta* uptime) {
640 base::TimeTicks now = base::TimeTicks::Now();
641 // If this is the first call, init |first_updated_time_| and
642 // |last_updated_time_|.
643 if (last_updated_time_.is_null()) {
644 first_updated_time_ = now;
645 last_updated_time_ = now;
647 *incremental_uptime = now - last_updated_time_;
648 *uptime = now - first_updated_time_;
649 last_updated_time_ = now;
651 const int64 incremental_time_secs = incremental_uptime->InSeconds();
652 if (incremental_time_secs > 0) {
653 int64 metrics_uptime = pref->GetInt64(prefs::kUninstallMetricsUptimeSec);
654 metrics_uptime += incremental_time_secs;
655 pref->SetInt64(prefs::kUninstallMetricsUptimeSec, metrics_uptime);
659 void MetricsService::NotifyOnDidCreateMetricsLog() {
660 DCHECK(IsSingleThreaded());
661 for (size_t i = 0; i < metrics_providers_.size(); ++i)
662 metrics_providers_[i]->OnDidCreateMetricsLog();
665 //------------------------------------------------------------------------------
666 // State save methods
668 void MetricsService::ScheduleNextStateSave() {
669 state_saver_factory_.InvalidateWeakPtrs();
671 base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
672 base::Bind(&MetricsService::SaveLocalState,
673 state_saver_factory_.GetWeakPtr()),
674 base::TimeDelta::FromMinutes(kSaveStateIntervalMinutes));
677 void MetricsService::SaveLocalState() {
678 RecordCurrentState(local_state_);
680 // TODO(jar):110021 Does this run down the batteries????
681 ScheduleNextStateSave();
685 //------------------------------------------------------------------------------
686 // Recording control methods
688 void MetricsService::OpenNewLog() {
689 DCHECK(!log_manager_.current_log());
691 log_manager_.BeginLoggingWithLog(CreateLog(MetricsLog::ONGOING_LOG));
692 NotifyOnDidCreateMetricsLog();
693 if (state_ == INITIALIZED) {
694 // We only need to schedule that run once.
695 state_ = INIT_TASK_SCHEDULED;
697 base::MessageLoop::current()->PostDelayedTask(
698 FROM_HERE,
699 base::Bind(&MetricsService::StartGatheringMetrics,
700 self_ptr_factory_.GetWeakPtr()),
701 base::TimeDelta::FromSeconds(kInitializationDelaySeconds));
705 void MetricsService::StartGatheringMetrics() {
706 client_->StartGatheringMetrics(
707 base::Bind(&MetricsService::FinishedGatheringInitialMetrics,
708 self_ptr_factory_.GetWeakPtr()));
711 void MetricsService::CloseCurrentLog() {
712 if (!log_manager_.current_log())
713 return;
715 // TODO(jar): Integrate bounds on log recording more consistently, so that we
716 // can stop recording logs that are too big much sooner.
717 if (log_manager_.current_log()->num_events() > kEventLimit) {
718 UMA_HISTOGRAM_COUNTS("UMA.Discarded Log Events",
719 log_manager_.current_log()->num_events());
720 log_manager_.DiscardCurrentLog();
721 OpenNewLog(); // Start trivial log to hold our histograms.
724 // Put incremental data (histogram deltas, and realtime stats deltas) at the
725 // end of all log transmissions (initial log handles this separately).
726 // RecordIncrementalStabilityElements only exists on the derived
727 // MetricsLog class.
728 MetricsLog* current_log = log_manager_.current_log();
729 DCHECK(current_log);
730 RecordCurrentEnvironment(current_log);
731 base::TimeDelta incremental_uptime;
732 base::TimeDelta uptime;
733 GetUptimes(local_state_, &incremental_uptime, &uptime);
734 current_log->RecordStabilityMetrics(metrics_providers_.get(),
735 incremental_uptime, uptime);
737 current_log->RecordGeneralMetrics(metrics_providers_.get());
738 RecordCurrentHistograms();
740 log_manager_.FinishCurrentLog();
743 void MetricsService::PushPendingLogsToPersistentStorage() {
744 if (state_ < SENDING_LOGS)
745 return; // We didn't and still don't have time to get plugin list etc.
747 CloseCurrentLog();
748 log_manager_.PersistUnsentLogs();
751 //------------------------------------------------------------------------------
752 // Transmission of logs methods
754 void MetricsService::StartSchedulerIfNecessary() {
755 // Never schedule cutting or uploading of logs in test mode.
756 if (test_mode_active_)
757 return;
759 // Even if reporting is disabled, the scheduler is needed to trigger the
760 // creation of the initial log, which must be done in order for any logs to be
761 // persisted on shutdown or backgrounding.
762 if (recording_active() &&
763 (reporting_active() || state_ < SENDING_LOGS)) {
764 scheduler_->Start();
768 void MetricsService::StartScheduledUpload() {
769 DCHECK(state_ >= INIT_TASK_DONE);
770 // If we're getting no notifications, then the log won't have much in it, and
771 // it's possible the computer is about to go to sleep, so don't upload and
772 // stop the scheduler.
773 // If recording has been turned off, the scheduler doesn't need to run.
774 // If reporting is off, proceed if the initial log hasn't been created, since
775 // that has to happen in order for logs to be cut and stored when persisting.
776 // TODO(stuartmorgan): Call Stop() on the scheduler when reporting and/or
777 // recording are turned off instead of letting it fire and then aborting.
778 if (idle_since_last_transmission_ ||
779 !recording_active() ||
780 (!reporting_active() && state_ >= SENDING_LOGS)) {
781 scheduler_->Stop();
782 scheduler_->UploadCancelled();
783 return;
786 // If there are unsent logs, send the next one. If not, start the asynchronous
787 // process of finalizing the current log for upload.
788 if (state_ == SENDING_LOGS && log_manager_.has_unsent_logs()) {
789 SendNextLog();
790 } else {
791 // There are no logs left to send, so start creating a new one.
792 client_->CollectFinalMetrics(
793 base::Bind(&MetricsService::OnFinalLogInfoCollectionDone,
794 self_ptr_factory_.GetWeakPtr()));
798 void MetricsService::OnFinalLogInfoCollectionDone() {
799 // If somehow there is a log upload in progress, we return and hope things
800 // work out. The scheduler isn't informed since if this happens, the scheduler
801 // will get a response from the upload.
802 DCHECK(!log_upload_in_progress_);
803 if (log_upload_in_progress_)
804 return;
806 // Abort if metrics were turned off during the final info gathering.
807 if (!recording_active()) {
808 scheduler_->Stop();
809 scheduler_->UploadCancelled();
810 return;
813 if (state_ == INIT_TASK_DONE) {
814 PrepareInitialMetricsLog();
815 } else {
816 DCHECK_EQ(SENDING_LOGS, state_);
817 CloseCurrentLog();
818 OpenNewLog();
820 SendNextLog();
823 void MetricsService::SendNextLog() {
824 DCHECK_EQ(SENDING_LOGS, state_);
825 if (!reporting_active()) {
826 scheduler_->Stop();
827 scheduler_->UploadCancelled();
828 return;
830 if (!log_manager_.has_unsent_logs()) {
831 // Should only get here if serializing the log failed somehow.
832 // Just tell the scheduler it was uploaded and wait for the next log
833 // interval.
834 scheduler_->UploadFinished(true, log_manager_.has_unsent_logs());
835 return;
837 if (!log_manager_.has_staged_log())
838 log_manager_.StageNextLogForUpload();
839 SendStagedLog();
842 bool MetricsService::ProvidersHaveStabilityMetrics() {
843 // Check whether any metrics provider has stability metrics.
844 for (size_t i = 0; i < metrics_providers_.size(); ++i) {
845 if (metrics_providers_[i]->HasStabilityMetrics())
846 return true;
849 return false;
852 bool MetricsService::PrepareInitialStabilityLog() {
853 DCHECK_EQ(INITIALIZED, state_);
855 scoped_ptr<MetricsLog> initial_stability_log(
856 CreateLog(MetricsLog::INITIAL_STABILITY_LOG));
858 // Do not call NotifyOnDidCreateMetricsLog here because the stability
859 // log describes stats from the _previous_ session.
861 if (!initial_stability_log->LoadSavedEnvironmentFromPrefs())
862 return false;
864 log_manager_.PauseCurrentLog();
865 log_manager_.BeginLoggingWithLog(initial_stability_log.Pass());
867 // Note: Some stability providers may record stability stats via histograms,
868 // so this call has to be after BeginLoggingWithLog().
869 log_manager_.current_log()->RecordStabilityMetrics(
870 metrics_providers_.get(), base::TimeDelta(), base::TimeDelta());
871 RecordCurrentStabilityHistograms();
873 // Note: RecordGeneralMetrics() intentionally not called since this log is for
874 // stability stats from a previous session only.
876 log_manager_.FinishCurrentLog();
877 log_manager_.ResumePausedLog();
879 // Store unsent logs, including the stability log that was just saved, so
880 // that they're not lost in case of a crash before upload time.
881 log_manager_.PersistUnsentLogs();
883 return true;
886 void MetricsService::PrepareInitialMetricsLog() {
887 DCHECK_EQ(INIT_TASK_DONE, state_);
889 RecordCurrentEnvironment(initial_metrics_log_.get());
890 base::TimeDelta incremental_uptime;
891 base::TimeDelta uptime;
892 GetUptimes(local_state_, &incremental_uptime, &uptime);
894 // Histograms only get written to the current log, so make the new log current
895 // before writing them.
896 log_manager_.PauseCurrentLog();
897 log_manager_.BeginLoggingWithLog(initial_metrics_log_.Pass());
899 // Note: Some stability providers may record stability stats via histograms,
900 // so this call has to be after BeginLoggingWithLog().
901 MetricsLog* current_log = log_manager_.current_log();
902 current_log->RecordStabilityMetrics(metrics_providers_.get(),
903 base::TimeDelta(), base::TimeDelta());
904 current_log->RecordGeneralMetrics(metrics_providers_.get());
905 RecordCurrentHistograms();
907 log_manager_.FinishCurrentLog();
908 log_manager_.ResumePausedLog();
910 // Store unsent logs, including the initial log that was just saved, so
911 // that they're not lost in case of a crash before upload time.
912 log_manager_.PersistUnsentLogs();
914 state_ = SENDING_LOGS;
917 void MetricsService::SendStagedLog() {
918 DCHECK(log_manager_.has_staged_log());
919 if (!log_manager_.has_staged_log())
920 return;
922 DCHECK(!log_upload_in_progress_);
923 log_upload_in_progress_ = true;
925 if (!log_uploader_) {
926 log_uploader_ = client_->CreateUploader(
927 base::Bind(&MetricsService::OnLogUploadComplete,
928 self_ptr_factory_.GetWeakPtr()));
931 const std::string hash =
932 base::HexEncode(log_manager_.staged_log_hash().data(),
933 log_manager_.staged_log_hash().size());
934 bool success = log_uploader_->UploadLog(log_manager_.staged_log(), hash);
935 UMA_HISTOGRAM_BOOLEAN("UMA.UploadCreation", success);
936 if (!success) {
937 // Skip this upload and hope things work out next time.
938 log_manager_.DiscardStagedLog();
939 scheduler_->UploadCancelled();
940 log_upload_in_progress_ = false;
941 return;
944 HandleIdleSinceLastTransmission(true);
948 void MetricsService::OnLogUploadComplete(int response_code) {
949 DCHECK_EQ(SENDING_LOGS, state_);
950 DCHECK(log_upload_in_progress_);
951 log_upload_in_progress_ = false;
953 // Log a histogram to track response success vs. failure rates.
954 UMA_HISTOGRAM_ENUMERATION("UMA.UploadResponseStatus.Protobuf",
955 ResponseCodeToStatus(response_code),
956 NUM_RESPONSE_STATUSES);
958 bool upload_succeeded = response_code == 200;
960 // Provide boolean for error recovery (allow us to ignore response_code).
961 bool discard_log = false;
962 const size_t log_size = log_manager_.staged_log().length();
963 if (upload_succeeded) {
964 UMA_HISTOGRAM_COUNTS_10000("UMA.LogSize.OnSuccess", log_size / 1024);
965 } else if (log_size > kUploadLogAvoidRetransmitSize) {
966 UMA_HISTOGRAM_COUNTS("UMA.Large Rejected Log was Discarded",
967 static_cast<int>(log_size));
968 discard_log = true;
969 } else if (response_code == 400) {
970 // Bad syntax. Retransmission won't work.
971 discard_log = true;
974 if (upload_succeeded || discard_log) {
975 log_manager_.DiscardStagedLog();
976 // Store the updated list to disk now that the removed log is uploaded.
977 log_manager_.PersistUnsentLogs();
980 // Error 400 indicates a problem with the log, not with the server, so
981 // don't consider that a sign that the server is in trouble.
982 bool server_is_healthy = upload_succeeded || response_code == 400;
983 scheduler_->UploadFinished(server_is_healthy, log_manager_.has_unsent_logs());
985 if (server_is_healthy)
986 client_->OnLogUploadComplete();
989 void MetricsService::IncrementPrefValue(const char* path) {
990 int value = local_state_->GetInteger(path);
991 local_state_->SetInteger(path, value + 1);
994 void MetricsService::IncrementLongPrefsValue(const char* path) {
995 int64 value = local_state_->GetInt64(path);
996 local_state_->SetInt64(path, value + 1);
999 bool MetricsService::UmaMetricsProperlyShutdown() {
1000 CHECK(clean_shutdown_status_ == CLEANLY_SHUTDOWN ||
1001 clean_shutdown_status_ == NEED_TO_SHUTDOWN);
1002 return clean_shutdown_status_ == CLEANLY_SHUTDOWN;
1005 void MetricsService::AddSyntheticTrialObserver(
1006 SyntheticTrialObserver* observer) {
1007 synthetic_trial_observer_list_.AddObserver(observer);
1008 if (!synthetic_trial_groups_.empty())
1009 observer->OnSyntheticTrialsChanged(synthetic_trial_groups_);
1012 void MetricsService::RemoveSyntheticTrialObserver(
1013 SyntheticTrialObserver* observer) {
1014 synthetic_trial_observer_list_.RemoveObserver(observer);
1017 void MetricsService::RegisterSyntheticFieldTrial(
1018 const SyntheticTrialGroup& trial) {
1019 for (size_t i = 0; i < synthetic_trial_groups_.size(); ++i) {
1020 if (synthetic_trial_groups_[i].id.name == trial.id.name) {
1021 if (synthetic_trial_groups_[i].id.group != trial.id.group) {
1022 synthetic_trial_groups_[i].id.group = trial.id.group;
1023 synthetic_trial_groups_[i].start_time = base::TimeTicks::Now();
1024 NotifySyntheticTrialObservers();
1026 return;
1030 SyntheticTrialGroup trial_group = trial;
1031 trial_group.start_time = base::TimeTicks::Now();
1032 synthetic_trial_groups_.push_back(trial_group);
1033 NotifySyntheticTrialObservers();
1036 void MetricsService::RegisterMetricsProvider(
1037 scoped_ptr<MetricsProvider> provider) {
1038 DCHECK_EQ(INITIALIZED, state_);
1039 metrics_providers_.push_back(provider.release());
1042 void MetricsService::CheckForClonedInstall(
1043 scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
1044 state_manager_->CheckForClonedInstall(task_runner);
1047 void MetricsService::NotifySyntheticTrialObservers() {
1048 FOR_EACH_OBSERVER(SyntheticTrialObserver, synthetic_trial_observer_list_,
1049 OnSyntheticTrialsChanged(synthetic_trial_groups_));
1052 void MetricsService::GetCurrentSyntheticFieldTrials(
1053 std::vector<variations::ActiveGroupId>* synthetic_trials) {
1054 DCHECK(synthetic_trials);
1055 synthetic_trials->clear();
1056 const MetricsLog* current_log = log_manager_.current_log();
1057 for (size_t i = 0; i < synthetic_trial_groups_.size(); ++i) {
1058 if (synthetic_trial_groups_[i].start_time <= current_log->creation_time())
1059 synthetic_trials->push_back(synthetic_trial_groups_[i].id);
1063 scoped_ptr<MetricsLog> MetricsService::CreateLog(MetricsLog::LogType log_type) {
1064 return make_scoped_ptr(new MetricsLog(state_manager_->client_id(),
1065 session_id_,
1066 log_type,
1067 client_,
1068 local_state_));
1071 void MetricsService::RecordCurrentEnvironment(MetricsLog* log) {
1072 std::vector<variations::ActiveGroupId> synthetic_trials;
1073 GetCurrentSyntheticFieldTrials(&synthetic_trials);
1074 log->RecordEnvironment(metrics_providers_.get(), synthetic_trials,
1075 GetInstallDate());
1076 UMA_HISTOGRAM_COUNTS_100("UMA.SyntheticTrials.Count",
1077 synthetic_trials.size());
1080 void MetricsService::RecordCurrentHistograms() {
1081 DCHECK(log_manager_.current_log());
1082 histogram_snapshot_manager_.PrepareDeltas(
1083 base::Histogram::kNoFlags, base::Histogram::kUmaTargetedHistogramFlag);
1086 void MetricsService::RecordCurrentStabilityHistograms() {
1087 DCHECK(log_manager_.current_log());
1088 histogram_snapshot_manager_.PrepareDeltas(
1089 base::Histogram::kNoFlags, base::Histogram::kUmaStabilityHistogramFlag);
1092 void MetricsService::LogCleanShutdown() {
1093 // Redundant setting to assure that we always reset this value at shutdown
1094 // (and that we don't use some alternate path, and not call LogCleanShutdown).
1095 clean_shutdown_status_ = CLEANLY_SHUTDOWN;
1097 clean_exit_beacon_.WriteBeaconValue(true);
1098 RecordCurrentState(local_state_);
1099 local_state_->SetInteger(prefs::kStabilityExecutionPhase,
1100 MetricsService::SHUTDOWN_COMPLETE);
1103 bool MetricsService::ShouldLogEvents() {
1104 // We simply don't log events to UMA if there is a single incognito
1105 // session visible. The problem is that we always notify using the orginal
1106 // profile in order to simplify notification processing.
1107 return !client_->IsOffTheRecordSessionActive();
1110 void MetricsService::RecordBooleanPrefValue(const char* path, bool value) {
1111 DCHECK(IsSingleThreaded());
1112 local_state_->SetBoolean(path, value);
1113 RecordCurrentState(local_state_);
1116 void MetricsService::RecordCurrentState(PrefService* pref) {
1117 pref->SetInt64(prefs::kStabilityLastTimestampSec,
1118 base::Time::Now().ToTimeT());
1121 } // namespace metrics