sampler.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. // Copyright (c) 2017 Uber Technologies, Inc.
  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 jaeger
  15. import (
  16. "fmt"
  17. "math"
  18. "net/url"
  19. "sync"
  20. "sync/atomic"
  21. "time"
  22. "github.com/uber/jaeger-client-go/log"
  23. "github.com/uber/jaeger-client-go/thrift-gen/sampling"
  24. "github.com/uber/jaeger-client-go/utils"
  25. )
  26. const (
  27. defaultSamplingServerURL = "http://localhost:5778/sampling"
  28. defaultSamplingRefreshInterval = time.Minute
  29. defaultMaxOperations = 2000
  30. )
  31. // Sampler decides whether a new trace should be sampled or not.
  32. type Sampler interface {
  33. // IsSampled decides whether a trace with given `id` and `operation`
  34. // should be sampled. This function will also return the tags that
  35. // can be used to identify the type of sampling that was applied to
  36. // the root span. Most simple samplers would return two tags,
  37. // sampler.type and sampler.param, similar to those used in the Configuration
  38. IsSampled(id TraceID, operation string) (sampled bool, tags []Tag)
  39. // Close does a clean shutdown of the sampler, stopping any background
  40. // go-routines it may have started.
  41. Close()
  42. // Equal checks if the `other` sampler is functionally equivalent
  43. // to this sampler.
  44. // TODO remove this function. This function is used to determine if 2 samplers are equivalent
  45. // which does not bode well with the adaptive sampler which has to create all the composite samplers
  46. // for the comparison to occur. This is expensive to do if only one sampler has changed.
  47. Equal(other Sampler) bool
  48. }
  49. // -----------------------
  50. // ConstSampler is a sampler that always makes the same decision.
  51. type ConstSampler struct {
  52. Decision bool
  53. tags []Tag
  54. }
  55. // NewConstSampler creates a ConstSampler.
  56. func NewConstSampler(sample bool) Sampler {
  57. tags := []Tag{
  58. {key: SamplerTypeTagKey, value: SamplerTypeConst},
  59. {key: SamplerParamTagKey, value: sample},
  60. }
  61. return &ConstSampler{Decision: sample, tags: tags}
  62. }
  63. // IsSampled implements IsSampled() of Sampler.
  64. func (s *ConstSampler) IsSampled(id TraceID, operation string) (bool, []Tag) {
  65. return s.Decision, s.tags
  66. }
  67. // Close implements Close() of Sampler.
  68. func (s *ConstSampler) Close() {
  69. // nothing to do
  70. }
  71. // Equal implements Equal() of Sampler.
  72. func (s *ConstSampler) Equal(other Sampler) bool {
  73. if o, ok := other.(*ConstSampler); ok {
  74. return s.Decision == o.Decision
  75. }
  76. return false
  77. }
  78. // -----------------------
  79. // ProbabilisticSampler is a sampler that randomly samples a certain percentage
  80. // of traces.
  81. type ProbabilisticSampler struct {
  82. samplingRate float64
  83. samplingBoundary uint64
  84. tags []Tag
  85. }
  86. const maxRandomNumber = ^(uint64(1) << 63) // i.e. 0x7fffffffffffffff
  87. // NewProbabilisticSampler creates a sampler that randomly samples a certain percentage of traces specified by the
  88. // samplingRate, in the range between 0.0 and 1.0.
  89. //
  90. // It relies on the fact that new trace IDs are 63bit random numbers themselves, thus making the sampling decision
  91. // without generating a new random number, but simply calculating if traceID < (samplingRate * 2^63).
  92. // TODO remove the error from this function for next major release
  93. func NewProbabilisticSampler(samplingRate float64) (*ProbabilisticSampler, error) {
  94. if samplingRate < 0.0 || samplingRate > 1.0 {
  95. return nil, fmt.Errorf("Sampling Rate must be between 0.0 and 1.0, received %f", samplingRate)
  96. }
  97. return newProbabilisticSampler(samplingRate), nil
  98. }
  99. func newProbabilisticSampler(samplingRate float64) *ProbabilisticSampler {
  100. samplingRate = math.Max(0.0, math.Min(samplingRate, 1.0))
  101. tags := []Tag{
  102. {key: SamplerTypeTagKey, value: SamplerTypeProbabilistic},
  103. {key: SamplerParamTagKey, value: samplingRate},
  104. }
  105. return &ProbabilisticSampler{
  106. samplingRate: samplingRate,
  107. samplingBoundary: uint64(float64(maxRandomNumber) * samplingRate),
  108. tags: tags,
  109. }
  110. }
  111. // SamplingRate returns the sampling probability this sampled was constructed with.
  112. func (s *ProbabilisticSampler) SamplingRate() float64 {
  113. return s.samplingRate
  114. }
  115. // IsSampled implements IsSampled() of Sampler.
  116. func (s *ProbabilisticSampler) IsSampled(id TraceID, operation string) (bool, []Tag) {
  117. return s.samplingBoundary >= id.Low, s.tags
  118. }
  119. // Close implements Close() of Sampler.
  120. func (s *ProbabilisticSampler) Close() {
  121. // nothing to do
  122. }
  123. // Equal implements Equal() of Sampler.
  124. func (s *ProbabilisticSampler) Equal(other Sampler) bool {
  125. if o, ok := other.(*ProbabilisticSampler); ok {
  126. return s.samplingBoundary == o.samplingBoundary
  127. }
  128. return false
  129. }
  130. // -----------------------
  131. type rateLimitingSampler struct {
  132. maxTracesPerSecond float64
  133. rateLimiter utils.RateLimiter
  134. tags []Tag
  135. }
  136. // NewRateLimitingSampler creates a sampler that samples at most maxTracesPerSecond. The distribution of sampled
  137. // traces follows burstiness of the service, i.e. a service with uniformly distributed requests will have those
  138. // requests sampled uniformly as well, but if requests are bursty, especially sub-second, then a number of
  139. // sequential requests can be sampled each second.
  140. func NewRateLimitingSampler(maxTracesPerSecond float64) Sampler {
  141. tags := []Tag{
  142. {key: SamplerTypeTagKey, value: SamplerTypeRateLimiting},
  143. {key: SamplerParamTagKey, value: maxTracesPerSecond},
  144. }
  145. return &rateLimitingSampler{
  146. maxTracesPerSecond: maxTracesPerSecond,
  147. rateLimiter: utils.NewRateLimiter(maxTracesPerSecond, math.Max(maxTracesPerSecond, 1.0)),
  148. tags: tags,
  149. }
  150. }
  151. // IsSampled implements IsSampled() of Sampler.
  152. func (s *rateLimitingSampler) IsSampled(id TraceID, operation string) (bool, []Tag) {
  153. return s.rateLimiter.CheckCredit(1.0), s.tags
  154. }
  155. func (s *rateLimitingSampler) Close() {
  156. // nothing to do
  157. }
  158. func (s *rateLimitingSampler) Equal(other Sampler) bool {
  159. if o, ok := other.(*rateLimitingSampler); ok {
  160. return s.maxTracesPerSecond == o.maxTracesPerSecond
  161. }
  162. return false
  163. }
  164. // -----------------------
  165. // GuaranteedThroughputProbabilisticSampler is a sampler that leverages both probabilisticSampler and
  166. // rateLimitingSampler. The rateLimitingSampler is used as a guaranteed lower bound sampler such that
  167. // every operation is sampled at least once in a time interval defined by the lowerBound. ie a lowerBound
  168. // of 1.0 / (60 * 10) will sample an operation at least once every 10 minutes.
  169. //
  170. // The probabilisticSampler is given higher priority when tags are emitted, ie. if IsSampled() for both
  171. // samplers return true, the tags for probabilisticSampler will be used.
  172. type GuaranteedThroughputProbabilisticSampler struct {
  173. probabilisticSampler *ProbabilisticSampler
  174. lowerBoundSampler Sampler
  175. tags []Tag
  176. samplingRate float64
  177. lowerBound float64
  178. }
  179. // NewGuaranteedThroughputProbabilisticSampler returns a delegating sampler that applies both
  180. // probabilisticSampler and rateLimitingSampler.
  181. func NewGuaranteedThroughputProbabilisticSampler(
  182. lowerBound, samplingRate float64,
  183. ) (*GuaranteedThroughputProbabilisticSampler, error) {
  184. return newGuaranteedThroughputProbabilisticSampler(lowerBound, samplingRate), nil
  185. }
  186. func newGuaranteedThroughputProbabilisticSampler(lowerBound, samplingRate float64) *GuaranteedThroughputProbabilisticSampler {
  187. s := &GuaranteedThroughputProbabilisticSampler{
  188. lowerBoundSampler: NewRateLimitingSampler(lowerBound),
  189. lowerBound: lowerBound,
  190. }
  191. s.setProbabilisticSampler(samplingRate)
  192. return s
  193. }
  194. func (s *GuaranteedThroughputProbabilisticSampler) setProbabilisticSampler(samplingRate float64) {
  195. if s.probabilisticSampler == nil || s.samplingRate != samplingRate {
  196. s.probabilisticSampler = newProbabilisticSampler(samplingRate)
  197. s.samplingRate = s.probabilisticSampler.SamplingRate()
  198. s.tags = []Tag{
  199. {key: SamplerTypeTagKey, value: SamplerTypeLowerBound},
  200. {key: SamplerParamTagKey, value: s.samplingRate},
  201. }
  202. }
  203. }
  204. // IsSampled implements IsSampled() of Sampler.
  205. func (s *GuaranteedThroughputProbabilisticSampler) IsSampled(id TraceID, operation string) (bool, []Tag) {
  206. if sampled, tags := s.probabilisticSampler.IsSampled(id, operation); sampled {
  207. s.lowerBoundSampler.IsSampled(id, operation)
  208. return true, tags
  209. }
  210. sampled, _ := s.lowerBoundSampler.IsSampled(id, operation)
  211. return sampled, s.tags
  212. }
  213. // Close implements Close() of Sampler.
  214. func (s *GuaranteedThroughputProbabilisticSampler) Close() {
  215. s.probabilisticSampler.Close()
  216. s.lowerBoundSampler.Close()
  217. }
  218. // Equal implements Equal() of Sampler.
  219. func (s *GuaranteedThroughputProbabilisticSampler) Equal(other Sampler) bool {
  220. // NB The Equal() function is expensive and will be removed. See adaptiveSampler.Equal() for
  221. // more information.
  222. return false
  223. }
  224. // this function should only be called while holding a Write lock
  225. func (s *GuaranteedThroughputProbabilisticSampler) update(lowerBound, samplingRate float64) {
  226. s.setProbabilisticSampler(samplingRate)
  227. if s.lowerBound != lowerBound {
  228. s.lowerBoundSampler = NewRateLimitingSampler(lowerBound)
  229. s.lowerBound = lowerBound
  230. }
  231. }
  232. // -----------------------
  233. type adaptiveSampler struct {
  234. sync.RWMutex
  235. samplers map[string]*GuaranteedThroughputProbabilisticSampler
  236. defaultSampler *ProbabilisticSampler
  237. lowerBound float64
  238. maxOperations int
  239. }
  240. // NewAdaptiveSampler returns a delegating sampler that applies both probabilisticSampler and
  241. // rateLimitingSampler via the guaranteedThroughputProbabilisticSampler. This sampler keeps track of all
  242. // operations and delegates calls to the respective guaranteedThroughputProbabilisticSampler.
  243. func NewAdaptiveSampler(strategies *sampling.PerOperationSamplingStrategies, maxOperations int) (Sampler, error) {
  244. return newAdaptiveSampler(strategies, maxOperations), nil
  245. }
  246. func newAdaptiveSampler(strategies *sampling.PerOperationSamplingStrategies, maxOperations int) Sampler {
  247. samplers := make(map[string]*GuaranteedThroughputProbabilisticSampler)
  248. for _, strategy := range strategies.PerOperationStrategies {
  249. sampler := newGuaranteedThroughputProbabilisticSampler(
  250. strategies.DefaultLowerBoundTracesPerSecond,
  251. strategy.ProbabilisticSampling.SamplingRate,
  252. )
  253. samplers[strategy.Operation] = sampler
  254. }
  255. return &adaptiveSampler{
  256. samplers: samplers,
  257. defaultSampler: newProbabilisticSampler(strategies.DefaultSamplingProbability),
  258. lowerBound: strategies.DefaultLowerBoundTracesPerSecond,
  259. maxOperations: maxOperations,
  260. }
  261. }
  262. func (s *adaptiveSampler) IsSampled(id TraceID, operation string) (bool, []Tag) {
  263. s.RLock()
  264. sampler, ok := s.samplers[operation]
  265. if ok {
  266. defer s.RUnlock()
  267. return sampler.IsSampled(id, operation)
  268. }
  269. s.RUnlock()
  270. s.Lock()
  271. defer s.Unlock()
  272. // Check if sampler has already been created
  273. sampler, ok = s.samplers[operation]
  274. if ok {
  275. return sampler.IsSampled(id, operation)
  276. }
  277. // Store only up to maxOperations of unique ops.
  278. if len(s.samplers) >= s.maxOperations {
  279. return s.defaultSampler.IsSampled(id, operation)
  280. }
  281. newSampler := newGuaranteedThroughputProbabilisticSampler(s.lowerBound, s.defaultSampler.SamplingRate())
  282. s.samplers[operation] = newSampler
  283. return newSampler.IsSampled(id, operation)
  284. }
  285. func (s *adaptiveSampler) Close() {
  286. s.Lock()
  287. defer s.Unlock()
  288. for _, sampler := range s.samplers {
  289. sampler.Close()
  290. }
  291. s.defaultSampler.Close()
  292. }
  293. func (s *adaptiveSampler) Equal(other Sampler) bool {
  294. // NB The Equal() function is overly expensive for adaptiveSampler since it's composed of multiple
  295. // samplers which all need to be initialized before this function can be called for a comparison.
  296. // Therefore, adaptiveSampler uses the update() function to only alter the samplers that need
  297. // changing. Hence this function always returns false so that the update function can be called.
  298. // Once the Equal() function is removed from the Sampler API, this will no longer be needed.
  299. return false
  300. }
  301. func (s *adaptiveSampler) update(strategies *sampling.PerOperationSamplingStrategies) {
  302. s.Lock()
  303. defer s.Unlock()
  304. for _, strategy := range strategies.PerOperationStrategies {
  305. operation := strategy.Operation
  306. samplingRate := strategy.ProbabilisticSampling.SamplingRate
  307. lowerBound := strategies.DefaultLowerBoundTracesPerSecond
  308. if sampler, ok := s.samplers[operation]; ok {
  309. sampler.update(lowerBound, samplingRate)
  310. } else {
  311. sampler := newGuaranteedThroughputProbabilisticSampler(
  312. lowerBound,
  313. samplingRate,
  314. )
  315. s.samplers[operation] = sampler
  316. }
  317. }
  318. s.lowerBound = strategies.DefaultLowerBoundTracesPerSecond
  319. if s.defaultSampler.SamplingRate() != strategies.DefaultSamplingProbability {
  320. s.defaultSampler = newProbabilisticSampler(strategies.DefaultSamplingProbability)
  321. }
  322. }
  323. // -----------------------
  324. // RemotelyControlledSampler is a delegating sampler that polls a remote server
  325. // for the appropriate sampling strategy, constructs a corresponding sampler and
  326. // delegates to it for sampling decisions.
  327. type RemotelyControlledSampler struct {
  328. // These fields must be first in the struct because `sync/atomic` expects 64-bit alignment.
  329. // Cf. https://github.com/uber/jaeger-client-go/issues/155, https://goo.gl/zW7dgq
  330. closed int64 // 0 - not closed, 1 - closed
  331. sync.RWMutex
  332. samplerOptions
  333. serviceName string
  334. manager sampling.SamplingManager
  335. doneChan chan *sync.WaitGroup
  336. }
  337. type httpSamplingManager struct {
  338. serverURL string
  339. }
  340. func (s *httpSamplingManager) GetSamplingStrategy(serviceName string) (*sampling.SamplingStrategyResponse, error) {
  341. var out sampling.SamplingStrategyResponse
  342. v := url.Values{}
  343. v.Set("service", serviceName)
  344. if err := utils.GetJSON(s.serverURL+"?"+v.Encode(), &out); err != nil {
  345. return nil, err
  346. }
  347. return &out, nil
  348. }
  349. // NewRemotelyControlledSampler creates a sampler that periodically pulls
  350. // the sampling strategy from an HTTP sampling server (e.g. jaeger-agent).
  351. func NewRemotelyControlledSampler(
  352. serviceName string,
  353. opts ...SamplerOption,
  354. ) *RemotelyControlledSampler {
  355. options := applySamplerOptions(opts...)
  356. sampler := &RemotelyControlledSampler{
  357. samplerOptions: options,
  358. serviceName: serviceName,
  359. manager: &httpSamplingManager{serverURL: options.samplingServerURL},
  360. doneChan: make(chan *sync.WaitGroup),
  361. }
  362. go sampler.pollController()
  363. return sampler
  364. }
  365. func applySamplerOptions(opts ...SamplerOption) samplerOptions {
  366. options := samplerOptions{}
  367. for _, option := range opts {
  368. option(&options)
  369. }
  370. if options.sampler == nil {
  371. options.sampler = newProbabilisticSampler(0.001)
  372. }
  373. if options.logger == nil {
  374. options.logger = log.NullLogger
  375. }
  376. if options.maxOperations <= 0 {
  377. options.maxOperations = defaultMaxOperations
  378. }
  379. if options.samplingServerURL == "" {
  380. options.samplingServerURL = defaultSamplingServerURL
  381. }
  382. if options.metrics == nil {
  383. options.metrics = NewNullMetrics()
  384. }
  385. if options.samplingRefreshInterval <= 0 {
  386. options.samplingRefreshInterval = defaultSamplingRefreshInterval
  387. }
  388. return options
  389. }
  390. // IsSampled implements IsSampled() of Sampler.
  391. func (s *RemotelyControlledSampler) IsSampled(id TraceID, operation string) (bool, []Tag) {
  392. s.RLock()
  393. defer s.RUnlock()
  394. return s.sampler.IsSampled(id, operation)
  395. }
  396. // Close implements Close() of Sampler.
  397. func (s *RemotelyControlledSampler) Close() {
  398. if swapped := atomic.CompareAndSwapInt64(&s.closed, 0, 1); !swapped {
  399. s.logger.Error("Repeated attempt to close the sampler is ignored")
  400. return
  401. }
  402. var wg sync.WaitGroup
  403. wg.Add(1)
  404. s.doneChan <- &wg
  405. wg.Wait()
  406. }
  407. // Equal implements Equal() of Sampler.
  408. func (s *RemotelyControlledSampler) Equal(other Sampler) bool {
  409. // NB The Equal() function is expensive and will be removed. See adaptiveSampler.Equal() for
  410. // more information.
  411. if o, ok := other.(*RemotelyControlledSampler); ok {
  412. s.RLock()
  413. o.RLock()
  414. defer s.RUnlock()
  415. defer o.RUnlock()
  416. return s.sampler.Equal(o.sampler)
  417. }
  418. return false
  419. }
  420. func (s *RemotelyControlledSampler) pollController() {
  421. ticker := time.NewTicker(s.samplingRefreshInterval)
  422. defer ticker.Stop()
  423. s.pollControllerWithTicker(ticker)
  424. }
  425. func (s *RemotelyControlledSampler) pollControllerWithTicker(ticker *time.Ticker) {
  426. for {
  427. select {
  428. case <-ticker.C:
  429. s.updateSampler()
  430. case wg := <-s.doneChan:
  431. wg.Done()
  432. return
  433. }
  434. }
  435. }
  436. func (s *RemotelyControlledSampler) getSampler() Sampler {
  437. s.Lock()
  438. defer s.Unlock()
  439. return s.sampler
  440. }
  441. func (s *RemotelyControlledSampler) setSampler(sampler Sampler) {
  442. s.Lock()
  443. defer s.Unlock()
  444. s.sampler = sampler
  445. }
  446. func (s *RemotelyControlledSampler) updateSampler() {
  447. res, err := s.manager.GetSamplingStrategy(s.serviceName)
  448. if err != nil {
  449. s.metrics.SamplerQueryFailure.Inc(1)
  450. s.logger.Infof("Unable to query sampling strategy: %v", err)
  451. return
  452. }
  453. s.Lock()
  454. defer s.Unlock()
  455. s.metrics.SamplerRetrieved.Inc(1)
  456. if strategies := res.GetOperationSampling(); strategies != nil {
  457. s.updateAdaptiveSampler(strategies)
  458. } else {
  459. err = s.updateRateLimitingOrProbabilisticSampler(res)
  460. }
  461. if err != nil {
  462. s.metrics.SamplerUpdateFailure.Inc(1)
  463. s.logger.Infof("Unable to handle sampling strategy response %+v. Got error: %v", res, err)
  464. return
  465. }
  466. s.metrics.SamplerUpdated.Inc(1)
  467. }
  468. // NB: this function should only be called while holding a Write lock
  469. func (s *RemotelyControlledSampler) updateAdaptiveSampler(strategies *sampling.PerOperationSamplingStrategies) {
  470. if adaptiveSampler, ok := s.sampler.(*adaptiveSampler); ok {
  471. adaptiveSampler.update(strategies)
  472. } else {
  473. s.sampler = newAdaptiveSampler(strategies, s.maxOperations)
  474. }
  475. }
  476. // NB: this function should only be called while holding a Write lock
  477. func (s *RemotelyControlledSampler) updateRateLimitingOrProbabilisticSampler(res *sampling.SamplingStrategyResponse) error {
  478. var newSampler Sampler
  479. if probabilistic := res.GetProbabilisticSampling(); probabilistic != nil {
  480. newSampler = newProbabilisticSampler(probabilistic.SamplingRate)
  481. } else if rateLimiting := res.GetRateLimitingSampling(); rateLimiting != nil {
  482. newSampler = NewRateLimitingSampler(float64(rateLimiting.MaxTracesPerSecond))
  483. } else {
  484. return fmt.Errorf("Unsupported sampling strategy type %v", res.GetStrategyType())
  485. }
  486. if !s.sampler.Equal(newSampler) {
  487. s.sampler = newSampler
  488. }
  489. return nil
  490. }