sampling.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. // Sampler decides whether a trace should be sampled and exported.
  20. type Sampler func(SamplingParameters) SamplingDecision
  21. // SamplingParameters contains the values passed to a Sampler.
  22. type SamplingParameters struct {
  23. ParentContext SpanContext
  24. TraceID TraceID
  25. SpanID SpanID
  26. Name string
  27. HasRemoteParent bool
  28. }
  29. // SamplingDecision is the value returned by a Sampler.
  30. type SamplingDecision struct {
  31. Sample bool
  32. }
  33. // ProbabilitySampler returns a Sampler that samples a given fraction of traces.
  34. //
  35. // It also samples spans whose parents are sampled.
  36. func ProbabilitySampler(fraction float64) Sampler {
  37. if !(fraction >= 0) {
  38. fraction = 0
  39. } else if fraction >= 1 {
  40. return AlwaysSample()
  41. }
  42. traceIDUpperBound := uint64(fraction * (1 << 63))
  43. return Sampler(func(p SamplingParameters) SamplingDecision {
  44. if p.ParentContext.IsSampled() {
  45. return SamplingDecision{Sample: true}
  46. }
  47. x := binary.BigEndian.Uint64(p.TraceID[0:8]) >> 1
  48. return SamplingDecision{Sample: x < traceIDUpperBound}
  49. })
  50. }
  51. // AlwaysSample returns a Sampler that samples every trace.
  52. // Be careful about using this sampler in a production application with
  53. // significant traffic: a new trace will be started and exported for every
  54. // request.
  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. }