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.
5 #include "components/rappor/rappor_service.h"
7 #include "base/base64.h"
8 #include "base/metrics/field_trial.h"
9 #include "base/prefs/pref_registry_simple.h"
10 #include "base/prefs/pref_service.h"
11 #include "base/rand_util.h"
12 #include "base/stl_util.h"
13 #include "base/time/time.h"
14 #include "components/metrics/metrics_hashes.h"
15 #include "components/rappor/log_uploader.h"
16 #include "components/rappor/proto/rappor_metric.pb.h"
17 #include "components/rappor/rappor_metric.h"
18 #include "components/rappor/rappor_pref_names.h"
19 #include "components/variations/variations_associated_data.h"
25 // Seconds before the initial log is generated.
26 const int kInitialLogIntervalSeconds
= 15;
27 // Interval between ongoing logs.
28 const int kLogIntervalSeconds
= 30 * 60;
30 const char kMimeType
[] = "application/vnd.chrome.rappor";
32 const char kRapporDailyEventHistogram
[] = "Rappor.DailyEvent.IntervalType";
34 // Constants for the RAPPOR rollout field trial.
35 const char kRapporRolloutFieldTrialName
[] = "RapporRollout";
37 // Constant for the finch parameter name for the server URL
38 const char kRapporRolloutServerUrlParam
[] = "ServerUrl";
40 // The rappor server's URL.
41 const char kDefaultServerUrl
[] = "https://clients4.google.com/rappor";
44 std::string server_url
= variations::GetVariationParamValue(
45 kRapporRolloutFieldTrialName
,
46 kRapporRolloutServerUrlParam
);
47 if (!server_url
.empty())
48 return GURL(server_url
);
50 return GURL(kDefaultServerUrl
);
53 const RapporParameters kRapporParametersForType
[NUM_RAPPOR_TYPES
] = {
54 // ETLD_PLUS_ONE_RAPPOR_TYPE
55 {128 /* Num cohorts */,
56 16 /* Bloom filter size bytes */,
57 2 /* Bloom filter hash count */,
58 rappor::PROBABILITY_50
/* Fake data probability */,
59 rappor::PROBABILITY_50
/* Fake one probability */,
60 rappor::PROBABILITY_75
/* One coin probability */,
61 rappor::PROBABILITY_25
/* Zero coin probability */,
62 FINE_LEVEL
/* Reporting level */},
64 {128 /* Num cohorts */,
65 1 /* Bloom filter size bytes */,
66 2 /* Bloom filter hash count */,
67 rappor::PROBABILITY_50
/* Fake data probability */,
68 rappor::PROBABILITY_50
/* Fake one probability */,
69 rappor::PROBABILITY_75
/* One coin probability */,
70 rappor::PROBABILITY_25
/* Zero coin probability */,
71 COARSE_LEVEL
/* Reporting level */},
76 RapporService::RapporService(
77 PrefService
* pref_service
,
78 const base::Callback
<bool(void)> is_incognito_callback
)
79 : pref_service_(pref_service
),
80 is_incognito_callback_(is_incognito_callback
),
82 daily_event_(pref_service
,
83 prefs::kRapporLastDailySample
,
84 kRapporDailyEventHistogram
),
85 reporting_level_(REPORTING_DISABLED
) {
88 RapporService::~RapporService() {
89 STLDeleteValues(&metrics_map_
);
92 void RapporService::AddDailyObserver(
93 scoped_ptr
<metrics::DailyEvent::Observer
> observer
) {
94 daily_event_
.AddObserver(observer
.Pass());
97 void RapporService::Start(net::URLRequestContextGetter
* request_context
,
98 bool metrics_enabled
) {
99 const GURL server_url
= GetServerUrl();
100 if (!server_url
.is_valid()) {
101 DVLOG(1) << server_url
.spec() << " is invalid. "
102 << "RapporService not started.";
105 // TODO(holte): Consider moving this logic once we've determined the
106 // conditions for COARSE metrics.
107 ReportingLevel reporting_level
= metrics_enabled
?
108 FINE_LEVEL
: REPORTING_DISABLED
;
109 DVLOG(1) << "RapporService reporting_level_? " << reporting_level
;
110 if (reporting_level
<= REPORTING_DISABLED
)
112 DVLOG(1) << "RapporService started. Reporting to " << server_url
.spec();
114 Initialize(LoadCohort(), LoadSecret(), reporting_level
);
115 uploader_
.reset(new LogUploader(server_url
, kMimeType
, request_context
));
116 log_rotation_timer_
.Start(
118 base::TimeDelta::FromSeconds(kInitialLogIntervalSeconds
),
120 &RapporService::OnLogInterval
);
123 void RapporService::Initialize(int32_t cohort
,
124 const std::string
& secret
,
125 const ReportingLevel
& reporting_level
) {
126 DCHECK(!IsInitialized());
127 DCHECK(secret_
.empty());
130 reporting_level_
= reporting_level
;
133 void RapporService::OnLogInterval() {
135 DVLOG(2) << "RapporService::OnLogInterval";
136 daily_event_
.CheckInterval();
137 RapporReports reports
;
138 if (ExportMetrics(&reports
)) {
139 std::string log_text
;
140 bool success
= reports
.SerializeToString(&log_text
);
142 DVLOG(1) << "RapporService sending a report of "
143 << reports
.report_size() << " value(s).";
144 uploader_
->QueueLog(log_text
);
146 log_rotation_timer_
.Start(FROM_HERE
,
147 base::TimeDelta::FromSeconds(kLogIntervalSeconds
),
149 &RapporService::OnLogInterval
);
153 void RapporService::RegisterPrefs(PrefRegistrySimple
* registry
) {
154 registry
->RegisterStringPref(prefs::kRapporSecret
, std::string());
155 registry
->RegisterIntegerPref(prefs::kRapporCohortDeprecated
, -1);
156 registry
->RegisterIntegerPref(prefs::kRapporCohortSeed
, -1);
157 metrics::DailyEvent::RegisterPref(registry
,
158 prefs::kRapporLastDailySample
);
161 int32_t RapporService::LoadCohort() {
162 // Ignore and delete old cohort parameter.
163 pref_service_
->ClearPref(prefs::kRapporCohortDeprecated
);
165 int32_t cohort
= pref_service_
->GetInteger(prefs::kRapporCohortSeed
);
166 // If the user is already assigned to a valid cohort, we're done.
167 if (cohort
>= 0 && cohort
< RapporParameters::kMaxCohorts
)
170 // This is the first time the client has started the service (or their
171 // preferences were corrupted). Randomly assign them to a cohort.
172 cohort
= base::RandGenerator(RapporParameters::kMaxCohorts
);
173 DVLOG(2) << "Selected a new Rappor cohort: " << cohort
;
174 pref_service_
->SetInteger(prefs::kRapporCohortSeed
, cohort
);
178 std::string
RapporService::LoadSecret() {
180 std::string secret_base64
= pref_service_
->GetString(prefs::kRapporSecret
);
181 if (!secret_base64
.empty()) {
182 bool decoded
= base::Base64Decode(secret_base64
, &secret
);
183 if (decoded
&& secret_
.size() == HmacByteVectorGenerator::kEntropyInputSize
)
185 // If the preference fails to decode, or is the wrong size, it must be
186 // corrupt, so continue as though it didn't exist yet and generate a new
190 DVLOG(2) << "Generated a new Rappor secret.";
191 secret
= HmacByteVectorGenerator::GenerateEntropyInput();
192 base::Base64Encode(secret
, &secret_base64
);
193 pref_service_
->SetString(prefs::kRapporSecret
, secret_base64
);
197 bool RapporService::ExportMetrics(RapporReports
* reports
) {
198 if (metrics_map_
.empty()) {
199 DVLOG(2) << "metrics_map_ is empty.";
203 DCHECK_GE(cohort_
, 0);
204 reports
->set_cohort(cohort_
);
206 for (std::map
<std::string
, RapporMetric
*>::const_iterator it
=
207 metrics_map_
.begin();
208 it
!= metrics_map_
.end();
210 const RapporMetric
* metric
= it
->second
;
211 RapporReports::Report
* report
= reports
->add_report();
212 report
->set_name_hash(metrics::HashMetricName(it
->first
));
213 ByteVector bytes
= metric
->GetReport(secret_
);
214 report
->set_bits(std::string(bytes
.begin(), bytes
.end()));
216 STLDeleteValues(&metrics_map_
);
220 bool RapporService::IsInitialized() const {
224 void RapporService::RecordSample(const std::string
& metric_name
,
226 const std::string
& sample
) {
227 // Ignore the sample if the service hasn't started yet.
228 if (!IsInitialized())
230 DCHECK_LT(type
, NUM_RAPPOR_TYPES
);
231 const RapporParameters
& parameters
= kRapporParametersForType
[type
];
232 DVLOG(2) << "Recording sample \"" << sample
233 << "\" for metric \"" << metric_name
234 << "\" of type: " << type
;
235 RecordSampleInternal(metric_name
, parameters
, sample
);
238 void RapporService::RecordSampleInternal(const std::string
& metric_name
,
239 const RapporParameters
& parameters
,
240 const std::string
& sample
) {
241 DCHECK(IsInitialized());
242 if (is_incognito_callback_
.Run()) {
243 DVLOG(2) << "Metric not logged due to incognito mode.";
246 // Skip this metric if it's reporting level is less than the enabled
248 if (reporting_level_
< parameters
.reporting_level
) {
249 DVLOG(2) << "Metric not logged due to reporting_level "
250 << reporting_level_
<< " < " << parameters
.reporting_level
;
253 RapporMetric
* metric
= LookUpMetric(metric_name
, parameters
);
254 metric
->AddSample(sample
);
257 RapporMetric
* RapporService::LookUpMetric(const std::string
& metric_name
,
258 const RapporParameters
& parameters
) {
259 DCHECK(IsInitialized());
260 std::map
<std::string
, RapporMetric
*>::const_iterator it
=
261 metrics_map_
.find(metric_name
);
262 if (it
!= metrics_map_
.end()) {
263 RapporMetric
* metric
= it
->second
;
264 DCHECK_EQ(parameters
.ToString(), metric
->parameters().ToString());
268 RapporMetric
* new_metric
= new RapporMetric(metric_name
, parameters
, cohort_
);
269 metrics_map_
[metric_name
] = new_metric
;
273 } // namespace rappor