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.
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_
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_store.h"
37 #include "components/metrics/metrics_logs_event_manager.h"
38 #include "components/metrics/metrics_provider.h"
39 #include "components/metrics/metrics_reporting_service.h"
42 class PrefRegistrySimple;
43 FORWARD_DECLARE_TEST(ChromeMetricsServiceClientTest,
44 TestRegisterMetricsServiceProviders);
45 FORWARD_DECLARE_TEST(IOSChromeMetricsServiceClientTest,
46 TestRegisterMetricsServiceProviders);
52 namespace variations {
53 class SyntheticTrialRegistry;
58 class MetricsRotationScheduler;
59 class MetricsServiceClient;
60 class MetricsServiceObserver;
61 class MetricsStateManager;
63 // See metrics_service.cc for a detailed description.
64 class MetricsService {
66 // Creates the MetricsService with the given |state_manager|, |client|, and
67 // |local_state|. Does not take ownership of the paramaters; instead stores
68 // a weak pointer to each. Caller should ensure that the parameters are valid
69 // for the lifetime of this class.
70 MetricsService(MetricsStateManager* state_manager,
71 MetricsServiceClient* client,
72 PrefService* local_state);
74 MetricsService(const MetricsService&) = delete;
75 MetricsService& operator=(const MetricsService&) = delete;
77 virtual ~MetricsService();
79 // Initializes metrics recording state. Updates various bookkeeping values in
80 // prefs and sets up the scheduler. This is a separate function rather than
81 // being done by the constructor so that field trials could be created before
83 void InitializeMetricsRecordingState();
85 // Starts the metrics system, turning on recording and uploading of metrics.
86 // Should be called when starting up with metrics enabled, or when metrics
90 // Starts the metrics system in a special test-only mode. Metrics won't ever
91 // be uploaded or persisted in this mode, but metrics will be recorded in
93 void StartRecordingForTests();
95 // Starts updating the "last live" browser timestamp.
96 void StartUpdatingLastLiveTimestamp();
98 // Shuts down the metrics system. Should be called at shutdown, or if metrics
102 // Enable/disable transmission of accumulated logs and crash reports (dumps).
103 // Calling Start() automatically enables reporting, but sending is
104 // asyncronous so this can be called immediately after Start() to prevent
106 void EnableReporting();
107 void DisableReporting();
109 // Returns the client ID for this client, or the empty string if metrics
110 // recording is not currently running.
111 std::string GetClientId() const;
113 // Get the low entropy source values.
114 int GetLowEntropySource();
115 int GetOldLowEntropySource();
116 int GetPseudoLowEntropySource();
118 // Set an external provided id for the metrics service. This method can be
119 // set by a caller which wants to explicitly control the *next* id used by the
120 // metrics service. Note that setting the external client id will *not* change
121 // the current metrics client id. In order to change the current client id,
122 // callers should call ResetClientId to change the current client id to the
124 void SetExternalClientId(const std::string& id);
126 // Returns the date at which the current metrics client ID was created as
127 // an int64_t containing seconds since the epoch.
128 int64_t GetMetricsReportingEnabledDate();
130 // Returns true if the last session exited cleanly.
131 bool WasLastShutdownClean() const;
133 // Registers local state prefs used by this class.
134 static void RegisterPrefs(PrefRegistrySimple* registry);
136 // This should be called when the application is not idle, i.e. the user seems
137 // to be interacting with the application.
138 void OnApplicationNotIdle();
140 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
141 // Called when the application is going into background mode.
142 // If |keep_recording_in_background| is true, UMA is still recorded and
143 // reported while in the background.
144 void OnAppEnterBackground(bool keep_recording_in_background = false);
146 // Called when the application is coming out of background mode.
147 void OnAppEnterForeground(bool force_open_new_log = false);
148 #endif // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
150 // Signals that the browser is shutting down cleanly. Intended to be called
151 // during shutdown after critical shutdown tasks have completed.
152 void LogCleanShutdown();
154 bool recording_active() const;
155 bool reporting_active() const;
156 bool has_unsent_logs() const;
158 bool IsMetricsReportingEnabled() const;
160 // Register the specified |provider| to provide additional metrics into the
161 // UMA log. Should be called during MetricsService initialization only.
162 void RegisterMetricsProvider(std::unique_ptr<MetricsProvider> provider);
164 // Check if this install was cloned or imaged from another machine. If a
165 // clone is detected, reset the client id and low entropy source. This
166 // should not be called more than once.
167 void CheckForClonedInstall();
169 // Checks if the cloned install detector says that client ids should be reset.
170 bool ShouldResetClientIdsOnClonedInstall();
172 // Clears the stability metrics that are saved in local state.
173 void ClearSavedStabilityMetrics();
175 // Marks current histograms as reported by snapshotting them, without
176 // actually saving the deltas. At a higher level, this is used to throw
177 // away new histogram samples (since the last log) so that they will not
178 // be included in the next log.
179 void MarkCurrentHistogramsAsReported();
181 #if BUILDFLAG(IS_CHROMEOS_ASH)
182 // Binds a user log store to store unsent logs. This log store will be
183 // fully managed by MetricsLogStore. This will no-op if another log store has
186 // If this is called before initial logs are recorded, then histograms
187 // recorded before user log store is set will be included with user histograms
188 // when initial logs are recorded.
190 // If this is called after initial logs are recorded, then this will flush all
191 // logs recorded before swapping to |user_log_store|.
192 void SetUserLogStore(std::unique_ptr<UnsentLogStore> user_log_store);
194 // Unbinds the user log store. If there was no user log store, then this does
197 // If this is called before initial logs are recorded, then histograms and the
198 // current log will be discarded.
200 // If called after initial logs are recorded, then this will flush all logs
201 // before the user log store is unset.
202 void UnsetUserLogStore();
204 // Returns true if a user log store has been bound.
205 bool HasUserLogStore();
207 // Initializes per-user metrics collection. Logs recorded during a user
208 // session will be stored within each user's directory and consent to send
209 // these logs will be controlled by each user. Logs recorded before any user
210 // logs in or during guest sessions (given device owner has consented) will be
211 // stored in local_state.
213 // This is in its own function because the MetricsService is created very
214 // early on and a user metrics service may have dependencies on services that
215 // are created happen after MetricsService is initialized.
216 void InitPerUserMetrics();
218 // Returns the current user metrics consent if it should be applied to
219 // determine metrics reporting state.
221 // See comments at MetricsServiceClient::GetCurrentUserMetricsConsent() for
223 absl::optional<bool> GetCurrentUserMetricsConsent() const;
225 // Returns the current logged in user id. See comments at
226 // MetricsServiceClient::GetCurrentUserId() for more details.
227 absl::optional<std::string> GetCurrentUserId() const;
229 // Updates the current user metrics consent. No-ops if no user has logged in.
230 void UpdateCurrentUserMetricsConsent(bool user_metrics_consent);
231 #endif // BUILDFLAG(IS_CHROMEOS_ASH)
233 #if BUILDFLAG(IS_CHROMEOS)
234 // Forces the client ID to be reset and generates a new client ID. This will
235 // be called when a user re-consents to metrics collection and the user had
236 // consented in the past.
238 // This is to preserve the pseudo-anonymous identifier <client_id, user_id>.
239 void ResetClientId();
240 #endif // BUILDFLAG(IS_CHROMEOS)
242 variations::SyntheticTrialRegistry* GetSyntheticTrialRegistry();
244 // Returns the delay before the init tasks (to asynchronously initialize
245 // metrics providers) run.
246 base::TimeDelta GetInitializationDelay();
248 // Returns the delay before the task to update the "last alive timestamp" is
250 base::TimeDelta GetUpdateLastAliveTimestampDelay();
252 MetricsLogStore* LogStoreForTest() {
253 return reporting_service_.metrics_log_store();
256 // Test hook to safely stage the current log in the log store.
257 bool StageCurrentLogForTest();
259 MetricsLog* GetCurrentLogForTest() { return current_log_.get(); }
261 DelegatingProvider* GetDelegatingProviderForTesting() {
262 return &delegating_provider_;
265 // Adds/Removes a logs observer. Observers are notified when a log is newly
266 // created and is now known by the metrics service. This may occur when
267 // closing a log, or when loading a log from persistent storage. Observers are
268 // also notified when an event occurs on the log (e.g., log is staged,
269 // uploaded, etc.). See MetricsLogsEventManager::LogEvent for more details.
270 void AddLogsObserver(MetricsLogsEventManager::Observer* observer);
271 void RemoveLogsObserver(MetricsLogsEventManager::Observer* observer);
273 MetricsServiceObserver* logs_event_observer() {
274 return logs_event_observer_.get();
277 // Observers will be notified when the enablement state changes. The callback
278 // should accept one boolean argument, which will signal whether or not the
279 // metrics collection has been enabled.
280 base::CallbackListSubscription AddEnablementObserver(
281 const base::RepeatingCallback<void(bool)>& observer);
283 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
284 bool IsInForegroundForTesting() const { return is_in_foreground_; }
287 // Creates a new MetricsLog instance with the given |log_type|.
288 std::unique_ptr<MetricsLog> CreateLogForTesting(
289 MetricsLog::LogType log_type) {
290 return CreateLog(log_type);
294 // Sets the persistent system profile. Virtual for tests.
295 virtual void SetPersistentSystemProfile(const std::string& serialized_proto,
298 // Records the current environment (system profile) in |log|, and persists
299 // the results in prefs.
300 // Exposed for testing.
301 static std::string RecordCurrentEnvironmentHelper(
303 PrefService* local_state,
304 DelegatingProvider* delegating_provider);
306 // The MetricsService has a lifecycle that is stored as a state.
307 // See metrics_service.cc for description of this lifecycle.
309 CONSTRUCTED, // Constructor was called.
310 INITIALIZED, // InitializeMetricsRecordingState() was called.
311 INIT_TASK_SCHEDULED, // Waiting for deferred init tasks to finish.
312 INIT_TASK_DONE, // Waiting for timer to send initial log.
313 SENDING_LOGS, // Sending logs and creating new ones when we run out.
316 State state() const { return state_; }
319 // The current state of recording for the MetricsService. The state is UNSET
320 // until set to something else, at which point it remains INACTIVE or ACTIVE
321 // for the lifetime of the object.
322 enum RecordingState {
328 // The result of a call to FinalizeLog().
329 struct FinalizedLog {
333 // This type is move only.
334 FinalizedLog(FinalizedLog&& other);
335 FinalizedLog& operator=(FinalizedLog&& other);
337 // The size of the uncompressed log data. This is only used for calculating
339 size_t uncompressed_log_size;
341 // A LogInfo object representing the log, which contains its compressed
342 // data, hash, signature, timestamp, and some metadata.
343 std::unique_ptr<UnsentLogStore::LogInfo> log_info;
346 // Writes snapshots of histograms owned by the StatisticsRecorder to a log.
347 // Does not take ownership of the log.
348 // TODO(crbug/1423653): Although this class takes in |required_flags| in its
349 // constructor to filter the StatisticsRecorder histograms being put into
350 // the log, the |histogram_snapshot_manager_| is not aware of this. So if
351 // the |histogram_snapshot_manager_| is passed to some other caller, this
352 // caller will need to manually filter the histograms. Re-factor the code so
353 // that this is not needed.
354 class MetricsLogHistogramWriter {
356 explicit MetricsLogHistogramWriter(MetricsLog* log);
358 MetricsLogHistogramWriter(MetricsLog* log,
359 base::HistogramBase::Flags required_flags);
361 MetricsLogHistogramWriter(const MetricsLogHistogramWriter&) = delete;
362 MetricsLogHistogramWriter& operator=(const MetricsLogHistogramWriter&) =
365 ~MetricsLogHistogramWriter();
367 // Snapshots the deltas of histograms known by the StatisticsRecorder and
368 // writes them to the log passed in the constructor. This also marks the
369 // samples (the deltas) as logged.
370 void SnapshotStatisticsRecorderDeltas();
372 // Snapshots the unlogged samples of histograms known by the
373 // StatisticsRecorder and writes them to the log passed in the constructor.
374 // Note that unlike SnapshotStatisticsRecorderDeltas(), this does not mark
375 // the samples as logged. To do so, a call to MarkUnloggedSamplesAsLogged()
376 // (in |histogram_snapshot_manager_|) should be made.
377 void SnapshotStatisticsRecorderUnloggedSamples();
379 base::HistogramSnapshotManager* histogram_snapshot_manager() {
380 return histogram_snapshot_manager_.get();
383 base::StatisticsRecorder::SnapshotTransactionId snapshot_transaction_id() {
384 return snapshot_transaction_id_;
388 // Used to select which histograms to record when calling
389 // SnapshotStatisticsRecorderHistograms() or
390 // SnapshotStatisticsRecorderUnloggedSamples().
391 const base::HistogramBase::Flags required_flags_;
393 // Used to write histograms to the log passed in the constructor.
394 std::unique_ptr<base::HistogramFlattener> flattener_;
396 // Used to snapshot histograms.
397 std::unique_ptr<base::HistogramSnapshotManager> histogram_snapshot_manager_;
399 // The snapshot transaction ID of a call to either
400 // SnapshotStatisticsRecorderDeltas() or
401 // SnapshotStatisticsRecorderUnloggedSamples().
402 base::StatisticsRecorder::SnapshotTransactionId snapshot_transaction_id_;
405 // Loads "independent" metrics from a metrics provider and executes a
406 // callback when complete, which could be immediate or after some
407 // execution on a background thread.
408 class IndependentMetricsLoader {
410 explicit IndependentMetricsLoader(std::unique_ptr<MetricsLog> log,
411 std::string app_version,
412 std::string signing_key);
414 IndependentMetricsLoader(const IndependentMetricsLoader&) = delete;
415 IndependentMetricsLoader& operator=(const IndependentMetricsLoader&) =
418 ~IndependentMetricsLoader();
420 // Call ProvideIndependentMetrics (which may execute on a background thread)
421 // for the |metrics_provider| and execute the |done_callback| when complete
422 // with the result (true if successful). |done_callback| must own |this|.
423 void Run(base::OnceCallback<void(bool)> done_callback,
424 MetricsProvider* metrics_provider);
426 // Finalizes/serializes |log_|, and stores the result in |finalized_log_|.
427 // Should only be called once, after |log_| has been filled.
430 // Returns whether FinalizeLog() was called.
431 bool HasFinalizedLog();
433 // Extracts |finalized_log_|. Should be only called once, after
434 // FinalizeLog() has been called. No more operations should be done after
436 FinalizedLog ReleaseFinalizedLog();
439 std::unique_ptr<MetricsLog> log_;
440 std::unique_ptr<base::HistogramFlattener> flattener_;
441 std::unique_ptr<base::HistogramSnapshotManager> snapshot_manager_;
442 bool run_called_ = false;
444 // Used for finalizing |log_| in FinalizeLog().
445 const std::string app_version_;
446 const std::string signing_key_;
448 // Stores the result of FinalizeLog().
449 FinalizedLog finalized_log_;
450 bool finalize_log_called_ = false;
451 bool release_finalized_log_called_ = false;
454 // Gets the LogStore for UMA logs.
455 MetricsLogStore* log_store() {
456 return reporting_service_.metrics_log_store();
459 // Calls into the client to initialize some system profile metrics.
460 void StartInitTask();
462 // Callback that moves the state to INIT_TASK_DONE. When this is called, the
463 // state should be INIT_TASK_SCHEDULED.
464 void FinishedInitTask();
466 void OnUserAction(const std::string& action, base::TimeTicks action_time);
468 // Get the amount of uptime since this process started and since the last
469 // call to this function. Also updates the cumulative uptime metric (stored
470 // as a pref) for uninstall. Uptimes are measured using TimeTicks, which
471 // guarantees that it is monotonic and does not jump if the user changes
472 // their clock. The TimeTicks implementation also makes the clock not
473 // count time the computer is suspended.
474 void GetUptimes(PrefService* pref,
475 base::TimeDelta* incremental_uptime,
476 base::TimeDelta* uptime);
478 // Turns recording on or off.
479 // DisableRecording() also forces a persistent save of logging state (if
480 // anything has been recorded, or transmitted).
481 void EnableRecording();
482 void DisableRecording();
484 // If in_idle is true, sets idle_since_last_transmission to true.
485 // If in_idle is false and idle_since_last_transmission_ is true, sets
486 // idle_since_last_transmission to false and starts the timer (provided
487 // starting the timer is permitted).
488 void HandleIdleSinceLastTransmission(bool in_idle);
490 // Set up client ID, session ID, etc.
491 void InitializeMetricsState();
493 // Opens a new log for recording user experience metrics. If |call_providers|
494 // is true, OnDidCreateMetricsLog() of providers will be called right after
495 // opening the new log.
496 void OpenNewLog(bool call_providers = true);
498 // Closes out the current log after adding any last information. |async|
499 // determines whether finalizing the log will be done in a background thread.
500 // |log_stored_callback| will be run (on the main thread) after the finalized
501 // log is stored. Note that when |async| is true, the closed log could end up
502 // not being stored (see MaybeCleanUpAndStoreFinalizedLog()). Regardless,
503 // |log_stored_callback| is still run. Note that currently, there is only
504 // support to close one log asynchronously at a time (this should be enforced
506 void CloseCurrentLog(
508 MetricsLogsEventManager::CreateReason reason,
509 base::OnceClosure log_stored_callback = base::DoNothing());
511 // Stores the |finalized_log| in |log_store()|.
512 void StoreFinalizedLog(MetricsLog::LogType log_type,
513 MetricsLogsEventManager::CreateReason reason,
514 base::OnceClosure done_callback,
515 FinalizedLog finalized_log);
517 // Calls MarkUnloggedSamplesAsLogged() on |log_histogram_writer| and stores
518 // the |finalized_log| (see StoreFinalizedLog()), but only if the
519 // StatisticRecorder's last transaction ID is the same as the one from
520 // |log_histogram_writer| at the time of calling. See comments in the
521 // implementation for more details.
522 void MaybeCleanUpAndStoreFinalizedLog(
523 std::unique_ptr<MetricsLogHistogramWriter> log_histogram_writer,
524 MetricsLog::LogType log_type,
525 MetricsLogsEventManager::CreateReason reason,
526 base::OnceClosure done_callback,
527 FinalizedLog finalized_log);
529 // Pushes the text of the current and staged logs into persistent storage.
530 void PushPendingLogsToPersistentStorage(
531 MetricsLogsEventManager::CreateReason reason);
533 // Ensures that scheduler is running, assuming the current settings are such
534 // that metrics should be reported. If not, this is a no-op.
535 void StartSchedulerIfNecessary();
537 // Starts the process of uploading metrics data.
538 void StartScheduledUpload();
540 // Called by the client via a callback when final log info collection is
542 void OnFinalLogInfoCollectionDone();
544 // Called via a callback after a periodic ongoing log (created through the
545 // MetricsRotationScheduler) was stored in |log_store()|.
546 void OnAsyncPeriodicOngoingLogStored();
548 // Prepares the initial stability log, which is only logged when the previous
549 // run of Chrome crashed. This log contains any stability metrics left over
550 // from that previous run, and only these stability metrics. It uses the
551 // system profile from the previous session. |prefs_previous_version| is used
552 // to validate the version number recovered from the system profile. Returns
553 // true if a log was created.
554 bool PrepareInitialStabilityLog(const std::string& prefs_previous_version);
556 // Creates a new MetricsLog instance with the given |log_type|.
557 std::unique_ptr<MetricsLog> CreateLog(MetricsLog::LogType log_type);
559 // Records the current environment (system profile) in |log|, and persists
560 // the results in prefs and GlobalPersistentSystemProfile.
561 void RecordCurrentEnvironment(MetricsLog* log, bool complete);
563 // Handle completion of PrepareProviderMetricsLog which is run as a
565 void PrepareProviderMetricsLogDone(
566 std::unique_ptr<IndependentMetricsLoader> loader,
569 // Record a single independent profile and associated histogram from
570 // metrics providers. If this returns true, one was found and there may
572 bool PrepareProviderMetricsLog();
574 // Records one independent histogram log and then reschedules itself to
575 // check for others. The interval is so as to not adversely impact the UI.
576 void PrepareProviderMetricsTask();
578 // Updates the "last live" browser timestamp and schedules the next update.
579 void UpdateLastLiveTimestampTask();
581 // Returns whether it is too early to close a log.
582 bool IsTooEarlyToCloseLog();
584 // Called if this install is detected as cloned.
585 void OnClonedInstallDetected();
587 // Snapshots histogram deltas using the passed |log_histogram_writer| and then
588 // finalizes |log| by calling FinalizeLog(). |log|, |current_app_version| and
589 // |signing_key| are used to finalize the log (see FinalizeLog()).
590 // Semantically, this is equivalent to SnapshotUnloggedSamplesAndFinalizeLog()
591 // followed by MarkUnloggedSamplesAsLogged().
592 static FinalizedLog SnapshotDeltasAndFinalizeLog(
593 std::unique_ptr<MetricsLogHistogramWriter> log_histogram_writer,
594 std::unique_ptr<MetricsLog> log,
595 bool truncate_events,
596 absl::optional<ChromeUserMetricsExtension::RealLocalTime> close_time,
597 std::string&& current_app_version,
598 std::string&& signing_key);
600 // Snapshots unlogged histogram samples using the passed
601 // |log_histogram_writer| and then finalizes |log| by calling FinalizeLog().
602 // |log|, |current_app_version| and |signing_key| are used to finalize the log
603 // (see FinalizeLog()). Note that unlike SnapshotDeltasAndFinalizeLog(), this
604 // does not own the passed |log_histogram_writer|, because it should be
605 // available to eventually mark the unlogged samples as logged.
606 static FinalizedLog SnapshotUnloggedSamplesAndFinalizeLog(
607 MetricsLogHistogramWriter* log_histogram_writer,
608 std::unique_ptr<MetricsLog> log,
609 bool truncate_events,
610 absl::optional<ChromeUserMetricsExtension::RealLocalTime> close_time,
611 std::string&& current_app_version,
612 std::string&& signing_key);
614 // Finalizes |log| (see MetricsLog::FinalizeLog()). The |signing_key| is used
615 // to compute a signature for the log.
616 static FinalizedLog FinalizeLog(
617 std::unique_ptr<MetricsLog> log,
618 bool truncate_events,
619 absl::optional<ChromeUserMetricsExtension::RealLocalTime> close_time,
620 const std::string& current_app_version,
621 const std::string& signing_key);
623 // Sub-service for uploading logs.
624 MetricsReportingService reporting_service_;
626 // The log that we are still appending to.
627 std::unique_ptr<MetricsLog> current_log_;
629 // Used to manage various metrics reporting state prefs, such as client id,
630 // low entropy source and whether metrics reporting is enabled. Weak pointer.
631 const raw_ptr<MetricsStateManager> state_manager_;
633 // Used to interact with the embedder. Weak pointer; must outlive |this|
635 const raw_ptr<MetricsServiceClient> client_;
637 // Registered metrics providers.
638 DelegatingProvider delegating_provider_;
640 raw_ptr<PrefService> local_state_;
642 base::ActionCallback action_callback_;
644 // Indicate whether recording and reporting are currently happening.
645 // These should not be set directly, but by calling SetRecording and
647 RecordingState recording_state_;
649 // Indicate whether test mode is enabled, where the initial log should never
650 // be cut, and logs are neither persisted nor uploaded.
651 bool test_mode_active_;
653 // The progression of states made by the browser are recorded in the following
657 // Whether the MetricsService object has received any notifications since
658 // the last time a transmission was sent.
659 bool idle_since_last_transmission_;
661 // A number that identifies the how many times the app has been launched.
664 // The scheduler for determining when log rotations should happen.
665 std::unique_ptr<MetricsRotationScheduler> rotation_scheduler_;
667 // Stores the time of the first call to |GetUptimes()|.
668 base::TimeTicks first_updated_time_;
670 // Stores the time of the last call to |GetUptimes()|.
671 base::TimeTicks last_updated_time_;
673 // Indicates if loading of independent metrics is currently active.
674 bool independent_loader_active_ = false;
676 // Indicates whether or not there is currently a periodic ongoing log being
677 // finalized (or is scheduled to be finalized).
678 bool pending_ongoing_log_ = false;
680 // Stores the time when we last posted a task to finalize a periodic ongoing
681 // log asynchronously.
682 base::TimeTicks async_ongoing_log_posted_time_;
684 // Logs event manager to keep track of the various logs that the metrics
685 // service interacts with. An unowned pointer of this instance is passed down
686 // to various objects that are owned by this class.
687 MetricsLogsEventManager logs_event_manager_;
689 // An observer that observes all events notified through |logs_event_manager_|
690 // since the creation of this MetricsService instance. This is only created
691 // if this is a debug build, or the |kExportUmaLogsToFile| command line flag
692 // is passed. This is primarily used by the chrome://metrics-internals debug
694 std::unique_ptr<MetricsServiceObserver> logs_event_observer_;
696 // A set of observers that keeps track of the metrics reporting state.
697 base::RepeatingCallbackList<void(bool)> enablement_observers_;
699 // Subscription for a callback that runs if this install is detected as
701 base::CallbackListSubscription cloned_install_subscription_;
703 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
704 // Indicates whether OnAppEnterForeground() (true) or OnAppEnterBackground
705 // (false) was called.
706 bool is_in_foreground_ = false;
709 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, ActiveFieldTrialsReported);
710 FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, IsPluginProcess);
711 FRIEND_TEST_ALL_PREFIXES(::ChromeMetricsServiceClientTest,
712 TestRegisterMetricsServiceProviders);
713 FRIEND_TEST_ALL_PREFIXES(::IOSChromeMetricsServiceClientTest,
714 TestRegisterMetricsServiceProviders);
715 SEQUENCE_CHECKER(sequence_checker_);
717 // Weak pointers factory used to post task on different threads. All weak
718 // pointers managed by this factory have the same lifetime as MetricsService.
719 base::WeakPtrFactory<MetricsService> self_ptr_factory_{this};
722 } // namespace metrics
724 #endif // COMPONENTS_METRICS_METRICS_SERVICE_H_