sampler.go 18 KB

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