-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathextension.go
307 lines (263 loc) · 9.41 KB
/
extension.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
// Copyright (c) 2024 The Jaeger Authors.
// SPDX-License-Identifier: Apache-2.0
package remotesampling
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"sync"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/component/componentstatus"
"go.opentelemetry.io/collector/extension"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
"github.com/jaegertracing/jaeger-idl/proto-gen/api_v2"
"github.com/jaegertracing/jaeger/cmd/jaeger/internal/extension/jaegerstorage"
"github.com/jaegertracing/jaeger/internal/leaderelection"
"github.com/jaegertracing/jaeger/internal/metrics/otelmetrics"
samplinggrpc "github.com/jaegertracing/jaeger/internal/sampling/grpc"
samplinghttp "github.com/jaegertracing/jaeger/internal/sampling/http"
"github.com/jaegertracing/jaeger/internal/sampling/samplingstrategy"
"github.com/jaegertracing/jaeger/internal/sampling/samplingstrategy/adaptive"
"github.com/jaegertracing/jaeger/internal/sampling/samplingstrategy/file"
"github.com/jaegertracing/jaeger/pkg/metrics"
"github.com/jaegertracing/jaeger/storage"
"github.com/jaegertracing/jaeger/storage/samplingstore"
)
var _ extension.Extension = (*rsExtension)(nil)
// type Extension interface {
// extension.Extension
// // rs *rsExtension
// }
const defaultResourceName = "sampling_store_leader"
type rsExtension struct {
cfg *Config
telemetry component.TelemetrySettings
httpServer *http.Server
grpcServer *grpc.Server
strategyProvider samplingstrategy.Provider // TODO we should rename this to Provider, not "store"
adaptiveStore samplingstore.Store
distLock *leaderelection.DistributedElectionParticipant
shutdownWG sync.WaitGroup
}
func newExtension(cfg *Config, telemetry component.TelemetrySettings) *rsExtension {
return &rsExtension{
cfg: cfg,
telemetry: telemetry,
}
}
// AdaptiveSamplingComponents is a struct that holds the components needed for adaptive sampling.
type AdaptiveSamplingComponents struct {
SamplingStore samplingstore.Store
DistLock *leaderelection.DistributedElectionParticipant
Options *adaptive.Options
}
// GetAdaptiveSamplingComponents locates the `remotesampling` extension in Host
// and returns the sampling store and a loader/follower implementation, provided
// that the extension is configured with adaptive sampling (vs. file-based config).
func GetAdaptiveSamplingComponents(host component.Host) (*AdaptiveSamplingComponents, error) {
var comp component.Component
var compID component.ID
for id, ext := range host.GetExtensions() {
if id.Type() == ComponentType {
comp = ext
compID = id
break
}
}
if comp == nil {
return nil, fmt.Errorf(
"cannot find extension '%s' (make sure it's defined earlier in the config)",
ComponentType,
)
}
ext, ok := comp.(*rsExtension)
if !ok {
return nil, fmt.Errorf("extension '%s' is not of type '%s'", compID, ComponentType)
}
if ext.adaptiveStore == nil || ext.distLock == nil {
return nil, fmt.Errorf("extension '%s' is not configured for adaptive sampling", compID)
}
return &AdaptiveSamplingComponents{
SamplingStore: ext.adaptiveStore,
DistLock: ext.distLock,
Options: &ext.cfg.Adaptive.Options,
}, nil
}
func (ext *rsExtension) Start(ctx context.Context, host component.Host) error {
if ext.cfg.File != nil {
ext.telemetry.Logger.Info(
"Starting file-based sampling strategy provider",
zap.String("path", ext.cfg.File.Path),
)
if err := ext.startFileBasedStrategyProvider(ctx); err != nil {
return err
}
}
if ext.cfg.Adaptive != nil {
ext.telemetry.Logger.Info(
"Starting adaptive sampling strategy provider",
zap.String("sampling_store", ext.cfg.Adaptive.SamplingStore),
)
if err := ext.startAdaptiveStrategyProvider(host); err != nil {
return err
}
}
if ext.cfg.HTTP != nil {
if err := ext.startHTTPServer(ctx, host); err != nil {
return fmt.Errorf("failed to start sampling http server: %w", err)
}
}
if ext.cfg.GRPC != nil {
if err := ext.startGRPCServer(ctx, host); err != nil {
return fmt.Errorf("failed to start sampling gRPC server: %w", err)
}
}
return nil
}
func (ext *rsExtension) Shutdown(ctx context.Context) error {
var errs []error
if ext.httpServer != nil {
if err := ext.httpServer.Shutdown(ctx); err != nil {
errs = append(errs, fmt.Errorf("failed to stop the sampling HTTP server: %w", err))
}
}
if ext.grpcServer != nil {
ext.grpcServer.GracefulStop()
}
if ext.distLock != nil {
if err := ext.distLock.Close(); err != nil {
errs = append(errs, fmt.Errorf("failed to stop the distributed lock: %w", err))
}
}
if ext.strategyProvider != nil {
if err := ext.strategyProvider.Close(); err != nil {
errs = append(errs, fmt.Errorf("failed to stop strategy provider: %w", err))
}
}
return errors.Join(errs...)
}
func (ext *rsExtension) startFileBasedStrategyProvider(_ context.Context) error {
opts := file.Options{
StrategiesFile: ext.cfg.File.Path,
ReloadInterval: ext.cfg.File.ReloadInterval,
IncludeDefaultOpStrategies: includeDefaultOpStrategies.IsEnabled(),
DefaultSamplingProbability: ext.cfg.File.DefaultSamplingProbability,
}
// contextcheck linter complains about next line that context is not passed.
//nolint:contextcheck
provider, err := file.NewProvider(opts, ext.telemetry.Logger)
if err != nil {
return fmt.Errorf("failed to create the local file strategy store: %w", err)
}
ext.strategyProvider = provider
return nil
}
func (ext *rsExtension) startAdaptiveStrategyProvider(host component.Host) error {
storageName := ext.cfg.Adaptive.SamplingStore
f, err := jaegerstorage.GetStorageFactory(storageName, host)
if err != nil {
return fmt.Errorf("cannot find storage factory: %w", err)
}
storeFactory, ok := f.(storage.SamplingStoreFactory)
if !ok {
return fmt.Errorf("storage '%s' does not support sampling store", storageName)
}
store, err := storeFactory.CreateSamplingStore(ext.cfg.Adaptive.AggregationBuckets)
if err != nil {
return fmt.Errorf("failed to create the sampling store: %w", err)
}
ext.adaptiveStore = store
{
lock, err := storeFactory.CreateLock()
if err != nil {
return fmt.Errorf("failed to create the distributed lock: %w", err)
}
ep := leaderelection.NewElectionParticipant(lock, defaultResourceName,
leaderelection.ElectionParticipantOptions{
LeaderLeaseRefreshInterval: ext.cfg.Adaptive.LeaderLeaseRefreshInterval,
FollowerLeaseRefreshInterval: ext.cfg.Adaptive.FollowerLeaseRefreshInterval,
Logger: ext.telemetry.Logger,
})
if err := ep.Start(); err != nil {
return fmt.Errorf("failed to start the leader election participant: %w", err)
}
ext.distLock = ep
}
provider := adaptive.NewProvider(ext.cfg.Adaptive.Options, ext.telemetry.Logger, ext.distLock, store)
if err := provider.Start(); err != nil {
return fmt.Errorf("failed to start the adaptive strategy store: %w", err)
}
ext.strategyProvider = provider
return nil
}
func (ext *rsExtension) startHTTPServer(ctx context.Context, host component.Host) error {
mf := otelmetrics.NewFactory(ext.telemetry.MeterProvider)
mf = mf.Namespace(metrics.NSOptions{Name: "jaeger_remote_sampling"})
handler := samplinghttp.NewHandler(samplinghttp.HandlerParams{
ConfigManager: &samplinghttp.ConfigManager{
SamplingProvider: ext.strategyProvider,
},
MetricsFactory: mf,
// In v1 the sampling endpoint in the collector was at /api/sampling, because
// the collector reused the same port for multiple services. In v2, the extension
// always uses a separate port, making /api prefix unnecessary.
BasePath: "",
})
httpMux := http.NewServeMux()
handler.RegisterRoutesWithHTTP(httpMux)
var err error
if ext.httpServer, err = ext.cfg.HTTP.ToServer(ctx, host, ext.telemetry, httpMux); err != nil {
return err
}
ext.telemetry.Logger.Info(
"Starting remote sampling HTTP server",
zap.String("endpoint", ext.cfg.HTTP.Endpoint),
)
var hln net.Listener
if hln, err = ext.cfg.HTTP.ToListener(ctx); err != nil {
return err
}
ext.shutdownWG.Add(1)
go func() {
defer ext.shutdownWG.Done()
err := ext.httpServer.Serve(hln)
if err != nil && !errors.Is(err, http.ErrServerClosed) {
componentstatus.ReportStatus(host, componentstatus.NewFatalErrorEvent(err))
}
}()
return nil
}
func (ext *rsExtension) startGRPCServer(ctx context.Context, host component.Host) error {
var err error
if ext.grpcServer, err = ext.cfg.GRPC.ToServer(ctx, host, ext.telemetry); err != nil {
return err
}
api_v2.RegisterSamplingManagerServer(ext.grpcServer, samplinggrpc.NewHandler(ext.strategyProvider))
healthServer := health.NewServer() // support health checks on the gRPC server
healthServer.SetServingStatus("jaeger.api_v2.SamplingManager", grpc_health_v1.HealthCheckResponse_SERVING)
grpc_health_v1.RegisterHealthServer(ext.grpcServer, healthServer)
ext.telemetry.Logger.Info(
"Starting remote sampling GRPC server",
zap.String("endpoint", ext.cfg.GRPC.NetAddr.Endpoint),
)
var gln net.Listener
if gln, err = ext.cfg.GRPC.NetAddr.Listen(ctx); err != nil {
return err
}
ext.shutdownWG.Add(1)
go func() {
defer ext.shutdownWG.Done()
if err := ext.grpcServer.Serve(gln); err != nil && !errors.Is(err, grpc.ErrServerStopped) {
componentstatus.ReportStatus(host, componentstatus.NewFatalErrorEvent(err))
}
}()
return nil
}
func (*rsExtension) Dependencies() []component.ID {
return []component.ID{jaegerstorage.ID}
}