Roll src/third_party/skia d32087a:1052f51
[chromium-blink-merge.git] / base / metrics / field_trial.cc
blob391bfc5f7cdb2976b03e54d9f27c4a7badf33304
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"
7 #include <algorithm>
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"
17 namespace base {
19 namespace {
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);
24 DCHECK_GT(month, 0);
25 DCHECK_LT(month, 13);
26 DCHECK_GT(day_of_month, 0);
27 DCHECK_LT(day_of_month, 32);
29 Time::Exploded exploded;
30 exploded.year = year;
31 exploded.month = month;
32 exploded.day_of_week = 0; // Should be unused.
33 exploded.day_of_month = day_of_month;
34 exploded.hour = 0;
35 exploded.minute = 0;
36 exploded.second = 0;
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);
61 } // namespace
63 // statics
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.
97 if (forced_) {
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.
104 return group_;
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);
132 return group_;
135 const std::string& FieldTrial::group_name() {
136 // Call |group()| to ensure group gets assigned and observers are notified.
137 group();
138 DCHECK(!group_name_.empty());
139 return group_name_;
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.
145 if (forced_)
146 return;
148 // And we must finalize the group choice before we mark ourselves as forced.
149 FinalizeGroupChoice();
150 forced_ = true;
153 // static
154 void FieldTrial::EnableBenchmarking() {
155 DCHECK_EQ(0u, FieldTrialList::GetFieldTrialCount());
156 enable_benchmarking_ = true;
159 // static
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,
166 entropy_value);
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),
181 forced_(false),
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) {
198 group_ = number;
199 if (group_name.empty())
200 StringAppendF(&group_name_, "%d", group_);
201 else
202 group_name_ = group_name;
203 DVLOG(1) << "Field trial: " << trial_name_ << " Group choice:" << group_name_;
206 void FieldTrial::FinalizeGroupChoice() {
207 if (group_ != kNotFinalized)
208 return;
209 accumulated_group_probability_ = divisor_;
210 // Here it's OK to use |kDefaultGroupNumber| since we can't be forced and not
211 // finalized.
212 DCHECK(!forced_);
213 SetGroupChoice(default_group_name_, kDefaultGroupNumber);
216 bool FieldTrial::GetActiveGroup(ActiveGroup* active_group) const {
217 if (!group_reported_ || !enable_field_trial_)
218 return false;
219 DCHECK_NE(group_, kNotFinalized);
220 active_group->trial_name = trial_name_;
221 active_group->group_name = group_name_;
222 return true;
225 bool FieldTrial::GetState(FieldTrialState* field_trial_state) const {
226 if (!enable_field_trial_)
227 return false;
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_;
233 else
234 field_trial_state->group_name = default_group_name_;
235 field_trial_state->activated = group_reported_;
236 return true;
239 //------------------------------------------------------------------------------
240 // FieldTrialList methods and members.
242 // static
243 FieldTrialList* FieldTrialList::global_ = NULL;
245 // static
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)) {
256 DCHECK(!global_);
257 DCHECK(!used_without_global_);
258 global_ = this;
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_);
274 global_ = NULL;
277 // static
278 FieldTrial* FieldTrialList::FactoryGetFieldTrial(
279 const std::string& trial_name,
280 FieldTrial::Probability total_probability,
281 const std::string& default_group_name,
282 const int year,
283 const int month,
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);
292 // static
293 FieldTrial* FieldTrialList::FactoryGetFieldTrialWithRandomizationSeed(
294 const std::string& trial_name,
295 FieldTrial::Probability total_probability,
296 const std::string& default_group_name,
297 const int year,
298 const int month,
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_;
318 } else {
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;
323 COMPILE_ASSERT(
324 kNonConflictingGroupNumber != FieldTrial::kDefaultGroupNumber,
325 conflicting_default_group_number);
326 COMPILE_ASSERT(
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,
341 randomization_seed);
342 } else {
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);
353 return field_trial;
356 // static
357 FieldTrial* FieldTrialList::Find(const std::string& name) {
358 if (!global_)
359 return NULL;
360 AutoLock auto_lock(global_->lock_);
361 return global_->PreLockedFind(name);
364 // static
365 int FieldTrialList::FindValue(const std::string& name) {
366 FieldTrial* field_trial = Find(name);
367 if (field_trial)
368 return field_trial->group();
369 return FieldTrial::kNotFinalized;
372 // static
373 std::string FieldTrialList::FindFullName(const std::string& name) {
374 FieldTrial* field_trial = Find(name);
375 if (field_trial)
376 return field_trial->group_name();
377 return std::string();
380 // static
381 bool FieldTrialList::TrialExists(const std::string& name) {
382 return Find(name) != NULL;
385 // static
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);
402 // static
403 void FieldTrialList::AllStatesToString(std::string* output) {
404 if (!global_)
405 return;
406 AutoLock auto_lock(global_->lock_);
408 for (const auto& registered : global_->registered_) {
409 FieldTrial::FieldTrialState trial;
410 if (!registered.second->GetState(&trial))
411 continue;
412 DCHECK_EQ(std::string::npos,
413 trial.trial_name.find(kPersistentStringSeparator));
414 DCHECK_EQ(std::string::npos,
415 trial.group_name.find(kPersistentStringSeparator));
416 if (trial.activated)
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);
425 // static
426 void FieldTrialList::GetActiveFieldTrialGroups(
427 FieldTrial::ActiveGroups* active_groups) {
428 DCHECK(active_groups->empty());
429 if (!global_)
430 return;
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);
441 // static
442 bool FieldTrialList::CreateTrialsFromString(
443 const std::string& trials_string,
444 FieldTrialActivationMode mode,
445 const std::set<std::string>& ignored_trial_names) {
446 DCHECK(global_);
447 if (trials_string.empty() || !global_)
448 return true;
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)
454 return false;
455 size_t group_name_end = trials_string.find(kPersistentStringSeparator,
456 name_end + 1);
457 if (name_end + 1 == group_name_end)
458 return false;
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.
463 std::string name;
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)
468 return false;
469 next_item++;
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())
478 continue;
480 FieldTrial* trial = CreateFieldTrial(name, group_name);
481 if (!trial)
482 return false;
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.
487 trial->group();
490 return true;
493 // static
494 FieldTrial* FieldTrialList::CreateFieldTrial(
495 const std::string& name,
496 const std::string& group_name) {
497 DCHECK(global_);
498 DCHECK_GE(name.size(), 0u);
499 DCHECK_GE(group_name.size(), 0u);
500 if (name.empty() || group_name.empty() || !global_)
501 return NULL;
503 FieldTrial* field_trial = FieldTrialList::Find(name);
504 if (field_trial) {
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)
508 return NULL;
509 return field_trial;
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();
516 return field_trial;
519 // static
520 void FieldTrialList::AddObserver(Observer* observer) {
521 if (!global_)
522 return;
523 global_->observer_list_->AddObserver(observer);
526 // static
527 void FieldTrialList::RemoveObserver(Observer* observer) {
528 if (!global_)
529 return;
530 global_->observer_list_->RemoveObserver(observer);
533 // static
534 void FieldTrialList::NotifyFieldTrialGroupSelection(FieldTrial* field_trial) {
535 if (!global_)
536 return;
539 AutoLock auto_lock(global_->lock_);
540 if (field_trial->group_reported_)
541 return;
542 field_trial->group_reported_ = true;
545 if (!field_trial->enable_field_trial_)
546 return;
548 global_->observer_list_->Notify(
549 FROM_HERE, &FieldTrialList::Observer::OnFieldTrialGroupFinalized,
550 field_trial->trial_name(), field_trial->group_name_internal());
553 // static
554 size_t FieldTrialList::GetFieldTrialCount() {
555 if (!global_)
556 return 0;
557 AutoLock auto_lock(global_->lock_);
558 return global_->registered_.size();
561 // static
562 const FieldTrial::EntropyProvider*
563 FieldTrialList::GetEntropyProviderForOneTimeRandomization() {
564 if (!global_) {
565 used_without_global_ = true;
566 return NULL;
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)
575 return NULL;
576 return it->second;
579 // static
580 void FieldTrialList::Register(FieldTrial* trial) {
581 if (!global_) {
582 used_without_global_ = true;
583 return;
585 AutoLock auto_lock(global_->lock_);
586 DCHECK(!global_->PreLockedFind(trial->trial_name()));
587 trial->AddRef();
588 trial->SetTrialRegistered();
589 global_->registered_[trial->trial_name()] = trial;
592 } // namespace base