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
;
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 date at which the current metrics client ID was created as
154 // an int64 containing seconds since the epoch.
155 int64
GetMetricsReportingEnabledDate();
157 // Returns the preferred entropy provider used to seed persistent activities
158 // based on whether or not metrics reporting will be permitted on this client.
160 // If metrics reporting is enabled, this method returns an entropy provider
161 // that has a high source of entropy, partially based on the client ID.
162 // Otherwise, it returns an entropy provider that is based on a low entropy
164 scoped_ptr
<const base::FieldTrial::EntropyProvider
> CreateEntropyProvider();
166 // At startup, prefs needs to be called with a list of all the pref names and
167 // types we'll be using.
168 static void RegisterPrefs(PrefRegistrySimple
* registry
);
170 // HistogramFlattener:
171 void RecordDelta(const base::HistogramBase
& histogram
,
172 const base::HistogramSamples
& snapshot
) override
;
173 void InconsistencyDetected(
174 base::HistogramBase::Inconsistency problem
) override
;
175 void UniqueInconsistencyDetected(
176 base::HistogramBase::Inconsistency problem
) override
;
177 void InconsistencyDetectedInLoggedCount(int amount
) override
;
179 // This should be called when the application is not idle, i.e. the user seems
180 // to be interacting with the application.
181 void OnApplicationNotIdle();
183 // Invoked when we get a WM_SESSIONEND. This places a value in prefs that is
184 // reset when RecordCompletedSessionEnd is invoked.
185 void RecordStartOfSessionEnd();
187 // This should be called when the application is shutting down. It records
188 // that session end was successful.
189 void RecordCompletedSessionEnd();
191 #if defined(OS_ANDROID) || defined(OS_IOS)
192 // Called when the application is going into background mode.
193 void OnAppEnterBackground();
195 // Called when the application is coming out of background mode.
196 void OnAppEnterForeground();
198 // Set the dirty flag, which will require a later call to LogCleanShutdown().
199 void LogNeedForCleanShutdown();
200 #endif // defined(OS_ANDROID) || defined(OS_IOS)
202 static void SetExecutionPhase(ExecutionPhase execution_phase
,
203 PrefService
* local_state
);
205 // Saves in the preferences if the crash report registration was successful.
206 // This count is eventually send via UMA logs.
207 void RecordBreakpadRegistration(bool success
);
209 // Saves in the preferences if the browser is running under a debugger.
210 // This count is eventually send via UMA logs.
211 void RecordBreakpadHasDebugger(bool has_debugger
);
213 bool recording_active() const;
214 bool reporting_active() const;
216 // Redundant test to ensure that we are notified of a clean exit.
217 // This value should be true when process has completed shutdown.
218 static bool UmaMetricsProperlyShutdown();
220 // Registers a field trial name and group to be used to annotate a UMA report
221 // with a particular Chrome configuration state. A UMA report will be
222 // annotated with this trial group if and only if all events in the report
223 // were created after the trial is registered. Only one group name may be
224 // registered at a time for a given trial_name. Only the last group name that
225 // is registered for a given trial name will be recorded. The values passed
226 // in must not correspond to any real field trial in the code.
227 // To use this method, SyntheticTrialGroup should friend your class.
228 void RegisterSyntheticFieldTrial(const SyntheticTrialGroup
& trial_group
);
230 // Adds an observer to be notified when the synthetic trials list changes.
231 void AddSyntheticTrialObserver(SyntheticTrialObserver
* observer
);
233 // Removes an existing observer of synthetic trials list changes.
234 void RemoveSyntheticTrialObserver(SyntheticTrialObserver
* observer
);
236 // Register the specified |provider| to provide additional metrics into the
237 // UMA log. Should be called during MetricsService initialization only.
238 void RegisterMetricsProvider(scoped_ptr
<MetricsProvider
> provider
);
240 // Check if this install was cloned or imaged from another machine. If a
241 // clone is detected, reset the client id and low entropy source. This
242 // should not be called more than once.
243 void CheckForClonedInstall(
244 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
);
246 // Clears the stability metrics that are saved in local state.
247 void ClearSavedStabilityMetrics();
249 // Pushes a log that has been generated by an external component.
250 void PushExternalLog(const std::string
& log
);
253 // Exposed for testing.
254 MetricsLogManager
* log_manager() { return &log_manager_
; }
257 // The MetricsService has a lifecycle that is stored as a state.
258 // See metrics_service.cc for description of this lifecycle.
260 INITIALIZED
, // Constructor was called.
261 INIT_TASK_SCHEDULED
, // Waiting for deferred init tasks to finish.
262 INIT_TASK_DONE
, // Waiting for timer to send initial log.
263 SENDING_LOGS
, // Sending logs an creating new ones when we run out.
266 enum ShutdownCleanliness
{
267 CLEANLY_SHUTDOWN
= 0xdeadbeef,
268 NEED_TO_SHUTDOWN
= ~CLEANLY_SHUTDOWN
271 friend class ::MetricsServiceAccessor
;
273 typedef std::vector
<SyntheticTrialGroup
> SyntheticTrialGroups
;
275 // Calls into the client to start metrics gathering.
276 void StartGatheringMetrics();
278 // Callback that moves the state to INIT_TASK_DONE. When this is called, the
279 // state should be INIT_TASK_SCHEDULED.
280 void FinishedGatheringInitialMetrics();
282 void OnUserAction(const std::string
& action
);
284 // Get the amount of uptime since this process started and since the last
285 // call to this function. Also updates the cumulative uptime metric (stored
286 // as a pref) for uninstall. Uptimes are measured using TimeTicks, which
287 // guarantees that it is monotonic and does not jump if the user changes
288 // his/her clock. The TimeTicks implementation also makes the clock not
289 // count time the computer is suspended.
290 void GetUptimes(PrefService
* pref
,
291 base::TimeDelta
* incremental_uptime
,
292 base::TimeDelta
* uptime
);
294 // Turns recording on or off.
295 // DisableRecording() also forces a persistent save of logging state (if
296 // anything has been recorded, or transmitted).
297 void EnableRecording();
298 void DisableRecording();
300 // If in_idle is true, sets idle_since_last_transmission to true.
301 // If in_idle is false and idle_since_last_transmission_ is true, sets
302 // idle_since_last_transmission to false and starts the timer (provided
303 // starting the timer is permitted).
304 void HandleIdleSinceLastTransmission(bool in_idle
);
306 // Set up client ID, session ID, etc.
307 void InitializeMetricsState();
309 // Notifies providers when a new metrics log is created.
310 void NotifyOnDidCreateMetricsLog();
312 // Schedule the next save of LocalState information. This is called
313 // automatically by the task that performs each save to schedule the next one.
314 void ScheduleNextStateSave();
316 // Save the LocalState information immediately. This should not be called by
317 // anybody other than the scheduler to avoid doing too many writes. When you
318 // make a change, call ScheduleNextStateSave() instead.
319 void SaveLocalState();
321 // Opens a new log for recording user experience metrics.
324 // Closes out the current log after adding any last information.
325 void CloseCurrentLog();
327 // Pushes the text of the current and staged logs into persistent storage.
328 // Called when Chrome shuts down.
329 void PushPendingLogsToPersistentStorage();
331 // Ensures that scheduler is running, assuming the current settings are such
332 // that metrics should be reported. If not, this is a no-op.
333 void StartSchedulerIfNecessary();
335 // Starts the process of uploading metrics data.
336 void StartScheduledUpload();
338 // Called by the client via a callback when final log info collection is
340 void OnFinalLogInfoCollectionDone();
342 // If recording is enabled, begins uploading the next completed log from
343 // the log manager, staging it if necessary.
346 // Returns true if any of the registered metrics providers have critical
347 // stability metrics to report in an initial stability log.
348 bool ProvidersHaveInitialStabilityMetrics();
350 // Prepares the initial stability log, which is only logged when the previous
351 // run of Chrome crashed. This log contains any stability metrics left over
352 // from that previous run, and only these stability metrics. It uses the
353 // system profile from the previous session. Returns true if a log was
355 bool PrepareInitialStabilityLog();
357 // Prepares the initial metrics log, which includes startup histograms and
358 // profiler data, as well as incremental stability-related metrics.
359 void PrepareInitialMetricsLog();
361 // Uploads the currently staged log (which must be non-null).
362 void SendStagedLog();
364 // Called after transmission completes (either successfully or with failure).
365 void OnLogUploadComplete(int response_code
);
367 // Reads, increments and then sets the specified integer preference.
368 void IncrementPrefValue(const char* path
);
370 // Reads, increments and then sets the specified long preference that is
371 // stored as a string.
372 void IncrementLongPrefsValue(const char* path
);
374 // Records that the browser was shut down cleanly.
375 void LogCleanShutdown();
377 // Records state that should be periodically saved, like uptime and
378 // buffered plugin stability statistics.
379 void RecordCurrentState(PrefService
* pref
);
381 // Checks whether events should currently be logged.
382 bool ShouldLogEvents();
384 // Sets the value of the specified path in prefs and schedules a save.
385 void RecordBooleanPrefValue(const char* path
, bool value
);
387 // Notifies observers on a synthetic trial list change.
388 void NotifySyntheticTrialObservers();
390 // Returns a list of synthetic field trials that were active for the entire
391 // duration of the current log.
392 void GetCurrentSyntheticFieldTrials(
393 std::vector
<variations::ActiveGroupId
>* synthetic_trials
);
395 // Creates a new MetricsLog instance with the given |log_type|.
396 scoped_ptr
<MetricsLog
> CreateLog(MetricsLog::LogType log_type
);
398 // Records the current environment (system profile) in |log|.
399 void RecordCurrentEnvironment(MetricsLog
* log
);
401 // Record complete list of histograms into the current log.
402 // Called when we close a log.
403 void RecordCurrentHistograms();
405 // Record complete list of stability histograms into the current log,
406 // i.e., histograms with the |kUmaStabilityHistogramFlag| flag set.
407 void RecordCurrentStabilityHistograms();
409 // Manager for the various in-flight logs.
410 MetricsLogManager log_manager_
;
412 // |histogram_snapshot_manager_| prepares histogram deltas for transmission.
413 base::HistogramSnapshotManager histogram_snapshot_manager_
;
415 // Used to manage various metrics reporting state prefs, such as client id,
416 // low entropy source and whether metrics reporting is enabled. Weak pointer.
417 MetricsStateManager
* const state_manager_
;
419 // Used to interact with the embedder. Weak pointer; must outlive |this|
421 MetricsServiceClient
* const client_
;
423 // Registered metrics providers.
424 ScopedVector
<MetricsProvider
> metrics_providers_
;
426 PrefService
* local_state_
;
428 CleanExitBeacon clean_exit_beacon_
;
430 base::ActionCallback action_callback_
;
432 // Indicate whether recording and reporting are currently happening.
433 // These should not be set directly, but by calling SetRecording and
435 bool recording_active_
;
436 bool reporting_active_
;
438 // Indicate whether test mode is enabled, where the initial log should never
439 // be cut, and logs are neither persisted nor uploaded.
440 bool test_mode_active_
;
442 // The progression of states made by the browser are recorded in the following
446 // The initial metrics log, used to record startup metrics (histograms and
447 // profiler data). Note that if a crash occurred in the previous session, an
448 // initial stability log may be sent before this.
449 scoped_ptr
<MetricsLog
> initial_metrics_log_
;
451 // Instance of the helper class for uploading logs.
452 scoped_ptr
<MetricsLogUploader
> log_uploader_
;
454 // Whether there is a current log upload in progress.
455 bool log_upload_in_progress_
;
457 // Whether the MetricsService object has received any notifications since
458 // the last time a transmission was sent.
459 bool idle_since_last_transmission_
;
461 // A number that identifies the how many times the app has been launched.
464 // The scheduler for determining when uploads should happen.
465 scoped_ptr
<MetricsReportingScheduler
> scheduler_
;
467 // Stores the time of the first call to |GetUptimes()|.
468 base::TimeTicks first_updated_time_
;
470 // Stores the time of the last call to |GetUptimes()|.
471 base::TimeTicks last_updated_time_
;
473 // Field trial groups that map to Chrome configuration states.
474 SyntheticTrialGroups synthetic_trial_groups_
;
476 // List of observers of |synthetic_trial_groups_| changes.
477 base::ObserverList
<SyntheticTrialObserver
> synthetic_trial_observer_list_
;
479 // Execution phase the browser is in.
480 static ExecutionPhase execution_phase_
;
482 // Reduntant marker to check that we completed our shutdown, and set the
483 // exited-cleanly bit in the prefs.
484 static ShutdownCleanliness clean_shutdown_status_
;
486 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest
, IsPluginProcess
);
487 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest
,
488 PermutedEntropyCacheClearedWhenLowEntropyReset
);
489 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest
, RegisterSyntheticTrial
);
491 // Weak pointers factory used to post task on different threads. All weak
492 // pointers managed by this factory have the same lifetime as MetricsService.
493 base::WeakPtrFactory
<MetricsService
> self_ptr_factory_
;
495 // Weak pointers factory used for saving state. All weak pointers managed by
496 // this factory are invalidated in ScheduleNextStateSave.
497 base::WeakPtrFactory
<MetricsService
> state_saver_factory_
;
499 DISALLOW_COPY_AND_ASSIGN(MetricsService
);
502 } // namespace metrics
504 #endif // COMPONENTS_METRICS_METRICS_SERVICE_H_