2 * Copyright (c) 2017 Uber Technologies, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #ifndef JAEGERTRACING_SAMPLERS_PROBABILISTICSAMPLER_H
18 #define JAEGERTRACING_SAMPLERS_PROBABILISTICSAMPLER_H
20 #include "jaegertracing/Compilers.h"
22 #include "jaegertracing/Constants.h"
23 #include "jaegertracing/Tag.h"
24 #include "jaegertracing/TraceID.h"
25 #include "jaegertracing/samplers/Sampler.h"
26 #include "jaegertracing/samplers/SamplingStatus.h"
33 namespace jaegertracing
{
36 class ProbabilisticSampler
: public Sampler
{
38 explicit ProbabilisticSampler(double samplingRate
)
39 : _samplingRate(std::max(0.0, std::min(samplingRate
, 1.0)))
40 , _samplingBoundary(computeSamplingBoundary(_samplingRate
))
41 , _tags({ { kSamplerTypeTagKey
, kSamplerTypeProbabilistic
},
42 { kSamplerParamTagKey
, _samplingRate
} })
46 double samplingRate() const { return _samplingRate
; }
48 SamplingStatus
isSampled(const TraceID
& id
,
49 const std::string
& operation
) override
51 return SamplingStatus(_samplingBoundary
>= id
.low(), _tags
);
54 void close() override
{}
56 Type
type() const override
{ return Type::kProbabilisticSampler
; }
59 static constexpr auto kMaxRandomNumber
=
60 std::numeric_limits
<uint64_t>::max();
63 uint64_t _samplingBoundary
;
64 std::vector
<Tag
> _tags
;
66 static uint64_t computeSamplingBoundary(long double samplingRate
)
68 const auto maxRandNumber
= static_cast<long double>(kMaxRandomNumber
);
69 const auto samplingBoundary
= samplingRate
* maxRandNumber
;
71 // Protect against overflow in case samplingBoundary rounds
72 // higher than kMaxRandNumber.
73 if (samplingBoundary
== maxRandNumber
) {
74 return kMaxRandomNumber
;
77 return static_cast<uint64_t>(samplingBoundary
);
81 } // namespace samplers
82 } // namespace jaegertracing
84 #endif // JAEGERTRACING_SAMPLERS_PROBABILISTICSAMPLER_H