Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(157)

Side by Side Diff: components/variations/synthetic_trial_registry.h

Issue 2975273003: Extract SyntheticTrialRegistry from MetricsService (Closed)
Patch Set: asdf Created 3 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « components/variations/BUILD.gn ('k') | components/variations/synthetic_trial_registry.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 1 // Copyright 2017 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 // This file defines a service that collects information about the user 5 #ifndef COMPONENTS_VARIATIONS_SYNTHETIC_TRIAL_REGISTRY_H_
6 // experience in order to help improve future versions of the app. 6 #define COMPONENTS_VARIATIONS_SYNTHETIC_TRIAL_REGISTRY_H_
7 7
8 #ifndef COMPONENTS_METRICS_METRICS_SERVICE_H_
9 #define COMPONENTS_METRICS_METRICS_SERVICE_H_
10
11 #include <stdint.h>
12
13 #include <map>
14 #include <memory>
15 #include <string>
16 #include <vector> 8 #include <vector>
17 9
18 #include "base/gtest_prod_util.h"
19 #include "base/macros.h"
20 #include "base/memory/weak_ptr.h"
21 #include "base/metrics/field_trial.h"
22 #include "base/metrics/histogram_flattener.h"
23 #include "base/metrics/histogram_snapshot_manager.h"
24 #include "base/metrics/user_metrics.h"
25 #include "base/observer_list.h" 10 #include "base/observer_list.h"
26 #include "base/threading/thread_checker.h"
27 #include "base/time/time.h"
28 #include "build/build_config.h"
29 #include "components/metrics/clean_exit_beacon.h"
30 #include "components/metrics/execution_phase.h"
31 #include "components/metrics/metrics_log.h"
32 #include "components/metrics/metrics_log_manager.h"
33 #include "components/metrics/metrics_log_store.h"
34 #include "components/metrics/metrics_provider.h"
35 #include "components/metrics/metrics_reporting_service.h"
36 #include "components/metrics/net/network_metrics_provider.h"
37 #include "components/variations/synthetic_trials.h" 11 #include "components/variations/synthetic_trials.h"
38 12
39 class PrefService; 13 namespace variations {
40 class PrefRegistrySimple;
41 14
42 namespace base { 15 struct ActiveGroupId;
43 class HistogramSamples;
44 class PrefService;
45 }
46 16
47 namespace variations { 17 class SyntheticTrialRegistry {
48 struct ActiveGroupId;
49 }
50
51 namespace metrics {
52
53 class MetricsRotationScheduler;
54 class MetricsServiceAccessor;
55 class MetricsServiceClient;
56 class MetricsStateManager;
57
58 // See metrics_service.cc for a detailed description.
59 class MetricsService : public base::HistogramFlattener {
60 public: 18 public:
61 // Creates the MetricsService with the given |state_manager|, |client|, and 19 SyntheticTrialRegistry();
62 // |local_state|. Does not take ownership of the paramaters; instead stores 20 ~SyntheticTrialRegistry();
63 // a weak pointer to each. Caller should ensure that the parameters are valid
64 // for the lifetime of this class.
65 MetricsService(MetricsStateManager* state_manager,
66 MetricsServiceClient* client,
67 PrefService* local_state);
68 ~MetricsService() override;
69
70 // Initializes metrics recording state. Updates various bookkeeping values in
71 // prefs and sets up the scheduler. This is a separate function rather than
72 // being done by the constructor so that field trials could be created before
73 // this is run.
74 void InitializeMetricsRecordingState();
75
76 // Starts the metrics system, turning on recording and uploading of metrics.
77 // Should be called when starting up with metrics enabled, or when metrics
78 // are turned on.
79 void Start();
80
81 // Starts the metrics system in a special test-only mode. Metrics won't ever
82 // be uploaded or persisted in this mode, but metrics will be recorded in
83 // memory.
84 void StartRecordingForTests();
85
86 // Shuts down the metrics system. Should be called at shutdown, or if metrics
87 // are turned off.
88 void Stop();
89
90 // Enable/disable transmission of accumulated logs and crash reports (dumps).
91 // Calling Start() automatically enables reporting, but sending is
92 // asyncronous so this can be called immediately after Start() to prevent
93 // any uploading.
94 void EnableReporting();
95 void DisableReporting();
96
97 // Returns the client ID for this client, or the empty string if metrics
98 // recording is not currently running.
99 std::string GetClientId();
100
101 // Returns the install date of the application, in seconds since the epoch.
102 int64_t GetInstallDate();
103
104 // Returns the date at which the current metrics client ID was created as
105 // an int64_t containing seconds since the epoch.
106 int64_t GetMetricsReportingEnabledDate();
107
108 // Returns true if the last session exited cleanly.
109 bool WasLastShutdownClean() const;
110
111 // Registers local state prefs used by this class.
112 static void RegisterPrefs(PrefRegistrySimple* registry);
113
114 // HistogramFlattener:
115 void RecordDelta(const base::HistogramBase& histogram,
116 const base::HistogramSamples& snapshot) override;
117 void InconsistencyDetected(
118 base::HistogramBase::Inconsistency problem) override;
119 void UniqueInconsistencyDetected(
120 base::HistogramBase::Inconsistency problem) override;
121 void InconsistencyDetectedInLoggedCount(int amount) override;
122
123 // This should be called when the application is not idle, i.e. the user seems
124 // to be interacting with the application.
125 void OnApplicationNotIdle();
126
127 // Invoked when we get a WM_SESSIONEND. This places a value in prefs that is
128 // reset when RecordCompletedSessionEnd is invoked.
129 void RecordStartOfSessionEnd();
130
131 // This should be called when the application is shutting down. It records
132 // that session end was successful.
133 void RecordCompletedSessionEnd();
134
135 #if defined(OS_ANDROID) || defined(OS_IOS)
136 // Called when the application is going into background mode.
137 void OnAppEnterBackground();
138
139 // Called when the application is coming out of background mode.
140 void OnAppEnterForeground();
141 #else
142 // Set the dirty flag, which will require a later call to LogCleanShutdown().
143 void LogNeedForCleanShutdown();
144 #endif // defined(OS_ANDROID) || defined(OS_IOS)
145
146 static void SetExecutionPhase(ExecutionPhase execution_phase,
147 PrefService* local_state);
148
149 // Saves in the preferences if the crash report registration was successful.
150 // This count is eventually send via UMA logs.
151 void RecordBreakpadRegistration(bool success);
152
153 // Saves in the preferences if the browser is running under a debugger.
154 // This count is eventually send via UMA logs.
155 void RecordBreakpadHasDebugger(bool has_debugger);
156
157 bool recording_active() const;
158 bool reporting_active() const;
159 bool has_unsent_logs() const;
160
161 // Redundant test to ensure that we are notified of a clean exit.
162 // This value should be true when process has completed shutdown.
163 static bool UmaMetricsProperlyShutdown();
164 21
165 // Public accessor that returns the list of synthetic field trials. It must 22 // Public accessor that returns the list of synthetic field trials. It must
166 // only be used for testing. 23 // only be used for testing.
167 void GetCurrentSyntheticFieldTrialsForTesting( 24 void GetCurrentSyntheticFieldTrialsForTesting(
168 std::vector<variations::ActiveGroupId>* synthetic_trials); 25 std::vector<ActiveGroupId>* synthetic_trials);
169 26
170 // Adds an observer to be notified when the synthetic trials list changes. 27 // Adds an observer to be notified when the synthetic trials list changes.
171 void AddSyntheticTrialObserver(variations::SyntheticTrialObserver* observer); 28 void AddSyntheticTrialObserver(SyntheticTrialObserver* observer);
172 29
173 // Removes an existing observer of synthetic trials list changes. 30 // Removes an existing observer of synthetic trials list changes.
174 void RemoveSyntheticTrialObserver( 31 void RemoveSyntheticTrialObserver(SyntheticTrialObserver* observer);
175 variations::SyntheticTrialObserver* observer);
176
177 // Register the specified |provider| to provide additional metrics into the
178 // UMA log. Should be called during MetricsService initialization only.
179 void RegisterMetricsProvider(std::unique_ptr<MetricsProvider> provider);
180
181 // Check if this install was cloned or imaged from another machine. If a
182 // clone is detected, reset the client id and low entropy source. This
183 // should not be called more than once.
184 void CheckForClonedInstall();
185
186 // Clears the stability metrics that are saved in local state.
187 void ClearSavedStabilityMetrics();
188
189 // Pushes a log that has been generated by an external component.
190 void PushExternalLog(const std::string& log);
191
192 // Updates data usage tracking prefs with the specified values.
193 void UpdateMetricsUsagePrefs(const std::string& service_name,
194 int message_size,
195 bool is_cellular);
196
197 protected:
198 // Exposed for testing.
199 MetricsLogManager* log_manager() { return &log_manager_; }
200 MetricsLogStore* log_store() {
201 return reporting_service_.metrics_log_store();
202 }
203
204 private:
205 friend class MetricsServiceAccessor;
206
207 // The MetricsService has a lifecycle that is stored as a state.
208 // See metrics_service.cc for description of this lifecycle.
209 enum State {
210 INITIALIZED, // Constructor was called.
211 INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to finish.
212 INIT_TASK_DONE, // Waiting for timer to send initial log.
213 SENDING_LOGS, // Sending logs an creating new ones when we run out.
214 };
215
216 enum ShutdownCleanliness {
217 CLEANLY_SHUTDOWN = 0xdeadbeef,
218 NEED_TO_SHUTDOWN = ~CLEANLY_SHUTDOWN
219 };
220
221 // The current state of recording for the MetricsService. The state is UNSET
222 // until set to something else, at which point it remains INACTIVE or ACTIVE
223 // for the lifetime of the object.
224 enum RecordingState {
225 INACTIVE,
226 ACTIVE,
227 UNSET
228 };
229
230 typedef std::vector<variations::SyntheticTrialGroup> SyntheticTrialGroups;
231 32
232 // Registers a field trial name and group to be used to annotate a UMA report 33 // Registers a field trial name and group to be used to annotate a UMA report
233 // with a particular Chrome configuration state. A UMA report will be 34 // with a particular Chrome configuration state. A UMA report will be
234 // annotated with this trial group if and only if all events in the report 35 // annotated with this trial group if and only if all events in the report
235 // were created after the trial is registered. Only one group name may be 36 // were created after the trial is registered. Only one group name may be
236 // registered at a time for a given trial_name. Only the last group name that 37 // registered at a time for a given trial_name. Only the last group name that
237 // is registered for a given trial name will be recorded. The values passed 38 // is registered for a given trial name will be recorded. The values passed
238 // in must not correspond to any real field trial in the code. 39 // in must not correspond to any real field trial in the code.
239 // Note: Should not be used to replace trials that were registered with 40 // Note: Should not be used to replace trials that were registered with
240 // RegisterMultiGroupSyntheticFieldTrial(). 41 // RegisterMultiGroupSyntheticFieldTrial().
241 void RegisterSyntheticFieldTrial( 42 void RegisterSyntheticFieldTrial(const SyntheticTrialGroup& trial_group);
242 const variations::SyntheticTrialGroup& trial_group);
243 43
244 // Similar to RegisterSyntheticFieldTrial(), but registers a synthetic trial 44 // Similar to RegisterSyntheticFieldTrial(), but registers a synthetic trial
245 // that has multiple active groups for a given trial name hash. Any previous 45 // that has multiple active groups for a given trial name hash. Any previous
246 // groups registered for |trial_name_hash| will be replaced. 46 // groups registered for |trial_name_hash| will be replaced.
247 void RegisterSyntheticMultiGroupFieldTrial( 47 void RegisterSyntheticMultiGroupFieldTrial(
248 uint32_t trial_name_hash, 48 uint32_t trial_name_hash,
249 const std::vector<uint32_t>& group_name_hashes); 49 const std::vector<uint32_t>& group_name_hashes);
250 50
251 // Calls into the client to initialize some system profile metrics.
252 void StartInitTask();
253
254 // Callback that moves the state to INIT_TASK_DONE. When this is called, the
255 // state should be INIT_TASK_SCHEDULED.
256 void FinishedInitTask();
257
258 void OnUserAction(const std::string& action);
259
260 // Get the amount of uptime since this process started and since the last
261 // call to this function. Also updates the cumulative uptime metric (stored
262 // as a pref) for uninstall. Uptimes are measured using TimeTicks, which
263 // guarantees that it is monotonic and does not jump if the user changes
264 // their clock. The TimeTicks implementation also makes the clock not
265 // count time the computer is suspended.
266 void GetUptimes(PrefService* pref,
267 base::TimeDelta* incremental_uptime,
268 base::TimeDelta* uptime);
269
270 // Turns recording on or off.
271 // DisableRecording() also forces a persistent save of logging state (if
272 // anything has been recorded, or transmitted).
273 void EnableRecording();
274 void DisableRecording();
275
276 // If in_idle is true, sets idle_since_last_transmission to true.
277 // If in_idle is false and idle_since_last_transmission_ is true, sets
278 // idle_since_last_transmission to false and starts the timer (provided
279 // starting the timer is permitted).
280 void HandleIdleSinceLastTransmission(bool in_idle);
281
282 // Set up client ID, session ID, etc.
283 void InitializeMetricsState();
284
285 // Notifies providers when a new metrics log is created.
286 void NotifyOnDidCreateMetricsLog();
287
288 // Opens a new log for recording user experience metrics.
289 void OpenNewLog();
290
291 // Closes out the current log after adding any last information.
292 void CloseCurrentLog();
293
294 // Pushes the text of the current and staged logs into persistent storage.
295 // Called when Chrome shuts down.
296 void PushPendingLogsToPersistentStorage();
297
298 // Ensures that scheduler is running, assuming the current settings are such
299 // that metrics should be reported. If not, this is a no-op.
300 void StartSchedulerIfNecessary();
301
302 // Starts the process of uploading metrics data.
303 void StartScheduledUpload();
304
305 // Called by the client via a callback when final log info collection is
306 // complete.
307 void OnFinalLogInfoCollectionDone();
308
309 // Returns true if any of the registered metrics providers have critical
310 // stability metrics to report in an initial stability log.
311 bool ProvidersHaveInitialStabilityMetrics();
312
313 // Prepares the initial stability log, which is only logged when the previous
314 // run of Chrome crashed. This log contains any stability metrics left over
315 // from that previous run, and only these stability metrics. It uses the
316 // system profile from the previous session. |prefs_previous_version| is used
317 // to validate the version number recovered from the system profile. Returns
318 // true if a log was created.
319 bool PrepareInitialStabilityLog(const std::string& prefs_previous_version);
320
321 // Prepares the initial metrics log, which includes startup histograms and
322 // profiler data, as well as incremental stability-related metrics.
323 void PrepareInitialMetricsLog();
324
325 // Reads, increments and then sets the specified long preference that is
326 // stored as a string.
327 void IncrementLongPrefsValue(const char* path);
328
329 // Records that the browser was shut down cleanly.
330 void LogCleanShutdown(bool end_completed);
331
332 // Notifies observers on a synthetic trial list change.
333 void NotifySyntheticTrialObservers();
334
335 // Returns a list of synthetic field trials that are older than |time|. 51 // Returns a list of synthetic field trials that are older than |time|.
336 void GetSyntheticFieldTrialsOlderThan( 52 void GetSyntheticFieldTrialsOlderThan(
337 base::TimeTicks time, 53 base::TimeTicks time,
338 std::vector<variations::ActiveGroupId>* synthetic_trials); 54 std::vector<ActiveGroupId>* synthetic_trials);
339 55
340 // Creates a new MetricsLog instance with the given |log_type|. 56 private:
341 std::unique_ptr<MetricsLog> CreateLog(MetricsLog::LogType log_type); 57 // Notifies observers on a synthetic trial list change.
342 58 void NotifySyntheticTrialObservers();
343 // Records the current environment (system profile) in |log|.
344 void RecordCurrentEnvironment(MetricsLog* log);
345
346 // Record complete list of histograms into the current log.
347 // Called when we close a log.
348 void RecordCurrentHistograms();
349
350 // Record complete list of stability histograms into the current log,
351 // i.e., histograms with the |kUmaStabilityHistogramFlag| flag set.
352 void RecordCurrentStabilityHistograms();
353
354 // Record a single independent profile and assocatied histogram from
355 // metrics providers. If this returns true, one was found and there may
356 // be more.
357 bool PrepareProviderMetricsLog();
358
359 // Records one independent histogram log and then reschedules itself to
360 // check for others. The interval is so as to not adversely impact the UI.
361 void PrepareProviderMetricsTask();
362
363 // Sub-service for uploading logs.
364 MetricsReportingService reporting_service_;
365
366 // Manager for the various in-flight logs.
367 MetricsLogManager log_manager_;
368
369 // |histogram_snapshot_manager_| prepares histogram deltas for transmission.
370 base::HistogramSnapshotManager histogram_snapshot_manager_;
371
372 // Used to manage various metrics reporting state prefs, such as client id,
373 // low entropy source and whether metrics reporting is enabled. Weak pointer.
374 MetricsStateManager* const state_manager_;
375
376 // Used to interact with the embedder. Weak pointer; must outlive |this|
377 // instance.
378 MetricsServiceClient* const client_;
379
380 // Registered metrics providers.
381 std::vector<std::unique_ptr<MetricsProvider>> metrics_providers_;
382
383 PrefService* local_state_;
384
385 base::ActionCallback action_callback_;
386
387 // Indicate whether recording and reporting are currently happening.
388 // These should not be set directly, but by calling SetRecording and
389 // SetReporting.
390 RecordingState recording_state_;
391
392 // Indicate whether test mode is enabled, where the initial log should never
393 // be cut, and logs are neither persisted nor uploaded.
394 bool test_mode_active_;
395
396 // The progression of states made by the browser are recorded in the following
397 // state.
398 State state_;
399
400 // The initial metrics log, used to record startup metrics (histograms and
401 // profiler data). Note that if a crash occurred in the previous session, an
402 // initial stability log may be sent before this.
403 std::unique_ptr<MetricsLog> initial_metrics_log_;
404
405 // Whether the MetricsService object has received any notifications since
406 // the last time a transmission was sent.
407 bool idle_since_last_transmission_;
408
409 // A number that identifies the how many times the app has been launched.
410 int session_id_;
411
412 // The scheduler for determining when log rotations should happen.
413 std::unique_ptr<MetricsRotationScheduler> rotation_scheduler_;
414
415 // Stores the time of the first call to |GetUptimes()|.
416 base::TimeTicks first_updated_time_;
417
418 // Stores the time of the last call to |GetUptimes()|.
419 base::TimeTicks last_updated_time_;
420 59
421 // Field trial groups that map to Chrome configuration states. 60 // Field trial groups that map to Chrome configuration states.
422 SyntheticTrialGroups synthetic_trial_groups_; 61 std::vector<SyntheticTrialGroup> synthetic_trial_groups_;
423 62
424 // List of observers of |synthetic_trial_groups_| changes. 63 // List of observers of |synthetic_trial_groups_| changes.
425 base::ObserverList<variations::SyntheticTrialObserver> 64 base::ObserverList<SyntheticTrialObserver> synthetic_trial_observer_list_;
426 synthetic_trial_observer_list_;
427
428 // Redundant marker to check that we completed our shutdown, and set the
429 // exited-cleanly bit in the prefs.
430 static ShutdownCleanliness clean_shutdown_status_;
431
432 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, IsPluginProcess);
433 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest,
434 PermutedEntropyCacheClearedWhenLowEntropyReset);
435 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, RegisterSyntheticTrial);
436 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest,
437 RegisterSyntheticMultiGroupFieldTrial);
438 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest,
439 GetSyntheticFieldTrialActiveGroups);
440
441 base::ThreadChecker thread_checker_;
442
443 // Weak pointers factory used to post task on different threads. All weak
444 // pointers managed by this factory have the same lifetime as MetricsService.
445 base::WeakPtrFactory<MetricsService> self_ptr_factory_;
446
447 DISALLOW_COPY_AND_ASSIGN(MetricsService);
448 }; 65 };
449 66
450 } // namespace metrics 67 } // namespace variations
451 68
452 #endif // COMPONENTS_METRICS_METRICS_SERVICE_H_ 69 #endif // COMPONENTS_VARIATIONS_SYNTHETIC_TRIAL_REGISTRY_H_
OLDNEW
« no previous file with comments | « components/variations/BUILD.gn ('k') | components/variations/synthetic_trial_registry.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698