Give names to all utility processes.
[chromium-blink-merge.git] / components / metrics / metrics_service.h
blob4f1859905b3249f7a72b6599724f94e7bb586870
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 date at which the current metrics client ID was created as
155 // an int64 containing seconds since the epoch.
156 int64 GetMetricsReportingEnabledDate();
158 // Returns the preferred entropy provider used to seed persistent activities
159 // based on whether or not metrics reporting will be permitted on this client.
161 // If metrics reporting is enabled, this method returns an entropy provider
162 // that has a high source of entropy, partially based on the client ID.
163 // Otherwise, it returns an entropy provider that is based on a low entropy
164 // source.
165 scoped_ptr<const base::FieldTrial::EntropyProvider> CreateEntropyProvider();
167 // At startup, prefs needs to be called with a list of all the pref names and
168 // types we'll be using.
169 static void RegisterPrefs(PrefRegistrySimple* registry);
171 // HistogramFlattener:
172 void RecordDelta(const base::HistogramBase& histogram,
173 const base::HistogramSamples& snapshot) override;
174 void InconsistencyDetected(
175 base::HistogramBase::Inconsistency problem) override;
176 void UniqueInconsistencyDetected(
177 base::HistogramBase::Inconsistency problem) override;
178 void InconsistencyDetectedInLoggedCount(int amount) override;
180 // This should be called when the application is not idle, i.e. the user seems
181 // to be interacting with the application.
182 void OnApplicationNotIdle();
184 // Invoked when we get a WM_SESSIONEND. This places a value in prefs that is
185 // reset when RecordCompletedSessionEnd is invoked.
186 void RecordStartOfSessionEnd();
188 // This should be called when the application is shutting down. It records
189 // that session end was successful.
190 void RecordCompletedSessionEnd();
192 #if defined(OS_ANDROID) || defined(OS_IOS)
193 // Called when the application is going into background mode.
194 void OnAppEnterBackground();
196 // Called when the application is coming out of background mode.
197 void OnAppEnterForeground();
198 #else
199 // Set the dirty flag, which will require a later call to LogCleanShutdown().
200 void LogNeedForCleanShutdown();
201 #endif // defined(OS_ANDROID) || defined(OS_IOS)
203 static void SetExecutionPhase(ExecutionPhase execution_phase,
204 PrefService* local_state);
206 // Saves in the preferences if the crash report registration was successful.
207 // This count is eventually send via UMA logs.
208 void RecordBreakpadRegistration(bool success);
210 // Saves in the preferences if the browser is running under a debugger.
211 // This count is eventually send via UMA logs.
212 void RecordBreakpadHasDebugger(bool has_debugger);
214 bool recording_active() const;
215 bool reporting_active() const;
217 // Redundant test to ensure that we are notified of a clean exit.
218 // This value should be true when process has completed shutdown.
219 static bool UmaMetricsProperlyShutdown();
221 // Registers a field trial name and group to be used to annotate a UMA report
222 // with a particular Chrome configuration state. A UMA report will be
223 // annotated with this trial group if and only if all events in the report
224 // were created after the trial is registered. Only one group name may be
225 // registered at a time for a given trial_name. Only the last group name that
226 // is registered for a given trial name will be recorded. The values passed
227 // in must not correspond to any real field trial in the code.
228 // To use this method, SyntheticTrialGroup should friend your class.
229 void RegisterSyntheticFieldTrial(const SyntheticTrialGroup& trial_group);
231 // Adds an observer to be notified when the synthetic trials list changes.
232 void AddSyntheticTrialObserver(SyntheticTrialObserver* observer);
234 // Removes an existing observer of synthetic trials list changes.
235 void RemoveSyntheticTrialObserver(SyntheticTrialObserver* observer);
237 // Register the specified |provider| to provide additional metrics into the
238 // UMA log. Should be called during MetricsService initialization only.
239 void RegisterMetricsProvider(scoped_ptr<MetricsProvider> provider);
241 // Check if this install was cloned or imaged from another machine. If a
242 // clone is detected, reset the client id and low entropy source. This
243 // should not be called more than once.
244 void CheckForClonedInstall(
245 scoped_refptr<base::SingleThreadTaskRunner> task_runner);
247 // Clears the stability metrics that are saved in local state.
248 void ClearSavedStabilityMetrics();
250 // Pushes a log that has been generated by an external component.
251 void PushExternalLog(const std::string& log);
253 protected:
254 // Exposed for testing.
255 MetricsLogManager* log_manager() { return &log_manager_; }
257 private:
258 // The MetricsService has a lifecycle that is stored as a state.
259 // See metrics_service.cc for description of this lifecycle.
260 enum State {
261 INITIALIZED, // Constructor was called.
262 INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to finish.
263 INIT_TASK_DONE, // Waiting for timer to send initial log.
264 SENDING_LOGS, // Sending logs an creating new ones when we run out.
267 enum ShutdownCleanliness {
268 CLEANLY_SHUTDOWN = 0xdeadbeef,
269 NEED_TO_SHUTDOWN = ~CLEANLY_SHUTDOWN
272 friend class ::MetricsServiceAccessor;
274 typedef std::vector<SyntheticTrialGroup> SyntheticTrialGroups;
276 // Calls into the client to start metrics gathering.
277 void StartGatheringMetrics();
279 // Callback that moves the state to INIT_TASK_DONE. When this is called, the
280 // state should be INIT_TASK_SCHEDULED.
281 void FinishedGatheringInitialMetrics();
283 void OnUserAction(const std::string& action);
285 // Get the amount of uptime since this process started and since the last
286 // call to this function. Also updates the cumulative uptime metric (stored
287 // as a pref) for uninstall. Uptimes are measured using TimeTicks, which
288 // guarantees that it is monotonic and does not jump if the user changes
289 // his/her clock. The TimeTicks implementation also makes the clock not
290 // count time the computer is suspended.
291 void GetUptimes(PrefService* pref,
292 base::TimeDelta* incremental_uptime,
293 base::TimeDelta* uptime);
295 // Turns recording on or off.
296 // DisableRecording() also forces a persistent save of logging state (if
297 // anything has been recorded, or transmitted).
298 void EnableRecording();
299 void DisableRecording();
301 // If in_idle is true, sets idle_since_last_transmission to true.
302 // If in_idle is false and idle_since_last_transmission_ is true, sets
303 // idle_since_last_transmission to false and starts the timer (provided
304 // starting the timer is permitted).
305 void HandleIdleSinceLastTransmission(bool in_idle);
307 // Set up client ID, session ID, etc.
308 void InitializeMetricsState();
310 // Notifies providers when a new metrics log is created.
311 void NotifyOnDidCreateMetricsLog();
313 // Schedule the next save of LocalState information. This is called
314 // automatically by the task that performs each save to schedule the next one.
315 void ScheduleNextStateSave();
317 // Save the LocalState information immediately. This should not be called by
318 // anybody other than the scheduler to avoid doing too many writes. When you
319 // make a change, call ScheduleNextStateSave() instead.
320 void SaveLocalState();
322 // Opens a new log for recording user experience metrics.
323 void OpenNewLog();
325 // Closes out the current log after adding any last information.
326 void CloseCurrentLog();
328 // Pushes the text of the current and staged logs into persistent storage.
329 // Called when Chrome shuts down.
330 void PushPendingLogsToPersistentStorage();
332 // Ensures that scheduler is running, assuming the current settings are such
333 // that metrics should be reported. If not, this is a no-op.
334 void StartSchedulerIfNecessary();
336 // Starts the process of uploading metrics data.
337 void StartScheduledUpload();
339 // Called by the client via a callback when final log info collection is
340 // complete.
341 void OnFinalLogInfoCollectionDone();
343 // If recording is enabled, begins uploading the next completed log from
344 // the log manager, staging it if necessary.
345 void SendNextLog();
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. Returns true if a log was
355 // created.
356 bool PrepareInitialStabilityLog();
358 // Prepares the initial metrics log, which includes startup histograms and
359 // profiler data, as well as incremental stability-related metrics.
360 void PrepareInitialMetricsLog();
362 // Uploads the currently staged log (which must be non-null).
363 void SendStagedLog();
365 // Called after transmission completes (either successfully or with failure).
366 void OnLogUploadComplete(int response_code);
368 // Reads, increments and then sets the specified integer preference.
369 void IncrementPrefValue(const char* path);
371 // Reads, increments and then sets the specified long preference that is
372 // stored as a string.
373 void IncrementLongPrefsValue(const char* path);
375 // Records that the browser was shut down cleanly.
376 void LogCleanShutdown();
378 // Records state that should be periodically saved, like uptime and
379 // buffered plugin stability statistics.
380 void RecordCurrentState(PrefService* pref);
382 // Checks whether events should currently be logged.
383 bool ShouldLogEvents();
385 // Sets the value of the specified path in prefs and schedules a save.
386 void RecordBooleanPrefValue(const char* path, bool value);
388 // Notifies observers on a synthetic trial list change.
389 void NotifySyntheticTrialObservers();
391 // Returns a list of synthetic field trials that were active for the entire
392 // duration of the current log.
393 void GetCurrentSyntheticFieldTrials(
394 std::vector<variations::ActiveGroupId>* synthetic_trials);
396 // Creates a new MetricsLog instance with the given |log_type|.
397 scoped_ptr<MetricsLog> CreateLog(MetricsLog::LogType log_type);
399 // Records the current environment (system profile) in |log|.
400 void RecordCurrentEnvironment(MetricsLog* log);
402 // Record complete list of histograms into the current log.
403 // Called when we close a log.
404 void RecordCurrentHistograms();
406 // Record complete list of stability histograms into the current log,
407 // i.e., histograms with the |kUmaStabilityHistogramFlag| flag set.
408 void RecordCurrentStabilityHistograms();
410 // Manager for the various in-flight logs.
411 MetricsLogManager log_manager_;
413 // |histogram_snapshot_manager_| prepares histogram deltas for transmission.
414 base::HistogramSnapshotManager histogram_snapshot_manager_;
416 // Used to manage various metrics reporting state prefs, such as client id,
417 // low entropy source and whether metrics reporting is enabled. Weak pointer.
418 MetricsStateManager* const state_manager_;
420 // Used to interact with the embedder. Weak pointer; must outlive |this|
421 // instance.
422 MetricsServiceClient* const client_;
424 // Registered metrics providers.
425 ScopedVector<MetricsProvider> metrics_providers_;
427 PrefService* local_state_;
429 CleanExitBeacon clean_exit_beacon_;
431 base::ActionCallback action_callback_;
433 // Indicate whether recording and reporting are currently happening.
434 // These should not be set directly, but by calling SetRecording and
435 // SetReporting.
436 bool recording_active_;
437 bool reporting_active_;
439 // Indicate whether test mode is enabled, where the initial log should never
440 // be cut, and logs are neither persisted nor uploaded.
441 bool test_mode_active_;
443 // The progression of states made by the browser are recorded in the following
444 // state.
445 State state_;
447 // The initial metrics log, used to record startup metrics (histograms and
448 // profiler data). Note that if a crash occurred in the previous session, an
449 // initial stability log may be sent before this.
450 scoped_ptr<MetricsLog> initial_metrics_log_;
452 // Instance of the helper class for uploading logs.
453 scoped_ptr<MetricsLogUploader> log_uploader_;
455 // Whether there is a current log upload in progress.
456 bool log_upload_in_progress_;
458 // Whether the MetricsService object has received any notifications since
459 // the last time a transmission was sent.
460 bool idle_since_last_transmission_;
462 // A number that identifies the how many times the app has been launched.
463 int session_id_;
465 // The scheduler for determining when uploads should happen.
466 scoped_ptr<MetricsReportingScheduler> scheduler_;
468 // Stores the time of the first call to |GetUptimes()|.
469 base::TimeTicks first_updated_time_;
471 // Stores the time of the last call to |GetUptimes()|.
472 base::TimeTicks last_updated_time_;
474 // Field trial groups that map to Chrome configuration states.
475 SyntheticTrialGroups synthetic_trial_groups_;
477 // List of observers of |synthetic_trial_groups_| changes.
478 ObserverList<SyntheticTrialObserver> synthetic_trial_observer_list_;
480 // Execution phase the browser is in.
481 static ExecutionPhase execution_phase_;
483 // Reduntant marker to check that we completed our shutdown, and set the
484 // exited-cleanly bit in the prefs.
485 static ShutdownCleanliness clean_shutdown_status_;
487 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, IsPluginProcess);
488 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest,
489 PermutedEntropyCacheClearedWhenLowEntropyReset);
490 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, RegisterSyntheticTrial);
492 // Weak pointers factory used to post task on different threads. All weak
493 // pointers managed by this factory have the same lifetime as MetricsService.
494 base::WeakPtrFactory<MetricsService> self_ptr_factory_;
496 // Weak pointers factory used for saving state. All weak pointers managed by
497 // this factory are invalidated in ScheduleNextStateSave.
498 base::WeakPtrFactory<MetricsService> state_saver_factory_;
500 DISALLOW_COPY_AND_ASSIGN(MetricsService);
503 } // namespace metrics
505 #endif // COMPONENTS_METRICS_METRICS_SERVICE_H_