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