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