1 // Copyright 2014 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 // This file defines a service that collects information about the user 6 // experience in order to help improve future versions of the app. 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 17 #include "base/callback_list.h" 18 #include "base/functional/bind.h" 19 #include "base/functional/callback_forward.h" 20 #include "base/gtest_prod_util.h" 21 #include "base/memory/raw_ptr.h" 22 #include "base/memory/weak_ptr.h" 23 #include "base/metrics/field_trial.h" 24 #include "base/metrics/histogram_flattener.h" 25 #include "base/metrics/histogram_snapshot_manager.h" 26 #include "base/metrics/statistics_recorder.h" 27 #include "base/metrics/user_metrics.h" 28 #include "base/observer_list.h" 29 #include "base/scoped_observation.h" 30 #include "base/sequence_checker.h" 31 #include "base/time/time.h" 32 #include "build/build_config.h" 33 #include "build/chromeos_buildflags.h" 34 #include "components/metrics/delegating_provider.h" 35 #include "components/metrics/metrics_log.h" 36 #include "components/metrics/metrics_log_manager.h" 37 #include "components/metrics/metrics_log_store.h" 38 #include "components/metrics/metrics_logs_event_manager.h" 39 #include "components/metrics/metrics_provider.h" 40 #include "components/metrics/metrics_reporting_service.h" 41 42 class PrefService; 43 class PrefRegistrySimple; 44 FORWARD_DECLARE_TEST(ChromeMetricsServiceClientTest, 45 TestRegisterMetricsServiceProviders); 46 FORWARD_DECLARE_TEST(IOSChromeMetricsServiceClientTest, 47 TestRegisterMetricsServiceProviders); 48 49 namespace base { 50 class PrefService; 51 } // namespace base 52 53 namespace variations { 54 class SyntheticTrialRegistry; 55 } 56 57 namespace metrics { 58 59 class MetricsRotationScheduler; 60 class MetricsServiceClient; 61 class MetricsServiceObserver; 62 class MetricsStateManager; 63 64 // See metrics_service.cc for a detailed description. 65 class MetricsService { 66 public: 67 // Creates the MetricsService with the given |state_manager|, |client|, and 68 // |local_state|. Does not take ownership of the paramaters; instead stores 69 // a weak pointer to each. Caller should ensure that the parameters are valid 70 // for the lifetime of this class. 71 MetricsService(MetricsStateManager* state_manager, 72 MetricsServiceClient* client, 73 PrefService* local_state); 74 75 MetricsService(const MetricsService&) = delete; 76 MetricsService& operator=(const MetricsService&) = delete; 77 78 virtual ~MetricsService(); 79 80 // Initializes metrics recording state. Updates various bookkeeping values in 81 // prefs and sets up the scheduler. This is a separate function rather than 82 // being done by the constructor so that field trials could be created before 83 // this is run. 84 void InitializeMetricsRecordingState(); 85 86 // Starts the metrics system, turning on recording and uploading of metrics. 87 // Should be called when starting up with metrics enabled, or when metrics 88 // are turned on. 89 void Start(); 90 91 // Starts the metrics system in a special test-only mode. Metrics won't ever 92 // be uploaded or persisted in this mode, but metrics will be recorded in 93 // memory. 94 void StartRecordingForTests(); 95 96 // Starts updating the "last live" browser timestamp. 97 void StartUpdatingLastLiveTimestamp(); 98 99 // Shuts down the metrics system. Should be called at shutdown, or if metrics 100 // are turned off. 101 void Stop(); 102 103 // Enable/disable transmission of accumulated logs and crash reports (dumps). 104 // Calling Start() automatically enables reporting, but sending is 105 // asyncronous so this can be called immediately after Start() to prevent 106 // any uploading. 107 void EnableReporting(); 108 void DisableReporting(); 109 110 // Returns the client ID for this client, or the empty string if metrics 111 // recording is not currently running. 112 std::string GetClientId() const; 113 114 // Set an external provided id for the metrics service. This method can be 115 // set by a caller which wants to explicitly control the *next* id used by the 116 // metrics service. Note that setting the external client id will *not* change 117 // the current metrics client id. In order to change the current client id, 118 // callers should call ResetClientId to change the current client id to the 119 // provided id. 120 void SetExternalClientId(const std::string& id); 121 122 // Returns the date at which the current metrics client ID was created as 123 // an int64_t containing seconds since the epoch. 124 int64_t GetMetricsReportingEnabledDate(); 125 126 // Returns true if the last session exited cleanly. 127 bool WasLastShutdownClean() const; 128 129 // Registers local state prefs used by this class. 130 static void RegisterPrefs(PrefRegistrySimple* registry); 131 132 // This should be called when the application is not idle, i.e. the user seems 133 // to be interacting with the application. 134 void OnApplicationNotIdle(); 135 136 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS) 137 // Called when the application is going into background mode. 138 // If |keep_recording_in_background| is true, UMA is still recorded and 139 // reported while in the background. 140 void OnAppEnterBackground(bool keep_recording_in_background = false); 141 142 // Called when the application is coming out of background mode. 143 void OnAppEnterForeground(bool force_open_new_log = false); 144 #endif // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS) 145 146 // Signals that the browser is shutting down cleanly. Intended to be called 147 // during shutdown after critical shutdown tasks have completed. 148 void LogCleanShutdown(); 149 150 bool recording_active() const; 151 bool reporting_active() const; 152 bool has_unsent_logs() const; 153 154 bool IsMetricsReportingEnabled() const; 155 156 // Register the specified |provider| to provide additional metrics into the 157 // UMA log. Should be called during MetricsService initialization only. 158 void RegisterMetricsProvider(std::unique_ptr<MetricsProvider> provider); 159 160 // Check if this install was cloned or imaged from another machine. If a 161 // clone is detected, reset the client id and low entropy source. This 162 // should not be called more than once. 163 void CheckForClonedInstall(); 164 165 // Checks if the cloned install detector says that client ids should be reset. 166 bool ShouldResetClientIdsOnClonedInstall(); 167 168 // Clears the stability metrics that are saved in local state. 169 void ClearSavedStabilityMetrics(); 170 171 // Marks current histograms as reported by snapshotting them, without 172 // actually saving the deltas. At a higher level, this is used to throw 173 // away new histogram samples (since the last log) so that they will not 174 // be included in the next log. 175 void MarkCurrentHistogramsAsReported(); 176 177 #if BUILDFLAG(IS_CHROMEOS_ASH) 178 // Binds a user log store to store unsent logs. This log store will be 179 // fully managed by MetricsLogStore. This will no-op if another log store has 180 // already been set. 181 // 182 // If this is called before initial logs are recorded, then histograms 183 // recorded before user log store is set will be included with user histograms 184 // when initial logs are recorded. 185 // 186 // If this is called after initial logs are recorded, then this will flush all 187 // logs recorded before swapping to |user_log_store|. 188 void SetUserLogStore(std::unique_ptr<UnsentLogStore> user_log_store); 189 190 // Unbinds the user log store. If there was no user log store, then this does 191 // nothing. 192 // 193 // If this is called before initial logs are recorded, then histograms and the 194 // current log will be discarded. 195 // 196 // If called after initial logs are recorded, then this will flush all logs 197 // before the user log store is unset. 198 void UnsetUserLogStore(); 199 200 // Returns true if a user log store has been bound. 201 bool HasUserLogStore(); 202 203 // Initializes per-user metrics collection. Logs recorded during a user 204 // session will be stored within each user's directory and consent to send 205 // these logs will be controlled by each user. Logs recorded before any user 206 // logs in or during guest sessions (given device owner has consented) will be 207 // stored in local_state. 208 // 209 // This is in its own function because the MetricsService is created very 210 // early on and a user metrics service may have dependencies on services that 211 // are created happen after MetricsService is initialized. 212 void InitPerUserMetrics(); 213 214 // Returns the current user metrics consent if it should be applied to 215 // determine metrics reporting state. 216 // 217 // See comments at MetricsServiceClient::GetCurrentUserMetricsConsent() for 218 // more details. 219 absl::optional<bool> GetCurrentUserMetricsConsent() const; 220 221 // Returns the current logged in user id. See comments at 222 // MetricsServiceClient::GetCurrentUserId() for more details. 223 absl::optional<std::string> GetCurrentUserId() const; 224 225 // Updates the current user metrics consent. No-ops if no user has logged in. 226 void UpdateCurrentUserMetricsConsent(bool user_metrics_consent); 227 #endif // BUILDFLAG(IS_CHROMEOS_ASH) 228 229 #if BUILDFLAG(IS_CHROMEOS) 230 // Forces the client ID to be reset and generates a new client ID. This will 231 // be called when a user re-consents to metrics collection and the user had 232 // consented in the past. 233 // 234 // This is to preserve the pseudo-anonymous identifier <client_id, user_id>. 235 void ResetClientId(); 236 #endif // BUILDFLAG(IS_CHROMEOS) 237 238 variations::SyntheticTrialRegistry* GetSyntheticTrialRegistry(); 239 240 // Returns the delay before the init tasks (to asynchronously initialize 241 // metrics providers) run. 242 base::TimeDelta GetInitializationDelay(); 243 244 // Returns the delay before the task to update the "last alive timestamp" is 245 // run. 246 base::TimeDelta GetUpdateLastAliveTimestampDelay(); 247 LogStoreForTest()248 MetricsLogStore* LogStoreForTest() { 249 return reporting_service_.metrics_log_store(); 250 } 251 252 // Test hook to safely stage the current log in the log store. 253 bool StageCurrentLogForTest(); 254 GetCurrentLogForTest()255 MetricsLog* GetCurrentLogForTest() { return log_manager_.current_log(); } 256 GetDelegatingProviderForTesting()257 DelegatingProvider* GetDelegatingProviderForTesting() { 258 return &delegating_provider_; 259 } 260 261 // Adds/Removes a logs observer. Observers are notified when a log is newly 262 // created and is now known by the metrics service. This may occur when 263 // closing a log, or when loading a log from persistent storage. Observers are 264 // also notified when an event occurs on the log (e.g., log is staged, 265 // uploaded, etc.). See MetricsLogsEventManager::LogEvent for more details. 266 void AddLogsObserver(MetricsLogsEventManager::Observer* observer); 267 void RemoveLogsObserver(MetricsLogsEventManager::Observer* observer); 268 logs_event_observer()269 MetricsServiceObserver* logs_event_observer() { 270 return logs_event_observer_.get(); 271 } 272 273 // Observers will be notified when the enablement state changes. The callback 274 // should accept one boolean argument, which will signal whether or not the 275 // metrics collection has been enabled. 276 base::CallbackListSubscription AddEnablementObserver( 277 const base::RepeatingCallback<void(bool)>& observer); 278 279 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS) IsInForegroundForTesting()280 bool IsInForegroundForTesting() const { return is_in_foreground_; } 281 #endif 282 283 // Creates a new MetricsLog instance with the given |log_type|. CreateLogForTesting(MetricsLog::LogType log_type)284 std::unique_ptr<MetricsLog> CreateLogForTesting( 285 MetricsLog::LogType log_type) { 286 return CreateLog(log_type); 287 } 288 289 protected: 290 // Sets the persistent system profile. Virtual for tests. 291 virtual void SetPersistentSystemProfile(const std::string& serialized_proto, 292 bool complete); 293 294 // Records the current environment (system profile) in |log|, and persists 295 // the results in prefs. 296 // Exposed for testing. 297 static std::string RecordCurrentEnvironmentHelper( 298 MetricsLog* log, 299 PrefService* local_state, 300 DelegatingProvider* delegating_provider); 301 302 // The MetricsService has a lifecycle that is stored as a state. 303 // See metrics_service.cc for description of this lifecycle. 304 enum State { 305 CONSTRUCTED, // Constructor was called. 306 INITIALIZED, // InitializeMetricsRecordingState() was called. 307 INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to finish. 308 INIT_TASK_DONE, // Waiting for timer to send initial log. 309 SENDING_LOGS, // Sending logs and creating new ones when we run out. 310 }; 311 state()312 State state() const { return state_; } 313 314 private: 315 // The current state of recording for the MetricsService. The state is UNSET 316 // until set to something else, at which point it remains INACTIVE or ACTIVE 317 // for the lifetime of the object. 318 enum RecordingState { 319 INACTIVE, 320 ACTIVE, 321 UNSET, 322 }; 323 324 // The result of a call to FinalizeLog(). 325 struct FinalizedLog { 326 FinalizedLog(); 327 ~FinalizedLog(); 328 329 // This type is move only. 330 FinalizedLog(FinalizedLog&& other); 331 332 // The size of the uncompressed log data. This is only used for calculating 333 // some metrics. 334 size_t uncompressed_log_size; 335 336 // A LogInfo object representing the log, which contains its compressed 337 // data, hash, signature, timestamp, and some metadata. 338 std::unique_ptr<UnsentLogStore::LogInfo> log_info; 339 }; 340 341 // Writes snapshots of histograms owned by the StatisticsRecorder to a log. 342 // Does not take ownership of the log. 343 // TODO(crbug/1423653): Although this class takes in |required_flags| in its 344 // constructor to filter the StatisticsRecorder histograms being put into 345 // the log, the |histogram_snapshot_manager_| is not aware of this. So if 346 // the |histogram_snapshot_manager_| is passed to some other caller, this 347 // caller will need to manually filter the histograms. Re-factor the code so 348 // that this is not needed. 349 class MetricsLogHistogramWriter { 350 public: 351 explicit MetricsLogHistogramWriter(MetricsLog* log); 352 353 MetricsLogHistogramWriter(MetricsLog* log, 354 base::HistogramBase::Flags required_flags); 355 356 MetricsLogHistogramWriter(const MetricsLogHistogramWriter&) = delete; 357 MetricsLogHistogramWriter& operator=(const MetricsLogHistogramWriter&) = 358 delete; 359 360 ~MetricsLogHistogramWriter(); 361 362 // Snapshots the deltas of histograms known by the StatisticsRecorder and 363 // writes them to the log passed in the constructor. This also marks the 364 // samples (the deltas) as logged. 365 void SnapshotStatisticsRecorderDeltas(); 366 367 // Snapshots the unlogged samples of histograms known by the 368 // StatisticsRecorder and writes them to the log passed in the constructor. 369 // Note that unlike SnapshotStatisticsRecorderDeltas(), this does not mark 370 // the samples as logged. To do so, a call to MarkUnloggedSamplesAsLogged() 371 // (in |histogram_snapshot_manager_|) should be made. 372 void SnapshotStatisticsRecorderUnloggedSamples(); 373 histogram_snapshot_manager()374 base::HistogramSnapshotManager* histogram_snapshot_manager() { 375 return histogram_snapshot_manager_.get(); 376 } 377 snapshot_transaction_id()378 base::StatisticsRecorder::SnapshotTransactionId snapshot_transaction_id() { 379 return snapshot_transaction_id_; 380 } 381 382 private: 383 // Used to select which histograms to record when calling 384 // SnapshotStatisticsRecorderHistograms() or 385 // SnapshotStatisticsRecorderUnloggedSamples(). 386 const base::HistogramBase::Flags required_flags_; 387 388 // Used to write histograms to the log passed in the constructor. 389 std::unique_ptr<base::HistogramFlattener> flattener_; 390 391 // Used to snapshot histograms. 392 std::unique_ptr<base::HistogramSnapshotManager> histogram_snapshot_manager_; 393 394 // The snapshot transaction ID of a call to either 395 // SnapshotStatisticsRecorderDeltas() or 396 // SnapshotStatisticsRecorderUnloggedSamples(). 397 base::StatisticsRecorder::SnapshotTransactionId snapshot_transaction_id_; 398 }; 399 400 // Loads "independent" metrics from a metrics provider and executes a 401 // callback when complete, which could be immediate or after some 402 // execution on a background thread. 403 class IndependentMetricsLoader { 404 public: 405 explicit IndependentMetricsLoader(std::unique_ptr<MetricsLog> log); 406 407 IndependentMetricsLoader(const IndependentMetricsLoader&) = delete; 408 IndependentMetricsLoader& operator=(const IndependentMetricsLoader&) = 409 delete; 410 411 ~IndependentMetricsLoader(); 412 413 // Call ProvideIndependentMetrics (which may execute on a background thread) 414 // for the |metrics_provider| and execute the |done_callback| when complete 415 // with the result (true if successful). Though this can be called multiple 416 // times to include data from multiple providers, later calls will override 417 // system profile information set by earlier calls. 418 void Run(base::OnceCallback<void(bool)> done_callback, 419 MetricsProvider* metrics_provider); 420 421 // Extract the filled log. No more Run() operations can be done after this. 422 std::unique_ptr<MetricsLog> ReleaseLog(); 423 424 private: 425 std::unique_ptr<MetricsLog> log_; 426 std::unique_ptr<base::HistogramFlattener> flattener_; 427 std::unique_ptr<base::HistogramSnapshotManager> snapshot_manager_; 428 }; 429 430 // Gets the LogStore for UMA logs. log_store()431 MetricsLogStore* log_store() { 432 return reporting_service_.metrics_log_store(); 433 } 434 435 // Calls into the client to initialize some system profile metrics. 436 void StartInitTask(); 437 438 // Callback that moves the state to INIT_TASK_DONE. When this is called, the 439 // state should be INIT_TASK_SCHEDULED. 440 void FinishedInitTask(); 441 442 void OnUserAction(const std::string& action, base::TimeTicks action_time); 443 444 // Get the amount of uptime since this process started and since the last 445 // call to this function. Also updates the cumulative uptime metric (stored 446 // as a pref) for uninstall. Uptimes are measured using TimeTicks, which 447 // guarantees that it is monotonic and does not jump if the user changes 448 // their clock. The TimeTicks implementation also makes the clock not 449 // count time the computer is suspended. 450 void GetUptimes(PrefService* pref, 451 base::TimeDelta* incremental_uptime, 452 base::TimeDelta* uptime); 453 454 // Turns recording on or off. 455 // DisableRecording() also forces a persistent save of logging state (if 456 // anything has been recorded, or transmitted). 457 void EnableRecording(); 458 void DisableRecording(); 459 460 // If in_idle is true, sets idle_since_last_transmission to true. 461 // If in_idle is false and idle_since_last_transmission_ is true, sets 462 // idle_since_last_transmission to false and starts the timer (provided 463 // starting the timer is permitted). 464 void HandleIdleSinceLastTransmission(bool in_idle); 465 466 // Set up client ID, session ID, etc. 467 void InitializeMetricsState(); 468 469 // Opens a new log for recording user experience metrics. If |call_providers| 470 // is true, OnDidCreateMetricsLog() of providers will be called right after 471 // opening the new log. 472 void OpenNewLog(bool call_providers = true); 473 474 // Closes out the current log after adding any last information. |async| 475 // determines whether finalizing the log will be done in a background thread. 476 // |log_stored_callback| will be run (on the main thread) after the finalized 477 // log is stored. Note that when |async| is true, the closed log could end up 478 // not being stored (see MaybeCleanUpAndStoreFinalizedLog()). Regardless, 479 // |log_stored_callback| is still run. Note that currently, there is only 480 // support to close one log asynchronously at a time (this should be enforced 481 // by the caller). 482 void CloseCurrentLog( 483 bool async, 484 MetricsLogsEventManager::CreateReason reason, 485 base::OnceClosure log_stored_callback = base::DoNothing()); 486 487 // Stores the |finalized_log| in |log_store()|. 488 void StoreFinalizedLog(MetricsLog::LogType log_type, 489 MetricsLogsEventManager::CreateReason reason, 490 base::OnceClosure done_callback, 491 FinalizedLog finalized_log); 492 493 // Calls MarkUnloggedSamplesAsLogged() on |log_histogram_writer| and stores 494 // the |finalized_log| (see StoreFinalizedLog()), but only if the 495 // StatisticRecorder's last transaction ID is the same as the one from 496 // |log_histogram_writer| at the time of calling. See comments in the 497 // implementation for more details. 498 void MaybeCleanUpAndStoreFinalizedLog( 499 std::unique_ptr<MetricsLogHistogramWriter> log_histogram_writer, 500 MetricsLog::LogType log_type, 501 MetricsLogsEventManager::CreateReason reason, 502 base::OnceClosure done_callback, 503 FinalizedLog finalized_log); 504 505 // Pushes the text of the current and staged logs into persistent storage. 506 void PushPendingLogsToPersistentStorage( 507 MetricsLogsEventManager::CreateReason reason); 508 509 // Ensures that scheduler is running, assuming the current settings are such 510 // that metrics should be reported. If not, this is a no-op. 511 void StartSchedulerIfNecessary(); 512 513 // Starts the process of uploading metrics data. 514 void StartScheduledUpload(); 515 516 // Called by the client via a callback when final log info collection is 517 // complete. 518 void OnFinalLogInfoCollectionDone(); 519 520 // Called via a callback after a periodic ongoing log (created through the 521 // MetricsRotationScheduler) was stored in |log_store()|. 522 void OnPeriodicOngoingLogStored(); 523 524 // Prepares the initial stability log, which is only logged when the previous 525 // run of Chrome crashed. This log contains any stability metrics left over 526 // from that previous run, and only these stability metrics. It uses the 527 // system profile from the previous session. |prefs_previous_version| is used 528 // to validate the version number recovered from the system profile. Returns 529 // true if a log was created. 530 bool PrepareInitialStabilityLog(const std::string& prefs_previous_version); 531 532 // Creates a new MetricsLog instance with the given |log_type|. 533 std::unique_ptr<MetricsLog> CreateLog(MetricsLog::LogType log_type); 534 535 // Records the current environment (system profile) in |log|, and persists 536 // the results in prefs and GlobalPersistentSystemProfile. 537 void RecordCurrentEnvironment(MetricsLog* log, bool complete); 538 539 // Handle completion of PrepareProviderMetricsLog which is run as a 540 // background task. 541 void PrepareProviderMetricsLogDone( 542 std::unique_ptr<IndependentMetricsLoader> loader, 543 bool success); 544 545 // Record a single independent profile and associated histogram from 546 // metrics providers. If this returns true, one was found and there may 547 // be more. 548 bool PrepareProviderMetricsLog(); 549 550 // Records one independent histogram log and then reschedules itself to 551 // check for others. The interval is so as to not adversely impact the UI. 552 void PrepareProviderMetricsTask(); 553 554 // Updates the "last live" browser timestamp and schedules the next update. 555 void UpdateLastLiveTimestampTask(); 556 557 // Returns whether it is too early to close a log. 558 bool IsTooEarlyToCloseLog(); 559 560 // Called if this install is detected as cloned. 561 void OnClonedInstallDetected(); 562 563 // Snapshots histogram deltas using the passed |log_histogram_writer| and then 564 // finalizes |log| by calling FinalizeLog(). |log|, |current_app_version| and 565 // |signing_key| are used to finalize the log (see FinalizeLog()). 566 static FinalizedLog SnapshotDeltasAndFinalizeLog( 567 std::unique_ptr<MetricsLogHistogramWriter> log_histogram_writer, 568 std::unique_ptr<MetricsLog> log, 569 bool truncate_events, 570 std::string current_app_version, 571 std::string signing_key); 572 573 // Snapshots unlogged histogram samples using the passed 574 // |log_histogram_writer| and then finalizes |log| by calling FinalizeLog(). 575 // |log|, |current_app_version| and |signing_key| are used to finalize the log 576 // (see FinalizeLog()). Note that unlike SnapshotDeltasAndFinalizeLog(), this 577 // does not own the passed |log_histogram_writer|, because it should be 578 // available to eventually mark the unlogged samples as logged. 579 static FinalizedLog SnapshotUnloggedSamplesAndFinalizeLog( 580 MetricsLogHistogramWriter* log_histogram_writer, 581 std::unique_ptr<MetricsLog> log, 582 bool truncate_events, 583 std::string current_app_version, 584 std::string signing_key); 585 586 // Finalizes |log| (see MetricsLog::FinalizeLog()). The |signing_key| is used 587 // to compute a signature for the log. 588 static FinalizedLog FinalizeLog(std::unique_ptr<MetricsLog> log, 589 bool truncate_events, 590 std::string current_app_version, 591 std::string signing_key); 592 593 // Sub-service for uploading logs. 594 MetricsReportingService reporting_service_; 595 596 // Manager for the various in-flight logs. 597 MetricsLogManager log_manager_; 598 599 // Used to manage various metrics reporting state prefs, such as client id, 600 // low entropy source and whether metrics reporting is enabled. Weak pointer. 601 const raw_ptr<MetricsStateManager> state_manager_; 602 603 // Used to interact with the embedder. Weak pointer; must outlive |this| 604 // instance. 605 const raw_ptr<MetricsServiceClient> client_; 606 607 // Registered metrics providers. 608 DelegatingProvider delegating_provider_; 609 610 raw_ptr<PrefService> local_state_; 611 612 base::ActionCallback action_callback_; 613 614 // Indicate whether recording and reporting are currently happening. 615 // These should not be set directly, but by calling SetRecording and 616 // SetReporting. 617 RecordingState recording_state_; 618 619 // Indicate whether test mode is enabled, where the initial log should never 620 // be cut, and logs are neither persisted nor uploaded. 621 bool test_mode_active_; 622 623 // The progression of states made by the browser are recorded in the following 624 // state. 625 State state_; 626 627 // Whether the MetricsService object has received any notifications since 628 // the last time a transmission was sent. 629 bool idle_since_last_transmission_; 630 631 // A number that identifies the how many times the app has been launched. 632 int session_id_; 633 634 // The scheduler for determining when log rotations should happen. 635 std::unique_ptr<MetricsRotationScheduler> rotation_scheduler_; 636 637 // Stores the time of the first call to |GetUptimes()|. 638 base::TimeTicks first_updated_time_; 639 640 // Stores the time of the last call to |GetUptimes()|. 641 base::TimeTicks last_updated_time_; 642 643 // Indicates if loading of independent metrics is currently active. 644 bool independent_loader_active_ = false; 645 646 // Indicates whether or not there is currently a periodic ongoing log being 647 // finalized (or is scheduled to be finalized). 648 bool pending_ongoing_log_ = false; 649 650 // Stores the time when we last posted a task to finalize a periodic ongoing 651 // log asynchronously. 652 base::TimeTicks async_ongoing_log_posted_time_; 653 654 // Logs event manager to keep track of the various logs that the metrics 655 // service interacts with. An unowned pointer of this instance is passed down 656 // to various objects that are owned by this class. 657 MetricsLogsEventManager logs_event_manager_; 658 659 // An observer that observes all events notified through |logs_event_manager_| 660 // since the creation of this MetricsService instance. This is only created 661 // if this is a debug build, or the |kExportUmaLogsToFile| command line flag 662 // is passed. This is primarily used by the chrome://metrics-internals debug 663 // page. 664 std::unique_ptr<MetricsServiceObserver> logs_event_observer_; 665 666 // A set of observers that keeps track of the metrics reporting state. 667 base::RepeatingCallbackList<void(bool)> enablement_observers_; 668 669 // Subscription for a callback that runs if this install is detected as 670 // cloned. 671 base::CallbackListSubscription cloned_install_subscription_; 672 673 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS) 674 // Indicates whether OnAppEnterForeground() (true) or OnAppEnterBackground 675 // (false) was called. 676 bool is_in_foreground_ = false; 677 #endif 678 679 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, ActiveFieldTrialsReported); 680 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, IsPluginProcess); 681 FRIEND_TEST_ALL_PREFIXES(::ChromeMetricsServiceClientTest, 682 TestRegisterMetricsServiceProviders); 683 FRIEND_TEST_ALL_PREFIXES(::IOSChromeMetricsServiceClientTest, 684 TestRegisterMetricsServiceProviders); 685 SEQUENCE_CHECKER(sequence_checker_); 686 687 // Weak pointers factory used to post task on different threads. All weak 688 // pointers managed by this factory have the same lifetime as MetricsService. 689 base::WeakPtrFactory<MetricsService> self_ptr_factory_{this}; 690 }; 691 692 } // namespace metrics 693 694 #endif // COMPONENTS_METRICS_METRICS_SERVICE_H_ 695