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/strings/string16.h"
26 #include "base/threading/thread_checker.h"
27 #include "base/time/time.h"
28 #include "components/metrics/metrics_log.h"
29 #include "components/metrics/metrics_log_manager.h"
30 #include "components/metrics/metrics_provider.h"
31 #include "components/metrics/metrics_service_observer.h"
32 #include "components/variations/active_field_trials.h"
34 class MetricsServiceAccessor
;
36 class PrefRegistrySimple
;
39 class DictionaryValue
;
40 class HistogramSamples
;
41 class MessageLoopProxy
;
45 namespace variations
{
55 class MetricsLogUploader
;
56 class MetricsReportingScheduler
;
57 class MetricsServiceClient
;
58 class MetricsStateManager
;
60 // A Field Trial and its selected group, which represent a particular
61 // Chrome configuration state. For example, the trial name could map to
62 // a preference name, and the group name could map to a preference value.
63 struct SyntheticTrialGroup
{
65 ~SyntheticTrialGroup();
67 variations::ActiveGroupId id
;
68 base::TimeTicks start_time
;
71 // Synthetic field trial users:
72 friend class ::MetricsServiceAccessor
;
73 friend class MetricsService
;
74 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest
, RegisterSyntheticTrial
);
76 // This constructor is private specifically so as to control which code is
77 // able to access it. New code that wishes to use it should be added as a
79 SyntheticTrialGroup(uint32 trial
, uint32 group
);
82 // See metrics_service.cc for a detailed description.
83 class MetricsService
: public base::HistogramFlattener
{
85 // The execution phase of the browser.
87 UNINITIALIZED_PHASE
= 0,
88 START_METRICS_RECORDING
= 100,
90 STARTUP_TIMEBOMB_ARM
= 300,
91 THREAD_WATCHER_START
= 400,
92 MAIN_MESSAGE_LOOP_RUN
= 500,
93 SHUTDOWN_TIMEBOMB_ARM
= 600,
94 SHUTDOWN_COMPLETE
= 700,
97 // Creates the MetricsService with the given |state_manager|, |client|, and
98 // |local_state|. Does not take ownership of the paramaters; instead stores
99 // a weak pointer to each. Caller should ensure that the parameters are valid
100 // for the lifetime of this class.
101 MetricsService(MetricsStateManager
* state_manager
,
102 MetricsServiceClient
* client
,
103 PrefService
* local_state
);
104 virtual ~MetricsService();
106 // Initializes metrics recording state. Updates various bookkeeping values in
107 // prefs and sets up the scheduler. This is a separate function rather than
108 // being done by the constructor so that field trials could be created before
110 void InitializeMetricsRecordingState();
112 // Starts the metrics system, turning on recording and uploading of metrics.
113 // Should be called when starting up with metrics enabled, or when metrics
117 // If metrics reporting is enabled, starts the metrics service. Returns
118 // whether the metrics service was started.
119 bool StartIfMetricsReportingEnabled();
121 // Starts the metrics system in a special test-only mode. Metrics won't ever
122 // be uploaded or persisted in this mode, but metrics will be recorded in
124 void StartRecordingForTests();
126 // Shuts down the metrics system. Should be called at shutdown, or if metrics
130 // Enable/disable transmission of accumulated logs and crash reports (dumps).
131 // Calling Start() automatically enables reporting, but sending is
132 // asyncronous so this can be called immediately after Start() to prevent
134 void EnableReporting();
135 void DisableReporting();
137 // Returns the client ID for this client, or the empty string if metrics
138 // recording is not currently running.
139 std::string
GetClientId();
141 // Returns the install date of the application, in seconds since the epoch.
142 int64
GetInstallDate();
144 // Returns the preferred entropy provider used to seed persistent activities
145 // based on whether or not metrics reporting will be permitted on this client.
147 // If metrics reporting is enabled, this method returns an entropy provider
148 // that has a high source of entropy, partially based on the client ID.
149 // Otherwise, it returns an entropy provider that is based on a low entropy
151 scoped_ptr
<const base::FieldTrial::EntropyProvider
> CreateEntropyProvider();
153 // At startup, prefs needs to be called with a list of all the pref names and
154 // types we'll be using.
155 static void RegisterPrefs(PrefRegistrySimple
* registry
);
157 // HistogramFlattener:
158 virtual void RecordDelta(const base::HistogramBase
& histogram
,
159 const base::HistogramSamples
& snapshot
) OVERRIDE
;
160 virtual void InconsistencyDetected(
161 base::HistogramBase::Inconsistency problem
) OVERRIDE
;
162 virtual void UniqueInconsistencyDetected(
163 base::HistogramBase::Inconsistency problem
) OVERRIDE
;
164 virtual void InconsistencyDetectedInLoggedCount(int amount
) OVERRIDE
;
166 // This should be called when the application is not idle, i.e. the user seems
167 // to be interacting with the application.
168 void OnApplicationNotIdle();
170 // Invoked when we get a WM_SESSIONEND. This places a value in prefs that is
171 // reset when RecordCompletedSessionEnd is invoked.
172 void RecordStartOfSessionEnd();
174 // This should be called when the application is shutting down. It records
175 // that session end was successful.
176 void RecordCompletedSessionEnd();
178 #if defined(OS_ANDROID) || defined(OS_IOS)
179 // Called when the application is going into background mode.
180 void OnAppEnterBackground();
182 // Called when the application is coming out of background mode.
183 void OnAppEnterForeground();
185 // Set the dirty flag, which will require a later call to LogCleanShutdown().
186 static void LogNeedForCleanShutdown(PrefService
* local_state
);
187 #endif // defined(OS_ANDROID) || defined(OS_IOS)
189 static void SetExecutionPhase(ExecutionPhase execution_phase
,
190 PrefService
* local_state
);
192 // Saves in the preferences if the crash report registration was successful.
193 // This count is eventually send via UMA logs.
194 void RecordBreakpadRegistration(bool success
);
196 // Saves in the preferences if the browser is running under a debugger.
197 // This count is eventually send via UMA logs.
198 void RecordBreakpadHasDebugger(bool has_debugger
);
200 bool recording_active() const;
201 bool reporting_active() const;
203 // Redundant test to ensure that we are notified of a clean exit.
204 // This value should be true when process has completed shutdown.
205 static bool UmaMetricsProperlyShutdown();
207 // Registers a field trial name and group to be used to annotate a UMA report
208 // with a particular Chrome configuration state. A UMA report will be
209 // annotated with this trial group if and only if all events in the report
210 // were created after the trial is registered. Only one group name may be
211 // registered at a time for a given trial_name. Only the last group name that
212 // is registered for a given trial name will be recorded. The values passed
213 // in must not correspond to any real field trial in the code.
214 // To use this method, SyntheticTrialGroup should friend your class.
215 void RegisterSyntheticFieldTrial(const SyntheticTrialGroup
& trial_group
);
217 // Register the specified |provider| to provide additional metrics into the
218 // UMA log. Should be called during MetricsService initialization only.
219 void RegisterMetricsProvider(scoped_ptr
<MetricsProvider
> provider
);
221 // Check if this install was cloned or imaged from another machine. If a
222 // clone is detected, reset the client id and low entropy source. This
223 // should not be called more than once.
224 void CheckForClonedInstall(
225 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
);
228 // Exposed for testing.
229 MetricsLogManager
* log_manager() { return &log_manager_
; }
232 // The MetricsService has a lifecycle that is stored as a state.
233 // See metrics_service.cc for description of this lifecycle.
235 INITIALIZED
, // Constructor was called.
236 INIT_TASK_SCHEDULED
, // Waiting for deferred init tasks to
238 INIT_TASK_DONE
, // Waiting for timer to send initial log.
239 SENDING_INITIAL_STABILITY_LOG
, // Initial stability log being sent.
240 SENDING_INITIAL_METRICS_LOG
, // Initial metrics log being sent.
241 SENDING_OLD_LOGS
, // Sending unsent logs from last session.
242 SENDING_CURRENT_LOGS
, // Sending ongoing logs as they accrue.
245 enum ShutdownCleanliness
{
246 CLEANLY_SHUTDOWN
= 0xdeadbeef,
247 NEED_TO_SHUTDOWN
= ~CLEANLY_SHUTDOWN
250 typedef std::vector
<SyntheticTrialGroup
> SyntheticTrialGroups
;
252 // Calls into the client to start metrics gathering.
253 void StartGatheringMetrics();
255 // Callback that moves the state to INIT_TASK_DONE. When this is called, the
256 // state should be INIT_TASK_SCHEDULED.
257 void FinishedGatheringInitialMetrics();
259 void OnUserAction(const std::string
& action
);
261 // Get the amount of uptime since this process started and since the last
262 // call to this function. Also updates the cumulative uptime metric (stored
263 // as a pref) for uninstall. Uptimes are measured using TimeTicks, which
264 // guarantees that it is monotonic and does not jump if the user changes
265 // his/her clock. The TimeTicks implementation also makes the clock not
266 // count time the computer is suspended.
267 void GetUptimes(PrefService
* pref
,
268 base::TimeDelta
* incremental_uptime
,
269 base::TimeDelta
* uptime
);
271 // Turns recording on or off.
272 // DisableRecording() also forces a persistent save of logging state (if
273 // anything has been recorded, or transmitted).
274 void EnableRecording();
275 void DisableRecording();
277 // If in_idle is true, sets idle_since_last_transmission to true.
278 // If in_idle is false and idle_since_last_transmission_ is true, sets
279 // idle_since_last_transmission to false and starts the timer (provided
280 // starting the timer is permitted).
281 void HandleIdleSinceLastTransmission(bool in_idle
);
283 // Set up client ID, session ID, etc.
284 void InitializeMetricsState();
286 // Registers/unregisters |observer| to receive MetricsLog notifications.
287 void AddObserver(MetricsServiceObserver
* observer
);
288 void RemoveObserver(MetricsServiceObserver
* observer
);
289 void NotifyOnDidCreateMetricsLog();
291 // Schedule the next save of LocalState information. This is called
292 // automatically by the task that performs each save to schedule the next one.
293 void ScheduleNextStateSave();
295 // Save the LocalState information immediately. This should not be called by
296 // anybody other than the scheduler to avoid doing too many writes. When you
297 // make a change, call ScheduleNextStateSave() instead.
298 void SaveLocalState();
300 // Opens a new log for recording user experience metrics.
303 // Closes out the current log after adding any last information.
304 void CloseCurrentLog();
306 // Pushes the text of the current and staged logs into persistent storage.
307 // Called when Chrome shuts down.
308 void PushPendingLogsToPersistentStorage();
310 // Ensures that scheduler is running, assuming the current settings are such
311 // that metrics should be reported. If not, this is a no-op.
312 void StartSchedulerIfNecessary();
314 // Starts the process of uploading metrics data.
315 void StartScheduledUpload();
317 // Called by the client when final log info collection is complete.
318 void OnFinalLogInfoCollectionDone();
320 // Either closes the current log or creates and closes the initial log
321 // (depending on |state_|), and stages it for upload.
324 // Prepares the initial stability log, which is only logged when the previous
325 // run of Chrome crashed. This log contains any stability metrics left over
326 // from that previous run, and only these stability metrics. It uses the
327 // system profile from the previous session.
328 void PrepareInitialStabilityLog();
330 // Prepares the initial metrics log, which includes startup histograms and
331 // profiler data, as well as incremental stability-related metrics.
332 void PrepareInitialMetricsLog();
334 // Uploads the currently staged log (which must be non-null).
335 void SendStagedLog();
337 // Called after transmission completes (either successfully or with failure).
338 void OnLogUploadComplete(int response_code
);
340 // Reads, increments and then sets the specified integer preference.
341 void IncrementPrefValue(const char* path
);
343 // Reads, increments and then sets the specified long preference that is
344 // stored as a string.
345 void IncrementLongPrefsValue(const char* path
);
347 // Records that the browser was shut down cleanly.
348 void LogCleanShutdown();
350 // Records state that should be periodically saved, like uptime and
351 // buffered plugin stability statistics.
352 void RecordCurrentState(PrefService
* pref
);
354 // Checks whether events should currently be logged.
355 bool ShouldLogEvents();
357 // Sets the value of the specified path in prefs and schedules a save.
358 void RecordBooleanPrefValue(const char* path
, bool value
);
360 // Returns a list of synthetic field trials that were active for the entire
361 // duration of the current log.
362 void GetCurrentSyntheticFieldTrials(
363 std::vector
<variations::ActiveGroupId
>* synthetic_trials
);
365 // Creates a new MetricsLog instance with the given |log_type|.
366 scoped_ptr
<MetricsLog
> CreateLog(MetricsLog::LogType log_type
);
368 // Record complete list of histograms into the current log.
369 // Called when we close a log.
370 void RecordCurrentHistograms();
372 // Record complete list of stability histograms into the current log,
373 // i.e., histograms with the |kUmaStabilityHistogramFlag| flag set.
374 void RecordCurrentStabilityHistograms();
376 // Manager for the various in-flight logs.
377 MetricsLogManager log_manager_
;
379 // |histogram_snapshot_manager_| prepares histogram deltas for transmission.
380 base::HistogramSnapshotManager histogram_snapshot_manager_
;
382 // Used to manage various metrics reporting state prefs, such as client id,
383 // low entropy source and whether metrics reporting is enabled. Weak pointer.
384 MetricsStateManager
* const state_manager_
;
386 // Used to interact with the embedder. Weak pointer; must outlive |this|
388 MetricsServiceClient
* const client_
;
390 // Registered metrics providers.
391 ScopedVector
<MetricsProvider
> metrics_providers_
;
393 PrefService
* local_state_
;
395 base::ActionCallback action_callback_
;
397 // Indicate whether recording and reporting are currently happening.
398 // These should not be set directly, but by calling SetRecording and
400 bool recording_active_
;
401 bool reporting_active_
;
403 // Indicate whether test mode is enabled, where the initial log should never
404 // be cut, and logs are neither persisted nor uploaded.
405 bool test_mode_active_
;
407 // The progression of states made by the browser are recorded in the following
411 // Whether the initial stability log has been recorded during startup.
412 bool has_initial_stability_log_
;
414 // The initial metrics log, used to record startup metrics (histograms and
415 // profiler data). Note that if a crash occurred in the previous session, an
416 // initial stability log may be sent before this.
417 scoped_ptr
<MetricsLog
> initial_metrics_log_
;
419 // Instance of the helper class for uploading logs.
420 scoped_ptr
<MetricsLogUploader
> log_uploader_
;
422 // Whether there is a current log upload in progress.
423 bool log_upload_in_progress_
;
425 // Whether the MetricsService object has received any notifications since
426 // the last time a transmission was sent.
427 bool idle_since_last_transmission_
;
429 // A number that identifies the how many times the app has been launched.
432 // Weak pointers factory used to post task on different threads. All weak
433 // pointers managed by this factory have the same lifetime as MetricsService.
434 base::WeakPtrFactory
<MetricsService
> self_ptr_factory_
;
436 // Weak pointers factory used for saving state. All weak pointers managed by
437 // this factory are invalidated in ScheduleNextStateSave.
438 base::WeakPtrFactory
<MetricsService
> state_saver_factory_
;
440 // The scheduler for determining when uploads should happen.
441 scoped_ptr
<MetricsReportingScheduler
> scheduler_
;
443 // Stores the time of the first call to |GetUptimes()|.
444 base::TimeTicks first_updated_time_
;
446 // Stores the time of the last call to |GetUptimes()|.
447 base::TimeTicks last_updated_time_
;
449 // Execution phase the browser is in.
450 static ExecutionPhase execution_phase_
;
452 // Reduntant marker to check that we completed our shutdown, and set the
453 // exited-cleanly bit in the prefs.
454 static ShutdownCleanliness clean_shutdown_status_
;
456 // Field trial groups that map to Chrome configuration states.
457 SyntheticTrialGroups synthetic_trial_groups_
;
459 ObserverList
<MetricsServiceObserver
> observers_
;
461 // Confirms single-threaded access to |observers_| in debug builds.
462 base::ThreadChecker thread_checker_
;
464 friend class ::MetricsServiceAccessor
;
466 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest
, IsPluginProcess
);
467 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest
, MetricsServiceObserver
);
468 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest
,
469 PermutedEntropyCacheClearedWhenLowEntropyReset
);
470 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest
, RegisterSyntheticTrial
);
472 DISALLOW_COPY_AND_ASSIGN(MetricsService
);
475 } // namespace metrics
477 #endif // COMPONENTS_METRICS_METRICS_SERVICE_H_