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 #ifndef COMPONENTS_METRICS_METRICS_SERVICE_CLIENT_H_ 6 #define COMPONENTS_METRICS_METRICS_SERVICE_CLIENT_H_ 7 8 #include <stdint.h> 9 #include <memory> 10 #include <string> 11 12 #include "base/callback_list.h" 13 #include "base/functional/callback.h" 14 #include "base/metrics/field_trial_params.h" 15 #include "base/time/time.h" 16 #include "components/metrics/metrics_log_store.h" 17 #include "components/metrics/metrics_log_uploader.h" 18 #include "components/metrics/metrics_reporting_default_state.h" 19 #include "third_party/metrics_proto/system_profile.pb.h" 20 #include "url/gurl.h" 21 22 namespace ukm { 23 class UkmService; 24 } 25 26 namespace network_time { 27 class NetworkTimeTracker; 28 } 29 30 namespace variations { 31 class SyntheticTrialRegistry; 32 } 33 34 namespace metrics { 35 36 class MetricsLogUploader; 37 class MetricsService; 38 39 namespace structured { 40 class StructuredMetricsService; 41 } 42 43 // The minimum number bytes of the queue to be persisted before logs are 44 // dropped. This will be applied to both log queues (initial/ongoing). This 45 // ensures that a reasonable amount of history will be stored even if there is a 46 // long series of very small logs. 47 // 48 // Refer to //components/metrics/unsent_log_store.h for more details on when 49 // logs are dropped. 50 extern const base::FeatureParam<int> kMinLogQueueBytes; 51 52 // The minimum number of ongoing logs to persist in the queue before logs are 53 // dropped. 54 // 55 // Note that each ongoing log may be pretty large, since "initial" logs must 56 // first be sent before any ongoing logs are transmitted. "Initial" logs will 57 // not be sent if a user is offline. As a result, the current ongoing log will 58 // accumulate until the "initial" log can be transmitted. We don't want to save 59 // too many of these mega-logs (this should be capped by kMaxLogQueueBytes). 60 // 61 // A "standard shutdown" will create a small log, including just the data that 62 // was not yet been transmitted, and that is normal (to have exactly one 63 // ongoing_log_ at startup). 64 // 65 // Refer to //components/metrics/unsent_log_store.h for more details on when 66 // logs are dropped. 67 extern const base::FeatureParam<int> kMinOngoingLogQueueCount; 68 69 // An abstraction of operations that depend on the embedder's (e.g. Chrome) 70 // environment. 71 class MetricsServiceClient { 72 public: 73 MetricsServiceClient(); 74 75 MetricsServiceClient(const MetricsServiceClient&) = delete; 76 MetricsServiceClient& operator=(const MetricsServiceClient&) = delete; 77 78 virtual ~MetricsServiceClient(); 79 80 // Returns the synthetic trial registry shared by MetricsService and 81 // UkmService. 82 virtual variations::SyntheticTrialRegistry* GetSyntheticTrialRegistry() = 0; 83 84 // Returns the MetricsService instance that this client is associated with. 85 // With the exception of testing contexts, the returned instance must be valid 86 // for the lifetime of this object (typically, the embedder's client 87 // implementation will own the MetricsService instance being returned). 88 virtual MetricsService* GetMetricsService() = 0; 89 90 // Returns the UkmService instance that this client is associated with. 91 virtual ukm::UkmService* GetUkmService(); 92 93 // Returns the StructuredMetricsService instance that this client is 94 // associated with. 95 virtual structured::StructuredMetricsService* GetStructuredMetricsService(); 96 97 // Returns true if metrics should be uploaded for the given |user_id|, which 98 // corresponds to the |user_id| field in ChromeUserMetricsExtension. 99 virtual bool ShouldUploadMetricsForUserId(uint64_t user_id); 100 101 // Registers the client id with other services (e.g. crash reporting), called 102 // when metrics recording gets enabled. 103 virtual void SetMetricsClientId(const std::string& client_id) = 0; 104 105 // Returns the product value to use in uploaded reports, which will be used to 106 // set the ChromeUserMetricsExtension.product field. See comments on that 107 // field on why it's an int32_t rather than an enum. 108 virtual int32_t GetProduct() = 0; 109 110 // Returns the current application locale (e.g. "en-US"). 111 virtual std::string GetApplicationLocale() = 0; 112 113 // Return a NetworkTimeTracker for access to a server-provided clock. 114 virtual const network_time::NetworkTimeTracker* GetNetworkTimeTracker() = 0; 115 116 // Retrieves the brand code string associated with the install, returning 117 // false if no brand code is available. 118 virtual bool GetBrand(std::string* brand_code) = 0; 119 120 // Returns the release channel (e.g. stable, beta, etc) of the application. 121 virtual SystemProfileProto::Channel GetChannel() = 0; 122 123 // Returns true if the application is on the extended stable channel. 124 virtual bool IsExtendedStableChannel() = 0; 125 126 // Returns the version of the application as a string. 127 virtual std::string GetVersionString() = 0; 128 129 // Called by the metrics service when a new environment has been recorded. 130 // Takes the serialized environment as a parameter. The contents of 131 // |serialized_environment| are consumed by the call, but the caller maintains 132 // ownership. OnEnvironmentUpdate(std::string * serialized_environment)133 virtual void OnEnvironmentUpdate(std::string* serialized_environment) {} 134 135 // Collects child process histograms and merges them into StatisticsRecorder. 136 // Called when child process histograms need to be merged ASAP. For example, 137 // on Android, when the browser was backgrounded. MergeSubprocessHistograms()138 virtual void MergeSubprocessHistograms() {} 139 140 // Called prior to a metrics log being closed, allowing the client to collect 141 // extra histograms that will go in that log. Asynchronous API - the client 142 // implementation should call |done_callback| when complete. 143 virtual void CollectFinalMetricsForLog(base::OnceClosure done_callback) = 0; 144 145 // Get the URL of the metrics server. 146 virtual GURL GetMetricsServerUrl(); 147 148 // Get the fallback HTTP URL of the metrics server. 149 virtual GURL GetInsecureMetricsServerUrl(); 150 151 // Creates a MetricsLogUploader with the specified parameters (see comments on 152 // MetricsLogUploader for details). 153 virtual std::unique_ptr<MetricsLogUploader> CreateUploader( 154 const GURL& server_url, 155 const GURL& insecure_server_url, 156 base::StringPiece mime_type, 157 metrics::MetricsLogUploader::MetricServiceType service_type, 158 const MetricsLogUploader::UploadCallback& on_upload_complete) = 0; 159 160 // Returns the interval between upload attempts. Checks if debugging flags 161 // have been set, otherwise defaults to GetStandardUploadInterval(). 162 base::TimeDelta GetUploadInterval(); 163 164 // Returns the standard interval between upload attempts. 165 virtual base::TimeDelta GetStandardUploadInterval() = 0; 166 167 // Whether or not the MetricsService should start up quickly and upload the 168 // initial report quickly. By default, this work may be delayed by some 169 // amount. Only the default behavior should be used in production, but clients 170 // can override this in tests if tests need to make assertions on the log 171 // data. 172 virtual bool ShouldStartUpFastForTesting() const; 173 174 // Called when loading state changed, e.g. start/stop loading. LoadingStateChanged(bool is_loading)175 virtual void LoadingStateChanged(bool is_loading) {} 176 177 // Returns whether metrics reporting is managed by policy. 178 virtual bool IsReportingPolicyManaged(); 179 180 // Gets information about the default value for the metrics reporting checkbox 181 // shown during first-run. 182 virtual EnableMetricsDefault GetMetricsReportingDefaultState(); 183 184 // Return true iff the system is currently on a cellular connection. 185 virtual bool IsOnCellularConnection(); 186 187 // Returns whether the allowlist for external experiment ids is enabled. Some 188 // embedders like WebLayer disable it. For Chrome, it should be enabled. 189 virtual bool IsExternalExperimentAllowlistEnabled(); 190 191 // Returns true iff UKM is allowed for all profiles. 192 // See //components/ukm/observers/ukm_consent_state_observer.h for details. 193 virtual bool IsUkmAllowedForAllProfiles(); 194 195 // Returns whether UKM notification listeners were attached to all profiles. 196 virtual bool AreNotificationListenersEnabledOnAllProfiles(); 197 198 // Gets the app package name (as defined by the embedder). Since package name 199 // is only meaningful for Android, other platforms should return the empty 200 // string (this is the same as the default behavior). If the package name 201 // should not be logged for privacy/fingerprintability reasons, the embedder 202 // should return the empty string. 203 virtual std::string GetAppPackageNameIfLoggable(); 204 205 // Gets the key used to sign metrics uploads. This will be used to compute an 206 // HMAC-SHA256 signature of an uploaded log. 207 virtual std::string GetUploadSigningKey(); 208 209 // Checks if the cloned install detector says that client ids should be reset. 210 virtual bool ShouldResetClientIdsOnClonedInstall(); 211 212 virtual base::CallbackListSubscription AddOnClonedInstallDetectedCallback( 213 base::OnceClosure callback); 214 215 // Specifies local log storage requirements and restrictions. 216 virtual MetricsLogStore::StorageLimits GetStorageLimits() const; 217 218 // Sets the callback to run MetricsServiceManager::UpdateRunningServices. 219 void SetUpdateRunningServicesCallback(const base::RepeatingClosure& callback); 220 221 // Notify MetricsServiceManager to UpdateRunningServices using callback. 222 void UpdateRunningServices(); 223 224 // Checks if the user has forced metrics collection on via the override flag. 225 bool IsMetricsReportingForceEnabled() const; 226 227 // Initializes per-user metrics collection. For more details what per-user 228 // metrics collection is, refer to MetricsService::InitPerUserMetrics. 229 // 230 // Since the concept of a user is only applicable in Ash Chrome, this function 231 // should no-op for other platforms. InitPerUserMetrics()232 virtual void InitPerUserMetrics() {} 233 234 // Updates the current user's metrics consent. This allows embedders to update 235 // the user consent. If there is no current user, then this function will 236 // no-op. 237 // 238 // Since the concept of a user is only applicable on Ash Chrome, this function 239 // should no-op for other platforms. UpdateCurrentUserMetricsConsent(bool user_metrics_consent)240 virtual void UpdateCurrentUserMetricsConsent(bool user_metrics_consent) {} 241 242 // Returns the current user metrics consent if it should be applied to decide 243 // the current metrics reporting state. This allows embedders to determine 244 // when a user metric consent state should not be applied (ie no logged in 245 // user or managed policy). 246 // 247 // Will return absl::nullopt if there is no current user or current user 248 // metrics consent should not be applied to determine metrics reporting state. 249 // 250 // Not all platforms support per-user consent. If per-user consent is not 251 // supported, this function should return absl::nullopt. 252 virtual absl::optional<bool> GetCurrentUserMetricsConsent() const; 253 254 // Returns the current user id. 255 // 256 // Will return absl::nullopt if there is no current user, metrics reporting is 257 // disabled, or current user should not have a user id. 258 // 259 // Not all platforms support per-user consent. If per-user consent is not 260 // supported, this function should return absl::nullopt. 261 virtual absl::optional<std::string> GetCurrentUserId() const; 262 263 private: 264 base::RepeatingClosure update_running_services_; 265 }; 266 267 } // namespace metrics 268 269 #endif // COMPONENTS_METRICS_METRICS_SERVICE_CLIENT_H_ 270