ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / components / metrics / metrics_service.h
blobc7bf8e57418b58207dd30359a8adb222a9843931
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_
11 #include <map>
12 #include <string>
13 #include <vector>
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;
34 class PrefService;
35 class PrefRegistrySimple;
37 namespace base {
38 class DictionaryValue;
39 class HistogramSamples;
40 class MessageLoopProxy;
41 class PrefService;
44 namespace variations {
45 struct ActiveGroupId;
48 namespace net {
49 class URLFetcher;
52 namespace metrics {
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 {
63 public:
64 ~SyntheticTrialGroup();
66 variations::ActiveGroupId id;
67 base::TimeTicks start_time;
69 private:
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
77 // friend class.
78 SyntheticTrialGroup(uint32 trial, uint32 group);
81 // Interface class to observe changes to synthetic trials in MetricsService.
82 class SyntheticTrialObserver {
83 public:
84 // Called when the list of synthetic field trial groups has changed.
85 virtual void OnSyntheticTrialsChanged(
86 const std::vector<SyntheticTrialGroup>& groups) = 0;
88 protected:
89 virtual ~SyntheticTrialObserver() {}
92 // See metrics_service.cc for a detailed description.
93 class MetricsService : public base::HistogramFlattener {
94 public:
95 // The execution phase of the browser.
96 enum ExecutionPhase {
97 UNINITIALIZED_PHASE = 0,
98 START_METRICS_RECORDING = 100,
99 CREATE_PROFILE = 200,
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
119 // this is run.
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
124 // are turned on.
125 void Start();
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
133 // memory.
134 void StartRecordingForTests();
136 // Shuts down the metrics system. Should be called at shutdown, or if metrics
137 // are turned off.
138 void Stop();
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
143 // any uploading.
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
160 // source.
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();
194 #else
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();
246 // Sets the connection type callback used to pass to the scheduler.
247 void SetConnectionTypeCallback(
248 base::Callback<void(bool*)> is_cellular_callback);
250 protected:
251 // Exposed for testing.
252 MetricsLogManager* log_manager() { return &log_manager_; }
254 private:
255 // The MetricsService has a lifecycle that is stored as a state.
256 // See metrics_service.cc for description of this lifecycle.
257 enum State {
258 INITIALIZED, // Constructor was called.
259 INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to
260 // complete.
261 INIT_TASK_DONE, // Waiting for timer to send initial log.
262 SENDING_INITIAL_STABILITY_LOG, // Initial stability log being sent.
263 SENDING_INITIAL_METRICS_LOG, // Initial metrics log being sent.
264 SENDING_OLD_LOGS, // Sending unsent logs from last session.
265 SENDING_CURRENT_LOGS, // Sending ongoing logs as they accrue.
268 enum ShutdownCleanliness {
269 CLEANLY_SHUTDOWN = 0xdeadbeef,
270 NEED_TO_SHUTDOWN = ~CLEANLY_SHUTDOWN
273 friend class ::MetricsServiceAccessor;
275 typedef std::vector<SyntheticTrialGroup> SyntheticTrialGroups;
277 // Calls into the client to start metrics gathering.
278 void StartGatheringMetrics();
280 // Callback that moves the state to INIT_TASK_DONE. When this is called, the
281 // state should be INIT_TASK_SCHEDULED.
282 void FinishedGatheringInitialMetrics();
284 void OnUserAction(const std::string& action);
286 // Get the amount of uptime since this process started and since the last
287 // call to this function. Also updates the cumulative uptime metric (stored
288 // as a pref) for uninstall. Uptimes are measured using TimeTicks, which
289 // guarantees that it is monotonic and does not jump if the user changes
290 // his/her clock. The TimeTicks implementation also makes the clock not
291 // count time the computer is suspended.
292 void GetUptimes(PrefService* pref,
293 base::TimeDelta* incremental_uptime,
294 base::TimeDelta* uptime);
296 // Turns recording on or off.
297 // DisableRecording() also forces a persistent save of logging state (if
298 // anything has been recorded, or transmitted).
299 void EnableRecording();
300 void DisableRecording();
302 // If in_idle is true, sets idle_since_last_transmission to true.
303 // If in_idle is false and idle_since_last_transmission_ is true, sets
304 // idle_since_last_transmission to false and starts the timer (provided
305 // starting the timer is permitted).
306 void HandleIdleSinceLastTransmission(bool in_idle);
308 // Set up client ID, session ID, etc.
309 void InitializeMetricsState();
311 // Notifies providers when a new metrics log is created.
312 void NotifyOnDidCreateMetricsLog();
314 // Schedule the next save of LocalState information. This is called
315 // automatically by the task that performs each save to schedule the next one.
316 void ScheduleNextStateSave();
318 // Save the LocalState information immediately. This should not be called by
319 // anybody other than the scheduler to avoid doing too many writes. When you
320 // make a change, call ScheduleNextStateSave() instead.
321 void SaveLocalState();
323 // Opens a new log for recording user experience metrics.
324 void OpenNewLog();
326 // Closes out the current log after adding any last information.
327 void CloseCurrentLog();
329 // Pushes the text of the current and staged logs into persistent storage.
330 // Called when Chrome shuts down.
331 void PushPendingLogsToPersistentStorage();
333 // Ensures that scheduler is running, assuming the current settings are such
334 // that metrics should be reported. If not, this is a no-op.
335 void StartSchedulerIfNecessary();
337 // Starts the process of uploading metrics data.
338 void StartScheduledUpload();
340 // Called by the client when final log info collection is complete.
341 void OnFinalLogInfoCollectionDone();
343 // Either closes the current log or creates and closes the initial log
344 // (depending on |state_|), and stages it for upload.
345 void StageNewLog();
347 // Returns true if any of the registered metrics providers have stability
348 // metrics to report.
349 bool ProvidersHaveStabilityMetrics();
351 // Prepares the initial stability log, which is only logged when the previous
352 // run of Chrome crashed. This log contains any stability metrics left over
353 // from that previous run, and only these stability metrics. It uses the
354 // system profile from the previous session.
355 void 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|
420 // instance.
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
434 // SetReporting.
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
443 // state.
444 State state_;
446 // Whether the initial stability log has been recorded during startup.
447 bool has_initial_stability_log_;
449 // The initial metrics log, used to record startup metrics (histograms and
450 // profiler data). Note that if a crash occurred in the previous session, an
451 // initial stability log may be sent before this.
452 scoped_ptr<MetricsLog> initial_metrics_log_;
454 // Instance of the helper class for uploading logs.
455 scoped_ptr<MetricsLogUploader> log_uploader_;
457 // Whether there is a current log upload in progress.
458 bool log_upload_in_progress_;
460 // Whether the MetricsService object has received any notifications since
461 // the last time a transmission was sent.
462 bool idle_since_last_transmission_;
464 // A number that identifies the how many times the app has been launched.
465 int session_id_;
467 // The scheduler for determining when uploads should happen.
468 scoped_ptr<MetricsReportingScheduler> scheduler_;
470 // Stores the time of the first call to |GetUptimes()|.
471 base::TimeTicks first_updated_time_;
473 // Stores the time of the last call to |GetUptimes()|.
474 base::TimeTicks last_updated_time_;
476 // Field trial groups that map to Chrome configuration states.
477 SyntheticTrialGroups synthetic_trial_groups_;
479 // List of observers of |synthetic_trial_groups_| changes.
480 ObserverList<SyntheticTrialObserver> synthetic_trial_observer_list_;
482 // Execution phase the browser is in.
483 static ExecutionPhase execution_phase_;
485 // Reduntant marker to check that we completed our shutdown, and set the
486 // exited-cleanly bit in the prefs.
487 static ShutdownCleanliness clean_shutdown_status_;
489 // Callback function used to get current network connection type.
490 base::Callback<void(bool*)> is_cellular_callback_;
492 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, IsPluginProcess);
493 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest,
494 PermutedEntropyCacheClearedWhenLowEntropyReset);
495 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, RegisterSyntheticTrial);
497 // Weak pointers factory used to post task on different threads. All weak
498 // pointers managed by this factory have the same lifetime as MetricsService.
499 base::WeakPtrFactory<MetricsService> self_ptr_factory_;
501 // Weak pointers factory used for saving state. All weak pointers managed by
502 // this factory are invalidated in ScheduleNextStateSave.
503 base::WeakPtrFactory<MetricsService> state_saver_factory_;
505 DISALLOW_COPY_AND_ASSIGN(MetricsService);
508 } // namespace metrics
510 #endif // COMPONENTS_METRICS_METRICS_SERVICE_H_