Re-land: content: Refactor GPU memory buffer framework.
[chromium-blink-merge.git] / base / metrics / field_trial.cc
blob7efca7a3ef53cdaa8093b880b44d7e469bebc27d
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"
16 #include "base/sys_byteorder.h"
18 namespace base {
20 namespace {
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);
25 DCHECK_GT(month, 0);
26 DCHECK_LT(month, 13);
27 DCHECK_GT(day_of_month, 0);
28 DCHECK_LT(day_of_month, 32);
30 Time::Exploded exploded;
31 exploded.year = year;
32 exploded.month = month;
33 exploded.day_of_week = 0; // Should be unused.
34 exploded.day_of_month = day_of_month;
35 exploded.hour = 0;
36 exploded.minute = 0;
37 exploded.second = 0;
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);
62 } // namespace
64 // statics
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.
98 if (forced_) {
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.
105 return group_;
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);
133 return group_;
136 const std::string& FieldTrial::group_name() {
137 // Call |group()| to ensure group gets assigned and observers are notified.
138 group();
139 DCHECK(!group_name_.empty());
140 return group_name_;
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.
146 if (forced_)
147 return;
149 // And we must finalize the group choice before we mark ourselves as forced.
150 FinalizeGroupChoice();
151 forced_ = true;
154 // static
155 void FieldTrial::EnableBenchmarking() {
156 DCHECK_EQ(0u, FieldTrialList::GetFieldTrialCount());
157 enable_benchmarking_ = true;
160 // static
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,
167 entropy_value);
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),
182 forced_(false),
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) {
199 group_ = number;
200 if (group_name.empty())
201 StringAppendF(&group_name_, "%d", group_);
202 else
203 group_name_ = group_name;
204 DVLOG(1) << "Field trial: " << trial_name_ << " Group choice:" << group_name_;
207 void FieldTrial::FinalizeGroupChoice() {
208 if (group_ != kNotFinalized)
209 return;
210 accumulated_group_probability_ = divisor_;
211 // Here it's OK to use |kDefaultGroupNumber| since we can't be forced and not
212 // finalized.
213 DCHECK(!forced_);
214 SetGroupChoice(default_group_name_, kDefaultGroupNumber);
217 bool FieldTrial::GetActiveGroup(ActiveGroup* active_group) const {
218 if (!group_reported_ || !enable_field_trial_)
219 return false;
220 DCHECK_NE(group_, kNotFinalized);
221 active_group->trial_name = trial_name_;
222 active_group->group_name = group_name_;
223 return true;
226 //------------------------------------------------------------------------------
227 // FieldTrialList methods and members.
229 // static
230 FieldTrialList* FieldTrialList::global_ = NULL;
232 // static
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)) {
243 DCHECK(!global_);
244 DCHECK(!used_without_global_);
245 global_ = this;
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_);
261 global_ = NULL;
264 // static
265 FieldTrial* FieldTrialList::FactoryGetFieldTrial(
266 const std::string& trial_name,
267 FieldTrial::Probability total_probability,
268 const std::string& default_group_name,
269 const int year,
270 const int month,
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);
279 // static
280 FieldTrial* FieldTrialList::FactoryGetFieldTrialWithRandomizationSeed(
281 const std::string& trial_name,
282 FieldTrial::Probability total_probability,
283 const std::string& default_group_name,
284 const int year,
285 const int month,
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_;
305 } else {
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;
310 COMPILE_ASSERT(
311 kNonConflictingGroupNumber != FieldTrial::kDefaultGroupNumber,
312 conflicting_default_group_number);
313 COMPILE_ASSERT(
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,
328 randomization_seed);
329 } else {
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);
340 return field_trial;
343 // static
344 FieldTrial* FieldTrialList::Find(const std::string& name) {
345 if (!global_)
346 return NULL;
347 AutoLock auto_lock(global_->lock_);
348 return global_->PreLockedFind(name);
351 // static
352 int FieldTrialList::FindValue(const std::string& name) {
353 FieldTrial* field_trial = Find(name);
354 if (field_trial)
355 return field_trial->group();
356 return FieldTrial::kNotFinalized;
359 // static
360 std::string FieldTrialList::FindFullName(const std::string& name) {
361 FieldTrial* field_trial = Find(name);
362 if (field_trial)
363 return field_trial->group_name();
364 return std::string();
367 // static
368 bool FieldTrialList::TrialExists(const std::string& name) {
369 return Find(name) != NULL;
372 // static
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);
389 // static
390 void FieldTrialList::GetActiveFieldTrialGroups(
391 FieldTrial::ActiveGroups* active_groups) {
392 DCHECK(active_groups->empty());
393 if (!global_)
394 return;
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);
405 // static
406 bool FieldTrialList::CreateTrialsFromString(
407 const std::string& trials_string,
408 FieldTrialActivationMode mode,
409 const std::set<std::string>& ignored_trial_names) {
410 DCHECK(global_);
411 if (trials_string.empty() || !global_)
412 return true;
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)
418 return false;
419 size_t group_name_end = trials_string.find(kPersistentStringSeparator,
420 name_end + 1);
421 if (name_end + 1 == group_name_end)
422 return false;
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.
427 std::string name;
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)
432 return false;
433 next_item++;
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())
442 continue;
444 FieldTrial* trial = CreateFieldTrial(name, group_name);
445 if (!trial)
446 return false;
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.
451 trial->group();
454 return true;
457 // static
458 FieldTrial* FieldTrialList::CreateFieldTrial(
459 const std::string& name,
460 const std::string& group_name) {
461 DCHECK(global_);
462 DCHECK_GE(name.size(), 0u);
463 DCHECK_GE(group_name.size(), 0u);
464 if (name.empty() || group_name.empty() || !global_)
465 return NULL;
467 FieldTrial* field_trial = FieldTrialList::Find(name);
468 if (field_trial) {
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)
472 return NULL;
473 return field_trial;
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();
480 return field_trial;
483 // static
484 void FieldTrialList::AddObserver(Observer* observer) {
485 if (!global_)
486 return;
487 global_->observer_list_->AddObserver(observer);
490 // static
491 void FieldTrialList::RemoveObserver(Observer* observer) {
492 if (!global_)
493 return;
494 global_->observer_list_->RemoveObserver(observer);
497 // static
498 void FieldTrialList::NotifyFieldTrialGroupSelection(FieldTrial* field_trial) {
499 if (!global_)
500 return;
503 AutoLock auto_lock(global_->lock_);
504 if (field_trial->group_reported_)
505 return;
506 field_trial->group_reported_ = true;
509 if (!field_trial->enable_field_trial_)
510 return;
512 global_->observer_list_->Notify(
513 &FieldTrialList::Observer::OnFieldTrialGroupFinalized,
514 field_trial->trial_name(),
515 field_trial->group_name_internal());
518 // static
519 size_t FieldTrialList::GetFieldTrialCount() {
520 if (!global_)
521 return 0;
522 AutoLock auto_lock(global_->lock_);
523 return global_->registered_.size();
526 // static
527 const FieldTrial::EntropyProvider*
528 FieldTrialList::GetEntropyProviderForOneTimeRandomization() {
529 if (!global_) {
530 used_without_global_ = true;
531 return NULL;
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)
540 return NULL;
541 return it->second;
544 // static
545 void FieldTrialList::Register(FieldTrial* trial) {
546 if (!global_) {
547 used_without_global_ = true;
548 return;
550 AutoLock auto_lock(global_->lock_);
551 DCHECK(!global_->PreLockedFind(trial->trial_name()));
552 trial->AddRef();
553 trial->SetTrialRegistered();
554 global_->registered_[trial->trial_name()] = trial;
557 } // namespace base