• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 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 sends metrics logs to a server.
6 
7 #ifndef COMPONENTS_METRICS_REPORTING_SERVICE_H_
8 #define COMPONENTS_METRICS_REPORTING_SERVICE_H_
9 
10 #include <stdint.h>
11 
12 #include <string>
13 #include <string_view>
14 
15 #include "base/memory/raw_ptr.h"
16 #include "base/time/time.h"
17 #include "build/build_config.h"
18 #include "components/metrics/data_use_tracker.h"
19 #include "components/metrics/metrics_log_uploader.h"
20 #include "components/metrics/metrics_logs_event_manager.h"
21 #include "third_party/metrics_proto/reporting_info.pb.h"
22 #include "url/gurl.h"
23 
24 class PrefService;
25 class PrefRegistrySimple;
26 
27 namespace metrics {
28 
29 class LogStore;
30 class MetricsUploadScheduler;
31 class MetricsServiceClient;
32 
33 // ReportingService is an abstract class which uploads serialized logs from a
34 // LogStore to a remote server. A concrete implementation of this class must
35 // provide the specific LogStore and parameters for the MetricsLogUploader, and
36 // can also implement hooks to record histograms based on certain events that
37 // occur while attempting to upload logs.
38 class ReportingService {
39  public:
40   // Creates a ReportingService with the given |client|, |local_state|,
41   // |max_retransmit_size|, and |logs_event_manager|. Does not take ownership
42   // of the parameters; instead it stores a weak pointer to each. Caller should
43   // ensure that the parameters are valid for the lifetime of this class.
44   // |logs_event_manager| is used to notify observers of log events. Can be set
45   // to null if observing the events is not necessary.
46   ReportingService(MetricsServiceClient* client,
47                    PrefService* local_state,
48                    size_t max_retransmit_size,
49                    MetricsLogsEventManager* logs_event_manager);
50 
51   ReportingService(const ReportingService&) = delete;
52   ReportingService& operator=(const ReportingService&) = delete;
53 
54   virtual ~ReportingService();
55 
56   // Completes setup tasks that can't be done at construction time.
57   // Loads persisted logs and creates the MetricsUploadScheduler.
58   void Initialize();
59 
60   // Starts the metrics reporting system.
61   // Should be called when metrics enabled or new logs are created.
62   // When the service is already running, this is a safe no-op.
63   void Start();
64 
65   // Shuts down the metrics system. Should be called at shutdown, or if metrics
66   // are turned off.
67   void Stop();
68 
69   // Enable/disable transmission of accumulated logs and crash reports (dumps).
70   // Calling Start() automatically enables reporting, but sending is
71   // asyncronous so this can be called immediately after Start() to prevent
72   // any uploading.
73   void EnableReporting();
74   void DisableReporting();
75 
76   // True iff reporting is currently enabled.
77   bool reporting_active() const;
78 
79 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
SetIsInForegound(bool is_in_foreground)80   void SetIsInForegound(bool is_in_foreground) {
81     is_in_foreground_ = is_in_foreground;
82   }
83 #endif  // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
84 
85   // Registers local state prefs used by this class. This should only be called
86   // once.
87   static void RegisterPrefs(PrefRegistrySimple* registry);
88 
89  protected:
client()90   MetricsServiceClient* client() const { return client_; }
91 
92  private:
93   // Retrieves the log store backing this service.
94   virtual LogStore* log_store() = 0;
95 
96   // Getters for MetricsLogUploader parameters.
97   virtual GURL GetUploadUrl() const = 0;
98   virtual GURL GetInsecureUploadUrl() const = 0;
99   virtual std::string_view upload_mime_type() const = 0;
100   virtual MetricsLogUploader::MetricServiceType service_type() const = 0;
101 
102   // Methods for recording data to histograms.
LogActualUploadInterval(base::TimeDelta interval)103   virtual void LogActualUploadInterval(base::TimeDelta interval) {}
LogCellularConstraint(bool upload_canceled)104   virtual void LogCellularConstraint(bool upload_canceled) {}
LogResponseOrErrorCode(int response_code,int error_code,bool was_https)105   virtual void LogResponseOrErrorCode(int response_code,
106                                       int error_code,
107                                       bool was_https) {}
LogSuccessLogSize(size_t log_size)108   virtual void LogSuccessLogSize(size_t log_size) {}
LogSuccessMetadata(const std::string & staged_log)109   virtual void LogSuccessMetadata(const std::string& staged_log) {}
LogLargeRejection(size_t log_size)110   virtual void LogLargeRejection(size_t log_size) {}
111 
112   // If recording is enabled, begins uploading the next completed log from
113   // the log manager, staging it if necessary.
114   void SendNextLog();
115 
116   // Uploads the currently staged log (which must be non-null).
117   void SendStagedLog();
118 
119   // Called after transmission completes (either successfully or with failure).
120   // If |force_discard| is true, discard the log regardless of the response or
121   // error code. For example, this is used for builds that do not include any
122   // metrics server URLs (no reason to keep re-sending to a non-existent URL).
123   void OnLogUploadComplete(int response_code,
124                            int error_code,
125                            bool was_https,
126                            bool force_discard,
127                            std::string_view force_discard_reason);
128 
129   // Used to interact with the embedder. Weak pointer; must outlive |this|
130   // instance.
131   const raw_ptr<MetricsServiceClient> client_;
132 
133   // Used to flush changes to disk after uploading a log. Weak pointer; must
134   // outlive |this| instance.
135   const raw_ptr<PrefService> local_state_;
136 
137   // Largest log size to attempt to retransmit.
138   size_t max_retransmit_size_;
139 
140   // Event manager to notify observers of log events.
141   const raw_ptr<MetricsLogsEventManager> logs_event_manager_;
142 
143   // Indicate whether recording and reporting are currently happening.
144   // These should not be set directly, but by calling SetRecording and
145   // SetReporting.
146   bool reporting_active_;
147 
148   // Instance of the helper class for uploading logs.
149   std::unique_ptr<MetricsLogUploader> log_uploader_;
150 
151   // Whether there is a current log upload in progress.
152   bool log_upload_in_progress_;
153 
154   // The scheduler for determining when uploads should happen.
155   std::unique_ptr<MetricsUploadScheduler> upload_scheduler_;
156 
157   // Pointer used for obtaining data use pref updater callback on above layers.
158   std::unique_ptr<DataUseTracker> data_use_tracker_;
159 
160   // The tick count of the last time log upload has been finished and null if no
161   // upload has been done yet.
162   base::TimeTicks last_upload_finish_time_;
163 
164   // Info on current reporting state to send along with reports.
165   ReportingInfo reporting_info_;
166 
167 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
168   // Indicates whether the browser is currently in the foreground. Used to
169   // determine whether |local_state_| should be flushed immediately after
170   // uploading a log.
171   bool is_in_foreground_ = false;
172 #endif  // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
173 
174   SEQUENCE_CHECKER(sequence_checker_);
175 
176   // Weak pointers factory used to post task on different threads. All weak
177   // pointers managed by this factory have the same lifetime as
178   // ReportingService.
179   base::WeakPtrFactory<ReportingService> self_ptr_factory_{this};
180 };
181 
182 }  // namespace metrics
183 
184 #endif  // COMPONENTS_METRICS_REPORTING_SERVICE_H_
185