Debian Codegraph @

samplers/jaegerremote/sampler_remote.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Copyright (c) 2021 The Jaeger Authors.
5 // Copyright (c) 2017 Uber Technologies, Inc.
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 // http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18
19 package jaegerremote // import "go.opentelemetry.io/contrib/samplers/jaegerremote"
20
21 import (
22 "bytes"
23 "context"
24 "fmt"
25 "io"
26 "net/http"
27 "net/url"
28 "sync"
29 "sync/atomic"
30 "time"
31
32 "github.com/gogo/protobuf/jsonpb"
33 jaeger_api_v2 "github.com/jaegertracing/jaeger-idl/proto-gen/api_v2"
34 "go.opentelemetry.io/otel/sdk/trace"
35 )
36
37 const (
38 defaultRemoteSamplingTimeout = 10 * time.Second
39 defaultSamplingRefreshInterval = time.Minute
40 defaultSamplingMaxOperations = 256
41 defaultSamplingOperationNameLateBinding = true
42 )
43
44 // SamplingStrategyFetcher is used to fetch sampling strategy updates from remote server.
45 type SamplingStrategyFetcher interface {
46 Fetch(service string) ([]byte, error)
47 }
48
49 // samplingStrategyParser is used to parse sampling strategy updates. The output object
50 // should be of the type that is recognized by the SamplerUpdaters.
51 type samplingStrategyParser interface {
52 Parse(response []byte) (any, error)
53 }
54
55 // samplerUpdater is used by Sampler to apply sampling strategies,
56 // retrieved from remote config server, to the current sampler. The updater can modify
57 // the sampler in-place if sampler supports it, or create a new one.
58 //
59 // If the strategy does not contain configuration for the sampler in question,
60 // updater must return modifiedSampler=nil to give other updaters a chance to inspect
61 // the sampling strategy response.
62 //
63 // Sampler invokes the updaters while holding a lock on the main sampler.
64 type samplerUpdater interface {
65 Update(sampler trace.Sampler, strategy any) (modified trace.Sampler, err error)
66 }
67
68 // Sampler is a delegating sampler that polls a remote server
69 // for the appropriate sampling strategy, constructs a corresponding sampler and
70 // delegates to it for sampling decisions.
71 type Sampler struct {
72 // These fields must be first in the struct because `sync/atomic` expects 64-bit alignment.
73 // Cf. https://github.com/jaegertracing/jaeger-client-go/issues/155, https://pkg.go.dev/sync/atomic#pkg-note-BUG
74 closed int64 // 0 - not closed, 1 - closed
75
76 sync.RWMutex // used to serialize access to samplerConfig.sampler
77 config
78
79 serviceName string
80 doneChan chan *sync.WaitGroup
81 }
82
83 // New creates a sampler that periodically pulls
84 // the sampling strategy from an HTTP sampling server (e.g. jaeger-agent).
85 func New(
86 serviceName string,
87 opts ...Option,
88 ) *Sampler {
89 options := newConfig(opts...)
90 sampler := &Sampler{
91 config: options,
92 serviceName: serviceName,
93 doneChan: make(chan *sync.WaitGroup),
94 }
95 go sampler.pollController()
96 return sampler
97 }
98
99 // ShouldSample returns a sampling choice based on the passed sampling
100 // parameters.
101 func (s *Sampler) ShouldSample(p trace.SamplingParameters) trace.SamplingResult {
102 s.RLock()
103 defer s.RUnlock()
104 return s.sampler.ShouldSample(p)
105 }
106
107 // Close does a clean shutdown of the sampler, stopping any background
108 // go-routines it may have started.
109 func (s *Sampler) Close() {
110 if swapped := atomic.CompareAndSwapInt64(&s.closed, 0, 1); !swapped {
111 s.logger.Info("repeated attempt to close the sampler is ignored")
112 return
113 }
114
115 var wg sync.WaitGroup
116 wg.Add(1)
117 s.doneChan <- &wg
118 wg.Wait()
119 }
120
121 // Description returns a human-readable name for the Sampler.
122 func (*Sampler) Description() string {
123 return "JaegerRemoteSampler{}"
124 }
125
126 func (s *Sampler) pollController() {
127 ticker := time.NewTicker(s.samplingRefreshInterval)
128 defer ticker.Stop()
129 s.pollControllerWithTicker(ticker)
130 }
131
132 func (s *Sampler) pollControllerWithTicker(ticker *time.Ticker) {
133 s.UpdateSampler()
134
135 for {
136 select {
137 case <-ticker.C:
138 s.UpdateSampler()
139 case wg := <-s.doneChan:
140 wg.Done()
141 return
142 }
143 }
144 }
145
146 func (s *Sampler) setSampler(sampler trace.Sampler) {
147 s.Lock()
148 defer s.Unlock()
149 s.sampler = sampler
150 }
151
152 // UpdateSampler forces the sampler to fetch sampling strategy from backend server.
153 // This function is called automatically on a timer, but can also be safely called manually, e.g. from tests.
154 func (s *Sampler) UpdateSampler() {
155 res, err := s.samplingFetcher.Fetch(s.serviceName)
156 if err != nil {
157 s.logger.Error(err, "failed to fetch sampling strategy")
158 return
159 }
160 strategy, err := s.samplingParser.Parse(res)
161 if err != nil {
162 s.logger.Error(err, "failed to parse sampling strategy response")
163 return
164 }
165
166 s.Lock()
167 defer s.Unlock()
168
169 if err := s.updateSamplerViaUpdaters(strategy); err != nil {
170 s.logger.Error(err, "failed to handle sampling strategy response", "response", res)
171 return
172 }
173 }
174
175 // NB: this function should only be called while holding a Write lock.
176 func (s *Sampler) updateSamplerViaUpdaters(strategy any) error {
177 for _, updater := range s.updaters {
178 sampler, err := updater.Update(s.sampler, strategy)
179 if err != nil {
180 return err
181 }
182 if sampler != nil {
183 s.sampler = sampler
184 return nil
185 }
186 }
187 return fmt.Errorf("unsupported sampling strategy %+v", strategy)
188 }
189
190 // -----------------------
191
192 // probabilisticSamplerUpdater is used by Sampler to parse sampling configuration.
193 type probabilisticSamplerUpdater struct {
194 attributesDisabled bool
195 }
196
197 // Update implements Update of samplerUpdater.
198 func (u *probabilisticSamplerUpdater) Update(sampler trace.Sampler, strategy any) (trace.Sampler, error) {
199 type response interface {
200 GetProbabilisticSampling() *jaeger_api_v2.ProbabilisticSamplingStrategy
201 }
202 var _ response = new(jaeger_api_v2.SamplingStrategyResponse) // sanity signature check
203 if resp, ok := strategy.(response); ok {
204 if probabilistic := resp.GetProbabilisticSampling(); probabilistic != nil {
205 if ps, ok := sampler.(*probabilisticSampler); ok {
206 if err := ps.Update(probabilistic.SamplingRate); err != nil {
207 return nil, err
208 }
209 return sampler, nil
210 }
211 return newProbabilisticSampler(probabilistic.SamplingRate, u.attributesDisabled), nil
212 }
213 }
214 return nil, nil
215 }
216
217 // -----------------------
218
219 // rateLimitingSamplerUpdater is used by Sampler to parse sampling configuration.
220 type rateLimitingSamplerUpdater struct {
221 attributesDisabled bool
222 }
223
224 // Update implements Update of samplerUpdater.
225 func (u *rateLimitingSamplerUpdater) Update(sampler trace.Sampler, strategy any) (trace.Sampler, error) {
226 type response interface {
227 GetRateLimitingSampling() *jaeger_api_v2.RateLimitingSamplingStrategy
228 }
229 var _ response = new(jaeger_api_v2.SamplingStrategyResponse) // sanity signature check
230 if resp, ok := strategy.(response); ok {
231 if rateLimiting := resp.GetRateLimitingSampling(); rateLimiting != nil {
232 rateLimit := float64(rateLimiting.MaxTracesPerSecond)
233 if rl, ok := sampler.(*rateLimitingSampler); ok {
234 rl.Update(rateLimit)
235 return rl, nil
236 }
237 return newRateLimitingSampler(rateLimit, u.attributesDisabled), nil
238 }
239 }
240 return nil, nil
241 }
242
243 // -----------------------
244
245 // perOperationSamplerUpdater is used by Sampler to parse sampling configuration.
246 // Fields have the same meaning as in perOperationSamplerParams.
247 type perOperationSamplerUpdater struct {
248 MaxOperations int
249 OperationNameLateBinding bool
250 attributesDisabled bool
251 }
252
253 // Update implements Update of samplerUpdater.
254 func (u *perOperationSamplerUpdater) Update(sampler trace.Sampler, strategy any) (trace.Sampler, error) {
255 type response interface {
256 GetOperationSampling() *jaeger_api_v2.PerOperationSamplingStrategies
257 }
258 var _ response = new(jaeger_api_v2.SamplingStrategyResponse) // sanity signature check
259 if p, ok := strategy.(response); ok {
260 if operations := p.GetOperationSampling(); operations != nil {
261 if as, ok := sampler.(*perOperationSampler); ok {
262 as.update(operations)
263 return as, nil
264 }
265 return newPerOperationSampler(perOperationSamplerParams{
266 MaxOperations: u.MaxOperations,
267 OperationNameLateBinding: u.OperationNameLateBinding,
268 Strategies: operations,
269 }, u.attributesDisabled), nil
270 }
271 }
272 return nil, nil
273 }
274
275 // -----------------------
276
277 type httpSamplingStrategyFetcher struct {
278 serverURL string
279 httpClient http.Client
280 }
281
282 func newHTTPSamplingStrategyFetcher(serverURL string) *httpSamplingStrategyFetcher {
283 return &httpSamplingStrategyFetcher{
284 serverURL: serverURL,
285 httpClient: http.Client{
286 Timeout: defaultRemoteSamplingTimeout,
287 },
288 }
289 }
290
291 func (f *httpSamplingStrategyFetcher) Fetch(serviceName string) ([]byte, error) {
292 v := url.Values{}
293 v.Set("service", serviceName)
294 uri := f.serverURL + "?" + v.Encode()
295 req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, uri, http.NoBody)
296 if err != nil {
297 return nil, err
298 }
299 resp, err := f.httpClient.Do(req)
300 if err != nil {
301 return nil, err
302 }
303 defer resp.Body.Close()
304
305 body, err := io.ReadAll(resp.Body)
306 if err != nil {
307 return nil, err
308 }
309
310 if resp.StatusCode >= 400 {
311 return nil, fmt.Errorf("status code: %d, body: %c", resp.StatusCode, body)
312 }
313
314 return body, nil
315 }
316
317 // -----------------------
318
319 type samplingStrategyParserImpl struct{}
320
321 func (*samplingStrategyParserImpl) Parse(response []byte) (any, error) {
322 strategy := new(jaeger_api_v2.SamplingStrategyResponse)
323 // Official Jaeger Remote Sampling protocol contains enums encoded as strings.
324 // Legacy protocol contains enums as numbers.
325 // Gogo's jsonpb module can parse either format.
326 // Cf. https://github.com/open-telemetry/opentelemetry-go-contrib/issues/3184
327 if err := jsonpb.Unmarshal(bytes.NewReader(response), strategy); err != nil {
328 return nil, err
329 }
330 return strategy, nil
331 }