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