1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
|
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/metrics/dwa/dwa_service.h"
#include <memory>
#include <string>
#include <string_view>
#include "base/containers/fixed_flat_set.h"
#include "base/i18n/timezone.h"
#include "base/rand_util.h"
#include "base/strings/string_util.h"
#include "base/version.h"
#include "components/metrics/dwa/dwa_pref_names.h"
#include "components/metrics/dwa/dwa_rotation_scheduler.h"
#include "components/metrics/metrics_log.h"
#include "components/metrics/metrics_pref_names.h"
#include "components/prefs/pref_service.h"
#include "components/version_info/version_info.h"
namespace metrics::dwa {
// Set of countries in the European Economic Area. Used by
// RecordCoarseSystemInformation to set geo_designation fields in
// CoarseSystemInfo. These will need to be manually updated using
// "IsEuropeanEconomicArea" from go/source/user_preference_country.impl.gcl.
constexpr auto kEuropeanEconomicAreaCountries =
base::MakeFixedFlatSet<std::string_view>({
"at", // Austria
"be", // Belgium
"bg", // Bulgaria
"hr", // Croatia
"cy", // Cyprus
"cz", // Czech Republic
"dk", // Denmark
"ee", // Estonia
"fi", // Finland
"fr", // France
"de", // Germany
"gr", // Greece
"hu", // Hungary
"is", // Iceland
"ie", // Ireland
"it", // Italy
"lv", // Latvia
"li", // Liechtenstein
"lt", // Lithuania
"lu", // Luxembourg
"mt", // Malta
"nl", // Netherlands
"no", // Norway
"pl", // Poland
"pt", // Portugal
"ro", // Romania
"sk", // Slovakia
"si", // Slovenia
"es", // Spain
"se", // Sweden
"uk", // United Kingdom
});
// One week or seven days represented in base::TimeDelta.
const base::TimeDelta kOneWeek = base::Days(7);
const size_t kMinLogQueueCount = 10;
const size_t kMinLogQueueSizeBytes = 300 * 1024; // 300 KiB
const size_t kMaxLogSizeBytes = 1024 * 1024; // 1 MiB
DwaService::DwaService(MetricsServiceClient* client, PrefService* local_state)
: recorder_(DwaRecorder::Get()),
client_(client),
pref_service_(local_state),
reporting_service_(client, local_state, GetLogStoreLimits()) {
reporting_service_.Initialize();
// Set up the scheduler for DwaService.
auto rotate_callback = base::BindRepeating(&DwaService::RotateLog,
self_ptr_factory_.GetWeakPtr());
auto get_upload_interval_callback =
base::BindRepeating(&metrics::MetricsServiceClient::GetUploadInterval,
base::Unretained(client_));
bool fast_startup = client_->ShouldStartUpFast();
scheduler_ = std::make_unique<DwaRotationScheduler>(
rotate_callback, get_upload_interval_callback, fast_startup);
scheduler_->InitTaskComplete();
}
DwaService::~DwaService() {
recorder_->DisableRecording();
DisableReporting();
}
void DwaService::EnableReporting() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (reporting_service_.reporting_active()) {
return;
}
scheduler_->Start();
reporting_service_.EnableReporting();
// Attempt to upload if there are unsent logs.
if (reporting_service_.unsent_log_store()->has_unsent_logs()) {
reporting_service_.Start();
}
}
void DwaService::DisableReporting() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
reporting_service_.DisableReporting();
scheduler_->Stop();
Flush(metrics::MetricsLogsEventManager::CreateReason::kServiceShutdown);
}
void DwaService::Flush(metrics::MetricsLogsEventManager::CreateReason reason) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// The log should not be built if there aren't any events to log.
if (!recorder_->HasPageLoadEvents()) {
return;
}
BuildAndStoreLog(reason);
reporting_service_.unsent_log_store()->TrimAndPersistUnsentLogs(true);
}
void DwaService::Purge() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
recorder_->Purge();
reporting_service_.unsent_log_store()->Purge();
}
// static
UnsentLogStore::UnsentLogStoreLimits DwaService::GetLogStoreLimits() {
return UnsentLogStore::UnsentLogStoreLimits{
.min_log_count = kMinLogQueueCount,
.min_queue_size_bytes = kMinLogQueueSizeBytes,
.max_log_size_bytes = kMaxLogSizeBytes,
};
}
// static
void DwaService::RecordCoarseSystemInformation(
MetricsServiceClient& client,
const PrefService& local_state,
::dwa::CoarseSystemInfo* coarse_system_info) {
switch (client.GetChannel()) {
case SystemProfileProto::CHANNEL_STABLE:
coarse_system_info->set_channel(::dwa::CoarseSystemInfo::CHANNEL_STABLE);
break;
case SystemProfileProto::CHANNEL_CANARY:
case SystemProfileProto::CHANNEL_DEV:
case SystemProfileProto::CHANNEL_BETA:
coarse_system_info->set_channel(
::dwa::CoarseSystemInfo::CHANNEL_NOT_STABLE);
break;
case SystemProfileProto::CHANNEL_UNKNOWN:
coarse_system_info->set_channel(::dwa::CoarseSystemInfo::CHANNEL_INVALID);
break;
}
#if BUILDFLAG(IS_WIN)
coarse_system_info->set_platform(::dwa::CoarseSystemInfo::PLATFORM_WINDOWS);
#elif BUILDFLAG(IS_MAC)
coarse_system_info->set_platform(::dwa::CoarseSystemInfo::PLATFORM_MACOS);
#elif BUILDFLAG(IS_LINUX)
coarse_system_info->set_platform(::dwa::CoarseSystemInfo::PLATFORM_LINUX);
#elif BUILDFLAG(IS_ANDROID)
// TODO(b/366276323): Populate set_platform using more granular
// PLATFORM_ANDROID enum.
coarse_system_info->set_platform(::dwa::CoarseSystemInfo::PLATFORM_ANDROID);
#elif BUILDFLAG(IS_IOS)
coarse_system_info->set_platform(::dwa::CoarseSystemInfo::PLATFORM_IOS);
#elif BUILDFLAG(IS_CHROMEOS)
coarse_system_info->set_platform(::dwa::CoarseSystemInfo::PLATFORM_CHROMEOS);
#else
coarse_system_info->set_platform(::dwa::CoarseSystemInfo::PLATFORM_OTHER);
#endif
std::string country =
base::ToLowerASCII(base::CountryCodeForCurrentTimezone());
if (country == "") {
coarse_system_info->set_geo_designation(
::dwa::CoarseSystemInfo::GEO_DESIGNATION_INVALID);
} else if (kEuropeanEconomicAreaCountries.contains(country)) {
coarse_system_info->set_geo_designation(
::dwa::CoarseSystemInfo::GEO_DESIGNATION_EEA);
} else {
// GEO_DESIGNATION_ROW is the geo designation for "rest of the world".
coarse_system_info->set_geo_designation(
::dwa::CoarseSystemInfo::GEO_DESIGNATION_ROW);
}
base::TimeDelta time_since_install =
base::Time::Now() -
base::Time::FromTimeT(local_state.GetInt64(metrics::prefs::kInstallDate));
coarse_system_info->set_client_age(
time_since_install < kOneWeek
? ::dwa::CoarseSystemInfo::CLIENT_AGE_RECENT
: ::dwa::CoarseSystemInfo::CLIENT_AGE_NOT_RECENT);
// GetVersion() returns base::Version, which represents a dotted version
// number, like "1.2.3.4". We %16 in milestone_prefix_trimmed because it is
// required by the DWA proto in
// //third_party/metrics_proto/dwa/deidentified_web_analytics.proto.
int milestone = version_info::GetVersion().components()[0];
coarse_system_info->set_milestone_prefix_trimmed(milestone % 16);
coarse_system_info->set_is_ukm_enabled(client.IsUkmAllowedForAllProfiles());
}
// static
uint64_t DwaService::GetEphemeralClientId(PrefService& local_state) {
// We want to update the client id once a day (measured in UTC), so our date
// should only contain information up to day level.
base::Time now_day_level = base::Time::Now().UTCMidnight();
uint64_t client_id = local_state.GetUint64(prefs::kDwaClientId);
if (local_state.GetTime(prefs::kDwaClientIdLastUpdated) != now_day_level ||
client_id == 0u) {
client_id = 0u;
while (!client_id) {
client_id = base::RandUint64();
}
local_state.SetUint64(prefs::kDwaClientId, client_id);
local_state.SetTime(prefs::kDwaClientIdLastUpdated, now_day_level);
}
return client_id;
}
void DwaService::RotateLog() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!reporting_service_.unsent_log_store()->has_unsent_logs()) {
BuildAndStoreLog(metrics::MetricsLogsEventManager::CreateReason::kPeriodic);
}
reporting_service_.Start();
scheduler_->RotationFinished();
}
void DwaService::BuildAndStoreLog(
metrics::MetricsLogsEventManager::CreateReason reason) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// There are no new page load events, so no new logs should be created.
if (!recorder_->HasPageLoadEvents()) {
return;
}
::dwa::DeidentifiedWebAnalyticsReport report;
RecordCoarseSystemInformation(*client_, *pref_service_,
report.mutable_coarse_system_info());
report.set_dwa_ephemeral_id(GetEphemeralClientId(*pref_service_));
std::vector<::dwa::PageLoadEvents> page_load_events =
recorder_->TakePageLoadEvents();
report.mutable_page_load_events()->Add(
std::make_move_iterator(page_load_events.begin()),
std::make_move_iterator(page_load_events.end()));
report.set_timestamp(MetricsLog::GetCurrentTime());
std::string serialized_log;
report.SerializeToString(&serialized_log);
LogMetadata metadata;
reporting_service_.unsent_log_store()->StoreLog(serialized_log, metadata,
reason);
}
// static
void DwaService::RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterUint64Pref(prefs::kDwaClientId, 0u);
registry->RegisterTimePref(prefs::kDwaClientIdLastUpdated, base::Time());
DwaReportingService::RegisterPrefs(registry);
}
metrics::UnsentLogStore* DwaService::unsent_log_store() {
return reporting_service_.unsent_log_store();
}
} // namespace metrics::dwa
|