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