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/metrics/net/network_metrics_provider.h"
31 #include "components/variations/active_field_trials.h"
33 class MetricsServiceAccessor
;
35 class PrefRegistrySimple
;
38 class DictionaryValue
;
39 class HistogramSamples
;
40 class MessageLoopProxy
;
44 namespace variations
{
54 class MetricsLogUploader
;
55 class MetricsReportingScheduler
;
56 class MetricsServiceClient
;
57 class MetricsStateManager
;
59 // A Field Trial and its selected group, which represent a particular
60 // Chrome configuration state. For example, the trial name could map to
61 // a preference name, and the group name could map to a preference value.
62 struct SyntheticTrialGroup
{
64 ~SyntheticTrialGroup();
66 variations::ActiveGroupId id
;
67 base::TimeTicks start_time
;
70 // Synthetic field trial users:
71 friend class MetricsServiceAccessor
;
72 friend class MetricsService
;
73 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest
, RegisterSyntheticTrial
);
75 // This constructor is private specifically so as to control which code is
76 // able to access it. New code that wishes to use it should be added as a
78 SyntheticTrialGroup(uint32 trial
, uint32 group
);
81 // Interface class to observe changes to synthetic trials in MetricsService.
82 class SyntheticTrialObserver
{
84 // Called when the list of synthetic field trial groups has changed.
85 virtual void OnSyntheticTrialsChanged(
86 const std::vector
<SyntheticTrialGroup
>& groups
) = 0;
89 virtual ~SyntheticTrialObserver() {}
92 // See metrics_service.cc for a detailed description.
93 class MetricsService
: public base::HistogramFlattener
{
95 // The execution phase of the browser.
97 UNINITIALIZED_PHASE
= 0,
98 START_METRICS_RECORDING
= 100,
100 STARTUP_TIMEBOMB_ARM
= 300,
101 THREAD_WATCHER_START
= 400,
102 MAIN_MESSAGE_LOOP_RUN
= 500,
103 SHUTDOWN_TIMEBOMB_ARM
= 600,
104 SHUTDOWN_COMPLETE
= 700,
107 // Creates the MetricsService with the given |state_manager|, |client|, and
108 // |local_state|. Does not take ownership of the paramaters; instead stores
109 // a weak pointer to each. Caller should ensure that the parameters are valid
110 // for the lifetime of this class.
111 MetricsService(MetricsStateManager
* state_manager
,
112 MetricsServiceClient
* client
,
113 PrefService
* local_state
);
114 ~MetricsService() override
;
116 // Initializes metrics recording state. Updates various bookkeeping values in
117 // prefs and sets up the scheduler. This is a separate function rather than
118 // being done by the constructor so that field trials could be created before
120 void InitializeMetricsRecordingState();
122 // Starts the metrics system, turning on recording and uploading of metrics.
123 // Should be called when starting up with metrics enabled, or when metrics
127 // If metrics reporting is enabled, starts the metrics service. Returns
128 // whether the metrics service was started.
129 bool StartIfMetricsReportingEnabled();
131 // Starts the metrics system in a special test-only mode. Metrics won't ever
132 // be uploaded or persisted in this mode, but metrics will be recorded in
134 void StartRecordingForTests();
136 // Shuts down the metrics system. Should be called at shutdown, or if metrics
140 // Enable/disable transmission of accumulated logs and crash reports (dumps).
141 // Calling Start() automatically enables reporting, but sending is
142 // asyncronous so this can be called immediately after Start() to prevent
144 void EnableReporting();
145 void DisableReporting();
147 // Returns the client ID for this client, or the empty string if metrics
148 // recording is not currently running.
149 std::string
GetClientId();
151 // Returns the install date of the application, in seconds since the epoch.
152 int64
GetInstallDate();
154 // Returns the preferred entropy provider used to seed persistent activities
155 // based on whether or not metrics reporting will be permitted on this client.
157 // If metrics reporting is enabled, this method returns an entropy provider
158 // that has a high source of entropy, partially based on the client ID.
159 // Otherwise, it returns an entropy provider that is based on a low entropy
161 scoped_ptr
<const base::FieldTrial::EntropyProvider
> CreateEntropyProvider();
163 // At startup, prefs needs to be called with a list of all the pref names and
164 // types we'll be using.
165 static void RegisterPrefs(PrefRegistrySimple
* registry
);
167 // HistogramFlattener:
168 void RecordDelta(const base::HistogramBase
& histogram
,
169 const base::HistogramSamples
& snapshot
) override
;
170 void InconsistencyDetected(
171 base::HistogramBase::Inconsistency problem
) override
;
172 void UniqueInconsistencyDetected(
173 base::HistogramBase::Inconsistency problem
) override
;
174 void InconsistencyDetectedInLoggedCount(int amount
) override
;
176 // This should be called when the application is not idle, i.e. the user seems
177 // to be interacting with the application.
178 void OnApplicationNotIdle();
180 // Invoked when we get a WM_SESSIONEND. This places a value in prefs that is
181 // reset when RecordCompletedSessionEnd is invoked.
182 void RecordStartOfSessionEnd();
184 // This should be called when the application is shutting down. It records
185 // that session end was successful.
186 void RecordCompletedSessionEnd();
188 #if defined(OS_ANDROID) || defined(OS_IOS)
189 // Called when the application is going into background mode.
190 void OnAppEnterBackground();
192 // Called when the application is coming out of background mode.
193 void OnAppEnterForeground();
195 // Set the dirty flag, which will require a later call to LogCleanShutdown().
196 void LogNeedForCleanShutdown();
197 #endif // defined(OS_ANDROID) || defined(OS_IOS)
199 static void SetExecutionPhase(ExecutionPhase execution_phase
,
200 PrefService
* local_state
);
202 // Saves in the preferences if the crash report registration was successful.
203 // This count is eventually send via UMA logs.
204 void RecordBreakpadRegistration(bool success
);
206 // Saves in the preferences if the browser is running under a debugger.
207 // This count is eventually send via UMA logs.
208 void RecordBreakpadHasDebugger(bool has_debugger
);
210 bool recording_active() const;
211 bool reporting_active() const;
213 // Redundant test to ensure that we are notified of a clean exit.
214 // This value should be true when process has completed shutdown.
215 static bool UmaMetricsProperlyShutdown();
217 // Registers a field trial name and group to be used to annotate a UMA report
218 // with a particular Chrome configuration state. A UMA report will be
219 // annotated with this trial group if and only if all events in the report
220 // were created after the trial is registered. Only one group name may be
221 // registered at a time for a given trial_name. Only the last group name that
222 // is registered for a given trial name will be recorded. The values passed
223 // in must not correspond to any real field trial in the code.
224 // To use this method, SyntheticTrialGroup should friend your class.
225 void RegisterSyntheticFieldTrial(const SyntheticTrialGroup
& trial_group
);
227 // Adds an observer to be notified when the synthetic trials list changes.
228 void AddSyntheticTrialObserver(SyntheticTrialObserver
* observer
);
230 // Removes an existing observer of synthetic trials list changes.
231 void RemoveSyntheticTrialObserver(SyntheticTrialObserver
* observer
);
233 // Register the specified |provider| to provide additional metrics into the
234 // UMA log. Should be called during MetricsService initialization only.
235 void RegisterMetricsProvider(scoped_ptr
<MetricsProvider
> provider
);
237 // Check if this install was cloned or imaged from another machine. If a
238 // clone is detected, reset the client id and low entropy source. This
239 // should not be called more than once.
240 void CheckForClonedInstall(
241 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
);
243 // Clears the stability metrics that are saved in local state.
244 void ClearSavedStabilityMetrics();
247 // Exposed for testing.
248 MetricsLogManager
* log_manager() { return &log_manager_
; }
251 // The MetricsService has a lifecycle that is stored as a state.
252 // See metrics_service.cc for description of this lifecycle.
254 INITIALIZED
, // Constructor was called.
255 INIT_TASK_SCHEDULED
, // Waiting for deferred init tasks to finish.
256 INIT_TASK_DONE
, // Waiting for timer to send initial log.
257 SENDING_LOGS
, // Sending logs an creating new ones when we run out.
260 enum ShutdownCleanliness
{
261 CLEANLY_SHUTDOWN
= 0xdeadbeef,
262 NEED_TO_SHUTDOWN
= ~CLEANLY_SHUTDOWN
265 friend class ::MetricsServiceAccessor
;
267 typedef std::vector
<SyntheticTrialGroup
> SyntheticTrialGroups
;
269 // Calls into the client to start metrics gathering.
270 void StartGatheringMetrics();
272 // Callback that moves the state to INIT_TASK_DONE. When this is called, the
273 // state should be INIT_TASK_SCHEDULED.
274 void FinishedGatheringInitialMetrics();
276 void OnUserAction(const std::string
& action
);
278 // Get the amount of uptime since this process started and since the last
279 // call to this function. Also updates the cumulative uptime metric (stored
280 // as a pref) for uninstall. Uptimes are measured using TimeTicks, which
281 // guarantees that it is monotonic and does not jump if the user changes
282 // his/her clock. The TimeTicks implementation also makes the clock not
283 // count time the computer is suspended.
284 void GetUptimes(PrefService
* pref
,
285 base::TimeDelta
* incremental_uptime
,
286 base::TimeDelta
* uptime
);
288 // Turns recording on or off.
289 // DisableRecording() also forces a persistent save of logging state (if
290 // anything has been recorded, or transmitted).
291 void EnableRecording();
292 void DisableRecording();
294 // If in_idle is true, sets idle_since_last_transmission to true.
295 // If in_idle is false and idle_since_last_transmission_ is true, sets
296 // idle_since_last_transmission to false and starts the timer (provided
297 // starting the timer is permitted).
298 void HandleIdleSinceLastTransmission(bool in_idle
);
300 // Set up client ID, session ID, etc.
301 void InitializeMetricsState();
303 // Notifies providers when a new metrics log is created.
304 void NotifyOnDidCreateMetricsLog();
306 // Schedule the next save of LocalState information. This is called
307 // automatically by the task that performs each save to schedule the next one.
308 void ScheduleNextStateSave();
310 // Save the LocalState information immediately. This should not be called by
311 // anybody other than the scheduler to avoid doing too many writes. When you
312 // make a change, call ScheduleNextStateSave() instead.
313 void SaveLocalState();
315 // Opens a new log for recording user experience metrics.
318 // Closes out the current log after adding any last information.
319 void CloseCurrentLog();
321 // Pushes the text of the current and staged logs into persistent storage.
322 // Called when Chrome shuts down.
323 void PushPendingLogsToPersistentStorage();
325 // Ensures that scheduler is running, assuming the current settings are such
326 // that metrics should be reported. If not, this is a no-op.
327 void StartSchedulerIfNecessary();
329 // Starts the process of uploading metrics data.
330 void StartScheduledUpload();
332 // Called by the client when final log info collection is complete.
333 void OnFinalLogInfoCollectionDone();
335 // Either closes the current log or creates and closes the initial log
336 // (depending on |state_|), and stages it for upload.
339 // Returns true if any of the registered metrics providers have stability
340 // metrics to report.
341 bool ProvidersHaveStabilityMetrics();
343 // Prepares the initial stability log, which is only logged when the previous
344 // run of Chrome crashed. This log contains any stability metrics left over
345 // from that previous run, and only these stability metrics. It uses the
346 // system profile from the previous session. Returns true if a log was
348 bool PrepareInitialStabilityLog();
350 // Prepares the initial metrics log, which includes startup histograms and
351 // profiler data, as well as incremental stability-related metrics.
352 void PrepareInitialMetricsLog();
354 // Uploads the currently staged log (which must be non-null).
355 void SendStagedLog();
357 // Called after transmission completes (either successfully or with failure).
358 void OnLogUploadComplete(int response_code
);
360 // Reads, increments and then sets the specified integer preference.
361 void IncrementPrefValue(const char* path
);
363 // Reads, increments and then sets the specified long preference that is
364 // stored as a string.
365 void IncrementLongPrefsValue(const char* path
);
367 // Records that the browser was shut down cleanly.
368 void LogCleanShutdown();
370 // Records state that should be periodically saved, like uptime and
371 // buffered plugin stability statistics.
372 void RecordCurrentState(PrefService
* pref
);
374 // Checks whether events should currently be logged.
375 bool ShouldLogEvents();
377 // Sets the value of the specified path in prefs and schedules a save.
378 void RecordBooleanPrefValue(const char* path
, bool value
);
380 // Notifies observers on a synthetic trial list change.
381 void NotifySyntheticTrialObservers();
383 // Returns a list of synthetic field trials that were active for the entire
384 // duration of the current log.
385 void GetCurrentSyntheticFieldTrials(
386 std::vector
<variations::ActiveGroupId
>* synthetic_trials
);
388 // Creates a new MetricsLog instance with the given |log_type|.
389 scoped_ptr
<MetricsLog
> CreateLog(MetricsLog::LogType log_type
);
391 // Records the current environment (system profile) in |log|.
392 void RecordCurrentEnvironment(MetricsLog
* log
);
394 // Record complete list of histograms into the current log.
395 // Called when we close a log.
396 void RecordCurrentHistograms();
398 // Record complete list of stability histograms into the current log,
399 // i.e., histograms with the |kUmaStabilityHistogramFlag| flag set.
400 void RecordCurrentStabilityHistograms();
402 // Manager for the various in-flight logs.
403 MetricsLogManager log_manager_
;
405 // |histogram_snapshot_manager_| prepares histogram deltas for transmission.
406 base::HistogramSnapshotManager histogram_snapshot_manager_
;
408 // Used to manage various metrics reporting state prefs, such as client id,
409 // low entropy source and whether metrics reporting is enabled. Weak pointer.
410 MetricsStateManager
* const state_manager_
;
412 // Used to interact with the embedder. Weak pointer; must outlive |this|
414 MetricsServiceClient
* const client_
;
416 // Registered metrics providers.
417 ScopedVector
<MetricsProvider
> metrics_providers_
;
419 PrefService
* local_state_
;
421 CleanExitBeacon clean_exit_beacon_
;
423 base::ActionCallback action_callback_
;
425 // Indicate whether recording and reporting are currently happening.
426 // These should not be set directly, but by calling SetRecording and
428 bool recording_active_
;
429 bool reporting_active_
;
431 // Indicate whether test mode is enabled, where the initial log should never
432 // be cut, and logs are neither persisted nor uploaded.
433 bool test_mode_active_
;
435 // The progression of states made by the browser are recorded in the following
439 // The initial metrics log, used to record startup metrics (histograms and
440 // profiler data). Note that if a crash occurred in the previous session, an
441 // initial stability log may be sent before this.
442 scoped_ptr
<MetricsLog
> initial_metrics_log_
;
444 // Instance of the helper class for uploading logs.
445 scoped_ptr
<MetricsLogUploader
> log_uploader_
;
447 // Whether there is a current log upload in progress.
448 bool log_upload_in_progress_
;
450 // Whether the MetricsService object has received any notifications since
451 // the last time a transmission was sent.
452 bool idle_since_last_transmission_
;
454 // A number that identifies the how many times the app has been launched.
457 // The scheduler for determining when uploads should happen.
458 scoped_ptr
<MetricsReportingScheduler
> scheduler_
;
460 // Stores the time of the first call to |GetUptimes()|.
461 base::TimeTicks first_updated_time_
;
463 // Stores the time of the last call to |GetUptimes()|.
464 base::TimeTicks last_updated_time_
;
466 // Field trial groups that map to Chrome configuration states.
467 SyntheticTrialGroups synthetic_trial_groups_
;
469 // List of observers of |synthetic_trial_groups_| changes.
470 ObserverList
<SyntheticTrialObserver
> synthetic_trial_observer_list_
;
472 // Execution phase the browser is in.
473 static ExecutionPhase execution_phase_
;
475 // Reduntant marker to check that we completed our shutdown, and set the
476 // exited-cleanly bit in the prefs.
477 static ShutdownCleanliness clean_shutdown_status_
;
479 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest
, IsPluginProcess
);
480 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest
,
481 PermutedEntropyCacheClearedWhenLowEntropyReset
);
482 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest
, RegisterSyntheticTrial
);
484 // Weak pointers factory used to post task on different threads. All weak
485 // pointers managed by this factory have the same lifetime as MetricsService.
486 base::WeakPtrFactory
<MetricsService
> self_ptr_factory_
;
488 // Weak pointers factory used for saving state. All weak pointers managed by
489 // this factory are invalidated in ScheduleNextStateSave.
490 base::WeakPtrFactory
<MetricsService
> state_saver_factory_
;
492 DISALLOW_COPY_AND_ASSIGN(MetricsService
);
495 } // namespace metrics
497 #endif // COMPONENTS_METRICS_METRICS_SERVICE_H_