1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/metrics/statistics_recorder.h"
#include <stddef.h>
#include <memory>
#include <optional>
#include <utility>
#include <vector>
#include "base/functional/bind.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_base.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/metrics_hashes.h"
#include "base/metrics/persistent_histogram_allocator.h"
#include "base/metrics/record_histogram_checker.h"
#include "base/metrics/sparse_histogram.h"
#include "base/test/task_environment.h"
#include "base/trace_event/histogram_scope.h" // no-presubmit-check
#include "base/values.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// Class to make sure any manipulations we do to the min log level are
// contained (i.e., do not affect other unit tests).
class LogStateSaver {
public:
LogStateSaver() = default;
LogStateSaver(const LogStateSaver&) = delete;
LogStateSaver& operator=(const LogStateSaver&) = delete;
~LogStateSaver() { logging::SetMinLogLevel(old_min_log_level_); }
private:
int old_min_log_level_ = logging::GetMinLogLevel();
};
// Test implementation of RecordHistogramChecker interface.
class OddRecordHistogramChecker : public base::RecordHistogramChecker {
public:
~OddRecordHistogramChecker() override = default;
// base::RecordHistogramChecker:
bool ShouldRecord(uint32_t histogram_hash) const override {
return histogram_hash % 2;
}
};
} // namespace
namespace base {
using testing::IsEmpty;
using testing::SizeIs;
using testing::UnorderedElementsAre;
class StatisticsRecorderTest : public testing::TestWithParam<bool> {
public:
StatisticsRecorderTest(const StatisticsRecorderTest&) = delete;
StatisticsRecorderTest& operator=(const StatisticsRecorderTest&) = delete;
protected:
const int32_t kAllocatorMemorySize = 64 << 10; // 64 KiB
StatisticsRecorderTest() : use_persistent_histogram_allocator_(GetParam()) {
// Each test will have a clean state (no Histogram / BucketRanges
// registered).
InitializeStatisticsRecorder();
// Use persistent memory for histograms if so indicated by test parameter.
if (use_persistent_histogram_allocator_) {
GlobalHistogramAllocator::CreateWithLocalMemory(kAllocatorMemorySize, 0,
"StatisticsRecorderTest");
}
}
~StatisticsRecorderTest() override {
GlobalHistogramAllocator::ReleaseForTesting();
UninitializeStatisticsRecorder();
}
void InitializeStatisticsRecorder() {
DCHECK(!statistics_recorder_);
statistics_recorder_ = StatisticsRecorder::CreateTemporaryForTesting();
}
// Deletes the global recorder if there is any. This is used by test
// NotInitialized to ensure a clean global state.
void UninitializeStatisticsRecorder() {
statistics_recorder_.reset();
// Grab the lock, so we can access |top_| to satisfy locking annotations.
// Normally, this wouldn't be OK (we're taking a pointer to |top_| and then
// freeing it outside the lock), but in this case, it's benign because the
// test is single-threaded.
//
// Note: We can't clear |top_| in the locked block, because the
// StatisticsRecorder destructor expects that the lock isn't already held.
{
const AutoLock auto_lock(StatisticsRecorder::GetLock());
statistics_recorder_.reset(StatisticsRecorder::top_);
if (statistics_recorder_) {
// Prevent releasing ranges in test to avoid dangling pointers in
// created histogram objects.
statistics_recorder_->ranges_manager_
.DoNotReleaseRangesOnDestroyForTesting();
}
}
statistics_recorder_.reset();
DCHECK(!HasGlobalRecorder());
}
bool HasGlobalRecorder() {
const AutoLock auto_lock(StatisticsRecorder::GetLock());
return StatisticsRecorder::top_ != nullptr;
}
Histogram* CreateHistogram(DurableStringView durable_name,
HistogramBase::Sample32 min,
HistogramBase::Sample32 max,
size_t bucket_count) {
BucketRanges* ranges = new BucketRanges(bucket_count + 1);
Histogram::InitializeBucketRanges(min, max, ranges);
const BucketRanges* registered_ranges =
StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges);
return new Histogram(durable_name, registered_ranges);
}
template <size_t N>
Histogram* CreateHistogram(const char (&literal)[N],
HistogramBase::Sample32 min,
HistogramBase::Sample32 max,
size_t bucket_count) {
return CreateHistogram(DurableStringView(std::string_view(literal, N - 1)),
min, max, bucket_count);
}
void InitLogOnShutdown() { StatisticsRecorder::InitLogOnShutdown(); }
bool IsVLogInitialized() { return StatisticsRecorder::is_vlog_initialized_; }
void ResetVLogInitialized() {
UninitializeStatisticsRecorder();
StatisticsRecorder::is_vlog_initialized_ = false;
}
const bool use_persistent_histogram_allocator_;
std::unique_ptr<StatisticsRecorder> statistics_recorder_;
private:
LogStateSaver log_state_saver_;
};
// Run all HistogramTest cases with both heap and persistent memory.
INSTANTIATE_TEST_SUITE_P(Allocator, StatisticsRecorderTest, testing::Bool());
TEST_P(StatisticsRecorderTest, NotInitialized) {
UninitializeStatisticsRecorder();
EXPECT_FALSE(HasGlobalRecorder());
HistogramBase* const histogram =
CreateHistogram("TestHistogram", 1, 1000, 10);
EXPECT_EQ(StatisticsRecorder::RegisterOrDeleteDuplicate(histogram),
histogram);
EXPECT_TRUE(HasGlobalRecorder());
EXPECT_THAT(StatisticsRecorder::GetHistograms(),
UnorderedElementsAre(histogram));
UninitializeStatisticsRecorder();
EXPECT_FALSE(HasGlobalRecorder());
BucketRanges* const ranges = new BucketRanges(3);
ranges->ResetChecksum();
EXPECT_EQ(StatisticsRecorder::RegisterOrDeleteDuplicateRanges(ranges),
ranges);
EXPECT_TRUE(HasGlobalRecorder());
EXPECT_THAT(StatisticsRecorder::GetBucketRanges(),
UnorderedElementsAre(ranges));
}
TEST_P(StatisticsRecorderTest, RegisterHistogram) {
// Create a Histogram that was not registered.
Histogram* const histogram1 = CreateHistogram("TestHistogram1", 1, 1000, 10);
EXPECT_THAT(StatisticsRecorder::GetHistograms(), IsEmpty());
// Register the Histogram.
EXPECT_EQ(histogram1,
StatisticsRecorder::RegisterOrDeleteDuplicate(histogram1));
EXPECT_THAT(StatisticsRecorder::GetHistograms(),
UnorderedElementsAre(histogram1));
// Register the same Histogram again.
EXPECT_EQ(histogram1,
StatisticsRecorder::RegisterOrDeleteDuplicate(histogram1));
EXPECT_THAT(StatisticsRecorder::GetHistograms(),
UnorderedElementsAre(histogram1));
// Register another Histogram with the same name.
Histogram* const histogram2 = CreateHistogram("TestHistogram1", 1, 1000, 10);
EXPECT_NE(histogram1, histogram2);
EXPECT_EQ(histogram1,
StatisticsRecorder::RegisterOrDeleteDuplicate(histogram2));
EXPECT_THAT(StatisticsRecorder::GetHistograms(),
UnorderedElementsAre(histogram1));
// Register another Histogram with a different name.
Histogram* const histogram3 = CreateHistogram("TestHistogram0", 1, 1000, 10);
EXPECT_NE(histogram1, histogram3);
EXPECT_EQ(histogram3,
StatisticsRecorder::RegisterOrDeleteDuplicate(histogram3));
EXPECT_THAT(StatisticsRecorder::GetHistograms(),
UnorderedElementsAre(histogram1, histogram3));
}
TEST_P(StatisticsRecorderTest, FindHistogram) {
HistogramBase* histogram1 = Histogram::FactoryGet(
"TestHistogram1", 1, 1000, 10, HistogramBase::kNoFlags);
HistogramBase* histogram2 = Histogram::FactoryGet(
"TestHistogram2", 1, 1000, 10, HistogramBase::kNoFlags);
EXPECT_EQ(histogram1, StatisticsRecorder::FindHistogram("TestHistogram1"));
EXPECT_EQ(histogram2, StatisticsRecorder::FindHistogram("TestHistogram2"));
EXPECT_FALSE(StatisticsRecorder::FindHistogram("TestHistogram"));
// Create a new global allocator using the same memory as the old one. Any
// old one is kept around so the memory doesn't get released.
GlobalHistogramAllocator* old_global_allocator =
GlobalHistogramAllocator::ReleaseForTesting();
if (use_persistent_histogram_allocator_) {
GlobalHistogramAllocator::CreateWithPersistentMemory(
const_cast<void*>(old_global_allocator->data()),
old_global_allocator->length(), 0, old_global_allocator->Id(),
old_global_allocator->Name());
}
// Reset statistics-recorder to validate operation from a clean start.
UninitializeStatisticsRecorder();
InitializeStatisticsRecorder();
if (use_persistent_histogram_allocator_) {
EXPECT_TRUE(StatisticsRecorder::FindHistogram("TestHistogram1"));
EXPECT_TRUE(StatisticsRecorder::FindHistogram("TestHistogram2"));
} else {
EXPECT_FALSE(StatisticsRecorder::FindHistogram("TestHistogram1"));
EXPECT_FALSE(StatisticsRecorder::FindHistogram("TestHistogram2"));
}
EXPECT_FALSE(StatisticsRecorder::FindHistogram("TestHistogram"));
}
TEST_P(StatisticsRecorderTest, FindHistogramWithHash) {
HistogramBase* histogram1 = Histogram::FactoryGet(
"TestHistogram1", 1, 1000, 10, HistogramBase::kNoFlags);
HistogramBase* histogram2 = Histogram::FactoryGet(
"TestHistogram2", 1, 1000, 10, HistogramBase::kNoFlags);
auto hash_h1 = HashMetricName("TestHistogram1");
auto hash_h2 = HashMetricName("TestHistogram2");
auto hash_h = HashMetricName("TestHistogram");
EXPECT_EQ(histogram1,
StatisticsRecorder::FindHistogram(hash_h1, "TestHistogram1"));
EXPECT_EQ(histogram2,
StatisticsRecorder::FindHistogram(hash_h2, "TestHistogram2"));
EXPECT_FALSE(StatisticsRecorder::FindHistogram(hash_h, "TestHistogram"));
// Create a new global allocator using the same memory as the old one. Any
// old one is kept around so the memory doesn't get released.
GlobalHistogramAllocator* old_global_allocator =
GlobalHistogramAllocator::ReleaseForTesting();
if (use_persistent_histogram_allocator_) {
GlobalHistogramAllocator::CreateWithPersistentMemory(
const_cast<void*>(old_global_allocator->data()),
old_global_allocator->length(), 0, old_global_allocator->Id(),
old_global_allocator->Name());
}
// Reset statistics-recorder to validate operation from a clean start.
UninitializeStatisticsRecorder();
InitializeStatisticsRecorder();
if (use_persistent_histogram_allocator_) {
EXPECT_TRUE(StatisticsRecorder::FindHistogram(hash_h1, "TestHistogram1"));
EXPECT_TRUE(StatisticsRecorder::FindHistogram(hash_h2, "TestHistogram2"));
} else {
EXPECT_FALSE(StatisticsRecorder::FindHistogram(hash_h1, "TestHistogram1"));
EXPECT_FALSE(StatisticsRecorder::FindHistogram(hash_h2, "TestHistogram2"));
}
EXPECT_FALSE(StatisticsRecorder::FindHistogram(hash_h, "TestHistogram"));
}
TEST_P(StatisticsRecorderTest, WithName) {
Histogram::FactoryGet("TestHistogram1", 1, 1000, 10, Histogram::kNoFlags);
Histogram::FactoryGet("TestHistogram2", 1, 1000, 10, Histogram::kNoFlags);
Histogram::FactoryGet("TestHistogram3", 1, 1000, 10, Histogram::kNoFlags);
const auto histograms = StatisticsRecorder::GetHistograms();
EXPECT_THAT(histograms, SizeIs(3));
EXPECT_THAT(
StatisticsRecorder::WithName(histograms, "", /*case_sensitive=*/true),
SizeIs(3));
EXPECT_THAT(
StatisticsRecorder::WithName(histograms, "Test", /*case_sensitive=*/true),
SizeIs(3));
EXPECT_THAT(
StatisticsRecorder::WithName(histograms, "1", /*case_sensitive=*/true),
SizeIs(1));
EXPECT_THAT(StatisticsRecorder::WithName(histograms, "hello",
/*case_sensitive=*/true),
IsEmpty());
EXPECT_THAT(StatisticsRecorder::WithName(histograms, "hello",
/*case_sensitive=*/false),
IsEmpty());
EXPECT_THAT(
StatisticsRecorder::WithName(histograms, "test", /*case_sensitive=*/true),
IsEmpty());
EXPECT_THAT(StatisticsRecorder::WithName(histograms, "test",
/*case_sensitive=*/false),
SizeIs(3));
}
TEST_P(StatisticsRecorderTest, RegisterHistogramWithFactoryGet) {
EXPECT_THAT(StatisticsRecorder::GetHistograms(), IsEmpty());
// Create a histogram.
HistogramBase* const histogram1 = Histogram::FactoryGet(
"TestHistogram", 1, 1000, 10, HistogramBase::kNoFlags);
EXPECT_THAT(StatisticsRecorder::GetHistograms(),
UnorderedElementsAre(histogram1));
// Get an existing histogram.
HistogramBase* const histogram2 = Histogram::FactoryGet(
"TestHistogram", 1, 1000, 10, HistogramBase::kNoFlags);
EXPECT_EQ(histogram1, histogram2);
EXPECT_THAT(StatisticsRecorder::GetHistograms(),
UnorderedElementsAre(histogram1));
// Create a LinearHistogram.
HistogramBase* const histogram3 = LinearHistogram::FactoryGet(
"TestLinearHistogram", 1, 1000, 10, HistogramBase::kNoFlags);
EXPECT_THAT(StatisticsRecorder::GetHistograms(),
UnorderedElementsAre(histogram1, histogram3));
// Create a BooleanHistogram.
HistogramBase* const histogram4 = BooleanHistogram::FactoryGet(
"TestBooleanHistogram", HistogramBase::kNoFlags);
EXPECT_THAT(StatisticsRecorder::GetHistograms(),
UnorderedElementsAre(histogram1, histogram3, histogram4));
// Create a CustomHistogram.
std::vector<int> custom_ranges;
custom_ranges.push_back(1);
custom_ranges.push_back(5);
HistogramBase* const histogram5 = CustomHistogram::FactoryGet(
"TestCustomHistogram", custom_ranges, HistogramBase::kNoFlags);
EXPECT_THAT(
StatisticsRecorder::GetHistograms(),
UnorderedElementsAre(histogram1, histogram3, histogram4, histogram5));
}
TEST_P(StatisticsRecorderTest, RegisterHistogramWithMacros) {
// Macros cache pointers and so tests that use them can only be run once.
// Stop immediately if this test has run previously.
static bool already_run = false;
if (already_run) {
return;
}
already_run = true;
StatisticsRecorder::Histograms registered_histograms;
HistogramBase* histogram = Histogram::FactoryGet(
"TestHistogramCounts", 1, 1000000, 50, HistogramBase::kNoFlags);
// The histogram we got from macro is the same as from FactoryGet.
LOCAL_HISTOGRAM_COUNTS("TestHistogramCounts", 30);
registered_histograms = StatisticsRecorder::GetHistograms();
ASSERT_EQ(1u, registered_histograms.size());
EXPECT_EQ(histogram, registered_histograms[0]);
LOCAL_HISTOGRAM_TIMES("TestHistogramTimes", Days(1));
LOCAL_HISTOGRAM_ENUMERATION("TestHistogramEnumeration", 20, 200);
EXPECT_THAT(StatisticsRecorder::GetHistograms(), SizeIs(3));
}
TEST_P(StatisticsRecorderTest, BucketRangesSharing) {
EXPECT_THAT(StatisticsRecorder::GetBucketRanges(), IsEmpty());
Histogram::FactoryGet("Histogram", 1, 64, 8, HistogramBase::kNoFlags);
Histogram::FactoryGet("Histogram2", 1, 64, 8, HistogramBase::kNoFlags);
EXPECT_THAT(StatisticsRecorder::GetBucketRanges(), SizeIs(1));
Histogram::FactoryGet("Histogram3", 1, 64, 16, HistogramBase::kNoFlags);
EXPECT_THAT(StatisticsRecorder::GetBucketRanges(), SizeIs(2));
}
TEST_P(StatisticsRecorderTest, ToJSON) {
Histogram::FactoryGet("TestHistogram1", 1, 1000, 50, HistogramBase::kNoFlags)
->Add(30);
Histogram::FactoryGet("TestHistogram1", 1, 1000, 50, HistogramBase::kNoFlags)
->Add(40);
Histogram::FactoryGet("TestHistogram2", 1, 1000, 50, HistogramBase::kNoFlags)
->Add(30);
Histogram::FactoryGet("TestHistogram2", 1, 1000, 50, HistogramBase::kNoFlags)
->Add(40);
std::string json(StatisticsRecorder::ToJSON(JSON_VERBOSITY_LEVEL_FULL));
// Check for valid JSON.
std::optional<Value> root = JSONReader::Read(json);
ASSERT_TRUE(root);
Value::Dict* root_dict = root->GetIfDict();
ASSERT_TRUE(root_dict);
// No query should be set.
ASSERT_FALSE(root_dict->Find("query"));
const Value::List* histogram_list = root_dict->FindList("histograms");
ASSERT_TRUE(histogram_list);
ASSERT_EQ(2u, histogram_list->size());
// Examine the first histogram.
const Value::Dict* histogram_dict = (*histogram_list)[0].GetIfDict();
ASSERT_TRUE(histogram_dict);
auto sample_count = histogram_dict->FindInt("count");
ASSERT_TRUE(sample_count);
EXPECT_EQ(2, *sample_count);
const Value::List* buckets_list = histogram_dict->FindList("buckets");
ASSERT_TRUE(buckets_list);
EXPECT_EQ(2u, buckets_list->size());
}
// Check the serialized JSON with a different verbosity level.
TEST_P(StatisticsRecorderTest, ToJSONOmitBuckets) {
Histogram::FactoryGet("TestHistogram1", 1, 1000, 50, HistogramBase::kNoFlags)
->Add(30);
Histogram::FactoryGet("TestHistogram1", 1, 1000, 50, HistogramBase::kNoFlags)
->Add(40);
Histogram::FactoryGet("TestHistogram2", 1, 1000, 50, HistogramBase::kNoFlags)
->Add(30);
Histogram::FactoryGet("TestHistogram2", 1, 1000, 50, HistogramBase::kNoFlags)
->Add(40);
std::string json =
StatisticsRecorder::ToJSON(JSON_VERBOSITY_LEVEL_OMIT_BUCKETS);
std::optional<Value> root = JSONReader::Read(json);
ASSERT_TRUE(root);
Value::Dict* root_dict = root->GetIfDict();
ASSERT_TRUE(root_dict);
const Value::List* histogram_list = root_dict->FindList("histograms");
ASSERT_TRUE(histogram_list);
ASSERT_EQ(2u, histogram_list->size());
const Value::Dict* histogram_dict2 = (*histogram_list)[0].GetIfDict();
ASSERT_TRUE(histogram_dict2);
auto sample_count = histogram_dict2->FindInt("count");
ASSERT_TRUE(sample_count);
EXPECT_EQ(2, *sample_count);
const Value::List* buckets_list = histogram_dict2->FindList("buckets");
// Bucket information should be omitted.
ASSERT_FALSE(buckets_list);
}
TEST_P(StatisticsRecorderTest, IterationTest) {
Histogram::FactoryGet("IterationTest1", 1, 64, 16, HistogramBase::kNoFlags);
Histogram::FactoryGet("IterationTest2", 1, 64, 16, HistogramBase::kNoFlags);
auto histograms = StatisticsRecorder::GetHistograms();
EXPECT_THAT(histograms, SizeIs(2));
histograms = StatisticsRecorder::GetHistograms(/*include_persistent=*/false);
EXPECT_THAT(histograms, SizeIs(use_persistent_histogram_allocator_ ? 0 : 2));
// Create a new global allocator using the same memory as the old one. Any
// old one is kept around so the memory doesn't get released.
GlobalHistogramAllocator* old_global_allocator =
GlobalHistogramAllocator::ReleaseForTesting();
if (use_persistent_histogram_allocator_) {
GlobalHistogramAllocator::CreateWithPersistentMemory(
const_cast<void*>(old_global_allocator->data()),
old_global_allocator->length(), 0, old_global_allocator->Id(),
old_global_allocator->Name());
}
// Reset statistics-recorder to validate operation from a clean start.
UninitializeStatisticsRecorder();
InitializeStatisticsRecorder();
histograms = StatisticsRecorder::GetHistograms();
EXPECT_THAT(histograms, SizeIs(use_persistent_histogram_allocator_ ? 2 : 0));
histograms = StatisticsRecorder::GetHistograms(/*include_persistent=*/false);
EXPECT_THAT(histograms, IsEmpty());
}
namespace {
// CallbackCheckWrapper is simply a convenient way to check and store that
// a callback was actually run.
struct CallbackCheckWrapper {
CallbackCheckWrapper() : last_name_hash(HashMetricName("")) {}
void OnHistogramChanged(std::string_view histogram_name,
uint64_t name_hash,
HistogramBase::Sample32 histogram_value) {
called = true;
last_histogram_name = std::string(histogram_name);
last_name_hash = name_hash;
last_histogram_value = histogram_value;
}
void OnHistogramChangedWithEventId(std::optional<uint64_t> event_id,
std::string_view histogram_name,
uint64_t name_hash,
HistogramBase::Sample32 histogram_value) {
last_event_id = event_id;
OnHistogramChanged(histogram_name, name_hash, histogram_value);
}
bool called = false;
std::optional<uint64_t> last_event_id;
std::string last_histogram_name = "";
uint64_t last_name_hash;
base::HistogramBase::Sample32 last_histogram_value = 0;
};
} // namespace
TEST_P(StatisticsRecorderTest,
AddHistogramCallbackBeforeHistogramRegistration) {
test::TaskEnvironment task_environment;
constexpr char histogram_name[] = "TestHistogram";
CallbackCheckWrapper callback_wrapper;
auto callback =
std::make_unique<base::StatisticsRecorder::ScopedHistogramSampleObserver>(
histogram_name,
base::BindRepeating(&CallbackCheckWrapper::OnHistogramChanged,
base::Unretained(&callback_wrapper)));
EXPECT_TRUE(base::StatisticsRecorder::have_active_callbacks());
HistogramBase* const histogram = CreateHistogram(histogram_name, 1, 1000, 10);
EXPECT_EQ(StatisticsRecorder::RegisterOrDeleteDuplicate(histogram),
histogram);
EXPECT_TRUE(histogram->HasFlags(HistogramBase::kCallbackExists));
EXPECT_TRUE(base::StatisticsRecorder::have_active_callbacks());
}
TEST_P(StatisticsRecorderTest,
RemoveHistogramCallbackBeforeHistogramRegistrationWithMultipleClients) {
test::TaskEnvironment task_environment;
constexpr char histogram_name[] = "TestHistogram";
CallbackCheckWrapper callback_wrapper1;
CallbackCheckWrapper callback_wrapper2;
auto callback1 =
std::make_unique<base::StatisticsRecorder::ScopedHistogramSampleObserver>(
histogram_name,
base::BindRepeating(&CallbackCheckWrapper::OnHistogramChanged,
base::Unretained(&callback_wrapper1)));
EXPECT_TRUE(base::StatisticsRecorder::have_active_callbacks());
auto callback2 =
std::make_unique<base::StatisticsRecorder::ScopedHistogramSampleObserver>(
histogram_name,
base::BindRepeating(&CallbackCheckWrapper::OnHistogramChanged,
base::Unretained(&callback_wrapper2)));
EXPECT_TRUE(base::StatisticsRecorder::have_active_callbacks());
callback1.reset();
EXPECT_TRUE(base::StatisticsRecorder::have_active_callbacks());
callback2.reset();
EXPECT_FALSE(base::StatisticsRecorder::have_active_callbacks());
HistogramBase* const histogram = CreateHistogram(histogram_name, 1, 1000, 10);
EXPECT_EQ(StatisticsRecorder::RegisterOrDeleteDuplicate(histogram),
histogram);
EXPECT_FALSE(histogram->HasFlags(HistogramBase::kCallbackExists));
EXPECT_FALSE(base::StatisticsRecorder::have_active_callbacks());
}
TEST_P(StatisticsRecorderTest, AddHistogramCallbackWithMultipleClients) {
test::TaskEnvironment task_environment;
std::string histogram_name = "TestHistogram";
HistogramBase* histogram = Histogram::FactoryGet(histogram_name, 1, 1000, 10,
HistogramBase::kNoFlags);
EXPECT_TRUE(histogram);
CallbackCheckWrapper callback_wrapper1;
CallbackCheckWrapper callback_wrapper2;
auto callback1 =
std::make_unique<base::StatisticsRecorder::ScopedHistogramSampleObserver>(
histogram_name,
base::BindRepeating(&CallbackCheckWrapper::OnHistogramChanged,
base::Unretained(&callback_wrapper1)));
EXPECT_TRUE(histogram->HasFlags(HistogramBase::kCallbackExists));
EXPECT_TRUE(base::StatisticsRecorder::have_active_callbacks());
auto callback2 =
std::make_unique<base::StatisticsRecorder::ScopedHistogramSampleObserver>(
histogram_name,
base::BindRepeating(&CallbackCheckWrapper::OnHistogramChanged,
base::Unretained(&callback_wrapper2)));
EXPECT_TRUE(histogram->HasFlags(HistogramBase::kCallbackExists));
EXPECT_TRUE(base::StatisticsRecorder::have_active_callbacks());
histogram->Add(1);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(callback_wrapper1.called);
histogram->Add(1);
EXPECT_TRUE(callback_wrapper2.called);
}
TEST_P(StatisticsRecorderTest, RemoveHistogramCallbackWithMultipleClients) {
test::TaskEnvironment task_environment;
std::string histogram_name = "TestHistogram";
HistogramBase* histogram = Histogram::FactoryGet(histogram_name, 1, 1000, 10,
HistogramBase::kNoFlags);
EXPECT_TRUE(histogram);
CallbackCheckWrapper callback_wrapper1;
CallbackCheckWrapper callback_wrapper2;
auto callback1 =
std::make_unique<base::StatisticsRecorder::ScopedHistogramSampleObserver>(
histogram_name,
base::BindRepeating(&CallbackCheckWrapper::OnHistogramChanged,
base::Unretained(&callback_wrapper1)));
auto callback2 =
std::make_unique<base::StatisticsRecorder::ScopedHistogramSampleObserver>(
histogram_name,
base::BindRepeating(&CallbackCheckWrapper::OnHistogramChanged,
base::Unretained(&callback_wrapper2)));
callback1.reset();
EXPECT_TRUE(histogram->HasFlags(HistogramBase::kCallbackExists));
EXPECT_TRUE(base::StatisticsRecorder::have_active_callbacks());
callback2.reset();
EXPECT_FALSE(histogram->HasFlags(HistogramBase::kCallbackExists));
EXPECT_FALSE(base::StatisticsRecorder::have_active_callbacks());
histogram->Add(1);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(callback_wrapper1.called);
EXPECT_FALSE(callback_wrapper2.called);
}
// Check that callback is used.
TEST_P(StatisticsRecorderTest, CallbackUsedTest) {
test::TaskEnvironment task_environment;
{
HistogramBase* histogram = Histogram::FactoryGet(
"TestHistogram", 1, 1000, 10, HistogramBase::kNoFlags);
EXPECT_TRUE(histogram);
CallbackCheckWrapper callback_wrapper;
auto callback = std::make_unique<
base::StatisticsRecorder::ScopedHistogramSampleObserver>(
"TestHistogram",
base::BindRepeating(&CallbackCheckWrapper::OnHistogramChanged,
base::Unretained(&callback_wrapper)));
histogram->Add(1);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(callback_wrapper.called);
EXPECT_EQ(callback_wrapper.last_histogram_name, "TestHistogram");
EXPECT_EQ(callback_wrapper.last_name_hash, HashMetricName("TestHistogram"));
EXPECT_EQ(callback_wrapper.last_histogram_value, 1);
}
{
HistogramBase* linear_histogram = LinearHistogram::FactoryGet(
"TestLinearHistogram", 1, 1000, 10, HistogramBase::kNoFlags);
CallbackCheckWrapper callback_wrapper;
auto callback = std::make_unique<
base::StatisticsRecorder::ScopedHistogramSampleObserver>(
"TestLinearHistogram",
base::BindRepeating(&CallbackCheckWrapper::OnHistogramChanged,
base::Unretained(&callback_wrapper)));
linear_histogram->Add(1);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(callback_wrapper.called);
EXPECT_EQ(callback_wrapper.last_histogram_name, "TestLinearHistogram");
EXPECT_EQ(callback_wrapper.last_name_hash,
HashMetricName("TestLinearHistogram"));
EXPECT_EQ(callback_wrapper.last_histogram_value, 1);
}
{
std::vector<int> custom_ranges;
custom_ranges.push_back(1);
custom_ranges.push_back(5);
HistogramBase* custom_histogram = CustomHistogram::FactoryGet(
"TestCustomHistogram", custom_ranges, HistogramBase::kNoFlags);
CallbackCheckWrapper callback_wrapper;
auto callback = std::make_unique<
base::StatisticsRecorder::ScopedHistogramSampleObserver>(
"TestCustomHistogram",
base::BindRepeating(&CallbackCheckWrapper::OnHistogramChanged,
base::Unretained(&callback_wrapper)));
custom_histogram->Add(1);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(callback_wrapper.called);
EXPECT_EQ(callback_wrapper.last_histogram_name, "TestCustomHistogram");
EXPECT_EQ(callback_wrapper.last_name_hash,
HashMetricName("TestCustomHistogram"));
EXPECT_EQ(callback_wrapper.last_histogram_value, 1);
}
{
HistogramBase* custom_histogram = SparseHistogram::FactoryGet(
"TestSparseHistogram", HistogramBase::kNoFlags);
CallbackCheckWrapper callback_wrapper;
auto callback = std::make_unique<
base::StatisticsRecorder::ScopedHistogramSampleObserver>(
"TestSparseHistogram",
base::BindRepeating(&CallbackCheckWrapper::OnHistogramChanged,
base::Unretained(&callback_wrapper)));
custom_histogram->Add(1);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(callback_wrapper.called);
EXPECT_EQ(callback_wrapper.last_histogram_name, "TestSparseHistogram");
EXPECT_EQ(callback_wrapper.last_name_hash,
HashMetricName("TestSparseHistogram"));
EXPECT_EQ(callback_wrapper.last_histogram_value, 1);
}
}
// Check that setting a callback before the histogram exists works.
TEST_P(StatisticsRecorderTest, CallbackUsedBeforeHistogramCreatedTest) {
test::TaskEnvironment task_environment;
CallbackCheckWrapper callback_wrapper;
auto callback =
std::make_unique<base::StatisticsRecorder::ScopedHistogramSampleObserver>(
"TestHistogram",
base::BindRepeating(&CallbackCheckWrapper::OnHistogramChanged,
base::Unretained(&callback_wrapper)));
HistogramBase* histogram = Histogram::FactoryGet("TestHistogram", 1, 1000, 10,
HistogramBase::kNoFlags);
EXPECT_TRUE(histogram);
histogram->Add(1);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(callback_wrapper.called);
EXPECT_EQ(callback_wrapper.last_histogram_name, "TestHistogram");
EXPECT_EQ(callback_wrapper.last_name_hash, HashMetricName("TestHistogram"));
EXPECT_EQ(callback_wrapper.last_histogram_value, 1);
}
// Check that setting a callback before the histogram exists works.
TEST_P(StatisticsRecorderTest, CallbackWithEventIdTest) {
test::TaskEnvironment task_environment;
CallbackCheckWrapper callback_wrapper;
auto callback =
std::make_unique<base::StatisticsRecorder::ScopedHistogramSampleObserver>(
"TestHistogram",
base::BindRepeating(
&CallbackCheckWrapper::OnHistogramChangedWithEventId,
base::Unretained(&callback_wrapper)));
HistogramBase* histogram = Histogram::FactoryGet("TestHistogram", 1, 1000, 10,
HistogramBase::kNoFlags);
EXPECT_TRUE(histogram);
{
base::trace_event::HistogramScope histogram_trace_scope(42);
histogram->Add(1);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(callback_wrapper.called);
EXPECT_EQ(callback_wrapper.last_histogram_name, "TestHistogram");
EXPECT_EQ(callback_wrapper.last_event_id, 42);
EXPECT_EQ(callback_wrapper.last_name_hash, HashMetricName("TestHistogram"));
EXPECT_EQ(callback_wrapper.last_histogram_value, 1);
}
callback_wrapper = CallbackCheckWrapper(); // clear previous callback data
histogram->Add(2);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(callback_wrapper.called);
EXPECT_EQ(callback_wrapper.last_histogram_name, "TestHistogram");
EXPECT_EQ(callback_wrapper.last_event_id, std::nullopt);
EXPECT_EQ(callback_wrapper.last_name_hash, HashMetricName("TestHistogram"));
EXPECT_EQ(callback_wrapper.last_histogram_value, 2);
}
TEST_P(StatisticsRecorderTest, GlobalCallbackCalled) {
HistogramBase* histogram = Histogram::FactoryGet("TestHistogram", 1, 1000, 10,
HistogramBase::kNoFlags);
EXPECT_TRUE(histogram);
// This is a static rather than passing the variable to the lambda
// as a reference capture, as only stateless lambdas can be cast to a raw
// function pointer.
static size_t callback_callcount;
callback_callcount = 0;
auto callback = [](std::string_view histogram_name, uint64_t name_hash,
HistogramBase::Sample32 sample,
std::optional<uint64_t> event_id) {
EXPECT_EQ(histogram_name, "TestHistogram");
EXPECT_EQ(sample, 1);
++callback_callcount;
};
base::StatisticsRecorder::SetGlobalSampleCallback(callback);
// Test that adding a histogram sample calls our callback.
histogram->Add(1);
EXPECT_EQ(callback_callcount, 1u);
// Test that the callback gets correctly unregistered.
base::StatisticsRecorder::SetGlobalSampleCallback(nullptr);
histogram->Add(2);
EXPECT_EQ(callback_callcount, 1u);
}
TEST_P(StatisticsRecorderTest, LogOnShutdownNotInitialized) {
// Some builds don't have runtime vlogging. See base/logging.h.
if (!VLOG_IS_ON(0)) {
GTEST_SKIP();
}
ResetVLogInitialized();
logging::SetMinLogLevel(logging::LOGGING_WARNING);
InitializeStatisticsRecorder();
EXPECT_FALSE(VLOG_IS_ON(1));
EXPECT_FALSE(IsVLogInitialized());
InitLogOnShutdown();
EXPECT_FALSE(IsVLogInitialized());
}
TEST_P(StatisticsRecorderTest, LogOnShutdownInitializedExplicitly) {
// Some builds don't have runtime vlogging. See base/logging.h.
if (!VLOG_IS_ON(0)) {
GTEST_SKIP();
}
ResetVLogInitialized();
logging::SetMinLogLevel(logging::LOGGING_WARNING);
InitializeStatisticsRecorder();
EXPECT_FALSE(VLOG_IS_ON(1));
EXPECT_FALSE(IsVLogInitialized());
logging::SetMinLogLevel(logging::LOGGING_VERBOSE);
EXPECT_TRUE(VLOG_IS_ON(1));
InitLogOnShutdown();
EXPECT_TRUE(IsVLogInitialized());
}
TEST_P(StatisticsRecorderTest, LogOnShutdownInitialized) {
// Some builds don't have runtime vlogging. See base/logging.h.
if (!VLOG_IS_ON(0)) {
GTEST_SKIP();
}
ResetVLogInitialized();
logging::SetMinLogLevel(logging::LOGGING_VERBOSE);
InitializeStatisticsRecorder();
EXPECT_TRUE(VLOG_IS_ON(1));
EXPECT_TRUE(IsVLogInitialized());
}
class TestHistogramProvider : public StatisticsRecorder::HistogramProvider {
public:
explicit TestHistogramProvider(PersistentHistogramAllocator* allocator)
: allocator_(std::move(allocator)) {
StatisticsRecorder::RegisterHistogramProvider(weak_factory_.GetWeakPtr());
}
TestHistogramProvider(const TestHistogramProvider&) = delete;
TestHistogramProvider& operator=(const TestHistogramProvider&) = delete;
void MergeHistogramDeltas(bool async, OnceClosure done_callback) override {
PersistentHistogramAllocator::Iterator hist_iter(allocator_.get());
while (true) {
std::unique_ptr<HistogramBase> histogram = hist_iter.GetNext();
if (!histogram) {
break;
}
allocator_->MergeHistogramDeltaToStatisticsRecorder(histogram.get());
}
std::move(done_callback).Run();
}
private:
const raw_ptr<PersistentHistogramAllocator> allocator_;
WeakPtrFactory<TestHistogramProvider> weak_factory_{this};
};
TEST_P(StatisticsRecorderTest, ImportHistogramsTest) {
// Create a second SR to create some histograms for later import.
std::unique_ptr<StatisticsRecorder> temp_sr =
StatisticsRecorder::CreateTemporaryForTesting();
// Extract any existing global allocator so a new one can be created.
GlobalHistogramAllocator* old_allocator =
GlobalHistogramAllocator::ReleaseForTesting();
// Create a histogram inside a new allocator for testing.
GlobalHistogramAllocator::CreateWithLocalMemory(kAllocatorMemorySize, 0, "");
HistogramBase* histogram = LinearHistogram::FactoryGet("Foo", 1, 10, 11, 0);
histogram->Add(3);
// Undo back to the starting point.
GlobalHistogramAllocator* new_allocator =
GlobalHistogramAllocator::ReleaseForTesting();
GlobalHistogramAllocator::Set(old_allocator);
temp_sr.reset();
// Create a provider that can supply histograms to the current SR.
TestHistogramProvider provider(new_allocator);
// Verify that the created histogram is no longer known.
ASSERT_FALSE(StatisticsRecorder::FindHistogram(histogram->histogram_name()));
// Now test that it merges.
StatisticsRecorder::ImportProvidedHistogramsSync();
HistogramBase* found =
StatisticsRecorder::FindHistogram(histogram->histogram_name());
ASSERT_TRUE(found);
EXPECT_NE(histogram, found);
std::unique_ptr<HistogramSamples> snapshot = found->SnapshotSamples();
EXPECT_EQ(1, snapshot->TotalCount());
EXPECT_EQ(1, snapshot->GetCount(3));
// Finally, verify that updates can also be merged.
histogram->Add(3);
histogram->Add(5);
StatisticsRecorder::ImportProvidedHistogramsSync();
snapshot = found->SnapshotSamples();
EXPECT_EQ(3, snapshot->TotalCount());
EXPECT_EQ(2, snapshot->GetCount(3));
EXPECT_EQ(1, snapshot->GetCount(5));
}
TEST_P(StatisticsRecorderTest, RecordHistogramChecker) {
// Before record checker is set all histograms should be recorded.
EXPECT_TRUE(StatisticsRecorder::ShouldRecordHistogram(1));
EXPECT_TRUE(StatisticsRecorder::ShouldRecordHistogram(2));
auto record_checker = std::make_unique<OddRecordHistogramChecker>();
StatisticsRecorder::SetRecordChecker(std::move(record_checker));
EXPECT_TRUE(StatisticsRecorder::ShouldRecordHistogram(1));
EXPECT_FALSE(StatisticsRecorder::ShouldRecordHistogram(2));
}
} // namespace base
|