File: metrics_services_manager.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (352 lines) | stat: -rw-r--r-- 12,487 bytes parent folder | download | duplicates (3)
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
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/metrics_services_manager/metrics_services_manager.h"

#include <memory>
#include <utility>

#include "base/check.h"
#include "base/check_is_test.h"
#include "base/functional/bind.h"
#include "base/metrics/histogram_macros.h"
#include "components/metrics/dwa/dwa_recorder.h"
#include "components/metrics/dwa/dwa_service.h"
#include "components/metrics/enabled_state_provider.h"
#include "components/metrics/metrics_service.h"
#include "components/metrics/metrics_service_client.h"
#include "components/metrics/metrics_state_manager.h"
#include "components/metrics/metrics_switches.h"
#include "components/metrics/structured/structured_metrics_service.h"  // nogncheck
#include "components/metrics_services_manager/metrics_services_manager_client.h"
#include "components/ukm/ukm_service.h"
#include "components/variations/service/variations_service.h"
#include "components/variations/synthetic_trial_registry.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"

namespace metrics_services_manager {

MetricsServicesManager::MetricsServicesManager(
    std::unique_ptr<MetricsServicesManagerClient> client)
    : client_(std::move(client)) {
  CHECK(client_);
}

MetricsServicesManager::~MetricsServicesManager() = default;

void MetricsServicesManager::InstantiateFieldTrialList() const {
  client_->GetMetricsStateManager()->InstantiateFieldTrialList();
}

variations::SyntheticTrialRegistry*
MetricsServicesManager::GetSyntheticTrialRegistry() {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!synthetic_trial_registry_) {
    synthetic_trial_registry_ =
        std::make_unique<variations::SyntheticTrialRegistry>();
  }
  return synthetic_trial_registry_.get();
}

metrics::MetricsService* MetricsServicesManager::GetMetricsService() {
  DCHECK(thread_checker_.CalledOnValidThread());
  return GetMetricsServiceClient()->GetMetricsService();
}

ukm::UkmService* MetricsServicesManager::GetUkmService() {
  DCHECK(thread_checker_.CalledOnValidThread());
  return GetMetricsServiceClient()->GetUkmService();
}

IdentifiabilityStudyState*
MetricsServicesManager::GetIdentifiabilityStudyState() {
  DCHECK(thread_checker_.CalledOnValidThread());
  return GetMetricsServiceClient()->GetIdentifiabilityStudyState();
}

metrics::structured::StructuredMetricsService*
MetricsServicesManager::GetStructuredMetricsService() {
  DCHECK(thread_checker_.CalledOnValidThread());
  return GetMetricsServiceClient()->GetStructuredMetricsService();
}

metrics::dwa::DwaService* MetricsServicesManager::GetDwaService() {
  DCHECK(thread_checker_.CalledOnValidThread());
  return GetMetricsServiceClient()->GetDwaService();
}

variations::VariationsService* MetricsServicesManager::GetVariationsService() {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!variations_service_) {
    variations_service_ = client_->CreateVariationsService();
  }
  return variations_service_.get();
}

MetricsServicesManager::OnDidStartLoadingCb
MetricsServicesManager::GetOnDidStartLoadingCb() {
  return base::BindRepeating(&MetricsServicesManager::LoadingStateChanged,
                             weak_ptr_factory_.GetWeakPtr(),
                             /*is_loading=*/true);
}

MetricsServicesManager::OnDidStopLoadingCb
MetricsServicesManager::GetOnDidStopLoadingCb() {
  return base::BindRepeating(&MetricsServicesManager::LoadingStateChanged,
                             weak_ptr_factory_.GetWeakPtr(),
                             /*is_loading=*/false);
}

MetricsServicesManager::OnRendererUnresponsiveCb
MetricsServicesManager::GetOnRendererUnresponsiveCb() {
  return base::BindRepeating(&MetricsServicesManager::OnRendererUnresponsive,
                             weak_ptr_factory_.GetWeakPtr());
}

std::unique_ptr<const variations::EntropyProviders>
MetricsServicesManager::CreateEntropyProvidersForTesting() {
  // Setting enable_limited_entropy_mode=true to maximize code coverage.
  return client_->GetMetricsStateManager()->CreateEntropyProviders(
      /*enable_limited_entropy_mode=*/true);
}

metrics::ClonedInstallDetector*
MetricsServicesManager::GetClonedInstallDetectorForTesting() {
  CHECK_IS_TEST();
  return client_->GetMetricsStateManager()
      ->cloned_install_detector_for_testing();  // IN-TEST
}

const metrics::ClonedInstallDetector&
MetricsServicesManager::GetClonedInstallDetector() const {
  return client_->GetMetricsStateManager()->GetClonedInstallDetector();
}

metrics::MetricsServiceClient*
MetricsServicesManager::GetMetricsServiceClient() {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!metrics_service_client_) {
    metrics_service_client_ =
        client_->CreateMetricsServiceClient(GetSyntheticTrialRegistry());
    // base::Unretained is safe since |this| owns the metrics_service_client_.
    metrics_service_client_->SetUpdateRunningServicesCallback(
        base::BindRepeating(&MetricsServicesManager::UpdateRunningServices,
                            base::Unretained(this)));
  }
  return metrics_service_client_.get();
}

void MetricsServicesManager::UpdatePermissions(bool current_may_record,
                                               bool current_consent_given,
                                               bool current_may_upload) {
  DCHECK(thread_checker_.CalledOnValidThread());
  // If the user has opted out of metrics, delete local UKM and DWA states.
  // TODO(crbug.com/40267999): Investigate if UMA needs purging logic.
  if (consent_given_ && !current_consent_given) {
    ukm::UkmService* ukm = GetUkmService();
    if (ukm) {
      ukm->Purge();
      ukm->ResetClientState(ukm::ResetReason::kUpdatePermissions);
    }
    metrics::dwa::DwaService* dwa_service = GetDwaService();
    if (dwa_service) {
      dwa_service->Purge();
    }
  }

  // If the user has opted out of metrics, purge Structured Metrics if consent
  // is not granted. On ChromeOS, SM will record specific events when consent is
  // unknown during primarily OOBE; but these events need to be purged once
  // consent is confirmed. This feature shouldn't be used on other platforms.
  if (!current_consent_given) {
    metrics::structured::StructuredMetricsService* sm_service =
        GetStructuredMetricsService();
    if (sm_service) {
      sm_service->Purge();
    }
  }

  // If metrics reporting goes from not consented to consented, create and
  // persist a client ID (either generate a new one or promote the provisional
  // client ID if this is the first run). This can occur in the following
  // situations:
  // 1. The user enables metrics reporting in the FRE
  // 2. The user enables metrics reporting in settings, crash bubble, etc.
  // 3. On startup, after fetching the enable status from the previous session
  //    (if enabled)
  //
  // ForceClientIdCreation() may be called again later on via
  // MetricsService::EnableRecording(), but in that case,
  // ForceClientIdCreation() will be a no-op (will return early since a client
  // ID will already exist).
  //
  // ForceClientIdCreation() must be called here, otherwise, in cases where the
  // user is sampled out, the passed |current_may_record| will be false, which
  // will result in not calling ForceClientIdCreation() in
  // MetricsService::EnableRecording() later on. This is problematic because
  // in the FRE, if the user consents to metrics reporting, this will cause the
  // provisional client ID to not be promoted/stored as the client ID. In the
  // next run, a different client ID will be generated and stored, which will
  // result in different trial assignments—and the client may even be sampled
  // in at that time.
  if (!consent_given_ && current_consent_given) {
    client_->GetMetricsStateManager()->ForceClientIdCreation();
  }

  // Stash the current permissions so that we can update the services correctly
  // when preferences change.
  may_record_ = current_may_record;
  consent_given_ = current_consent_given;
  may_upload_ = current_may_upload;
  UpdateRunningServices();
}

void MetricsServicesManager::LoadingStateChanged(bool is_loading) {
  DCHECK(thread_checker_.CalledOnValidThread());
  GetMetricsServiceClient()->LoadingStateChanged(is_loading);
  if (is_loading) {
    GetMetricsService()->OnPageLoadStarted();
  }
}

void MetricsServicesManager::OnRendererUnresponsive() {
  DCHECK(thread_checker_.CalledOnValidThread());
  GetMetricsService()->OnApplicationNotIdle();
}

void MetricsServicesManager::UpdateRunningServices() {
  DCHECK(thread_checker_.CalledOnValidThread());
  metrics::MetricsService* metrics = GetMetricsService();

  if (metrics::IsMetricsRecordingOnlyEnabled()) {
    metrics->StartRecordingForTests();
    return;
  }

  client_->UpdateRunningServices(may_record_, may_upload_);

  if (may_record_) {
    if (!metrics->recording_active())
      metrics->Start();
    if (may_upload_)
      metrics->EnableReporting();
    else
      metrics->DisableReporting();
  } else {
    metrics->Stop();
  }

  UpdateUkmService();
  UpdateStructuredMetricsService();
  UpdateDwaService();
}

void MetricsServicesManager::UpdateUkmService() {
  ukm::UkmService* ukm = GetUkmService();
  if (!ukm) {
    return;
  }

  bool listeners_active =
      metrics_service_client_->AreNotificationListenersEnabledOnAllProfiles();
  bool ukm_allowed =
      metrics_service_client_->IsMetricsReportingForceEnabled() ||
      metrics_service_client_->IsUkmAllowedForAllProfiles();
  bool is_incognito = client_->IsOffTheRecordSessionActive();

  if (consent_given_ && listeners_active && ukm_allowed && !is_incognito) {
    ukm->EnableRecording();
    if (may_upload_)
      ukm->EnableReporting();
    else
      ukm->DisableReporting();
  } else {
    ukm->DisableRecording();
    ukm->DisableReporting();
  }
}

void MetricsServicesManager::UpdateStructuredMetricsService() {
  metrics::structured::StructuredMetricsService* service =
      GetStructuredMetricsService();
  if (!service) {
    return;
  }

  // Maybe write some helper methods for this.
  if (may_record_) {
    service->EnableRecording();
    if (may_upload_) {
      service->EnableReporting();
    } else {
      service->DisableReporting();
    }
  } else {
    service->DisableRecording();
    service->DisableReporting();
  }
}

void MetricsServicesManager::UpdateDwaService() {
  metrics::dwa::DwaService* dwa = GetDwaService();
  if (!dwa) {
    return;
  }
  // DWA is tied to the settings for allowing UKM.
  bool listeners_active =
      metrics_service_client_->AreNotificationListenersEnabledOnAllProfiles();
  bool dwa_allowed =
      metrics_service_client_->IsMetricsReportingForceEnabled() ||
      metrics_service_client_->IsDwaAllowedForAllProfiles();
  bool is_incognito = client_->IsOffTheRecordSessionActive();

  if (consent_given_ && listeners_active && dwa_allowed && !is_incognito) {
    metrics::dwa::DwaRecorder::Get()->EnableRecording();
    if (may_upload_) {
      dwa->EnableReporting();
    } else {
      dwa->DisableReporting();
    }
  } else {
    metrics::dwa::DwaRecorder::Get()->DisableRecording();
    dwa->DisableReporting();
    // Purge the DWA recorder if the user is in incognito mode.
    if (is_incognito) {
      metrics::dwa::DwaRecorder::Get()->Purge();
    }
  }
}

void MetricsServicesManager::UpdateUploadPermissions(bool may_upload) {
  if (metrics_service_client_->IsMetricsReportingForceEnabled()) {
    UpdatePermissions(/*current_may_record=*/true,
                      /*current_consent_given=*/true,
                      /*current_may_upload=*/true);
    return;
  }

  const auto& enable_state_provider = client_->GetEnabledStateProvider();
  UpdatePermissions(
      /*current_may_record=*/enable_state_provider.IsReportingEnabled(),
      /*current_consent_given=*/enable_state_provider.IsConsentGiven(),
      may_upload);
}

bool MetricsServicesManager::IsMetricsReportingEnabled() const {
  return client_->GetEnabledStateProvider().IsReportingEnabled();
}

bool MetricsServicesManager::IsMetricsConsentGiven() const {
  return client_->GetEnabledStateProvider().IsConsentGiven();
}

bool MetricsServicesManager::IsUkmAllowedForAllProfiles() {
  return metrics_service_client_->IsUkmAllowedForAllProfiles();
}

bool MetricsServicesManager::IsDwaAllowedForAllProfiles() {
  return metrics_service_client_->IsDwaAllowedForAllProfiles();
}

}  // namespace metrics_services_manager