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

Side by Side Diff: components/metrics/metrics_service.h

Issue 2608833002: Move logic for uploading logs into a ReportingService object. (Closed)
Patch Set: Incorporate feedback Created 3 years, 9 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
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 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 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 // This file defines a service that collects information about the user
6 // experience in order to help improve future versions of the app. 6 // experience in order to help improve future versions of the app.
7 7
8 #ifndef COMPONENTS_METRICS_METRICS_SERVICE_H_ 8 #ifndef COMPONENTS_METRICS_METRICS_SERVICE_H_
9 #define COMPONENTS_METRICS_METRICS_SERVICE_H_ 9 #define COMPONENTS_METRICS_METRICS_SERVICE_H_
10 10
11 #include <stdint.h> 11 #include <stdint.h>
12 12
13 #include <map> 13 #include <map>
14 #include <memory> 14 #include <memory>
15 #include <string> 15 #include <string>
16 #include <vector> 16 #include <vector>
17 17
18 #include "base/gtest_prod_util.h" 18 #include "base/gtest_prod_util.h"
19 #include "base/macros.h" 19 #include "base/macros.h"
20 #include "base/memory/weak_ptr.h" 20 #include "base/memory/weak_ptr.h"
21 #include "base/metrics/field_trial.h" 21 #include "base/metrics/field_trial.h"
22 #include "base/metrics/histogram_flattener.h" 22 #include "base/metrics/histogram_flattener.h"
23 #include "base/metrics/histogram_snapshot_manager.h" 23 #include "base/metrics/histogram_snapshot_manager.h"
24 #include "base/metrics/user_metrics.h" 24 #include "base/metrics/user_metrics.h"
25 #include "base/observer_list.h" 25 #include "base/observer_list.h"
26 #include "base/threading/thread_checker.h" 26 #include "base/threading/thread_checker.h"
27 #include "base/time/time.h" 27 #include "base/time/time.h"
28 #include "build/build_config.h" 28 #include "build/build_config.h"
29 #include "components/metrics/clean_exit_beacon.h" 29 #include "components/metrics/clean_exit_beacon.h"
30 #include "components/metrics/data_use_tracker.h"
31 #include "components/metrics/execution_phase.h" 30 #include "components/metrics/execution_phase.h"
32 #include "components/metrics/metrics_log.h" 31 #include "components/metrics/metrics_log.h"
33 #include "components/metrics/metrics_log_manager.h" 32 #include "components/metrics/metrics_log_manager.h"
34 #include "components/metrics/metrics_log_store.h" 33 #include "components/metrics/metrics_log_store.h"
35 #include "components/metrics/metrics_provider.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" 36 #include "components/metrics/net/network_metrics_provider.h"
37 #include "components/variations/synthetic_trials.h" 37 #include "components/variations/synthetic_trials.h"
38 38
39 class PrefService; 39 class PrefService;
40 class PrefRegistrySimple; 40 class PrefRegistrySimple;
41 41
42 namespace base { 42 namespace base {
43 class HistogramSamples; 43 class HistogramSamples;
44 class PrefService; 44 class PrefService;
45 } 45 }
46 46
47 namespace variations { 47 namespace variations {
48 struct ActiveGroupId; 48 struct ActiveGroupId;
49 } 49 }
50 50
51 namespace metrics { 51 namespace metrics {
52 52
53 class MetricsLogUploader;
54 class MetricsRotationScheduler; 53 class MetricsRotationScheduler;
55 class MetricsUploadScheduler;
56 class MetricsServiceAccessor; 54 class MetricsServiceAccessor;
57 class MetricsServiceClient; 55 class MetricsServiceClient;
58 class MetricsStateManager; 56 class MetricsStateManager;
59 57
60 // See metrics_service.cc for a detailed description. 58 // See metrics_service.cc for a detailed description.
61 class MetricsService : public base::HistogramFlattener { 59 class MetricsService : public base::HistogramFlattener {
62 public: 60 public:
63 // Creates the MetricsService with the given |state_manager|, |client|, and 61 // Creates the MetricsService with the given |state_manager|, |client|, and
64 // |local_state|. Does not take ownership of the paramaters; instead stores 62 // |local_state|. Does not take ownership of the paramaters; instead stores
65 // a weak pointer to each. Caller should ensure that the parameters are valid 63 // a weak pointer to each. Caller should ensure that the parameters are valid
(...skipping 37 matching lines...) Expand 10 before | Expand all | Expand 10 after
103 // Returns the install date of the application, in seconds since the epoch. 101 // Returns the install date of the application, in seconds since the epoch.
104 int64_t GetInstallDate(); 102 int64_t GetInstallDate();
105 103
106 // Returns the date at which the current metrics client ID was created as 104 // Returns the date at which the current metrics client ID was created as
107 // an int64_t containing seconds since the epoch. 105 // an int64_t containing seconds since the epoch.
108 int64_t GetMetricsReportingEnabledDate(); 106 int64_t GetMetricsReportingEnabledDate();
109 107
110 // Returns true if the last session exited cleanly. 108 // Returns true if the last session exited cleanly.
111 bool WasLastShutdownClean() const; 109 bool WasLastShutdownClean() const;
112 110
113 // At startup, prefs needs to be called with a list of all the pref names and 111 // Registers local state prefs used by this class.
114 // types we'll be using.
115 static void RegisterPrefs(PrefRegistrySimple* registry); 112 static void RegisterPrefs(PrefRegistrySimple* registry);
116 113
117 // HistogramFlattener: 114 // HistogramFlattener:
118 void RecordDelta(const base::HistogramBase& histogram, 115 void RecordDelta(const base::HistogramBase& histogram,
119 const base::HistogramSamples& snapshot) override; 116 const base::HistogramSamples& snapshot) override;
120 void InconsistencyDetected( 117 void InconsistencyDetected(
121 base::HistogramBase::Inconsistency problem) override; 118 base::HistogramBase::Inconsistency problem) override;
122 void UniqueInconsistencyDetected( 119 void UniqueInconsistencyDetected(
123 base::HistogramBase::Inconsistency problem) override; 120 base::HistogramBase::Inconsistency problem) override;
124 void InconsistencyDetectedInLoggedCount(int amount) override; 121 void InconsistencyDetectedInLoggedCount(int amount) override;
(...skipping 27 matching lines...) Expand all
152 // Saves in the preferences if the crash report registration was successful. 149 // Saves in the preferences if the crash report registration was successful.
153 // This count is eventually send via UMA logs. 150 // This count is eventually send via UMA logs.
154 void RecordBreakpadRegistration(bool success); 151 void RecordBreakpadRegistration(bool success);
155 152
156 // Saves in the preferences if the browser is running under a debugger. 153 // Saves in the preferences if the browser is running under a debugger.
157 // This count is eventually send via UMA logs. 154 // This count is eventually send via UMA logs.
158 void RecordBreakpadHasDebugger(bool has_debugger); 155 void RecordBreakpadHasDebugger(bool has_debugger);
159 156
160 bool recording_active() const; 157 bool recording_active() const;
161 bool reporting_active() const; 158 bool reporting_active() const;
159 bool has_unsent_logs() const;
162 160
163 // Redundant test to ensure that we are notified of a clean exit. 161 // Redundant test to ensure that we are notified of a clean exit.
164 // This value should be true when process has completed shutdown. 162 // This value should be true when process has completed shutdown.
165 static bool UmaMetricsProperlyShutdown(); 163 static bool UmaMetricsProperlyShutdown();
166 164
167 // Public accessor that returns the list of synthetic field trials. It must 165 // Public accessor that returns the list of synthetic field trials. It must
168 // only be used for testing. 166 // only be used for testing.
169 void GetCurrentSyntheticFieldTrialsForTesting( 167 void GetCurrentSyntheticFieldTrialsForTesting(
170 std::vector<variations::ActiveGroupId>* synthetic_trials); 168 std::vector<variations::ActiveGroupId>* synthetic_trials);
171 169
(...skipping 21 matching lines...) Expand all
193 void PushExternalLog(const std::string& log); 191 void PushExternalLog(const std::string& log);
194 192
195 // Updates data usage tracking prefs with the specified values. 193 // Updates data usage tracking prefs with the specified values.
196 void UpdateMetricsUsagePrefs(const std::string& service_name, 194 void UpdateMetricsUsagePrefs(const std::string& service_name,
197 int message_size, 195 int message_size,
198 bool is_cellular); 196 bool is_cellular);
199 197
200 protected: 198 protected:
201 // Exposed for testing. 199 // Exposed for testing.
202 MetricsLogManager* log_manager() { return &log_manager_; } 200 MetricsLogManager* log_manager() { return &log_manager_; }
203 MetricsLogStore* log_store() { return &log_store_; } 201 MetricsLogStore* log_store() {
202 return reporting_service_.metrics_log_store();
203 }
204 204
205 private: 205 private:
206 friend class MetricsServiceAccessor; 206 friend class MetricsServiceAccessor;
207 207
208 // The MetricsService has a lifecycle that is stored as a state. 208 // The MetricsService has a lifecycle that is stored as a state.
209 // See metrics_service.cc for description of this lifecycle. 209 // See metrics_service.cc for description of this lifecycle.
210 enum State { 210 enum State {
211 INITIALIZED, // Constructor was called. 211 INITIALIZED, // Constructor was called.
212 INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to finish. 212 INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to finish.
213 INIT_TASK_DONE, // Waiting for timer to send initial log. 213 INIT_TASK_DONE, // Waiting for timer to send initial log.
(...skipping 86 matching lines...) Expand 10 before | Expand all | Expand 10 after
300 // that metrics should be reported. If not, this is a no-op. 300 // that metrics should be reported. If not, this is a no-op.
301 void StartSchedulerIfNecessary(); 301 void StartSchedulerIfNecessary();
302 302
303 // Starts the process of uploading metrics data. 303 // Starts the process of uploading metrics data.
304 void StartScheduledUpload(); 304 void StartScheduledUpload();
305 305
306 // Called by the client via a callback when final log info collection is 306 // Called by the client via a callback when final log info collection is
307 // complete. 307 // complete.
308 void OnFinalLogInfoCollectionDone(); 308 void OnFinalLogInfoCollectionDone();
309 309
310 // If recording is enabled, begins uploading the next completed log from
311 // the log manager, staging it if necessary.
312 void SendNextLog();
313
314 // Returns true if any of the registered metrics providers have critical 310 // Returns true if any of the registered metrics providers have critical
315 // stability metrics to report in an initial stability log. 311 // stability metrics to report in an initial stability log.
316 bool ProvidersHaveInitialStabilityMetrics(); 312 bool ProvidersHaveInitialStabilityMetrics();
317 313
318 // Prepares the initial stability log, which is only logged when the previous 314 // Prepares the initial stability log, which is only logged when the previous
319 // run of Chrome crashed. This log contains any stability metrics left over 315 // run of Chrome crashed. This log contains any stability metrics left over
320 // from that previous run, and only these stability metrics. It uses the 316 // from that previous run, and only these stability metrics. It uses the
321 // system profile from the previous session. |prefs_previous_version| is used 317 // system profile from the previous session. |prefs_previous_version| is used
322 // to validate the version number recovered from the system profile. Returns 318 // to validate the version number recovered from the system profile. Returns
323 // true if a log was created. 319 // true if a log was created.
324 bool PrepareInitialStabilityLog(const std::string& prefs_previous_version); 320 bool PrepareInitialStabilityLog(const std::string& prefs_previous_version);
325 321
326 // Prepares the initial metrics log, which includes startup histograms and 322 // Prepares the initial metrics log, which includes startup histograms and
327 // profiler data, as well as incremental stability-related metrics. 323 // profiler data, as well as incremental stability-related metrics.
328 void PrepareInitialMetricsLog(); 324 void PrepareInitialMetricsLog();
329 325
330 // Uploads the currently staged log (which must be non-null).
331 void SendStagedLog();
332
333 // Called after transmission completes (either successfully or with failure).
334 void OnLogUploadComplete(int response_code);
335
336 // Reads, increments and then sets the specified long preference that is 326 // Reads, increments and then sets the specified long preference that is
337 // stored as a string. 327 // stored as a string.
338 void IncrementLongPrefsValue(const char* path); 328 void IncrementLongPrefsValue(const char* path);
339 329
340 // Records that the browser was shut down cleanly. 330 // Records that the browser was shut down cleanly.
341 void LogCleanShutdown(bool end_completed); 331 void LogCleanShutdown(bool end_completed);
342 332
343 // Notifies observers on a synthetic trial list change. 333 // Notifies observers on a synthetic trial list change.
344 void NotifySyntheticTrialObservers(); 334 void NotifySyntheticTrialObservers();
345 335
346 // Returns a list of synthetic field trials that are older than |time|. 336 // Returns a list of synthetic field trials that are older than |time|.
347 void GetSyntheticFieldTrialsOlderThan( 337 void GetSyntheticFieldTrialsOlderThan(
348 base::TimeTicks time, 338 base::TimeTicks time,
349 std::vector<variations::ActiveGroupId>* synthetic_trials); 339 std::vector<variations::ActiveGroupId>* synthetic_trials);
350 340
351 // Creates a new MetricsLog instance with the given |log_type|. 341 // Creates a new MetricsLog instance with the given |log_type|.
352 std::unique_ptr<MetricsLog> CreateLog(MetricsLog::LogType log_type); 342 std::unique_ptr<MetricsLog> CreateLog(MetricsLog::LogType log_type);
353 343
354 // Records the current environment (system profile) in |log|. 344 // Records the current environment (system profile) in |log|.
355 void RecordCurrentEnvironment(MetricsLog* log); 345 void RecordCurrentEnvironment(MetricsLog* log);
356 346
357 // Record complete list of histograms into the current log. 347 // Record complete list of histograms into the current log.
358 // Called when we close a log. 348 // Called when we close a log.
359 void RecordCurrentHistograms(); 349 void RecordCurrentHistograms();
360 350
361 // Record complete list of stability histograms into the current log, 351 // Record complete list of stability histograms into the current log,
362 // i.e., histograms with the |kUmaStabilityHistogramFlag| flag set. 352 // i.e., histograms with the |kUmaStabilityHistogramFlag| flag set.
363 void RecordCurrentStabilityHistograms(); 353 void RecordCurrentStabilityHistograms();
364 354
355 // Sub-Service for uploading logs.
Alexei Svitkine (slow) 2017/03/01 16:06:29 Nit: Don't capitalize service
Steven Holte 2017/03/04 01:35:51 Done.
356 MetricsReportingService reporting_service_;
357
365 // Manager for the various in-flight logs. 358 // Manager for the various in-flight logs.
366 MetricsLogManager log_manager_; 359 MetricsLogManager log_manager_;
367 360
368 // Store of logs ready to be uploaded.
369 MetricsLogStore log_store_;
370
371 // |histogram_snapshot_manager_| prepares histogram deltas for transmission. 361 // |histogram_snapshot_manager_| prepares histogram deltas for transmission.
372 base::HistogramSnapshotManager histogram_snapshot_manager_; 362 base::HistogramSnapshotManager histogram_snapshot_manager_;
373 363
374 // Used to manage various metrics reporting state prefs, such as client id, 364 // Used to manage various metrics reporting state prefs, such as client id,
375 // low entropy source and whether metrics reporting is enabled. Weak pointer. 365 // low entropy source and whether metrics reporting is enabled. Weak pointer.
376 MetricsStateManager* const state_manager_; 366 MetricsStateManager* const state_manager_;
377 367
378 // Used to interact with the embedder. Weak pointer; must outlive |this| 368 // Used to interact with the embedder. Weak pointer; must outlive |this|
379 // instance. 369 // instance.
380 MetricsServiceClient* const client_; 370 MetricsServiceClient* const client_;
381 371
382 // Registered metrics providers. 372 // Registered metrics providers.
383 std::vector<std::unique_ptr<MetricsProvider>> metrics_providers_; 373 std::vector<std::unique_ptr<MetricsProvider>> metrics_providers_;
384 374
385 PrefService* local_state_; 375 PrefService* local_state_;
386 376
387 CleanExitBeacon clean_exit_beacon_; 377 CleanExitBeacon clean_exit_beacon_;
388 378
389 base::ActionCallback action_callback_; 379 base::ActionCallback action_callback_;
390 380
391 // Indicate whether recording and reporting are currently happening. 381 // Indicate whether recording and reporting are currently happening.
392 // These should not be set directly, but by calling SetRecording and 382 // These should not be set directly, but by calling SetRecording and
393 // SetReporting. 383 // SetReporting.
394 RecordingState recording_state_; 384 RecordingState recording_state_;
395 bool reporting_active_;
396 385
397 // Indicate whether test mode is enabled, where the initial log should never 386 // Indicate whether test mode is enabled, where the initial log should never
398 // be cut, and logs are neither persisted nor uploaded. 387 // be cut, and logs are neither persisted nor uploaded.
399 bool test_mode_active_; 388 bool test_mode_active_;
400 389
401 // The progression of states made by the browser are recorded in the following 390 // The progression of states made by the browser are recorded in the following
402 // state. 391 // state.
403 State state_; 392 State state_;
404 393
405 // The initial metrics log, used to record startup metrics (histograms and 394 // The initial metrics log, used to record startup metrics (histograms and
406 // profiler data). Note that if a crash occurred in the previous session, an 395 // profiler data). Note that if a crash occurred in the previous session, an
407 // initial stability log may be sent before this. 396 // initial stability log may be sent before this.
408 std::unique_ptr<MetricsLog> initial_metrics_log_; 397 std::unique_ptr<MetricsLog> initial_metrics_log_;
409 398
410 // Instance of the helper class for uploading logs.
411 std::unique_ptr<MetricsLogUploader> log_uploader_;
412
413 // Whether there is a current log upload in progress.
414 bool log_upload_in_progress_;
415
416 // Whether the MetricsService object has received any notifications since 399 // Whether the MetricsService object has received any notifications since
417 // the last time a transmission was sent. 400 // the last time a transmission was sent.
418 bool idle_since_last_transmission_; 401 bool idle_since_last_transmission_;
419 402
420 // A number that identifies the how many times the app has been launched. 403 // A number that identifies the how many times the app has been launched.
421 int session_id_; 404 int session_id_;
422 405
423 // The scheduler for determining when log rotations should happen. 406 // The scheduler for determining when log rotations should happen.
424 std::unique_ptr<MetricsRotationScheduler> rotation_scheduler_; 407 std::unique_ptr<MetricsRotationScheduler> rotation_scheduler_;
425 // The scheduler for determining when uploads should happen.
426 std::unique_ptr<MetricsUploadScheduler> upload_scheduler_;
427 408
428 // Stores the time of the first call to |GetUptimes()|. 409 // Stores the time of the first call to |GetUptimes()|.
429 base::TimeTicks first_updated_time_; 410 base::TimeTicks first_updated_time_;
430 411
431 // Stores the time of the last call to |GetUptimes()|. 412 // Stores the time of the last call to |GetUptimes()|.
432 base::TimeTicks last_updated_time_; 413 base::TimeTicks last_updated_time_;
433 414
434 // Field trial groups that map to Chrome configuration states. 415 // Field trial groups that map to Chrome configuration states.
435 SyntheticTrialGroups synthetic_trial_groups_; 416 SyntheticTrialGroups synthetic_trial_groups_;
436 417
437 // List of observers of |synthetic_trial_groups_| changes. 418 // List of observers of |synthetic_trial_groups_| changes.
438 base::ObserverList<variations::SyntheticTrialObserver> 419 base::ObserverList<variations::SyntheticTrialObserver>
439 synthetic_trial_observer_list_; 420 synthetic_trial_observer_list_;
440 421
441 // Redundant marker to check that we completed our shutdown, and set the 422 // Redundant marker to check that we completed our shutdown, and set the
442 // exited-cleanly bit in the prefs. 423 // exited-cleanly bit in the prefs.
443 static ShutdownCleanliness clean_shutdown_status_; 424 static ShutdownCleanliness clean_shutdown_status_;
444 425
445 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, IsPluginProcess); 426 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, IsPluginProcess);
446 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, 427 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest,
447 PermutedEntropyCacheClearedWhenLowEntropyReset); 428 PermutedEntropyCacheClearedWhenLowEntropyReset);
448 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, RegisterSyntheticTrial); 429 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, RegisterSyntheticTrial);
449 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, 430 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest,
450 RegisterSyntheticMultiGroupFieldTrial); 431 RegisterSyntheticMultiGroupFieldTrial);
451 432
452 // Pointer used for obtaining data use pref updater callback on above layers.
453 std::unique_ptr<DataUseTracker> data_use_tracker_;
454
455 base::ThreadChecker thread_checker_; 433 base::ThreadChecker thread_checker_;
456 434
457 // Weak pointers factory used to post task on different threads. All weak 435 // Weak pointers factory used to post task on different threads. All weak
458 // pointers managed by this factory have the same lifetime as MetricsService. 436 // pointers managed by this factory have the same lifetime as MetricsService.
459 base::WeakPtrFactory<MetricsService> self_ptr_factory_; 437 base::WeakPtrFactory<MetricsService> self_ptr_factory_;
460 438
461 DISALLOW_COPY_AND_ASSIGN(MetricsService); 439 DISALLOW_COPY_AND_ASSIGN(MetricsService);
462 }; 440 };
463 441
464 } // namespace metrics 442 } // namespace metrics
465 443
466 #endif // COMPONENTS_METRICS_METRICS_SERVICE_H_ 444 #endif // COMPONENTS_METRICS_METRICS_SERVICE_H_
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698