您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

118 行
3.4 KiB

  1. // Copyright 2016 Google LLC
  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. crand "crypto/rand"
  17. "encoding/binary"
  18. "fmt"
  19. "math/rand"
  20. "sync"
  21. "time"
  22. "golang.org/x/time/rate"
  23. )
  24. type SamplingPolicy interface {
  25. // Sample returns a Decision.
  26. // If Trace is false in the returned Decision, then the Decision should be
  27. // the zero value.
  28. Sample(p Parameters) Decision
  29. }
  30. // Parameters contains the values passed to a SamplingPolicy's Sample method.
  31. type Parameters struct {
  32. HasTraceHeader bool // whether the incoming request has a valid X-Cloud-Trace-Context header.
  33. }
  34. // Decision is the value returned by a call to a SamplingPolicy's Sample method.
  35. type Decision struct {
  36. Trace bool // Whether to trace the request.
  37. Sample bool // Whether the trace is included in the random sample.
  38. Policy string // Name of the sampling policy.
  39. Weight float64 // Sample weight to be used in statistical calculations.
  40. }
  41. type sampler struct {
  42. fraction float64
  43. skipped float64
  44. *rate.Limiter
  45. *rand.Rand
  46. sync.Mutex
  47. }
  48. func (s *sampler) Sample(p Parameters) Decision {
  49. s.Lock()
  50. x := s.Float64()
  51. d := s.sample(p, time.Now(), x)
  52. s.Unlock()
  53. return d
  54. }
  55. // sample contains the a deterministic, time-independent logic of Sample.
  56. func (s *sampler) sample(p Parameters, now time.Time, x float64) (d Decision) {
  57. d.Sample = x < s.fraction
  58. d.Trace = p.HasTraceHeader || d.Sample
  59. if !d.Trace {
  60. // We have no reason to trace this request.
  61. return Decision{}
  62. }
  63. // We test separately that the rate limit is not tiny before calling AllowN,
  64. // because of overflow problems in x/time/rate.
  65. if s.Limit() < 1e-9 || !s.AllowN(now, 1) {
  66. // Rejected by the rate limit.
  67. if d.Sample {
  68. s.skipped++
  69. }
  70. return Decision{}
  71. }
  72. if d.Sample {
  73. d.Policy, d.Weight = "default", (1.0+s.skipped)/s.fraction
  74. s.skipped = 0.0
  75. }
  76. return
  77. }
  78. // NewLimitedSampler returns a sampling policy that randomly samples a given
  79. // fraction of requests. It also enforces a limit on the number of traces per
  80. // second. It tries to trace every request with a trace header, but will not
  81. // exceed the qps limit to do it.
  82. func NewLimitedSampler(fraction, maxqps float64) (SamplingPolicy, error) {
  83. if !(fraction >= 0) {
  84. return nil, fmt.Errorf("invalid fraction %f", fraction)
  85. }
  86. if !(maxqps >= 0) {
  87. return nil, fmt.Errorf("invalid maxqps %f", maxqps)
  88. }
  89. // Set a limit on the number of accumulated "tokens", to limit bursts of
  90. // traced requests. Use one more than a second's worth of tokens, or 100,
  91. // whichever is smaller.
  92. // See https://godoc.org/golang.org/x/time/rate#NewLimiter.
  93. maxTokens := 100
  94. if maxqps < 99.0 {
  95. maxTokens = 1 + int(maxqps)
  96. }
  97. var seed int64
  98. if err := binary.Read(crand.Reader, binary.LittleEndian, &seed); err != nil {
  99. seed = time.Now().UnixNano()
  100. }
  101. s := sampler{
  102. fraction: fraction,
  103. Limiter: rate.NewLimiter(rate.Limit(maxqps), maxTokens),
  104. Rand: rand.New(rand.NewSource(seed)),
  105. }
  106. return &s, nil
  107. }