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 // This file defines a service that collects information about the user
6 // experience in order to help improve future versions of the app.
8 #ifndef COMPONENTS_METRICS_METRICS_SERVICE_H_
9 #define COMPONENTS_METRICS_METRICS_SERVICE_H_
15 #include "base/basictypes.h"
16 #include "base/gtest_prod_util.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/scoped_vector.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/metrics/field_trial.h"
21 #include "base/metrics/histogram_flattener.h"
22 #include "base/metrics/histogram_snapshot_manager.h"
23 #include "base/metrics/user_metrics.h"
24 #include "base/observer_list.h"
25 #include "base/time/time.h"
26 #include "components/metrics/clean_exit_beacon.h"
27 #include "components/metrics/metrics_log.h"
28 #include "components/metrics/metrics_log_manager.h"
29 #include "components/metrics/metrics_provider.h"
30 #include "components/variations/active_field_trials.h"
32 class MetricsServiceAccessor
;
34 class PrefRegistrySimple
;
37 class DictionaryValue
;
38 class HistogramSamples
;
39 class MessageLoopProxy
;
43 namespace variations
{
53 class MetricsLogUploader
;
54 class MetricsReportingScheduler
;
55 class MetricsServiceClient
;
56 class MetricsStateManager
;
58 // A Field Trial and its selected group, which represent a particular
59 // Chrome configuration state. For example, the trial name could map to
60 // a preference name, and the group name could map to a preference value.
61 struct SyntheticTrialGroup
{
63 ~SyntheticTrialGroup();
65 variations::ActiveGroupId id
;
66 base::TimeTicks start_time
;
69 // Synthetic field trial users:
70 friend class MetricsServiceAccessor
;
71 friend class MetricsService
;
72 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest
, RegisterSyntheticTrial
);
74 // This constructor is private specifically so as to control which code is
75 // able to access it. New code that wishes to use it should be added as a
77 SyntheticTrialGroup(uint32 trial
, uint32 group
);
80 // Interface class to observe changes to synthetic trials in MetricsService.
81 class SyntheticTrialObserver
{
83 // Called when the list of synthetic field trial groups has changed.
84 virtual void OnSyntheticTrialsChanged(
85 const std::vector
<SyntheticTrialGroup
>& groups
) = 0;
88 virtual ~SyntheticTrialObserver() {}
91 // See metrics_service.cc for a detailed description.
92 class MetricsService
: public base::HistogramFlattener
{
94 // The execution phase of the browser.
96 UNINITIALIZED_PHASE
= 0,
97 START_METRICS_RECORDING
= 100,
99 STARTUP_TIMEBOMB_ARM
= 300,
100 THREAD_WATCHER_START
= 400,
101 MAIN_MESSAGE_LOOP_RUN
= 500,
102 SHUTDOWN_TIMEBOMB_ARM
= 600,
103 SHUTDOWN_COMPLETE
= 700,
106 // Creates the MetricsService with the given |state_manager|, |client|, and
107 // |local_state|. Does not take ownership of the paramaters; instead stores
108 // a weak pointer to each. Caller should ensure that the parameters are valid
109 // for the lifetime of this class.
110 MetricsService(MetricsStateManager
* state_manager
,
111 MetricsServiceClient
* client
,
112 PrefService
* local_state
);
113 ~MetricsService() override
;
115 // Initializes metrics recording state. Updates various bookkeeping values in
116 // prefs and sets up the scheduler. This is a separate function rather than
117 // being done by the constructor so that field trials could be created before
119 void InitializeMetricsRecordingState();
121 // Starts the metrics system, turning on recording and uploading of metrics.
122 // Should be called when starting up with metrics enabled, or when metrics
126 // If metrics reporting is enabled, starts the metrics service. Returns
127 // whether the metrics service was started.
128 bool StartIfMetricsReportingEnabled();
130 // Starts the metrics system in a special test-only mode. Metrics won't ever
131 // be uploaded or persisted in this mode, but metrics will be recorded in
133 void StartRecordingForTests();
135 // Shuts down the metrics system. Should be called at shutdown, or if metrics
139 // Enable/disable transmission of accumulated logs and crash reports (dumps).
140 // Calling Start() automatically enables reporting, but sending is
141 // asyncronous so this can be called immediately after Start() to prevent
143 void EnableReporting();
144 void DisableReporting();
146 // Returns the client ID for this client, or the empty string if metrics
147 // recording is not currently running.
148 std::string
GetClientId();
150 // Returns the install date of the application, in seconds since the epoch.
151 int64
GetInstallDate();
153 // Returns the preferred entropy provider used to seed persistent activities
154 // based on whether or not metrics reporting will be permitted on this client.
156 // If metrics reporting is enabled, this method returns an entropy provider
157 // that has a high source of entropy, partially based on the client ID.
158 // Otherwise, it returns an entropy provider that is based on a low entropy
160 scoped_ptr
<const base::FieldTrial::EntropyProvider
> CreateEntropyProvider();
162 // At startup, prefs needs to be called with a list of all the pref names and
163 // types we'll be using.
164 static void RegisterPrefs(PrefRegistrySimple
* registry
);
166 // HistogramFlattener:
167 void RecordDelta(const base::HistogramBase
& histogram
,
168 const base::HistogramSamples
& snapshot
) override
;
169 void InconsistencyDetected(
170 base::HistogramBase::Inconsistency problem
) override
;
171 void UniqueInconsistencyDetected(
172 base::HistogramBase::Inconsistency problem
) override
;
173 void InconsistencyDetectedInLoggedCount(int amount
) override
;
175 // This should be called when the application is not idle, i.e. the user seems
176 // to be interacting with the application.
177 void OnApplicationNotIdle();
179 // Invoked when we get a WM_SESSIONEND. This places a value in prefs that is
180 // reset when RecordCompletedSessionEnd is invoked.
181 void RecordStartOfSessionEnd();
183 // This should be called when the application is shutting down. It records
184 // that session end was successful.
185 void RecordCompletedSessionEnd();
187 #if defined(OS_ANDROID) || defined(OS_IOS)
188 // Called when the application is going into background mode.
189 void OnAppEnterBackground();
191 // Called when the application is coming out of background mode.
192 void OnAppEnterForeground();
194 // Set the dirty flag, which will require a later call to LogCleanShutdown().
195 void LogNeedForCleanShutdown();
196 #endif // defined(OS_ANDROID) || defined(OS_IOS)
198 static void SetExecutionPhase(ExecutionPhase execution_phase
,
199 PrefService
* local_state
);
201 // Saves in the preferences if the crash report registration was successful.
202 // This count is eventually send via UMA logs.
203 void RecordBreakpadRegistration(bool success
);
205 // Saves in the preferences if the browser is running under a debugger.
206 // This count is eventually send via UMA logs.
207 void RecordBreakpadHasDebugger(bool has_debugger
);
209 bool recording_active() const;
210 bool reporting_active() const;
212 // Redundant test to ensure that we are notified of a clean exit.
213 // This value should be true when process has completed shutdown.
214 static bool UmaMetricsProperlyShutdown();
216 // Registers a field trial name and group to be used to annotate a UMA report
217 // with a particular Chrome configuration state. A UMA report will be
218 // annotated with this trial group if and only if all events in the report
219 // were created after the trial is registered. Only one group name may be
220 // registered at a time for a given trial_name. Only the last group name that
221 // is registered for a given trial name will be recorded. The values passed
222 // in must not correspond to any real field trial in the code.
223 // To use this method, SyntheticTrialGroup should friend your class.
224 void RegisterSyntheticFieldTrial(const SyntheticTrialGroup
& trial_group
);
226 // Adds an observer to be notified when the synthetic trials list changes.
227 void AddSyntheticTrialObserver(SyntheticTrialObserver
* observer
);
229 // Removes an existing observer of synthetic trials list changes.
230 void RemoveSyntheticTrialObserver(SyntheticTrialObserver
* observer
);
232 // Register the specified |provider| to provide additional metrics into the
233 // UMA log. Should be called during MetricsService initialization only.
234 void RegisterMetricsProvider(scoped_ptr
<MetricsProvider
> provider
);
236 // Check if this install was cloned or imaged from another machine. If a
237 // clone is detected, reset the client id and low entropy source. This
238 // should not be called more than once.
239 void CheckForClonedInstall(
240 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
);
242 // Clears the stability metrics that are saved in local state.
243 void ClearSavedStabilityMetrics();
246 // Exposed for testing.
247 MetricsLogManager
* log_manager() { return &log_manager_
; }
250 // The MetricsService has a lifecycle that is stored as a state.
251 // See metrics_service.cc for description of this lifecycle.
253 INITIALIZED
, // Constructor was called.
254 INIT_TASK_SCHEDULED
, // Waiting for deferred init tasks to
256 INIT_TASK_DONE
, // Waiting for timer to send initial log.
257 SENDING_INITIAL_STABILITY_LOG
, // Initial stability log being sent.
258 SENDING_INITIAL_METRICS_LOG
, // Initial metrics log being sent.
259 SENDING_OLD_LOGS
, // Sending unsent logs from last session.
260 SENDING_CURRENT_LOGS
, // Sending ongoing logs as they accrue.
263 enum ShutdownCleanliness
{
264 CLEANLY_SHUTDOWN
= 0xdeadbeef,
265 NEED_TO_SHUTDOWN
= ~CLEANLY_SHUTDOWN
268 friend class ::MetricsServiceAccessor
;
270 typedef std::vector
<SyntheticTrialGroup
> SyntheticTrialGroups
;
272 // Calls into the client to start metrics gathering.
273 void StartGatheringMetrics();
275 // Callback that moves the state to INIT_TASK_DONE. When this is called, the
276 // state should be INIT_TASK_SCHEDULED.
277 void FinishedGatheringInitialMetrics();
279 void OnUserAction(const std::string
& action
);
281 // Get the amount of uptime since this process started and since the last
282 // call to this function. Also updates the cumulative uptime metric (stored
283 // as a pref) for uninstall. Uptimes are measured using TimeTicks, which
284 // guarantees that it is monotonic and does not jump if the user changes
285 // his/her clock. The TimeTicks implementation also makes the clock not
286 // count time the computer is suspended.
287 void GetUptimes(PrefService
* pref
,
288 base::TimeDelta
* incremental_uptime
,
289 base::TimeDelta
* uptime
);
291 // Turns recording on or off.
292 // DisableRecording() also forces a persistent save of logging state (if
293 // anything has been recorded, or transmitted).
294 void EnableRecording();
295 void DisableRecording();
297 // If in_idle is true, sets idle_since_last_transmission to true.
298 // If in_idle is false and idle_since_last_transmission_ is true, sets
299 // idle_since_last_transmission to false and starts the timer (provided
300 // starting the timer is permitted).
301 void HandleIdleSinceLastTransmission(bool in_idle
);
303 // Set up client ID, session ID, etc.
304 void InitializeMetricsState();
306 // Notifies providers when a new metrics log is created.
307 void NotifyOnDidCreateMetricsLog();
309 // Schedule the next save of LocalState information. This is called
310 // automatically by the task that performs each save to schedule the next one.
311 void ScheduleNextStateSave();
313 // Save the LocalState information immediately. This should not be called by
314 // anybody other than the scheduler to avoid doing too many writes. When you
315 // make a change, call ScheduleNextStateSave() instead.
316 void SaveLocalState();
318 // Opens a new log for recording user experience metrics.
321 // Closes out the current log after adding any last information.
322 void CloseCurrentLog();
324 // Pushes the text of the current and staged logs into persistent storage.
325 // Called when Chrome shuts down.
326 void PushPendingLogsToPersistentStorage();
328 // Ensures that scheduler is running, assuming the current settings are such
329 // that metrics should be reported. If not, this is a no-op.
330 void StartSchedulerIfNecessary();
332 // Starts the process of uploading metrics data.
333 void StartScheduledUpload();
335 // Called by the client when final log info collection is complete.
336 void OnFinalLogInfoCollectionDone();
338 // Either closes the current log or creates and closes the initial log
339 // (depending on |state_|), and stages it for upload.
342 // Returns true if any of the registered metrics providers have stability
343 // metrics to report.
344 bool ProvidersHaveStabilityMetrics();
346 // Prepares the initial stability log, which is only logged when the previous
347 // run of Chrome crashed. This log contains any stability metrics left over
348 // from that previous run, and only these stability metrics. It uses the
349 // system profile from the previous session.
350 void PrepareInitialStabilityLog();
352 // Prepares the initial metrics log, which includes startup histograms and
353 // profiler data, as well as incremental stability-related metrics.
354 void PrepareInitialMetricsLog();
356 // Uploads the currently staged log (which must be non-null).
357 void SendStagedLog();
359 // Called after transmission completes (either successfully or with failure).
360 void OnLogUploadComplete(int response_code
);
362 // Reads, increments and then sets the specified integer preference.
363 void IncrementPrefValue(const char* path
);
365 // Reads, increments and then sets the specified long preference that is
366 // stored as a string.
367 void IncrementLongPrefsValue(const char* path
);
369 // Records that the browser was shut down cleanly.
370 void LogCleanShutdown();
372 // Records state that should be periodically saved, like uptime and
373 // buffered plugin stability statistics.
374 void RecordCurrentState(PrefService
* pref
);
376 // Checks whether events should currently be logged.
377 bool ShouldLogEvents();
379 // Sets the value of the specified path in prefs and schedules a save.
380 void RecordBooleanPrefValue(const char* path
, bool value
);
382 // Notifies observers on a synthetic trial list change.
383 void NotifySyntheticTrialObservers();
385 // Returns a list of synthetic field trials that were active for the entire
386 // duration of the current log.
387 void GetCurrentSyntheticFieldTrials(
388 std::vector
<variations::ActiveGroupId
>* synthetic_trials
);
390 // Creates a new MetricsLog instance with the given |log_type|.
391 scoped_ptr
<MetricsLog
> CreateLog(MetricsLog::LogType log_type
);
393 // Records the current environment (system profile) in |log|.
394 void RecordCurrentEnvironment(MetricsLog
* log
);
396 // Record complete list of histograms into the current log.
397 // Called when we close a log.
398 void RecordCurrentHistograms();
400 // Record complete list of stability histograms into the current log,
401 // i.e., histograms with the |kUmaStabilityHistogramFlag| flag set.
402 void RecordCurrentStabilityHistograms();
404 // Manager for the various in-flight logs.
405 MetricsLogManager log_manager_
;
407 // |histogram_snapshot_manager_| prepares histogram deltas for transmission.
408 base::HistogramSnapshotManager histogram_snapshot_manager_
;
410 // Used to manage various metrics reporting state prefs, such as client id,
411 // low entropy source and whether metrics reporting is enabled. Weak pointer.
412 MetricsStateManager
* const state_manager_
;
414 // Used to interact with the embedder. Weak pointer; must outlive |this|
416 MetricsServiceClient
* const client_
;
418 // Registered metrics providers.
419 ScopedVector
<MetricsProvider
> metrics_providers_
;
421 PrefService
* local_state_
;
423 CleanExitBeacon clean_exit_beacon_
;
425 base::ActionCallback action_callback_
;
427 // Indicate whether recording and reporting are currently happening.
428 // These should not be set directly, but by calling SetRecording and
430 bool recording_active_
;
431 bool reporting_active_
;
433 // Indicate whether test mode is enabled, where the initial log should never
434 // be cut, and logs are neither persisted nor uploaded.
435 bool test_mode_active_
;
437 // The progression of states made by the browser are recorded in the following
441 // Whether the initial stability log has been recorded during startup.
442 bool has_initial_stability_log_
;
444 // The initial metrics log, used to record startup metrics (histograms and
445 // profiler data). Note that if a crash occurred in the previous session, an
446 // initial stability log may be sent before this.
447 scoped_ptr
<MetricsLog
> initial_metrics_log_
;
449 // Instance of the helper class for uploading logs.
450 scoped_ptr
<MetricsLogUploader
> log_uploader_
;
452 // Whether there is a current log upload in progress.
453 bool log_upload_in_progress_
;
455 // Whether the MetricsService object has received any notifications since
456 // the last time a transmission was sent.
457 bool idle_since_last_transmission_
;
459 // A number that identifies the how many times the app has been launched.
462 // The scheduler for determining when uploads should happen.
463 scoped_ptr
<MetricsReportingScheduler
> scheduler_
;
465 // Stores the time of the first call to |GetUptimes()|.
466 base::TimeTicks first_updated_time_
;
468 // Stores the time of the last call to |GetUptimes()|.
469 base::TimeTicks last_updated_time_
;
471 // Field trial groups that map to Chrome configuration states.
472 SyntheticTrialGroups synthetic_trial_groups_
;
474 // List of observers of |synthetic_trial_groups_| changes.
475 ObserverList
<SyntheticTrialObserver
> synthetic_trial_observer_list_
;
477 // Execution phase the browser is in.
478 static ExecutionPhase execution_phase_
;
480 // Reduntant marker to check that we completed our shutdown, and set the
481 // exited-cleanly bit in the prefs.
482 static ShutdownCleanliness clean_shutdown_status_
;
484 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest
, IsPluginProcess
);
485 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest
,
486 PermutedEntropyCacheClearedWhenLowEntropyReset
);
487 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest
, RegisterSyntheticTrial
);
489 // Weak pointers factory used to post task on different threads. All weak
490 // pointers managed by this factory have the same lifetime as MetricsService.
491 base::WeakPtrFactory
<MetricsService
> self_ptr_factory_
;
493 // Weak pointers factory used for saving state. All weak pointers managed by
494 // this factory are invalidated in ScheduleNextStateSave.
495 base::WeakPtrFactory
<MetricsService
> state_saver_factory_
;
497 DISALLOW_COPY_AND_ASSIGN(MetricsService
);
500 } // namespace metrics
502 #endif // COMPONENTS_METRICS_METRICS_SERVICE_H_