1 // Copyright 2014 The Chromium Authors. All rights reserved.
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 <string>
11 
12 #include "base/build_time.h"
13 #include "base/cpu.h"
14 #include "base/logging.h"
15 #include "base/metrics/histogram_base.h"
16 #include "base/metrics/histogram_flattener.h"
17 #include "base/metrics/histogram_functions.h"
18 #include "base/metrics/histogram_macros.h"
19 #include "base/metrics/histogram_samples.h"
20 #include "base/metrics/histogram_snapshot_manager.h"
21 #include "base/metrics/metrics_hashes.h"
22 #include "base/strings/string_piece.h"
23 #include "base/strings/stringprintf.h"
24 #include "base/system/sys_info.h"
25 #include "base/time/time.h"
26 #include "build/build_config.h"
27 #include "build/chromeos_buildflags.h"
28 #include "components/metrics/delegating_provider.h"
29 #include "components/metrics/environment_recorder.h"
30 #include "components/metrics/histogram_encoder.h"
31 #include "components/metrics/metrics_pref_names.h"
32 #include "components/metrics/metrics_provider.h"
33 #include "components/metrics/metrics_service_client.h"
34 #include "components/prefs/pref_registry_simple.h"
35 #include "components/prefs/pref_service.h"
36 #include "third_party/metrics_proto/histogram_event.pb.h"
37 #include "third_party/metrics_proto/system_profile.pb.h"
38 #include "third_party/metrics_proto/user_action_event.pb.h"
39 
40 #if defined(OS_ANDROID)
41 #include "base/android/build_info.h"
42 #endif
43 
44 #if defined(OS_WIN)
45 #include <windows.h>
46 #include "base/win/current_module.h"
47 #endif
48 
49 using base::SampleCountIterator;
50 
51 namespace metrics {
52 
53 namespace {
54 
55 // A simple class to write histogram data to a log.
56 class IndependentFlattener : public base::HistogramFlattener {
57  public:
IndependentFlattener(MetricsLog * log)58   explicit IndependentFlattener(MetricsLog* log) : log_(log) {}
~IndependentFlattener()59   ~IndependentFlattener() override {}
60 
61   // base::HistogramFlattener:
RecordDelta(const base::HistogramBase & histogram,const base::HistogramSamples & snapshot)62   void RecordDelta(const base::HistogramBase& histogram,
63                    const base::HistogramSamples& snapshot) override {
64     log_->RecordHistogramDelta(histogram.histogram_name(), snapshot);
65   }
66 
67  private:
68   MetricsLog* const log_;
69 
70   DISALLOW_COPY_AND_ASSIGN(IndependentFlattener);
71 };
72 
73 // Convenience function to return the given time at a resolution in seconds.
ToMonotonicSeconds(base::TimeTicks time_ticks)74 static int64_t ToMonotonicSeconds(base::TimeTicks time_ticks) {
75   return (time_ticks - base::TimeTicks()).InSeconds();
76 }
77 
78 }  // namespace
79 
80 namespace internal {
81 
ToInstallerPackage(base::StringPiece installer_package_name)82 SystemProfileProto::InstallerPackage ToInstallerPackage(
83     base::StringPiece installer_package_name) {
84   if (installer_package_name.empty())
85     return SystemProfileProto::INSTALLER_PACKAGE_NONE;
86   if (installer_package_name == "com.android.vending")
87     return SystemProfileProto::INSTALLER_PACKAGE_GOOGLE_PLAY_STORE;
88   return SystemProfileProto::INSTALLER_PACKAGE_OTHER;
89 }
90 
91 }  // namespace internal
92 
IndependentMetricsLoader(std::unique_ptr<MetricsLog> log)93 MetricsLog::IndependentMetricsLoader::IndependentMetricsLoader(
94     std::unique_ptr<MetricsLog> log)
95     : log_(std::move(log)),
96       flattener_(new IndependentFlattener(log_.get())),
97       snapshot_manager_(new base::HistogramSnapshotManager(flattener_.get())) {}
98 
99 MetricsLog::IndependentMetricsLoader::~IndependentMetricsLoader() = default;
100 
Run(base::OnceCallback<void (bool)> done_callback,MetricsProvider * metrics_provider)101 void MetricsLog::IndependentMetricsLoader::Run(
102     base::OnceCallback<void(bool)> done_callback,
103     MetricsProvider* metrics_provider) {
104   metrics_provider->ProvideIndependentMetrics(
105       std::move(done_callback), log_->uma_proto(), snapshot_manager_.get());
106 }
107 
ReleaseLog()108 std::unique_ptr<MetricsLog> MetricsLog::IndependentMetricsLoader::ReleaseLog() {
109   return std::move(log_);
110 }
111 
MetricsLog(const std::string & client_id,int session_id,LogType log_type,MetricsServiceClient * client)112 MetricsLog::MetricsLog(const std::string& client_id,
113                        int session_id,
114                        LogType log_type,
115                        MetricsServiceClient* client)
116     : closed_(false),
117       log_type_(log_type),
118       client_(client),
119       creation_time_(base::TimeTicks::Now()),
120       has_environment_(false) {
121   uma_proto_.set_client_id(Hash(client_id));
122   uma_proto_.set_session_id(session_id);
123 
124   const int32_t product = client_->GetProduct();
125   // Only set the product if it differs from the default value.
126   if (product != uma_proto_.product())
127     uma_proto_.set_product(product);
128 
129   SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
130   // Record the unhashed the client_id to system profile. This is used to
131   // simulate field trial assignments for the client.
132   system_profile->set_client_uuid(client_id);
133   RecordCoreSystemProfile(client_, system_profile);
134 }
135 
~MetricsLog()136 MetricsLog::~MetricsLog() {
137 }
138 
139 // static
RegisterPrefs(PrefRegistrySimple * registry)140 void MetricsLog::RegisterPrefs(PrefRegistrySimple* registry) {
141   EnvironmentRecorder::RegisterPrefs(registry);
142 }
143 
144 // static
Hash(const std::string & value)145 uint64_t MetricsLog::Hash(const std::string& value) {
146   uint64_t hash = base::HashMetricName(value);
147 
148   // The following log is VERY helpful when folks add some named histogram into
149   // the code, but forgot to update the descriptive list of histograms.  When
150   // that happens, all we get to see (server side) is a hash of the histogram
151   // name.  We can then use this logging to find out what histogram name was
152   // being hashed to a given MD5 value by just running the version of Chromium
153   // in question with --enable-logging.
154   DVLOG(1) << "Metrics: Hash numeric [" << value << "]=[" << hash << "]";
155 
156   return hash;
157 }
158 
159 // static
GetBuildTime()160 int64_t MetricsLog::GetBuildTime() {
161   static int64_t integral_build_time = 0;
162   if (!integral_build_time)
163     integral_build_time = static_cast<int64_t>(base::GetBuildTime().ToTimeT());
164   return integral_build_time;
165 }
166 
167 // static
GetCurrentTime()168 int64_t MetricsLog::GetCurrentTime() {
169   return ToMonotonicSeconds(base::TimeTicks::Now());
170 }
171 
RecordUserAction(const std::string & key,base::TimeTicks action_time)172 void MetricsLog::RecordUserAction(const std::string& key,
173                                   base::TimeTicks action_time) {
174   DCHECK(!closed_);
175 
176   UserActionEventProto* user_action = uma_proto_.add_user_action_event();
177   user_action->set_name_hash(Hash(key));
178   user_action->set_time_sec(ToMonotonicSeconds(action_time));
179   base::UmaHistogramBoolean("UMA.UserActionsCount", true);
180 }
181 
182 // static
RecordCoreSystemProfile(MetricsServiceClient * client,SystemProfileProto * system_profile)183 void MetricsLog::RecordCoreSystemProfile(MetricsServiceClient* client,
184                                          SystemProfileProto* system_profile) {
185   RecordCoreSystemProfile(client->GetVersionString(), client->GetChannel(),
186                           client->GetApplicationLocale(),
187                           client->GetAppPackageName(), system_profile);
188 
189   std::string brand_code;
190   if (client->GetBrand(&brand_code))
191     system_profile->set_brand_code(brand_code);
192 }
193 
194 // static
RecordCoreSystemProfile(const std::string & version,metrics::SystemProfileProto::Channel channel,const std::string & application_locale,const std::string & package_name,SystemProfileProto * system_profile)195 void MetricsLog::RecordCoreSystemProfile(
196     const std::string& version,
197     metrics::SystemProfileProto::Channel channel,
198     const std::string& application_locale,
199     const std::string& package_name,
200     SystemProfileProto* system_profile) {
201   system_profile->set_build_timestamp(metrics::MetricsLog::GetBuildTime());
202   system_profile->set_app_version(version);
203   system_profile->set_channel(channel);
204   system_profile->set_application_locale(application_locale);
205 
206 #if defined(ADDRESS_SANITIZER) || DCHECK_IS_ON()
207   // Set if a build is instrumented (e.g. built with ASAN, or with DCHECKs).
208   system_profile->set_is_instrumented_build(true);
209 #endif
210 
211   metrics::SystemProfileProto::Hardware* hardware =
212       system_profile->mutable_hardware();
213 #if !defined(OS_IOS)
214   // On iOS, OperatingSystemArchitecture() returns values like iPad4,4 which is
215   // not the actual CPU architecture. Don't set it until the API is fixed. See
216   // crbug.com/370104 for details.
217   hardware->set_cpu_architecture(base::SysInfo::OperatingSystemArchitecture());
218 #endif
219   hardware->set_system_ram_mb(base::SysInfo::AmountOfPhysicalMemoryMB());
220   hardware->set_hardware_class(base::SysInfo::HardwareModelName());
221 #if defined(OS_WIN)
222   hardware->set_dll_base(reinterpret_cast<uint64_t>(CURRENT_MODULE()));
223 #endif
224 
225   metrics::SystemProfileProto::OS* os = system_profile->mutable_os();
226 #if BUILDFLAG(IS_LACROS)
227   // The Lacros browser runs on Chrome OS, but reports a special OS name to
228   // differentiate itself from the built-in ash browser + window manager binary.
229   os->set_name("Lacros");
230 #elif defined(OS_CHROMEOS)
231   os->set_name("CrOS");
232 #else
233   os->set_name(base::SysInfo::OperatingSystemName());
234 #endif
235   os->set_version(base::SysInfo::OperatingSystemVersion());
236 
237 // On ChromeOS, KernelVersion refers to the Linux kernel version and
238 // OperatingSystemVersion refers to the ChromeOS release version.
239 #if defined(OS_CHROMEOS)
240   os->set_kernel_version(base::SysInfo::KernelVersion());
241 #elif defined(OS_LINUX) || defined(OS_BSD)
242   // Linux operating system version is copied over into kernel version to be
243   // consistent.
244   os->set_kernel_version(base::SysInfo::OperatingSystemVersion());
245 #endif
246 
247 #if defined(OS_ANDROID)
248   const auto* build_info = base::android::BuildInfo::GetInstance();
249   os->set_build_fingerprint(build_info->android_build_fp());
250   if (!package_name.empty() && package_name != "com.android.chrome")
251     system_profile->set_app_package_name(package_name);
252   system_profile->set_installer_package(
253       internal::ToInstallerPackage(build_info->installer_package_name()));
254 #elif defined(OS_IOS)
255   os->set_build_number(base::SysInfo::GetIOSBuildNumber());
256 #endif
257 }
258 
RecordHistogramDelta(const std::string & histogram_name,const base::HistogramSamples & snapshot)259 void MetricsLog::RecordHistogramDelta(const std::string& histogram_name,
260                                       const base::HistogramSamples& snapshot) {
261   DCHECK(!closed_);
262   samples_count_ += snapshot.TotalCount();
263   EncodeHistogramDelta(histogram_name, snapshot, &uma_proto_);
264 }
265 
RecordPreviousSessionData(DelegatingProvider * delegating_provider)266 void MetricsLog::RecordPreviousSessionData(
267     DelegatingProvider* delegating_provider) {
268   delegating_provider->ProvidePreviousSessionData(uma_proto());
269 }
270 
RecordCurrentSessionData(DelegatingProvider * delegating_provider,base::TimeDelta incremental_uptime,base::TimeDelta uptime)271 void MetricsLog::RecordCurrentSessionData(
272     DelegatingProvider* delegating_provider,
273     base::TimeDelta incremental_uptime,
274     base::TimeDelta uptime) {
275   DCHECK(!closed_);
276   DCHECK(has_environment_);
277 
278   // Record recent delta for critical stability metrics.  We can't wait for a
279   // restart to gather these, as that delay biases our observation away from
280   // users that run happily for a looooong time.  We send increments with each
281   // uma log upload, just as we send histogram data.
282   WriteRealtimeStabilityAttributes(incremental_uptime, uptime);
283 
284   delegating_provider->ProvideCurrentSessionData(uma_proto());
285 }
286 
WriteMetricsEnableDefault(EnableMetricsDefault metrics_default,SystemProfileProto * system_profile)287 void MetricsLog::WriteMetricsEnableDefault(EnableMetricsDefault metrics_default,
288                                            SystemProfileProto* system_profile) {
289   if (client_->IsReportingPolicyManaged()) {
290     // If it's managed, then it must be reporting, otherwise we wouldn't be
291     // sending metrics.
292     system_profile->set_uma_default_state(
293         SystemProfileProto_UmaDefaultState_POLICY_FORCED_ENABLED);
294     return;
295   }
296 
297   switch (metrics_default) {
298     case EnableMetricsDefault::DEFAULT_UNKNOWN:
299       // Don't set the field if it's unknown.
300       break;
301     case EnableMetricsDefault::OPT_IN:
302       system_profile->set_uma_default_state(
303           SystemProfileProto_UmaDefaultState_OPT_IN);
304       break;
305     case EnableMetricsDefault::OPT_OUT:
306       system_profile->set_uma_default_state(
307           SystemProfileProto_UmaDefaultState_OPT_OUT);
308   }
309 }
310 
WriteRealtimeStabilityAttributes(base::TimeDelta incremental_uptime,base::TimeDelta uptime)311 void MetricsLog::WriteRealtimeStabilityAttributes(
312     base::TimeDelta incremental_uptime,
313     base::TimeDelta uptime) {
314   // Update the stats which are critical for real-time stability monitoring.
315   // Since these are "optional," only list ones that are non-zero, as the counts
316   // are aggregated (summed) server side.
317 
318   SystemProfileProto::Stability* stability =
319       uma_proto()->mutable_system_profile()->mutable_stability();
320 
321   const uint64_t incremental_uptime_sec = incremental_uptime.InSeconds();
322   if (incremental_uptime_sec)
323     stability->set_incremental_uptime_sec(incremental_uptime_sec);
324   const uint64_t uptime_sec = uptime.InSeconds();
325   if (uptime_sec)
326     stability->set_uptime_sec(uptime_sec);
327 }
328 
RecordEnvironment(DelegatingProvider * delegating_provider)329 const SystemProfileProto& MetricsLog::RecordEnvironment(
330     DelegatingProvider* delegating_provider) {
331   // If |has_environment_| is true, then the system profile in |uma_proto_| has
332   // previously been fully filled in. We still want to fill it in again with
333   // more up to date information (e.g. current field trials), but in order to
334   // not have duplicate repeated fields, we must first clear it. Clearing it
335   // will reset the information filled in by RecordCoreSystemProfile() that was
336   // previously done in the constructor, so re-add that too.
337   //
338   // The |has_environment| case will happen on the very first log, where we
339   // call RecordEnvironment() in order to persist the system profile in the
340   // persistent histograms .pma file.
341   if (has_environment_) {
342     uma_proto_.clear_system_profile();
343     MetricsLog::RecordCoreSystemProfile(client_,
344                                         uma_proto_.mutable_system_profile());
345   }
346 
347   has_environment_ = true;
348 
349   SystemProfileProto* system_profile = uma_proto_.mutable_system_profile();
350   WriteMetricsEnableDefault(client_->GetMetricsReportingDefaultState(),
351                             system_profile);
352 
353   delegating_provider->ProvideSystemProfileMetricsWithLogCreationTime(
354       creation_time_, system_profile);
355 
356   return *system_profile;
357 }
358 
LoadSavedEnvironmentFromPrefs(PrefService * local_state,std::string * app_version)359 bool MetricsLog::LoadSavedEnvironmentFromPrefs(PrefService* local_state,
360                                                std::string* app_version) {
361   DCHECK(!has_environment_);
362   has_environment_ = true;
363   app_version->clear();
364 
365   SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
366   EnvironmentRecorder recorder(local_state);
367   bool success = recorder.LoadEnvironmentFromPrefs(system_profile);
368   if (success)
369     *app_version = system_profile->app_version();
370   return success;
371 }
372 
CloseLog()373 void MetricsLog::CloseLog() {
374   DCHECK(!closed_);
375   closed_ = true;
376 }
377 
TruncateEvents()378 void MetricsLog::TruncateEvents() {
379   DCHECK(!closed_);
380   if (uma_proto_.user_action_event_size() > internal::kUserActionEventLimit) {
381     UMA_HISTOGRAM_COUNTS_100000("UMA.TruncatedEvents.UserAction",
382                                 uma_proto_.user_action_event_size());
383     for (int i = internal::kUserActionEventLimit;
384          i < uma_proto_.user_action_event_size(); ++i) {
385       // No histograms.xml entry is added for this histogram because it uses an
386       // enum that is generated from actions.xml in our processing pipelines.
387       // Instead, a histogram description will also be produced in our
388       // pipelines.
389       base::UmaHistogramSparse(
390           "UMA.TruncatedEvents.UserAction.Type",
391           // Truncate the unsigned 64-bit hash to 31 bits, to make it a suitable
392           // histogram sample.
393           uma_proto_.user_action_event(i).name_hash() & 0x7fffffff);
394     }
395     uma_proto_.mutable_user_action_event()->DeleteSubrange(
396         internal::kUserActionEventLimit,
397         uma_proto_.user_action_event_size() - internal::kUserActionEventLimit);
398   }
399 
400   if (uma_proto_.omnibox_event_size() > internal::kOmniboxEventLimit) {
401     UMA_HISTOGRAM_COUNTS_100000("UMA.TruncatedEvents.Omnibox",
402                                 uma_proto_.omnibox_event_size());
403     uma_proto_.mutable_omnibox_event()->DeleteSubrange(
404         internal::kOmniboxEventLimit,
405         uma_proto_.omnibox_event_size() - internal::kOmniboxEventLimit);
406   }
407 }
408 
GetEncodedLog(std::string * encoded_log)409 void MetricsLog::GetEncodedLog(std::string* encoded_log) {
410   DCHECK(closed_);
411   uma_proto_.SerializeToString(encoded_log);
412 }
413 
414 }  // namespace metrics
415