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"
21 // Created a time value based on |year|, |month| and |day_of_month| parameters.
22 Time
CreateTimeFromParams(int year
, int month
, int day_of_month
) {
23 DCHECK_GT(year
, 1970);
26 DCHECK_GT(day_of_month
, 0);
27 DCHECK_LT(day_of_month
, 32);
29 Time::Exploded exploded
;
31 exploded
.month
= month
;
32 exploded
.day_of_week
= 0; // Should be unused.
33 exploded
.day_of_month
= day_of_month
;
37 exploded
.millisecond
= 0;
39 return Time::FromLocalExploded(exploded
);
42 // Returns the boundary value for comparing against the FieldTrial's added
43 // groups for a given |divisor| (total probability) and |entropy_value|.
44 FieldTrial::Probability
GetGroupBoundaryValue(
45 FieldTrial::Probability divisor
,
46 double entropy_value
) {
47 // Add a tiny epsilon value to get consistent results when converting floating
48 // points to int. Without it, boundary values have inconsistent results, e.g.:
50 // static_cast<FieldTrial::Probability>(100 * 0.56) == 56
51 // static_cast<FieldTrial::Probability>(100 * 0.57) == 56
52 // static_cast<FieldTrial::Probability>(100 * 0.58) == 57
53 // static_cast<FieldTrial::Probability>(100 * 0.59) == 59
54 const double kEpsilon
= 1e-8;
55 const FieldTrial::Probability result
=
56 static_cast<FieldTrial::Probability
>(divisor
* entropy_value
+ kEpsilon
);
57 // Ensure that adding the epsilon still results in a value < |divisor|.
58 return std::min(result
, divisor
- 1);
64 const int FieldTrial::kNotFinalized
= -1;
65 const int FieldTrial::kDefaultGroupNumber
= 0;
66 bool FieldTrial::enable_benchmarking_
= false;
68 const char FieldTrialList::kPersistentStringSeparator('/');
69 const char FieldTrialList::kActivationMarker('*');
70 int FieldTrialList::kNoExpirationYear
= 0;
72 //------------------------------------------------------------------------------
73 // FieldTrial methods and members.
75 FieldTrial::EntropyProvider::~EntropyProvider() {
78 void FieldTrial::Disable() {
79 DCHECK(!group_reported_
);
80 enable_field_trial_
= false;
82 // In case we are disabled after initialization, we need to switch
83 // the trial to the default group.
84 if (group_
!= kNotFinalized
) {
85 // Only reset when not already the default group, because in case we were
86 // forced to the default group, the group number may not be
87 // kDefaultGroupNumber, so we should keep it as is.
88 if (group_name_
!= default_group_name_
)
89 SetGroupChoice(default_group_name_
, kDefaultGroupNumber
);
93 int FieldTrial::AppendGroup(const std::string
& name
,
94 Probability group_probability
) {
95 // When the group choice was previously forced, we only need to return the
96 // the id of the chosen group, and anything can be returned for the others.
98 DCHECK(!group_name_
.empty());
99 if (name
== group_name_
) {
100 // Note that while |group_| may be equal to |kDefaultGroupNumber| on the
101 // forced trial, it will not have the same value as the default group
102 // number returned from the non-forced |FactoryGetFieldTrial()| call,
103 // which takes care to ensure that this does not happen.
106 DCHECK_NE(next_group_number_
, group_
);
107 // We still return different numbers each time, in case some caller need
108 // them to be different.
109 return next_group_number_
++;
112 DCHECK_LE(group_probability
, divisor_
);
113 DCHECK_GE(group_probability
, 0);
115 if (enable_benchmarking_
|| !enable_field_trial_
)
116 group_probability
= 0;
118 accumulated_group_probability_
+= group_probability
;
120 DCHECK_LE(accumulated_group_probability_
, divisor_
);
121 if (group_
== kNotFinalized
&& accumulated_group_probability_
> random_
) {
122 // This is the group that crossed the random line, so we do the assignment.
123 SetGroupChoice(name
, next_group_number_
);
125 return next_group_number_
++;
128 int FieldTrial::group() {
129 FinalizeGroupChoice();
130 if (trial_registered_
)
131 FieldTrialList::NotifyFieldTrialGroupSelection(this);
135 const std::string
& FieldTrial::group_name() {
136 // Call |group()| to ensure group gets assigned and observers are notified.
138 DCHECK(!group_name_
.empty());
142 void FieldTrial::SetForced() {
143 // We might have been forced before (e.g., by CreateFieldTrial) and it's
144 // first come first served, e.g., command line switch has precedence.
148 // And we must finalize the group choice before we mark ourselves as forced.
149 FinalizeGroupChoice();
154 void FieldTrial::EnableBenchmarking() {
155 DCHECK_EQ(0u, FieldTrialList::GetFieldTrialCount());
156 enable_benchmarking_
= true;
160 FieldTrial
* FieldTrial::CreateSimulatedFieldTrial(
161 const std::string
& trial_name
,
162 Probability total_probability
,
163 const std::string
& default_group_name
,
164 double entropy_value
) {
165 return new FieldTrial(trial_name
, total_probability
, default_group_name
,
169 FieldTrial::FieldTrial(const std::string
& trial_name
,
170 const Probability total_probability
,
171 const std::string
& default_group_name
,
172 double entropy_value
)
173 : trial_name_(trial_name
),
174 divisor_(total_probability
),
175 default_group_name_(default_group_name
),
176 random_(GetGroupBoundaryValue(total_probability
, entropy_value
)),
177 accumulated_group_probability_(0),
178 next_group_number_(kDefaultGroupNumber
+ 1),
179 group_(kNotFinalized
),
180 enable_field_trial_(true),
182 group_reported_(false),
183 trial_registered_(false) {
184 DCHECK_GT(total_probability
, 0);
185 DCHECK(!trial_name_
.empty());
186 DCHECK(!default_group_name_
.empty());
189 FieldTrial::~FieldTrial() {}
191 void FieldTrial::SetTrialRegistered() {
192 DCHECK_EQ(kNotFinalized
, group_
);
193 DCHECK(!trial_registered_
);
194 trial_registered_
= true;
197 void FieldTrial::SetGroupChoice(const std::string
& group_name
, int number
) {
199 if (group_name
.empty())
200 StringAppendF(&group_name_
, "%d", group_
);
202 group_name_
= group_name
;
203 DVLOG(1) << "Field trial: " << trial_name_
<< " Group choice:" << group_name_
;
206 void FieldTrial::FinalizeGroupChoice() {
207 if (group_
!= kNotFinalized
)
209 accumulated_group_probability_
= divisor_
;
210 // Here it's OK to use |kDefaultGroupNumber| since we can't be forced and not
213 SetGroupChoice(default_group_name_
, kDefaultGroupNumber
);
216 bool FieldTrial::GetActiveGroup(ActiveGroup
* active_group
) const {
217 if (!group_reported_
|| !enable_field_trial_
)
219 DCHECK_NE(group_
, kNotFinalized
);
220 active_group
->trial_name
= trial_name_
;
221 active_group
->group_name
= group_name_
;
225 bool FieldTrial::GetState(FieldTrialState
* field_trial_state
) const {
226 if (!enable_field_trial_
)
228 field_trial_state
->trial_name
= trial_name_
;
229 // If the group name is empty (hasn't been finalized yet), use the default
230 // group name instead.
231 if (!group_name_
.empty())
232 field_trial_state
->group_name
= group_name_
;
234 field_trial_state
->group_name
= default_group_name_
;
235 field_trial_state
->activated
= group_reported_
;
239 //------------------------------------------------------------------------------
240 // FieldTrialList methods and members.
243 FieldTrialList
* FieldTrialList::global_
= NULL
;
246 bool FieldTrialList::used_without_global_
= false;
248 FieldTrialList::Observer::~Observer() {
251 FieldTrialList::FieldTrialList(
252 const FieldTrial::EntropyProvider
* entropy_provider
)
253 : entropy_provider_(entropy_provider
),
254 observer_list_(new ObserverListThreadSafe
<FieldTrialList::Observer
>(
255 ObserverListBase
<FieldTrialList::Observer
>::NOTIFY_EXISTING_ONLY
)) {
257 DCHECK(!used_without_global_
);
260 Time two_years_from_build_time
= GetBuildTime() + TimeDelta::FromDays(730);
261 Time::Exploded exploded
;
262 two_years_from_build_time
.LocalExplode(&exploded
);
263 kNoExpirationYear
= exploded
.year
;
266 FieldTrialList::~FieldTrialList() {
267 AutoLock
auto_lock(lock_
);
268 while (!registered_
.empty()) {
269 RegistrationMap::iterator it
= registered_
.begin();
270 it
->second
->Release();
271 registered_
.erase(it
->first
);
273 DCHECK_EQ(this, global_
);
278 FieldTrial
* FieldTrialList::FactoryGetFieldTrial(
279 const std::string
& trial_name
,
280 FieldTrial::Probability total_probability
,
281 const std::string
& default_group_name
,
284 const int day_of_month
,
285 FieldTrial::RandomizationType randomization_type
,
286 int* default_group_number
) {
287 return FactoryGetFieldTrialWithRandomizationSeed(
288 trial_name
, total_probability
, default_group_name
,
289 year
, month
, day_of_month
, randomization_type
, 0, default_group_number
);
293 FieldTrial
* FieldTrialList::FactoryGetFieldTrialWithRandomizationSeed(
294 const std::string
& trial_name
,
295 FieldTrial::Probability total_probability
,
296 const std::string
& default_group_name
,
299 const int day_of_month
,
300 FieldTrial::RandomizationType randomization_type
,
301 uint32 randomization_seed
,
302 int* default_group_number
) {
303 if (default_group_number
)
304 *default_group_number
= FieldTrial::kDefaultGroupNumber
;
305 // Check if the field trial has already been created in some other way.
306 FieldTrial
* existing_trial
= Find(trial_name
);
307 if (existing_trial
) {
308 CHECK(existing_trial
->forced_
);
309 // If the default group name differs between the existing forced trial
310 // and this trial, then use a different value for the default group number.
311 if (default_group_number
&&
312 default_group_name
!= existing_trial
->default_group_name()) {
313 // If the new default group number corresponds to the group that was
314 // chosen for the forced trial (which has been finalized when it was
315 // forced), then set the default group number to that.
316 if (default_group_name
== existing_trial
->group_name_internal()) {
317 *default_group_number
= existing_trial
->group_
;
319 // Otherwise, use |kNonConflictingGroupNumber| (-2) for the default
320 // group number, so that it does not conflict with the |AppendGroup()|
321 // result for the chosen group.
322 const int kNonConflictingGroupNumber
= -2;
324 kNonConflictingGroupNumber
!= FieldTrial::kDefaultGroupNumber
,
325 conflicting_default_group_number
);
327 kNonConflictingGroupNumber
!= FieldTrial::kNotFinalized
,
328 conflicting_default_group_number
);
329 *default_group_number
= kNonConflictingGroupNumber
;
332 return existing_trial
;
335 double entropy_value
;
336 if (randomization_type
== FieldTrial::ONE_TIME_RANDOMIZED
) {
337 const FieldTrial::EntropyProvider
* entropy_provider
=
338 GetEntropyProviderForOneTimeRandomization();
339 CHECK(entropy_provider
);
340 entropy_value
= entropy_provider
->GetEntropyForTrial(trial_name
,
343 DCHECK_EQ(FieldTrial::SESSION_RANDOMIZED
, randomization_type
);
344 DCHECK_EQ(0U, randomization_seed
);
345 entropy_value
= RandDouble();
348 FieldTrial
* field_trial
= new FieldTrial(trial_name
, total_probability
,
349 default_group_name
, entropy_value
);
350 if (GetBuildTime() > CreateTimeFromParams(year
, month
, day_of_month
))
351 field_trial
->Disable();
352 FieldTrialList::Register(field_trial
);
357 FieldTrial
* FieldTrialList::Find(const std::string
& name
) {
360 AutoLock
auto_lock(global_
->lock_
);
361 return global_
->PreLockedFind(name
);
365 int FieldTrialList::FindValue(const std::string
& name
) {
366 FieldTrial
* field_trial
= Find(name
);
368 return field_trial
->group();
369 return FieldTrial::kNotFinalized
;
373 std::string
FieldTrialList::FindFullName(const std::string
& name
) {
374 FieldTrial
* field_trial
= Find(name
);
376 return field_trial
->group_name();
377 return std::string();
381 bool FieldTrialList::TrialExists(const std::string
& name
) {
382 return Find(name
) != NULL
;
386 void FieldTrialList::StatesToString(std::string
* output
) {
387 FieldTrial::ActiveGroups active_groups
;
388 GetActiveFieldTrialGroups(&active_groups
);
389 for (FieldTrial::ActiveGroups::const_iterator it
= active_groups
.begin();
390 it
!= active_groups
.end(); ++it
) {
391 DCHECK_EQ(std::string::npos
,
392 it
->trial_name
.find(kPersistentStringSeparator
));
393 DCHECK_EQ(std::string::npos
,
394 it
->group_name
.find(kPersistentStringSeparator
));
395 output
->append(it
->trial_name
);
396 output
->append(1, kPersistentStringSeparator
);
397 output
->append(it
->group_name
);
398 output
->append(1, kPersistentStringSeparator
);
403 void FieldTrialList::AllStatesToString(std::string
* output
) {
406 AutoLock
auto_lock(global_
->lock_
);
408 for (const auto& registered
: global_
->registered_
) {
409 FieldTrial::FieldTrialState trial
;
410 if (!registered
.second
->GetState(&trial
))
412 DCHECK_EQ(std::string::npos
,
413 trial
.trial_name
.find(kPersistentStringSeparator
));
414 DCHECK_EQ(std::string::npos
,
415 trial
.group_name
.find(kPersistentStringSeparator
));
417 output
->append(1, kActivationMarker
);
418 output
->append(trial
.trial_name
);
419 output
->append(1, kPersistentStringSeparator
);
420 output
->append(trial
.group_name
);
421 output
->append(1, kPersistentStringSeparator
);
426 void FieldTrialList::GetActiveFieldTrialGroups(
427 FieldTrial::ActiveGroups
* active_groups
) {
428 DCHECK(active_groups
->empty());
431 AutoLock
auto_lock(global_
->lock_
);
433 for (RegistrationMap::iterator it
= global_
->registered_
.begin();
434 it
!= global_
->registered_
.end(); ++it
) {
435 FieldTrial::ActiveGroup active_group
;
436 if (it
->second
->GetActiveGroup(&active_group
))
437 active_groups
->push_back(active_group
);
442 bool FieldTrialList::CreateTrialsFromString(
443 const std::string
& trials_string
,
444 FieldTrialActivationMode mode
,
445 const std::set
<std::string
>& ignored_trial_names
) {
447 if (trials_string
.empty() || !global_
)
450 size_t next_item
= 0;
451 while (next_item
< trials_string
.length()) {
452 size_t name_end
= trials_string
.find(kPersistentStringSeparator
, next_item
);
453 if (name_end
== trials_string
.npos
|| next_item
== name_end
)
455 size_t group_name_end
= trials_string
.find(kPersistentStringSeparator
,
457 if (name_end
+ 1 == group_name_end
)
459 if (group_name_end
== trials_string
.npos
)
460 group_name_end
= trials_string
.length();
462 // Verify if the trial should be activated or not.
464 bool force_activation
= false;
465 if (trials_string
[next_item
] == kActivationMarker
) {
466 // Name cannot be only the indicator.
467 if (name_end
- next_item
== 1)
470 force_activation
= true;
472 name
.append(trials_string
, next_item
, name_end
- next_item
);
473 std::string
group_name(trials_string
, name_end
+ 1,
474 group_name_end
- name_end
- 1);
475 next_item
= group_name_end
+ 1;
477 if (ignored_trial_names
.find(name
) != ignored_trial_names
.end())
480 FieldTrial
* trial
= CreateFieldTrial(name
, group_name
);
483 if (mode
== ACTIVATE_TRIALS
|| force_activation
) {
484 // Call |group()| to mark the trial as "used" and notify observers, if
485 // any. This is useful to ensure that field trials created in child
486 // processes are properly reported in crash reports.
494 FieldTrial
* FieldTrialList::CreateFieldTrial(
495 const std::string
& name
,
496 const std::string
& group_name
) {
498 DCHECK_GE(name
.size(), 0u);
499 DCHECK_GE(group_name
.size(), 0u);
500 if (name
.empty() || group_name
.empty() || !global_
)
503 FieldTrial
* field_trial
= FieldTrialList::Find(name
);
505 // In single process mode, or when we force them from the command line,
506 // we may have already created the field trial.
507 if (field_trial
->group_name_internal() != group_name
)
511 const int kTotalProbability
= 100;
512 field_trial
= new FieldTrial(name
, kTotalProbability
, group_name
, 0);
513 FieldTrialList::Register(field_trial
);
514 // Force the trial, which will also finalize the group choice.
515 field_trial
->SetForced();
520 void FieldTrialList::AddObserver(Observer
* observer
) {
523 global_
->observer_list_
->AddObserver(observer
);
527 void FieldTrialList::RemoveObserver(Observer
* observer
) {
530 global_
->observer_list_
->RemoveObserver(observer
);
534 void FieldTrialList::NotifyFieldTrialGroupSelection(FieldTrial
* field_trial
) {
539 AutoLock
auto_lock(global_
->lock_
);
540 if (field_trial
->group_reported_
)
542 field_trial
->group_reported_
= true;
545 if (!field_trial
->enable_field_trial_
)
548 global_
->observer_list_
->Notify(
549 FROM_HERE
, &FieldTrialList::Observer::OnFieldTrialGroupFinalized
,
550 field_trial
->trial_name(), field_trial
->group_name_internal());
554 size_t FieldTrialList::GetFieldTrialCount() {
557 AutoLock
auto_lock(global_
->lock_
);
558 return global_
->registered_
.size();
562 const FieldTrial::EntropyProvider
*
563 FieldTrialList::GetEntropyProviderForOneTimeRandomization() {
565 used_without_global_
= true;
569 return global_
->entropy_provider_
.get();
572 FieldTrial
* FieldTrialList::PreLockedFind(const std::string
& name
) {
573 RegistrationMap::iterator it
= registered_
.find(name
);
574 if (registered_
.end() == it
)
580 void FieldTrialList::Register(FieldTrial
* trial
) {
582 used_without_global_
= true;
585 AutoLock
auto_lock(global_
->lock_
);
586 DCHECK(!global_
->PreLockedFind(trial
->trial_name()));
588 trial
->SetTrialRegistered();
589 global_
->registered_
[trial
->trial_name()] = trial
;