1 // Copyright (c) 2012 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 "base/metrics/field_trial.h"
9 #include "base/build_time.h"
10 #include "base/logging.h"
11 #include "base/rand_util.h"
12 #include "base/sha1.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/sys_byteorder.h"
22 // Created a time value based on |year|, |month| and |day_of_month| parameters.
23 Time
CreateTimeFromParams(int year
, int month
, int day_of_month
) {
24 DCHECK_GT(year
, 1970);
27 DCHECK_GT(day_of_month
, 0);
28 DCHECK_LT(day_of_month
, 32);
30 Time::Exploded exploded
;
32 exploded
.month
= month
;
33 exploded
.day_of_week
= 0; // Should be unused.
34 exploded
.day_of_month
= day_of_month
;
38 exploded
.millisecond
= 0;
40 return Time::FromLocalExploded(exploded
);
43 // Returns the boundary value for comparing against the FieldTrial's added
44 // groups for a given |divisor| (total probability) and |entropy_value|.
45 FieldTrial::Probability
GetGroupBoundaryValue(
46 FieldTrial::Probability divisor
,
47 double entropy_value
) {
48 // Add a tiny epsilon value to get consistent results when converting floating
49 // points to int. Without it, boundary values have inconsistent results, e.g.:
51 // static_cast<FieldTrial::Probability>(100 * 0.56) == 56
52 // static_cast<FieldTrial::Probability>(100 * 0.57) == 56
53 // static_cast<FieldTrial::Probability>(100 * 0.58) == 57
54 // static_cast<FieldTrial::Probability>(100 * 0.59) == 59
55 const double kEpsilon
= 1e-8;
56 const FieldTrial::Probability result
=
57 static_cast<FieldTrial::Probability
>(divisor
* entropy_value
+ kEpsilon
);
58 // Ensure that adding the epsilon still results in a value < |divisor|.
59 return std::min(result
, divisor
- 1);
65 const int FieldTrial::kNotFinalized
= -1;
66 const int FieldTrial::kDefaultGroupNumber
= 0;
67 bool FieldTrial::enable_benchmarking_
= false;
69 const char FieldTrialList::kPersistentStringSeparator('/');
70 const char FieldTrialList::kActivationMarker('*');
71 int FieldTrialList::kNoExpirationYear
= 0;
73 //------------------------------------------------------------------------------
74 // FieldTrial methods and members.
76 FieldTrial::EntropyProvider::~EntropyProvider() {
79 void FieldTrial::Disable() {
80 DCHECK(!group_reported_
);
81 enable_field_trial_
= false;
83 // In case we are disabled after initialization, we need to switch
84 // the trial to the default group.
85 if (group_
!= kNotFinalized
) {
86 // Only reset when not already the default group, because in case we were
87 // forced to the default group, the group number may not be
88 // kDefaultGroupNumber, so we should keep it as is.
89 if (group_name_
!= default_group_name_
)
90 SetGroupChoice(default_group_name_
, kDefaultGroupNumber
);
94 int FieldTrial::AppendGroup(const std::string
& name
,
95 Probability group_probability
) {
96 // When the group choice was previously forced, we only need to return the
97 // the id of the chosen group, and anything can be returned for the others.
99 DCHECK(!group_name_
.empty());
100 if (name
== group_name_
) {
101 // Note that while |group_| may be equal to |kDefaultGroupNumber| on the
102 // forced trial, it will not have the same value as the default group
103 // number returned from the non-forced |FactoryGetFieldTrial()| call,
104 // which takes care to ensure that this does not happen.
107 DCHECK_NE(next_group_number_
, group_
);
108 // We still return different numbers each time, in case some caller need
109 // them to be different.
110 return next_group_number_
++;
113 DCHECK_LE(group_probability
, divisor_
);
114 DCHECK_GE(group_probability
, 0);
116 if (enable_benchmarking_
|| !enable_field_trial_
)
117 group_probability
= 0;
119 accumulated_group_probability_
+= group_probability
;
121 DCHECK_LE(accumulated_group_probability_
, divisor_
);
122 if (group_
== kNotFinalized
&& accumulated_group_probability_
> random_
) {
123 // This is the group that crossed the random line, so we do the assignment.
124 SetGroupChoice(name
, next_group_number_
);
126 return next_group_number_
++;
129 int FieldTrial::group() {
130 FinalizeGroupChoice();
131 if (trial_registered_
)
132 FieldTrialList::NotifyFieldTrialGroupSelection(this);
136 const std::string
& FieldTrial::group_name() {
137 // Call |group()| to ensure group gets assigned and observers are notified.
139 DCHECK(!group_name_
.empty());
143 void FieldTrial::SetForced() {
144 // We might have been forced before (e.g., by CreateFieldTrial) and it's
145 // first come first served, e.g., command line switch has precedence.
149 // And we must finalize the group choice before we mark ourselves as forced.
150 FinalizeGroupChoice();
155 void FieldTrial::EnableBenchmarking() {
156 DCHECK_EQ(0u, FieldTrialList::GetFieldTrialCount());
157 enable_benchmarking_
= true;
161 FieldTrial
* FieldTrial::CreateSimulatedFieldTrial(
162 const std::string
& trial_name
,
163 Probability total_probability
,
164 const std::string
& default_group_name
,
165 double entropy_value
) {
166 return new FieldTrial(trial_name
, total_probability
, default_group_name
,
170 FieldTrial::FieldTrial(const std::string
& trial_name
,
171 const Probability total_probability
,
172 const std::string
& default_group_name
,
173 double entropy_value
)
174 : trial_name_(trial_name
),
175 divisor_(total_probability
),
176 default_group_name_(default_group_name
),
177 random_(GetGroupBoundaryValue(total_probability
, entropy_value
)),
178 accumulated_group_probability_(0),
179 next_group_number_(kDefaultGroupNumber
+ 1),
180 group_(kNotFinalized
),
181 enable_field_trial_(true),
183 group_reported_(false),
184 trial_registered_(false) {
185 DCHECK_GT(total_probability
, 0);
186 DCHECK(!trial_name_
.empty());
187 DCHECK(!default_group_name_
.empty());
190 FieldTrial::~FieldTrial() {}
192 void FieldTrial::SetTrialRegistered() {
193 DCHECK_EQ(kNotFinalized
, group_
);
194 DCHECK(!trial_registered_
);
195 trial_registered_
= true;
198 void FieldTrial::SetGroupChoice(const std::string
& group_name
, int number
) {
200 if (group_name
.empty())
201 StringAppendF(&group_name_
, "%d", group_
);
203 group_name_
= group_name
;
204 DVLOG(1) << "Field trial: " << trial_name_
<< " Group choice:" << group_name_
;
207 void FieldTrial::FinalizeGroupChoice() {
208 if (group_
!= kNotFinalized
)
210 accumulated_group_probability_
= divisor_
;
211 // Here it's OK to use |kDefaultGroupNumber| since we can't be forced and not
214 SetGroupChoice(default_group_name_
, kDefaultGroupNumber
);
217 bool FieldTrial::GetActiveGroup(ActiveGroup
* active_group
) const {
218 if (!group_reported_
|| !enable_field_trial_
)
220 DCHECK_NE(group_
, kNotFinalized
);
221 active_group
->trial_name
= trial_name_
;
222 active_group
->group_name
= group_name_
;
226 //------------------------------------------------------------------------------
227 // FieldTrialList methods and members.
230 FieldTrialList
* FieldTrialList::global_
= NULL
;
233 bool FieldTrialList::used_without_global_
= false;
235 FieldTrialList::Observer::~Observer() {
238 FieldTrialList::FieldTrialList(
239 const FieldTrial::EntropyProvider
* entropy_provider
)
240 : entropy_provider_(entropy_provider
),
241 observer_list_(new ObserverListThreadSafe
<FieldTrialList::Observer
>(
242 ObserverListBase
<FieldTrialList::Observer
>::NOTIFY_EXISTING_ONLY
)) {
244 DCHECK(!used_without_global_
);
247 Time two_years_from_build_time
= GetBuildTime() + TimeDelta::FromDays(730);
248 Time::Exploded exploded
;
249 two_years_from_build_time
.LocalExplode(&exploded
);
250 kNoExpirationYear
= exploded
.year
;
253 FieldTrialList::~FieldTrialList() {
254 AutoLock
auto_lock(lock_
);
255 while (!registered_
.empty()) {
256 RegistrationMap::iterator it
= registered_
.begin();
257 it
->second
->Release();
258 registered_
.erase(it
->first
);
260 DCHECK_EQ(this, global_
);
265 FieldTrial
* FieldTrialList::FactoryGetFieldTrial(
266 const std::string
& trial_name
,
267 FieldTrial::Probability total_probability
,
268 const std::string
& default_group_name
,
271 const int day_of_month
,
272 FieldTrial::RandomizationType randomization_type
,
273 int* default_group_number
) {
274 return FactoryGetFieldTrialWithRandomizationSeed(
275 trial_name
, total_probability
, default_group_name
,
276 year
, month
, day_of_month
, randomization_type
, 0, default_group_number
);
280 FieldTrial
* FieldTrialList::FactoryGetFieldTrialWithRandomizationSeed(
281 const std::string
& trial_name
,
282 FieldTrial::Probability total_probability
,
283 const std::string
& default_group_name
,
286 const int day_of_month
,
287 FieldTrial::RandomizationType randomization_type
,
288 uint32 randomization_seed
,
289 int* default_group_number
) {
290 if (default_group_number
)
291 *default_group_number
= FieldTrial::kDefaultGroupNumber
;
292 // Check if the field trial has already been created in some other way.
293 FieldTrial
* existing_trial
= Find(trial_name
);
294 if (existing_trial
) {
295 CHECK(existing_trial
->forced_
);
296 // If the default group name differs between the existing forced trial
297 // and this trial, then use a different value for the default group number.
298 if (default_group_number
&&
299 default_group_name
!= existing_trial
->default_group_name()) {
300 // If the new default group number corresponds to the group that was
301 // chosen for the forced trial (which has been finalized when it was
302 // forced), then set the default group number to that.
303 if (default_group_name
== existing_trial
->group_name_internal()) {
304 *default_group_number
= existing_trial
->group_
;
306 // Otherwise, use |kNonConflictingGroupNumber| (-2) for the default
307 // group number, so that it does not conflict with the |AppendGroup()|
308 // result for the chosen group.
309 const int kNonConflictingGroupNumber
= -2;
311 kNonConflictingGroupNumber
!= FieldTrial::kDefaultGroupNumber
,
312 conflicting_default_group_number
);
314 kNonConflictingGroupNumber
!= FieldTrial::kNotFinalized
,
315 conflicting_default_group_number
);
316 *default_group_number
= kNonConflictingGroupNumber
;
319 return existing_trial
;
322 double entropy_value
;
323 if (randomization_type
== FieldTrial::ONE_TIME_RANDOMIZED
) {
324 const FieldTrial::EntropyProvider
* entropy_provider
=
325 GetEntropyProviderForOneTimeRandomization();
326 CHECK(entropy_provider
);
327 entropy_value
= entropy_provider
->GetEntropyForTrial(trial_name
,
330 DCHECK_EQ(FieldTrial::SESSION_RANDOMIZED
, randomization_type
);
331 DCHECK_EQ(0U, randomization_seed
);
332 entropy_value
= RandDouble();
335 FieldTrial
* field_trial
= new FieldTrial(trial_name
, total_probability
,
336 default_group_name
, entropy_value
);
337 if (GetBuildTime() > CreateTimeFromParams(year
, month
, day_of_month
))
338 field_trial
->Disable();
339 FieldTrialList::Register(field_trial
);
344 FieldTrial
* FieldTrialList::Find(const std::string
& name
) {
347 AutoLock
auto_lock(global_
->lock_
);
348 return global_
->PreLockedFind(name
);
352 int FieldTrialList::FindValue(const std::string
& name
) {
353 FieldTrial
* field_trial
= Find(name
);
355 return field_trial
->group();
356 return FieldTrial::kNotFinalized
;
360 std::string
FieldTrialList::FindFullName(const std::string
& name
) {
361 FieldTrial
* field_trial
= Find(name
);
363 return field_trial
->group_name();
364 return std::string();
368 bool FieldTrialList::TrialExists(const std::string
& name
) {
369 return Find(name
) != NULL
;
373 void FieldTrialList::StatesToString(std::string
* output
) {
374 FieldTrial::ActiveGroups active_groups
;
375 GetActiveFieldTrialGroups(&active_groups
);
376 for (FieldTrial::ActiveGroups::const_iterator it
= active_groups
.begin();
377 it
!= active_groups
.end(); ++it
) {
378 DCHECK_EQ(std::string::npos
,
379 it
->trial_name
.find(kPersistentStringSeparator
));
380 DCHECK_EQ(std::string::npos
,
381 it
->group_name
.find(kPersistentStringSeparator
));
382 output
->append(it
->trial_name
);
383 output
->append(1, kPersistentStringSeparator
);
384 output
->append(it
->group_name
);
385 output
->append(1, kPersistentStringSeparator
);
390 void FieldTrialList::GetActiveFieldTrialGroups(
391 FieldTrial::ActiveGroups
* active_groups
) {
392 DCHECK(active_groups
->empty());
395 AutoLock
auto_lock(global_
->lock_
);
397 for (RegistrationMap::iterator it
= global_
->registered_
.begin();
398 it
!= global_
->registered_
.end(); ++it
) {
399 FieldTrial::ActiveGroup active_group
;
400 if (it
->second
->GetActiveGroup(&active_group
))
401 active_groups
->push_back(active_group
);
406 bool FieldTrialList::CreateTrialsFromString(
407 const std::string
& trials_string
,
408 FieldTrialActivationMode mode
,
409 const std::set
<std::string
>& ignored_trial_names
) {
411 if (trials_string
.empty() || !global_
)
414 size_t next_item
= 0;
415 while (next_item
< trials_string
.length()) {
416 size_t name_end
= trials_string
.find(kPersistentStringSeparator
, next_item
);
417 if (name_end
== trials_string
.npos
|| next_item
== name_end
)
419 size_t group_name_end
= trials_string
.find(kPersistentStringSeparator
,
421 if (name_end
+ 1 == group_name_end
)
423 if (group_name_end
== trials_string
.npos
)
424 group_name_end
= trials_string
.length();
426 // Verify if the trial should be activated or not.
428 bool force_activation
= false;
429 if (trials_string
[next_item
] == kActivationMarker
) {
430 // Name cannot be only the indicator.
431 if (name_end
- next_item
== 1)
434 force_activation
= true;
436 name
.append(trials_string
, next_item
, name_end
- next_item
);
437 std::string
group_name(trials_string
, name_end
+ 1,
438 group_name_end
- name_end
- 1);
439 next_item
= group_name_end
+ 1;
441 if (ignored_trial_names
.find(name
) != ignored_trial_names
.end())
444 FieldTrial
* trial
= CreateFieldTrial(name
, group_name
);
447 if (mode
== ACTIVATE_TRIALS
|| force_activation
) {
448 // Call |group()| to mark the trial as "used" and notify observers, if
449 // any. This is useful to ensure that field trials created in child
450 // processes are properly reported in crash reports.
458 FieldTrial
* FieldTrialList::CreateFieldTrial(
459 const std::string
& name
,
460 const std::string
& group_name
) {
462 DCHECK_GE(name
.size(), 0u);
463 DCHECK_GE(group_name
.size(), 0u);
464 if (name
.empty() || group_name
.empty() || !global_
)
467 FieldTrial
* field_trial
= FieldTrialList::Find(name
);
469 // In single process mode, or when we force them from the command line,
470 // we may have already created the field trial.
471 if (field_trial
->group_name_internal() != group_name
)
475 const int kTotalProbability
= 100;
476 field_trial
= new FieldTrial(name
, kTotalProbability
, group_name
, 0);
477 FieldTrialList::Register(field_trial
);
478 // Force the trial, which will also finalize the group choice.
479 field_trial
->SetForced();
484 void FieldTrialList::AddObserver(Observer
* observer
) {
487 global_
->observer_list_
->AddObserver(observer
);
491 void FieldTrialList::RemoveObserver(Observer
* observer
) {
494 global_
->observer_list_
->RemoveObserver(observer
);
498 void FieldTrialList::NotifyFieldTrialGroupSelection(FieldTrial
* field_trial
) {
503 AutoLock
auto_lock(global_
->lock_
);
504 if (field_trial
->group_reported_
)
506 field_trial
->group_reported_
= true;
509 if (!field_trial
->enable_field_trial_
)
512 global_
->observer_list_
->Notify(
513 &FieldTrialList::Observer::OnFieldTrialGroupFinalized
,
514 field_trial
->trial_name(),
515 field_trial
->group_name_internal());
519 size_t FieldTrialList::GetFieldTrialCount() {
522 AutoLock
auto_lock(global_
->lock_
);
523 return global_
->registered_
.size();
527 const FieldTrial::EntropyProvider
*
528 FieldTrialList::GetEntropyProviderForOneTimeRandomization() {
530 used_without_global_
= true;
534 return global_
->entropy_provider_
.get();
537 FieldTrial
* FieldTrialList::PreLockedFind(const std::string
& name
) {
538 RegistrationMap::iterator it
= registered_
.find(name
);
539 if (registered_
.end() == it
)
545 void FieldTrialList::Register(FieldTrial
* trial
) {
547 used_without_global_
= true;
550 AutoLock
auto_lock(global_
->lock_
);
551 DCHECK(!global_
->PreLockedFind(trial
->trial_name()));
553 trial
->SetTrialRegistered();
554 global_
->registered_
[trial
->trial_name()] = trial
;