sampling.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. package trace
  15. import (
  16. "encoding/binary"
  17. )
  18. const defaultSamplingProbability = 1e-4
  19. func newDefaultSampler() Sampler {
  20. return ProbabilitySampler(defaultSamplingProbability)
  21. }
  22. // Sampler decides whether a trace should be sampled and exported.
  23. type Sampler func(SamplingParameters) SamplingDecision
  24. // SamplingParameters contains the values passed to a Sampler.
  25. type SamplingParameters struct {
  26. ParentContext SpanContext
  27. TraceID TraceID
  28. SpanID SpanID
  29. Name string
  30. HasRemoteParent bool
  31. }
  32. // SamplingDecision is the value returned by a Sampler.
  33. type SamplingDecision struct {
  34. Sample bool
  35. }
  36. // ProbabilitySampler returns a Sampler that samples a given fraction of traces.
  37. //
  38. // It also samples spans whose parents are sampled.
  39. func ProbabilitySampler(fraction float64) Sampler {
  40. if !(fraction >= 0) {
  41. fraction = 0
  42. } else if fraction >= 1 {
  43. return AlwaysSample()
  44. }
  45. traceIDUpperBound := uint64(fraction * (1 << 63))
  46. return Sampler(func(p SamplingParameters) SamplingDecision {
  47. if p.ParentContext.IsSampled() {
  48. return SamplingDecision{Sample: true}
  49. }
  50. x := binary.BigEndian.Uint64(p.TraceID[0:8]) >> 1
  51. return SamplingDecision{Sample: x < traceIDUpperBound}
  52. })
  53. }
  54. // AlwaysSample returns a Sampler that samples every trace.
  55. func AlwaysSample() Sampler {
  56. return func(p SamplingParameters) SamplingDecision {
  57. return SamplingDecision{Sample: true}
  58. }
  59. }
  60. // NeverSample returns a Sampler that samples no traces.
  61. func NeverSample() Sampler {
  62. return func(p SamplingParameters) SamplingDecision {
  63. return SamplingDecision{Sample: false}
  64. }
  65. }