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