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 #include "components/metrics/metrics_log.h"
6
7 #include <stddef.h>
8
9 #include <algorithm>
10 #include <cstring>
11 #include <string>
12
13 #include "base/build_time.h"
14 #include "base/command_line.h"
15 #include "base/cpu.h"
16 #include "base/logging.h"
17 #include "base/memory/raw_ptr.h"
18 #include "base/metrics/histogram_base.h"
19 #include "base/metrics/histogram_macros.h"
20 #include "base/metrics/histogram_samples.h"
21 #include "base/metrics/histogram_snapshot_manager.h"
22 #include "base/metrics/metrics_hashes.h"
23 #include "base/strings/string_piece.h"
24 #include "base/strings/string_util.h"
25 #include "base/system/sys_info.h"
26 #include "base/time/clock.h"
27 #include "base/time/default_clock.h"
28 #include "base/time/time.h"
29 #include "build/build_config.h"
30 #include "build/chromeos_buildflags.h"
31 #include "components/flags_ui/flags_ui_switches.h"
32 #include "components/metrics/delegating_provider.h"
33 #include "components/metrics/environment_recorder.h"
34 #include "components/metrics/histogram_encoder.h"
35 #include "components/metrics/metrics_pref_names.h"
36 #include "components/metrics/metrics_provider.h"
37 #include "components/metrics/metrics_service_client.h"
38 #include "components/network_time/network_time_tracker.h"
39 #include "components/prefs/pref_registry_simple.h"
40 #include "components/prefs/pref_service.h"
41 #include "components/variations/hashing.h"
42 #include "third_party/icu/source/i18n/unicode/timezone.h"
43 #include "third_party/metrics_proto/histogram_event.pb.h"
44 #include "third_party/metrics_proto/system_profile.pb.h"
45 #include "third_party/metrics_proto/user_action_event.pb.h"
46
47 #if BUILDFLAG(IS_ANDROID)
48 #include "base/android/build_info.h"
49 #endif
50
51 #if BUILDFLAG(IS_WIN)
52 #include <windows.h>
53 #include "base/win/current_module.h"
54 #endif
55
56 #if BUILDFLAG(IS_LINUX)
57 #include "base/environment.h"
58 #include "base/nix/xdg_util.h"
59 #endif
60
61 using base::SampleCountIterator;
62
63 namespace metrics {
64
LogMetadata()65 LogMetadata::LogMetadata()
66 : samples_count(absl::nullopt), user_id(absl::nullopt) {}
LogMetadata(const absl::optional<base::HistogramBase::Count> samples_count,const absl::optional<uint64_t> user_id,const absl::optional<metrics::UkmLogSourceType> log_source_type)67 LogMetadata::LogMetadata(
68 const absl::optional<base::HistogramBase::Count> samples_count,
69 const absl::optional<uint64_t> user_id,
70 const absl::optional<metrics::UkmLogSourceType> log_source_type)
71 : samples_count(samples_count),
72 user_id(user_id),
73 log_source_type(log_source_type) {}
74 LogMetadata::LogMetadata(const LogMetadata& other) = default;
75 LogMetadata::~LogMetadata() = default;
76
AddSampleCount(base::HistogramBase::Count sample_count)77 void LogMetadata::AddSampleCount(base::HistogramBase::Count sample_count) {
78 if (samples_count.has_value()) {
79 samples_count = samples_count.value() + sample_count;
80 } else {
81 samples_count = sample_count;
82 }
83 }
84
85 namespace {
86
87 // Convenience function to return the given time at a resolution in seconds.
ToMonotonicSeconds(base::TimeTicks time_ticks)88 static int64_t ToMonotonicSeconds(base::TimeTicks time_ticks) {
89 return (time_ticks - base::TimeTicks()).InSeconds();
90 }
91
92 // Helper function to get, and increment, the next metrics log record id.
93 // This value is cached in local state.
GetNextRecordId(PrefService * local_state)94 int GetNextRecordId(PrefService* local_state) {
95 const int value = local_state->GetInteger(prefs::kMetricsLogRecordId) + 1;
96 local_state->SetInteger(prefs::kMetricsLogRecordId, value);
97 return value;
98 }
99
100 // Populates |time| with information about the current time and, if
101 // |record_time_zone| is true, the time zone.
RecordCurrentTime(const base::Clock * clock,const network_time::NetworkTimeTracker * network_time_tracker,bool record_time_zone,metrics::ChromeUserMetricsExtension::RealLocalTime * time)102 void RecordCurrentTime(
103 const base::Clock* clock,
104 const network_time::NetworkTimeTracker* network_time_tracker,
105 bool record_time_zone,
106 metrics::ChromeUserMetricsExtension::RealLocalTime* time) {
107 // Record the current time and the clock used to determine the time.
108 base::Time now;
109 if (network_time_tracker != nullptr &&
110 network_time_tracker->GetNetworkTime(&now, nullptr) ==
111 network_time::NetworkTimeTracker::NETWORK_TIME_AVAILABLE) {
112 // |network_time_tracker| can be null in certain settings such as WebView
113 // (which doesn't run a NetworkTimeTracker) and tests.
114 time->set_time_source(
115 metrics::ChromeUserMetricsExtension::RealLocalTime::NETWORK_TIME_CLOCK);
116 } else {
117 now = clock->Now();
118 time->set_time_source(
119 metrics::ChromeUserMetricsExtension::RealLocalTime::CLIENT_CLOCK);
120 }
121 time->set_time_sec(now.ToTimeT());
122
123 if (record_time_zone) {
124 // Determine time zone offset from GMT and store it.
125 int32_t raw_offset, dst_offset;
126 UErrorCode status = U_ZERO_ERROR;
127 // Ask for a new time zone object each time; don't cache it, as time zones
128 // may change while Chrome is running.
129 std::unique_ptr<icu::TimeZone> time_zone(icu::TimeZone::createDefault());
130 time_zone->getOffset(now.InMillisecondsFSinceUnixEpoch(),
131 false, // interpret |now| as from UTC/GMT
132 raw_offset, dst_offset, status);
133 base::TimeDelta time_zone_offset =
134 base::Milliseconds(raw_offset + dst_offset);
135 if (U_FAILURE(status)) {
136 DVLOG(1) << "Failed to get time zone offset, error code: " << status;
137 // The fallback case is to get the raw timezone offset ignoring the
138 // daylight saving time.
139 time_zone_offset = base::Milliseconds(time_zone->getRawOffset());
140 }
141 time->set_time_zone_offset_from_gmt_sec(time_zone_offset.InSeconds());
142 }
143 }
144
145 #if BUILDFLAG(IS_LINUX)
ToProtoSessionType(base::nix::SessionType session_type)146 metrics::SystemProfileProto::OS::XdgSessionType ToProtoSessionType(
147 base::nix::SessionType session_type) {
148 switch (session_type) {
149 case base::nix::SessionType::kUnset:
150 return metrics::SystemProfileProto::OS::UNSET;
151 case base::nix::SessionType::kOther:
152 return metrics::SystemProfileProto::OS::OTHER_SESSION_TYPE;
153 case base::nix::SessionType::kUnspecified:
154 return metrics::SystemProfileProto::OS::UNSPECIFIED;
155 case base::nix::SessionType::kTty:
156 return metrics::SystemProfileProto::OS::TTY;
157 case base::nix::SessionType::kX11:
158 return metrics::SystemProfileProto::OS::X11;
159 case base::nix::SessionType::kWayland:
160 return metrics::SystemProfileProto::OS::WAYLAND;
161 case base::nix::SessionType::kMir:
162 return metrics::SystemProfileProto::OS::MIR;
163 }
164
165 NOTREACHED();
166 return metrics::SystemProfileProto::OS::UNSET;
167 }
168
ToProtoCurrentDesktop(base::nix::DesktopEnvironment desktop_environment)169 metrics::SystemProfileProto::OS::XdgCurrentDesktop ToProtoCurrentDesktop(
170 base::nix::DesktopEnvironment desktop_environment) {
171 switch (desktop_environment) {
172 case base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_OTHER:
173 return metrics::SystemProfileProto::OS::OTHER;
174 case base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_CINNAMON:
175 return metrics::SystemProfileProto::OS::CINNAMON;
176 case base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_DEEPIN:
177 return metrics::SystemProfileProto::OS::DEEPIN;
178 case base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_GNOME:
179 return metrics::SystemProfileProto::OS::GNOME;
180 case base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_KDE3:
181 case base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_KDE4:
182 case base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_KDE5:
183 case base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_KDE6:
184 return metrics::SystemProfileProto::OS::KDE;
185 case base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_PANTHEON:
186 return metrics::SystemProfileProto::OS::PANTHEON;
187 case base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_UKUI:
188 return metrics::SystemProfileProto::OS::UKUI;
189 case base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_UNITY:
190 return metrics::SystemProfileProto::OS::UNITY;
191 case base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_XFCE:
192 return metrics::SystemProfileProto::OS::XFCE;
193 case base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_LXQT:
194 return metrics::SystemProfileProto::OS::LXQT;
195 }
196
197 NOTREACHED();
198 return metrics::SystemProfileProto::OS::OTHER;
199 }
200 #endif // BUILDFLAG(IS_LINUX)
201
202 } // namespace
203
204 namespace internal {
205
ToInstallerPackage(base::StringPiece installer_package_name)206 SystemProfileProto::InstallerPackage ToInstallerPackage(
207 base::StringPiece installer_package_name) {
208 if (installer_package_name.empty())
209 return SystemProfileProto::INSTALLER_PACKAGE_NONE;
210 if (installer_package_name == "com.android.vending")
211 return SystemProfileProto::INSTALLER_PACKAGE_GOOGLE_PLAY_STORE;
212 return SystemProfileProto::INSTALLER_PACKAGE_OTHER;
213 }
214
215 } // namespace internal
216
MetricsLog(const std::string & client_id,int session_id,LogType log_type,MetricsServiceClient * client)217 MetricsLog::MetricsLog(const std::string& client_id,
218 int session_id,
219 LogType log_type,
220 MetricsServiceClient* client)
221 : MetricsLog(client_id,
222 session_id,
223 log_type,
224 base::DefaultClock::GetInstance(),
225 client->GetNetworkTimeTracker(),
226 client) {}
227
MetricsLog(const std::string & client_id,int session_id,LogType log_type,base::Clock * clock,const network_time::NetworkTimeTracker * network_clock,MetricsServiceClient * client)228 MetricsLog::MetricsLog(const std::string& client_id,
229 int session_id,
230 LogType log_type,
231 base::Clock* clock,
232 const network_time::NetworkTimeTracker* network_clock,
233 MetricsServiceClient* client)
234 : closed_(false),
235 log_type_(log_type),
236 client_(client),
237 creation_time_(base::TimeTicks::Now()),
238 has_environment_(false),
239 clock_(clock),
240 network_clock_(network_clock) {
241 uma_proto_.set_client_id(Hash(client_id));
242 uma_proto_.set_session_id(session_id);
243
244 if (log_type == MetricsLog::ONGOING_LOG) {
245 // Don't record the time when creating a log because creating a log happens
246 // on startups and setting the timezone requires ICU initialization that is
247 // too expensive to run during this critical time.
248 RecordCurrentTime(clock_, network_clock_,
249 /*record_time_zone=*/false,
250 uma_proto_.mutable_time_log_created());
251 }
252
253 const int32_t product = client_->GetProduct();
254 // Only set the product if it differs from the default value.
255 if (product != uma_proto_.product())
256 uma_proto_.set_product(product);
257
258 SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
259 // Record the unhashed the client_id to system profile. This is used to
260 // simulate field trial assignments for the client.
261 DCHECK_EQ(client_id.size(), 36ull);
262 system_profile->set_client_uuid(client_id);
263 RecordCoreSystemProfile(client_, system_profile);
264 }
265
266 MetricsLog::~MetricsLog() = default;
267
268 // static
RegisterPrefs(PrefRegistrySimple * registry)269 void MetricsLog::RegisterPrefs(PrefRegistrySimple* registry) {
270 EnvironmentRecorder::RegisterPrefs(registry);
271 registry->RegisterIntegerPref(prefs::kMetricsLogRecordId, 0);
272 }
273
274 // static
Hash(const std::string & value)275 uint64_t MetricsLog::Hash(const std::string& value) {
276 uint64_t hash = base::HashMetricName(value);
277
278 // The following log is VERY helpful when folks add some named histogram into
279 // the code, but forgot to update the descriptive list of histograms. When
280 // that happens, all we get to see (server side) is a hash of the histogram
281 // name. We can then use this logging to find out what histogram name was
282 // being hashed to a given MD5 value by just running the version of Chromium
283 // in question with --enable-logging.
284 DVLOG(1) << "Metrics: Hash numeric [" << value << "]=[" << hash << "]";
285
286 return hash;
287 }
288
289 // static
GetBuildTime()290 int64_t MetricsLog::GetBuildTime() {
291 static int64_t integral_build_time = 0;
292 if (!integral_build_time)
293 integral_build_time = static_cast<int64_t>(base::GetBuildTime().ToTimeT());
294 return integral_build_time;
295 }
296
297 // static
GetCurrentTime()298 int64_t MetricsLog::GetCurrentTime() {
299 return ToMonotonicSeconds(base::TimeTicks::Now());
300 }
301
AssignRecordId(PrefService * local_state)302 void MetricsLog::AssignRecordId(PrefService* local_state) {
303 DCHECK(!uma_proto_.has_record_id());
304 uma_proto_.set_record_id(GetNextRecordId(local_state));
305 }
306
RecordUserAction(const std::string & key,base::TimeTicks action_time)307 void MetricsLog::RecordUserAction(const std::string& key,
308 base::TimeTicks action_time) {
309 DCHECK(!closed_);
310
311 UserActionEventProto* user_action = uma_proto_.add_user_action_event();
312 user_action->set_name_hash(Hash(key));
313 user_action->set_time_sec(ToMonotonicSeconds(action_time));
314 UMA_HISTOGRAM_BOOLEAN("UMA.UserActionsCount", true);
315 }
316
317 // static
RecordCoreSystemProfile(MetricsServiceClient * client,SystemProfileProto * system_profile)318 void MetricsLog::RecordCoreSystemProfile(MetricsServiceClient* client,
319 SystemProfileProto* system_profile) {
320 RecordCoreSystemProfile(
321 client->GetVersionString(), client->GetChannel(),
322 client->IsExtendedStableChannel(), client->GetApplicationLocale(),
323 client->GetAppPackageNameIfLoggable(), system_profile);
324
325 std::string brand_code;
326 if (client->GetBrand(&brand_code))
327 system_profile->set_brand_code(brand_code);
328
329 // Records 32-bit hashes of the command line keys.
330 base::CommandLine command_line_copy(*base::CommandLine::ForCurrentProcess());
331
332 // Exclude these switches which are very frequently on the command line but
333 // serve no meaningful purpose.
334 static const char* const kSwitchesToFilter[] = {
335 switches::kFlagSwitchesBegin,
336 switches::kFlagSwitchesEnd,
337 };
338
339 for (const char* filter_switch : kSwitchesToFilter)
340 command_line_copy.RemoveSwitch(filter_switch);
341
342 for (const auto& command_line_switch : command_line_copy.GetSwitches()) {
343 system_profile->add_command_line_key_hash(
344 variations::HashName(command_line_switch.first));
345 }
346 }
347
348 // static
RecordCoreSystemProfile(const std::string & version,metrics::SystemProfileProto::Channel channel,bool is_extended_stable_channel,const std::string & application_locale,const std::string & package_name,SystemProfileProto * system_profile)349 void MetricsLog::RecordCoreSystemProfile(
350 const std::string& version,
351 metrics::SystemProfileProto::Channel channel,
352 bool is_extended_stable_channel,
353 const std::string& application_locale,
354 const std::string& package_name,
355 SystemProfileProto* system_profile) {
356 system_profile->set_build_timestamp(metrics::MetricsLog::GetBuildTime());
357 system_profile->set_app_version(version);
358 system_profile->set_channel(channel);
359 if (is_extended_stable_channel)
360 system_profile->set_is_extended_stable_channel(true);
361 system_profile->set_application_locale(application_locale);
362
363 #if defined(ADDRESS_SANITIZER) || DCHECK_IS_ON()
364 // Set if a build is instrumented (e.g. built with ASAN, or with DCHECKs).
365 system_profile->set_is_instrumented_build(true);
366 #endif
367
368 metrics::SystemProfileProto::Hardware* hardware =
369 system_profile->mutable_hardware();
370 hardware->set_cpu_architecture(base::SysInfo::OperatingSystemArchitecture());
371 auto app_os_arch = base::SysInfo::ProcessCPUArchitecture();
372 if (!app_os_arch.empty())
373 hardware->set_app_cpu_architecture(app_os_arch);
374 hardware->set_system_ram_mb(base::SysInfo::AmountOfPhysicalMemoryMB());
375 hardware->set_hardware_class(base::SysInfo::HardwareModelName());
376 #if BUILDFLAG(IS_WIN)
377 hardware->set_dll_base(reinterpret_cast<uint64_t>(CURRENT_MODULE()));
378 #endif
379
380 metrics::SystemProfileProto::OS* os = system_profile->mutable_os();
381 #if BUILDFLAG(IS_CHROMEOS_LACROS)
382 // The Lacros browser runs on Chrome OS, but reports a special OS name to
383 // differentiate itself from the built-in ash browser + window manager binary.
384 os->set_name("Lacros");
385 #elif BUILDFLAG(IS_CHROMEOS_ASH)
386 os->set_name("CrOS");
387 #else
388 os->set_name(base::SysInfo::OperatingSystemName());
389 #endif
390 os->set_version(base::SysInfo::OperatingSystemVersion());
391
392 // On ChromeOS, KernelVersion refers to the Linux kernel version and
393 // OperatingSystemVersion refers to the ChromeOS release version.
394 #if BUILDFLAG(IS_CHROMEOS_ASH)
395 os->set_kernel_version(base::SysInfo::KernelVersion());
396 #elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
397 // Linux operating system version is copied over into kernel version to be
398 // consistent.
399 os->set_kernel_version(base::SysInfo::OperatingSystemVersion());
400 #endif
401
402 #if BUILDFLAG(IS_ANDROID)
403 const auto* build_info = base::android::BuildInfo::GetInstance();
404 os->set_build_fingerprint(build_info->android_build_fp());
405 if (!package_name.empty() && package_name != "com.android.chrome")
406 system_profile->set_app_package_name(package_name);
407 system_profile->set_installer_package(
408 internal::ToInstallerPackage(build_info->installer_package_name()));
409 #elif BUILDFLAG(IS_IOS)
410 os->set_build_number(base::SysInfo::GetIOSBuildNumber());
411 #endif
412
413 #if BUILDFLAG(IS_LINUX)
414 std::unique_ptr<base::Environment> env = base::Environment::Create();
415 os->set_xdg_session_type(ToProtoSessionType(base::nix::GetSessionType(*env)));
416 os->set_xdg_current_desktop(
417 ToProtoCurrentDesktop(base::nix::GetDesktopEnvironment(env.get())));
418 #endif
419 }
420
RecordHistogramDelta(const std::string & histogram_name,const base::HistogramSamples & snapshot)421 void MetricsLog::RecordHistogramDelta(const std::string& histogram_name,
422 const base::HistogramSamples& snapshot) {
423 DCHECK(!closed_);
424 log_metadata_.AddSampleCount(snapshot.TotalCount());
425 EncodeHistogramDelta(histogram_name, snapshot, &uma_proto_);
426 }
427
RecordPreviousSessionData(DelegatingProvider * delegating_provider,PrefService * local_state)428 void MetricsLog::RecordPreviousSessionData(
429 DelegatingProvider* delegating_provider,
430 PrefService* local_state) {
431 delegating_provider->ProvidePreviousSessionData(uma_proto());
432 // Schedule a Local State write to flush updated prefs to disk. This is done
433 // because a side effect of providing data—namely stability data—is updating
434 // Local State prefs.
435 local_state->CommitPendingWrite();
436 }
437
RecordCurrentSessionData(base::TimeDelta incremental_uptime,base::TimeDelta uptime,DelegatingProvider * delegating_provider,PrefService * local_state)438 void MetricsLog::RecordCurrentSessionData(
439 base::TimeDelta incremental_uptime,
440 base::TimeDelta uptime,
441 DelegatingProvider* delegating_provider,
442 PrefService* local_state) {
443 DCHECK(!closed_);
444 DCHECK(has_environment_);
445
446 // Record recent delta for critical stability metrics. We can't wait for a
447 // restart to gather these, as that delay biases our observation away from
448 // users that run happily for a looooong time. We send increments with each
449 // UMA log upload, just as we send histogram data.
450 WriteRealtimeStabilityAttributes(incremental_uptime, uptime);
451
452 delegating_provider->ProvideCurrentSessionData(uma_proto());
453 // Schedule a Local State write to flush updated prefs to disk. This is done
454 // because a side effect of providing data—namely stability data—is updating
455 // Local State prefs.
456 local_state->CommitPendingWrite();
457 }
458
WriteMetricsEnableDefault(EnableMetricsDefault metrics_default,SystemProfileProto * system_profile)459 void MetricsLog::WriteMetricsEnableDefault(EnableMetricsDefault metrics_default,
460 SystemProfileProto* system_profile) {
461 if (client_->IsReportingPolicyManaged()) {
462 // If it's managed, then it must be reporting, otherwise we wouldn't be
463 // sending metrics.
464 system_profile->set_uma_default_state(
465 SystemProfileProto_UmaDefaultState_POLICY_FORCED_ENABLED);
466 return;
467 }
468
469 switch (metrics_default) {
470 case EnableMetricsDefault::DEFAULT_UNKNOWN:
471 // Don't set the field if it's unknown.
472 break;
473 case EnableMetricsDefault::OPT_IN:
474 system_profile->set_uma_default_state(
475 SystemProfileProto_UmaDefaultState_OPT_IN);
476 break;
477 case EnableMetricsDefault::OPT_OUT:
478 system_profile->set_uma_default_state(
479 SystemProfileProto_UmaDefaultState_OPT_OUT);
480 }
481 }
482
WriteRealtimeStabilityAttributes(base::TimeDelta incremental_uptime,base::TimeDelta uptime)483 void MetricsLog::WriteRealtimeStabilityAttributes(
484 base::TimeDelta incremental_uptime,
485 base::TimeDelta uptime) {
486 // Update the stats which are critical for real-time stability monitoring.
487 // Since these are "optional," only list ones that are non-zero, as the counts
488 // are aggregated (summed) server side.
489
490 SystemProfileProto::Stability* stability =
491 uma_proto()->mutable_system_profile()->mutable_stability();
492
493 const uint64_t incremental_uptime_sec = incremental_uptime.InSeconds();
494 if (incremental_uptime_sec)
495 stability->set_incremental_uptime_sec(incremental_uptime_sec);
496 const uint64_t uptime_sec = uptime.InSeconds();
497 if (uptime_sec)
498 stability->set_uptime_sec(uptime_sec);
499 }
500
RecordEnvironment(DelegatingProvider * delegating_provider)501 const SystemProfileProto& MetricsLog::RecordEnvironment(
502 DelegatingProvider* delegating_provider) {
503 // If |has_environment_| is true, then the system profile in |uma_proto_| has
504 // previously been fully filled in. We still want to fill it in again with
505 // more up to date information (e.g. current field trials), but in order to
506 // not have duplicate repeated fields, we must first clear it. Clearing it
507 // will reset the information filled in by RecordCoreSystemProfile() that was
508 // previously done in the constructor, so re-add that too.
509 //
510 // The |has_environment| case will happen on the very first log, where we
511 // call RecordEnvironment() in order to persist the system profile in the
512 // persistent histograms .pma file.
513 if (has_environment_) {
514 std::string client_uuid = uma_proto_.system_profile().client_uuid();
515 uma_proto_.clear_system_profile();
516 MetricsLog::RecordCoreSystemProfile(client_,
517 uma_proto_.mutable_system_profile());
518 uma_proto_.mutable_system_profile()->set_client_uuid(client_uuid);
519 }
520
521 has_environment_ = true;
522
523 SystemProfileProto* system_profile = uma_proto_.mutable_system_profile();
524 WriteMetricsEnableDefault(client_->GetMetricsReportingDefaultState(),
525 system_profile);
526
527 delegating_provider->ProvideSystemProfileMetricsWithLogCreationTime(
528 creation_time_, system_profile);
529
530 return *system_profile;
531 }
532
LoadSavedEnvironmentFromPrefs(PrefService * local_state)533 bool MetricsLog::LoadSavedEnvironmentFromPrefs(PrefService* local_state) {
534 DCHECK(!has_environment_);
535 has_environment_ = true;
536
537 SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
538 EnvironmentRecorder recorder(local_state);
539 return recorder.LoadEnvironmentFromPrefs(system_profile);
540 }
541
542 metrics::ChromeUserMetricsExtension::RealLocalTime
GetCurrentClockTime(bool record_time_zone)543 MetricsLog::GetCurrentClockTime(bool record_time_zone) {
544 CHECK_EQ(log_type_, MetricsLog::ONGOING_LOG);
545 metrics::ChromeUserMetricsExtension::RealLocalTime time;
546 RecordCurrentTime(clock_, network_clock_, record_time_zone, &time);
547 return time;
548 }
549
FinalizeLog(bool truncate_events,const std::string & current_app_version,absl::optional<ChromeUserMetricsExtension::RealLocalTime> close_time,std::string * encoded_log)550 void MetricsLog::FinalizeLog(
551 bool truncate_events,
552 const std::string& current_app_version,
553 absl::optional<ChromeUserMetricsExtension::RealLocalTime> close_time,
554 std::string* encoded_log) {
555 if (truncate_events)
556 TruncateEvents();
557 RecordLogWrittenByAppVersionIfNeeded(current_app_version);
558 if (close_time.has_value()) {
559 *uma_proto_.mutable_time_log_closed() = std::move(close_time.value());
560 }
561 CloseLog();
562
563 uma_proto_.SerializeToString(encoded_log);
564 }
565
CloseLog()566 void MetricsLog::CloseLog() {
567 DCHECK(!closed_);
568
569 // Ongoing logs (and only ongoing logs) should have a closed timestamp. Other
570 // types of logs (initial stability and independent) contain metrics from
571 // previous sessions, so do not add timestamps as they would not accurately
572 // represent the time at which those metrics were emitted.
573 CHECK(log_type_ == MetricsLog::ONGOING_LOG
574 ? uma_proto_.has_time_log_closed()
575 : !uma_proto_.has_time_log_closed());
576
577 closed_ = true;
578 }
579
RecordLogWrittenByAppVersionIfNeeded(const std::string & current_version)580 void MetricsLog::RecordLogWrittenByAppVersionIfNeeded(
581 const std::string& current_version) {
582 DCHECK(!closed_);
583 if (uma_proto()->system_profile().app_version() != current_version) {
584 uma_proto()->mutable_system_profile()->set_log_written_by_app_version(
585 current_version);
586 }
587 }
588
TruncateEvents()589 void MetricsLog::TruncateEvents() {
590 DCHECK(!closed_);
591 if (uma_proto_.user_action_event_size() > internal::kUserActionEventLimit) {
592 UMA_HISTOGRAM_COUNTS_100000("UMA.TruncatedEvents.UserAction",
593 uma_proto_.user_action_event_size());
594 for (int i = internal::kUserActionEventLimit;
595 i < uma_proto_.user_action_event_size(); ++i) {
596 // No histograms.xml entry is added for this histogram because it uses an
597 // enum that is generated from actions.xml in our processing pipelines.
598 // Instead, a histogram description will also be produced in our
599 // pipelines.
600 UMA_HISTOGRAM_SPARSE(
601 "UMA.TruncatedEvents.UserAction.Type",
602 // Truncate the unsigned 64-bit hash to 31 bits, to make it a suitable
603 // histogram sample.
604 uma_proto_.user_action_event(i).name_hash() & 0x7fffffff);
605 }
606 uma_proto_.mutable_user_action_event()->DeleteSubrange(
607 internal::kUserActionEventLimit,
608 uma_proto_.user_action_event_size() - internal::kUserActionEventLimit);
609 }
610
611 if (uma_proto_.omnibox_event_size() > internal::kOmniboxEventLimit) {
612 uma_proto_.mutable_omnibox_event()->DeleteSubrange(
613 internal::kOmniboxEventLimit,
614 uma_proto_.omnibox_event_size() - internal::kOmniboxEventLimit);
615 }
616 }
617
618 #if BUILDFLAG(IS_CHROMEOS_ASH)
SetUserId(const std::string & user_id)619 void MetricsLog::SetUserId(const std::string& user_id) {
620 uint64_t hashed_user_id = Hash(user_id);
621 uma_proto_.set_user_id(hashed_user_id);
622 log_metadata_.user_id = hashed_user_id;
623 }
624 #endif // BUILDFLAG(IS_CHROMEOS_ASH)
625
626 } // namespace metrics
627