sampler.go 17 KB

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