|
| 1 | +// Copyright 2017, OpenCensus Authors |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +#include "opencensus/trace/sampler.h" |
| 16 | + |
| 17 | +#include <atomic> |
| 18 | + |
| 19 | +#include "absl/strings/str_cat.h" |
| 20 | +#include "absl/time/clock.h" |
| 21 | +#include "gtest/gtest.h" |
| 22 | +#include "opencensus/trace/span.h" |
| 23 | +#include "opencensus/trace/trace_params.h" |
| 24 | + |
| 25 | +namespace opencensus { |
| 26 | +namespace trace { |
| 27 | +namespace { |
| 28 | + |
| 29 | +// Example of a stateful sampler class. |
| 30 | +class SampleEveryNth : public Sampler { |
| 31 | + public: |
| 32 | + explicit SampleEveryNth(int nth) : state_(new State(nth)) {} |
| 33 | + |
| 34 | + bool ShouldSample(const SpanContext* parent_context, bool has_remote_parent, |
| 35 | + const TraceId& trace_id, const SpanId& span_id, |
| 36 | + absl::string_view name, |
| 37 | + const std::vector<Span*>& parent_links) const override { |
| 38 | + // The shared_ptr is const, but the underlying State it points to isn't. |
| 39 | + return state_->Increment(); |
| 40 | + } |
| 41 | + |
| 42 | + private: |
| 43 | + class State { |
| 44 | + public: |
| 45 | + explicit State(int nth) : nth_(nth), current_(0) {} |
| 46 | + bool Increment() { |
| 47 | + int prev = current_.fetch_add(1, std::memory_order_acq_rel); |
| 48 | + return (prev + 1) % nth_ == 0; |
| 49 | + } |
| 50 | + |
| 51 | + private: |
| 52 | + const int nth_; |
| 53 | + std::atomic<int> current_; |
| 54 | + }; |
| 55 | + |
| 56 | + std::shared_ptr<State> state_; |
| 57 | +}; |
| 58 | + |
| 59 | +TEST(SamplerTest, SampleNth) { |
| 60 | + static constexpr int kSampleRate = 4; |
| 61 | + SampleEveryNth sampler(kSampleRate); |
| 62 | + |
| 63 | + for (int i = 1; i <= 100; ++i) { |
| 64 | + auto span = Span::StartSpan(absl::StrCat("MySpan", i), nullptr, {&sampler}); |
| 65 | + if (i % kSampleRate == 0) { |
| 66 | + EXPECT_TRUE(span.IsSampled()); |
| 67 | + } else { |
| 68 | + EXPECT_FALSE(span.IsSampled()); |
| 69 | + } |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +} // namespace |
| 74 | +} // namespace trace |
| 75 | +} // namespace opencensus |
0 commit comments