File: chrome_metrics_services_manager_client.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (401 lines) | stat: -rw-r--r-- 16,523 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/metrics/chrome_metrics_services_manager_client.h"

#include <map>
#include <string>

#include "base/check_op.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram_functions.h"
#include "base/path_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/thread_pool.h"
#include "build/build_config.h"
#include "cc/base/switches.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
#include "chrome/browser/metrics/chrome_metrics_service_client.h"
#include "chrome/browser/metrics/variations/chrome_variations_service_client.h"
#include "chrome/browser/metrics/variations/ui_string_overrider_factory.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/ui/browser_otr_state.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/installer/util/google_update_settings.h"
#include "components/metrics/enabled_state_provider.h"
#include "components/metrics/metrics_pref_names.h"
#include "components/metrics/metrics_state_manager.h"
#include "components/prefs/pref_service.h"
#include "components/variations/service/limited_entropy_synthetic_trial.h"
#include "components/variations/service/variations_service.h"
#include "components/variations/synthetic_trial_registry.h"
#include "components/variations/variations_associated_data.h"
#include "components/version_info/version_info.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/network_service_instance.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"

#if BUILDFLAG(IS_ANDROID)
#include "base/metrics/histogram_functions.h"
#include "chrome/browser/android/metrics/uma_session_stats.h"
#include "chrome/browser/ui/android/tab_model/tab_model.h"
#include "chrome/browser/ui/android/tab_model/tab_model_list.h"
#else
#include "chrome/browser/ui/browser_list.h"
#endif  // BUILDFLAG(IS_ANDROID)

#if BUILDFLAG(IS_WIN)
#include "base/win/registry.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/install_static/install_util.h"
#include "components/crash/core/app/crash_export_thunks.h"
#include "components/crash/core/app/crashpad.h"
#endif  // BUILDFLAG(IS_WIN)

#if BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/ash/settings/stats_reporting_controller.h"
#include "components/metrics/structured/recorder.h"
#endif  // BUILDFLAG(IS_CHROMEOS)

namespace metrics {
namespace internal {

// Metrics reporting feature. This feature, along with user consent, controls if
// recording and reporting are enabled. If the feature is enabled, but no
// consent is given, then there will be no recording or reporting.
BASE_FEATURE(kMetricsReportingFeature,
             "MetricsReporting",
             base::FEATURE_ENABLED_BY_DEFAULT);

#if BUILDFLAG(IS_ANDROID)
// Same as |kMetricsReportingFeature|, but this feature is associated with a
// different trial, which has different sampling rates. This is due to a bug
// in which the old sampling rate was not being applied correctly. In order for
// the fix to not affect the overall sampling rate, this new feature was
// created. See crbug/1306481.
BASE_FEATURE(kPostFREFixMetricsReportingFeature,
             "PostFREFixMetricsReporting",
             base::FEATURE_ENABLED_BY_DEFAULT);
#endif  // BUILDFLAG(IS_ANDROID)

// Name of the variations param that defines the sampling rate.
const char kRateParamName[] = "sampling_rate_per_mille";

}  // namespace internal
}  // namespace metrics

namespace {

// Posts |GoogleUpdateSettings::StoreMetricsClientInfo| on blocking pool thread
// because it needs access to IO and cannot work from UI thread.
void PostStoreMetricsClientInfo(const metrics::ClientInfo& client_info) {
  // This must happen on the same sequence as the tasks to enable/disable
  // metrics reporting. Otherwise, this may run while disabling metrics
  // reporting if the user quickly enables and disables metrics reporting.
  GoogleUpdateSettings::CollectStatsConsentTaskRunner()->PostTask(
      FROM_HERE, base::BindOnce(&GoogleUpdateSettings::StoreMetricsClientInfo,
                                client_info));
}

#if BUILDFLAG(IS_ANDROID)
// Returns true if we should use the new sampling trial and feature to determine
// sampling. See the comment on |kUsePostFREFixSamplingTrial| for more details.
bool ShouldUsePostFREFixSamplingTrial(PrefService* local_state) {
  return local_state->GetBoolean(metrics::prefs::kUsePostFREFixSamplingTrial);
}

bool ShouldUsePostFREFixSamplingTrial() {
  // We check for g_browser_process and local_state() because some unit tests
  // may reach this point without creating a test browser process and/or local
  // state.
  // TODO(crbug.com/40837610): Fix the unit tests so that we do not need to
  // check for g_browser_process and local_state().
  return g_browser_process && g_browser_process->local_state() &&
         ShouldUsePostFREFixSamplingTrial(g_browser_process->local_state());
}
#endif  // BUILDFLAG(IS_ANDROID)

// Implementation of IsClientInSample() that takes a PrefService param.
bool IsClientInSampleImpl(PrefService* local_state) {
  // Test the MetricsReporting or PostFREFixMetricsReporting feature (depending
  // on the |kUsePostFREFixSamplingTrial| pref and platform) for all users to
  // ensure that the trial is reported. See the comment on
  // |kUsePostFREFixSamplingTrial| for more details on why there are two
  // different features.
#if BUILDFLAG(IS_ANDROID)
  if (ShouldUsePostFREFixSamplingTrial(local_state)) {
    return base::FeatureList::IsEnabled(
        metrics::internal::kPostFREFixMetricsReportingFeature);
  }
#endif  // BUILDFLAG(IS_ANDROID)
  return base::FeatureList::IsEnabled(
      metrics::internal::kMetricsReportingFeature);
}

#if BUILDFLAG(IS_CHROMEOS)
// Callback to update the metrics reporting state when the Chrome OS metrics
// reporting setting changes.
void OnCrosMetricsReportingSettingChange(
    ChangeMetricsReportingStateCalledFrom called_from) {
  bool enable_metrics = ash::StatsReportingController::Get()->IsEnabled();
  ChangeMetricsReportingState(enable_metrics, called_from);
}
#endif

// Returns the name of a key under HKEY_CURRENT_USER that can be used to store
// backups of metrics data. Unused except on Windows.
std::wstring GetRegistryBackupKey() {
#if BUILDFLAG(IS_WIN)
  return install_static::GetRegistryPath().append(L"\\StabilityMetrics");
#else
  return std::wstring();
#endif
}

}  // namespace

class ChromeMetricsServicesManagerClient::ChromeEnabledStateProvider
    : public metrics::EnabledStateProvider {
 public:
  explicit ChromeEnabledStateProvider(PrefService* local_state)
      : local_state_(local_state) {}

  ChromeEnabledStateProvider(const ChromeEnabledStateProvider&) = delete;
  ChromeEnabledStateProvider& operator=(const ChromeEnabledStateProvider&) =
      delete;

  ~ChromeEnabledStateProvider() override = default;

  bool IsConsentGiven() const override {
    return ChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled(
        local_state_);
  }

  bool IsReportingEnabled() const override {
    return metrics::EnabledStateProvider::IsReportingEnabled() &&
           IsClientInSampleImpl(local_state_);
  }

 private:
  const raw_ptr<PrefService> local_state_;
};

ChromeMetricsServicesManagerClient::ChromeMetricsServicesManagerClient(
    PrefService* local_state)
    : enabled_state_provider_(
          std::make_unique<ChromeEnabledStateProvider>(local_state)),
      local_state_(local_state) {
  DCHECK(local_state);
}

ChromeMetricsServicesManagerClient::~ChromeMetricsServicesManagerClient() =
    default;

metrics::MetricsStateManager*
ChromeMetricsServicesManagerClient::GetMetricsStateManagerForTesting() {
  return GetMetricsStateManager();
}

// static
bool ChromeMetricsServicesManagerClient::IsClientInSampleForMetrics() {
  return IsClientInSampleImpl(g_browser_process->local_state());
}

#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID)
// static
bool ChromeMetricsServicesManagerClient::IsClientInSampleForCrashes() {
#if BUILDFLAG(IS_ANDROID)
  // On Android, there are two field trials that, together, drive metrics and
  // crash reporting. The determination of which trial to use is based on
  // whether the client went through the FRE before or after the fix to
  // crbug.com/1306481 was deployed.
  //
  // The PostFREFixSamplingTrial controls crash and metrics sampling for clients
  // which went through the FRE after the FRE fix was deployed. These clients
  // use the PostFREFixMetricsReortingFeature and its "disable_crashes" feature
  // parameter to control whether the client is in-sample for crash reporting.
  if (ShouldUsePostFREFixSamplingTrial(g_browser_process->local_state())) {
    // If reporting isn't enabled at all, then we can return early.
    if (!base::FeatureList::IsEnabled(
            metrics::internal::kPostFREFixMetricsReportingFeature)) {
      return false;
    }
    // Otherwise, send crashes if crash reporting is NOT disabled. By default
    // crash reporting is not disabled.
    const bool crashes_are_disabled = base::GetFieldTrialParamByFeatureAsBool(
        metrics::internal::kPostFREFixMetricsReportingFeature,
        "disable_crashes", false);
    return !crashes_are_disabled;
  }
#endif  // BUILDFLAG(IS_ANDROID)

  // If this is a Windows client, or if this is an Android client that went
  // through the FRE before the FRE fix was deployed, then this client uses
  // the MetricsReportingFeature and its "disable_crashes" parameter to control
  // whether the client is in-sample for crash reporting.

  // If reporting isn't enabled at all, then we can return early.
  if (!base::FeatureList::IsEnabled(
          metrics::internal::kMetricsReportingFeature)) {
    return false;
  }

  const bool crashes_are_disabled = base::GetFieldTrialParamByFeatureAsBool(
      metrics::internal::kMetricsReportingFeature, "disable_crashes", false);
  return !crashes_are_disabled;
}
#endif  // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID)

// static
bool ChromeMetricsServicesManagerClient::GetSamplingRatePerMille(int* rate) {
#if BUILDFLAG(IS_ANDROID)
  const base::Feature& feature =
      ShouldUsePostFREFixSamplingTrial()
          ? metrics::internal::kPostFREFixMetricsReportingFeature
          : metrics::internal::kMetricsReportingFeature;
#else
  const base::Feature& feature = metrics::internal::kMetricsReportingFeature;
#endif  // BUILDFLAG(IS_ANDROID)
  std::string rate_str = base::GetFieldTrialParamValueByFeature(
      feature, metrics::internal::kRateParamName);
  if (rate_str.empty())
    return false;

  if (!base::StringToInt(rate_str, rate) || *rate > 1000)
    return false;

  return true;
}

#if BUILDFLAG(IS_CHROMEOS)
void ChromeMetricsServicesManagerClient::OnCrosSettingsCreated() {
  // Listen for changes to metrics reporting state.
  reporting_setting_subscription_ =
      ash::StatsReportingController::Get()->AddObserver(base::BindRepeating(
          &OnCrosMetricsReportingSettingChange,
          ChangeMetricsReportingStateCalledFrom::kCrosMetricsSettingsChange));
  // Invoke the callback once initially to set the metrics reporting state.
  OnCrosMetricsReportingSettingChange(
      ChangeMetricsReportingStateCalledFrom::kCrosMetricsSettingsCreated);
}
#endif

std::unique_ptr<variations::VariationsService>
ChromeMetricsServicesManagerClient::CreateVariationsService(
    variations::SyntheticTrialRegistry* synthetic_trial_registry) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  return variations::VariationsService::Create(
      std::make_unique<ChromeVariationsServiceClient>(), local_state_,
      GetMetricsStateManager(), switches::kDisableBackgroundNetworking,
      chrome_variations::CreateUIStringOverrider(),
      base::BindOnce(&content::GetNetworkConnectionTracker),
      synthetic_trial_registry);
}

std::unique_ptr<metrics::MetricsServiceClient>
ChromeMetricsServicesManagerClient::CreateMetricsServiceClient(
    variations::SyntheticTrialRegistry* synthetic_trial_registry) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  return ChromeMetricsServiceClient::Create(GetMetricsStateManager(),
                                            synthetic_trial_registry);
}

metrics::MetricsStateManager*
ChromeMetricsServicesManagerClient::GetMetricsStateManager() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (!metrics_state_manager_) {
    base::FilePath user_data_dir;
    base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);

    metrics::StartupVisibility startup_visibility;
#if BUILDFLAG(IS_ANDROID)
    startup_visibility = UmaSessionStats::HasVisibleActivity()
                             ? metrics::StartupVisibility::kForeground
                             : metrics::StartupVisibility::kBackground;
    base::UmaHistogramEnumeration("UMA.StartupVisibility", startup_visibility);
#else
    startup_visibility = metrics::StartupVisibility::kForeground;
#endif  // BUILDFLAG(IS_ANDROID)

    metrics_state_manager_ = metrics::MetricsStateManager::Create(
        local_state_, enabled_state_provider_.get(), GetRegistryBackupKey(),
        user_data_dir, startup_visibility,
        {
            .default_entropy_provider_type =
                metrics::EntropyProviderType::kDefault,
            .force_benchmarking_mode =
                base::CommandLine::ForCurrentProcess()->HasSwitch(
                    switches::kEnableGpuBenchmarking),
        },
        base::BindRepeating(&PostStoreMetricsClientInfo),
        base::BindRepeating(&GoogleUpdateSettings::LoadMetricsClientInfo));
  }
  return metrics_state_manager_.get();
}

scoped_refptr<network::SharedURLLoaderFactory>
ChromeMetricsServicesManagerClient::GetURLLoaderFactory() {
  return g_browser_process->system_network_context_manager()
      ->GetSharedURLLoaderFactory();
}

const metrics::EnabledStateProvider&
ChromeMetricsServicesManagerClient::GetEnabledStateProvider() {
  return *enabled_state_provider_;
}

bool ChromeMetricsServicesManagerClient::IsOffTheRecordSessionActive() {
#if BUILDFLAG(IS_ANDROID)
  // This differs from TabModelList::IsOffTheRecordSessionActive in that it
  // does not ignore TabModels that have no open tabs, because it may be checked
  // before tabs get added to the TabModel. This means it may be more
  // conservative in case unused TabModels are not cleaned up, but it seems to
  // work correctly.
  // TODO(crbug.com/40529753): Check if TabModelList's version can be updated
  // safely.
  // TODO(crbug.com/40107157): This function should return true for Incognito
  // CCTs.
  for (const TabModel* model : TabModelList::models()) {
    if (model->IsOffTheRecord())
      return true;
  }

  return false;
#else
  // Depending directly on BrowserList, since that is the implementation
  // that we get correct notifications for.
  return BrowserList::IsOffTheRecordBrowserActive();
#endif
}

#if BUILDFLAG(IS_WIN)
void ChromeMetricsServicesManagerClient::UpdateRunningServices(
    bool may_record,
    bool may_upload) {
  // First, set the registry value so that Crashpad will have the sampling state
  // now and for subsequent runs. Note that Crashpad uses *both* the registry
  // value and the value sent from SetUploadConsent below.
  // We use IsClientInSampleForCrash() which checks the feature for if crashes
  // are allowed.
  install_static::SetCollectStatsInSample(IsClientInSampleForCrashes());

  // The intent here is to set the value of the consent. However, since right
  // now we have may_record which is based off both consent and the Feature
  // state, this is redundant with the above value. This is pretty confusing
  // right now, and we may want to rethink this. One extra complexity here is we
  // currently check the disable_crashes parameter, which does not go
  // into may_record. This is because this is specifically intending to test for
  // consent, and as mentioned, on the crashpad side we check both. See
  // SetUploadConsent() in components/crash/core/app/crashpad.cc for how this
  // gets used.
  SetUploadConsent_ExportThunk(may_record && may_upload);
}
#endif  // BUILDFLAG(IS_WIN)