-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
config.go
488 lines (448 loc) · 15.8 KB
/
config.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
// Copyright (c) 2019 The Jaeger Authors.
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package config
import (
"bufio"
"context"
"crypto/tls"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/asaskevich/govalidator"
esV8 "github.com/elastic/go-elasticsearch/v8"
"github.com/olivere/elastic"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zapgrpc"
"github.com/jaegertracing/jaeger/pkg/bearertoken"
"github.com/jaegertracing/jaeger/pkg/config/tlscfg"
"github.com/jaegertracing/jaeger/pkg/es"
eswrapper "github.com/jaegertracing/jaeger/pkg/es/wrapper"
"github.com/jaegertracing/jaeger/pkg/metrics"
storageMetrics "github.com/jaegertracing/jaeger/storage/spanstore/metrics"
)
// Configuration describes the configuration properties needed to connect to an ElasticSearch cluster
type Configuration struct {
Servers []string `mapstructure:"server_urls" valid:"required,url"`
RemoteReadClusters []string `mapstructure:"remote_read_clusters"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password" json:"-"`
TokenFilePath string `mapstructure:"token_file"`
PasswordFilePath string `mapstructure:"password_file"`
AllowTokenFromContext bool `mapstructure:"-"`
Sniffer bool `mapstructure:"sniffer"` // https://github.com/olivere/elastic/wiki/Sniffing
SnifferTLSEnabled bool `mapstructure:"sniffer_tls_enabled"`
MaxDocCount int `mapstructure:"-"` // Defines maximum number of results to fetch from storage per query
MaxSpanAge time.Duration `mapstructure:"-"` // configures the maximum lookback on span reads
NumShards int64 `mapstructure:"num_shards"`
NumReplicas int64 `mapstructure:"num_replicas"`
PrioritySpanTemplate int64 `mapstructure:"priority_span_template"`
PriorityServiceTemplate int64 `mapstructure:"priority_service_template"`
PriorityDependenciesTemplate int64 `mapstructure:"priority_dependencies_template"`
Timeout time.Duration `mapstructure:"-"`
BulkSize int `mapstructure:"-"`
BulkWorkers int `mapstructure:"-"`
BulkActions int `mapstructure:"-"`
BulkFlushInterval time.Duration `mapstructure:"-"`
IndexPrefix string `mapstructure:"index_prefix"`
IndexDateLayoutSpans string `mapstructure:"-"`
IndexDateLayoutServices string `mapstructure:"-"`
IndexDateLayoutSampling string `mapstructure:"-"`
IndexDateLayoutDependencies string `mapstructure:"-"`
IndexRolloverFrequencySpans string `mapstructure:"-"`
IndexRolloverFrequencyServices string `mapstructure:"-"`
IndexRolloverFrequencySampling string `mapstructure:"-"`
AdaptiveSamplingLookback time.Duration `mapstructure:"-"`
Tags TagsAsFields `mapstructure:"tags_as_fields"`
Enabled bool `mapstructure:"-"`
TLS tlscfg.Options `mapstructure:"tls"`
UseReadWriteAliases bool `mapstructure:"use_aliases"`
CreateIndexTemplates bool `mapstructure:"create_mappings"`
UseILM bool `mapstructure:"use_ilm"`
Version uint `mapstructure:"version"`
LogLevel string `mapstructure:"log_level"`
SendGetBodyAs string `mapstructure:"send_get_body_as"`
}
// TagsAsFields holds configuration for tag schema.
// By default Jaeger stores tags in an array of nested objects.
// This configurations allows to store tags as object fields for better Kibana support.
type TagsAsFields struct {
// Store all tags as object fields, instead nested objects
AllAsFields bool `mapstructure:"all"`
// Dot replacement for tag keys when stored as object fields
DotReplacement string `mapstructure:"dot_replacement"`
// File path to tag keys which should be stored as object fields
File string `mapstructure:"config_file"`
// Comma delimited list of tags to store as object fields
Include string `mapstructure:"include"`
}
// NewClient creates a new ElasticSearch client
func NewClient(c *Configuration, logger *zap.Logger, metricsFactory metrics.Factory) (es.Client, error) {
if len(c.Servers) < 1 {
return nil, errors.New("no servers specified")
}
options, err := c.getConfigOptions(logger)
if err != nil {
return nil, err
}
rawClient, err := elastic.NewClient(options...)
if err != nil {
return nil, err
}
sm := storageMetrics.NewWriteMetrics(metricsFactory, "bulk_index")
m := sync.Map{}
bulkProc, err := rawClient.BulkProcessor().
Before(func(id int64, requests []elastic.BulkableRequest) {
m.Store(id, time.Now())
}).
After(func(id int64, requests []elastic.BulkableRequest, response *elastic.BulkResponse, err error) {
start, ok := m.Load(id)
if !ok {
return
}
m.Delete(id)
// log individual errors, note that err might be false and these errors still present
if response != nil && response.Errors {
for _, it := range response.Items {
for key, val := range it {
if val.Error != nil {
logger.Error("Elasticsearch part of bulk request failed", zap.String("map-key", key),
zap.Reflect("response", val))
}
}
}
}
sm.Emit(err, time.Since(start.(time.Time)))
if err != nil {
var failed int
if response == nil {
failed = 0
} else {
failed = len(response.Failed())
}
total := len(requests)
logger.Error("Elasticsearch could not process bulk request",
zap.Int("request_count", total),
zap.Int("failed_count", failed),
zap.Error(err),
zap.Any("response", response))
}
}).
BulkSize(c.BulkSize).
Workers(c.BulkWorkers).
BulkActions(c.BulkActions).
FlushInterval(c.BulkFlushInterval).
Do(context.Background())
if err != nil {
return nil, err
}
if c.Version == 0 {
// Determine ElasticSearch Version
pingResult, _, err := rawClient.Ping(c.Servers[0]).Do(context.Background())
if err != nil {
return nil, err
}
esVersion, err := strconv.Atoi(string(pingResult.Version.Number[0]))
if err != nil {
return nil, err
}
// OpenSearch is based on ES 7.x
if strings.Contains(pingResult.TagLine, "OpenSearch") {
if pingResult.Version.Number[0] == '1' {
logger.Info("OpenSearch 1.x detected, using ES 7.x index mappings")
esVersion = 7
}
if pingResult.Version.Number[0] == '2' {
logger.Info("OpenSearch 2.x detected, using ES 7.x index mappings")
esVersion = 7
}
}
logger.Info("Elasticsearch detected", zap.Int("version", esVersion))
c.Version = uint(esVersion)
}
var rawClientV8 *esV8.Client
if c.Version >= 8 {
rawClientV8, err = newElasticsearchV8(c, logger)
if err != nil {
return nil, fmt.Errorf("error creating v8 client: %w", err)
}
}
return eswrapper.WrapESClient(rawClient, bulkProc, c.Version, rawClientV8), nil
}
func newElasticsearchV8(c *Configuration, logger *zap.Logger) (*esV8.Client, error) {
var options esV8.Config
options.Addresses = c.Servers
options.Username = c.Username
options.Password = c.Password
options.DiscoverNodesOnStart = c.Sniffer
transport, err := GetHTTPRoundTripper(c, logger)
if err != nil {
return nil, err
}
options.Transport = transport
return esV8.NewClient(options)
}
// ApplyDefaults copies settings from source unless its own value is non-zero.
func (c *Configuration) ApplyDefaults(source *Configuration) {
if len(c.RemoteReadClusters) == 0 {
c.RemoteReadClusters = source.RemoteReadClusters
}
if c.Username == "" {
c.Username = source.Username
}
if c.Password == "" {
c.Password = source.Password
}
if !c.Sniffer {
c.Sniffer = source.Sniffer
}
if c.MaxSpanAge == 0 {
c.MaxSpanAge = source.MaxSpanAge
}
if c.AdaptiveSamplingLookback == 0 {
c.AdaptiveSamplingLookback = source.AdaptiveSamplingLookback
}
if c.NumShards == 0 {
c.NumShards = source.NumShards
}
if c.NumReplicas == 0 {
c.NumReplicas = source.NumReplicas
}
if c.PrioritySpanTemplate == 0 {
c.PrioritySpanTemplate = source.PrioritySpanTemplate
}
if c.PriorityServiceTemplate == 0 {
c.PriorityServiceTemplate = source.PriorityServiceTemplate
}
if c.PrioritySpanTemplate == 0 {
c.PriorityDependenciesTemplate = source.PriorityDependenciesTemplate
}
if c.BulkSize == 0 {
c.BulkSize = source.BulkSize
}
if c.BulkWorkers == 0 {
c.BulkWorkers = source.BulkWorkers
}
if c.BulkActions == 0 {
c.BulkActions = source.BulkActions
}
if c.BulkFlushInterval == 0 {
c.BulkFlushInterval = source.BulkFlushInterval
}
if !c.SnifferTLSEnabled {
c.SnifferTLSEnabled = source.SnifferTLSEnabled
}
if !c.Tags.AllAsFields {
c.Tags.AllAsFields = source.Tags.AllAsFields
}
if c.Tags.DotReplacement == "" {
c.Tags.DotReplacement = source.Tags.DotReplacement
}
if c.Tags.Include == "" {
c.Tags.Include = source.Tags.Include
}
if c.Tags.File == "" {
c.Tags.File = source.Tags.File
}
if c.MaxDocCount == 0 {
c.MaxDocCount = source.MaxDocCount
}
if c.LogLevel == "" {
c.LogLevel = source.LogLevel
}
if c.SendGetBodyAs == "" {
c.SendGetBodyAs = source.SendGetBodyAs
}
}
// GetIndexRolloverFrequencySpansDuration returns jaeger-span index rollover frequency duration
func (c *Configuration) GetIndexRolloverFrequencySpansDuration() time.Duration {
return getIndexRolloverFrequencyDuration(c.IndexRolloverFrequencySpans)
}
// GetIndexRolloverFrequencyServicesDuration returns jaeger-service index rollover frequency duration
func (c *Configuration) GetIndexRolloverFrequencyServicesDuration() time.Duration {
return getIndexRolloverFrequencyDuration(c.IndexRolloverFrequencyServices)
}
// GetIndexRolloverFrequencySamplingDuration returns jaeger-sampling index rollover frequency duration
func (c *Configuration) GetIndexRolloverFrequencySamplingDuration() time.Duration {
return getIndexRolloverFrequencyDuration(c.IndexRolloverFrequencySampling)
}
// GetIndexRolloverFrequencyDuration returns the index rollover frequency duration for the given frequency string
func getIndexRolloverFrequencyDuration(frequency string) time.Duration {
if frequency == "hour" {
return -1 * time.Hour
}
return -24 * time.Hour
}
// TagKeysAsFields returns tags from the file and command line merged
func (c *Configuration) TagKeysAsFields() ([]string, error) {
var tags []string
// from file
if c.Tags.File != "" {
file, err := os.Open(filepath.Clean(c.Tags.File))
if err != nil {
return nil, err
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if tag := strings.TrimSpace(line); tag != "" {
tags = append(tags, tag)
}
}
if err := file.Close(); err != nil {
return nil, err
}
}
// from params
if c.Tags.Include != "" {
tags = append(tags, strings.Split(c.Tags.Include, ",")...)
}
return tags, nil
}
// getConfigOptions wraps the configs to feed to the ElasticSearch client init
func (c *Configuration) getConfigOptions(logger *zap.Logger) ([]elastic.ClientOptionFunc, error) {
options := []elastic.ClientOptionFunc{
elastic.SetURL(c.Servers...), elastic.SetSniff(c.Sniffer),
// Disable health check when token from context is allowed, this is because at this time
// we don' have a valid token to do the check ad if we don't disable the check the service that
// uses this won't start.
elastic.SetHealthcheck(!c.AllowTokenFromContext),
}
if c.SnifferTLSEnabled {
options = append(options, elastic.SetScheme("https"))
}
httpClient := &http.Client{
Timeout: c.Timeout,
}
options = append(options, elastic.SetHttpClient(httpClient))
if c.Password != "" && c.PasswordFilePath != "" {
return nil, fmt.Errorf("both Password and PasswordFilePath are set")
}
if c.PasswordFilePath != "" {
passwordFromFile, err := loadTokenFromFile(c.PasswordFilePath)
if err != nil {
return nil, fmt.Errorf("failed to load password from file: %w", err)
}
c.Password = passwordFromFile
}
options = append(options, elastic.SetBasicAuth(c.Username, c.Password))
if c.SendGetBodyAs != "" {
options = append(options, elastic.SetSendGetBodyAs(c.SendGetBodyAs))
}
options, err := addLoggerOptions(options, c.LogLevel)
if err != nil {
return options, err
}
transport, err := GetHTTPRoundTripper(c, logger)
if err != nil {
return nil, err
}
httpClient.Transport = transport
return options, nil
}
func addLoggerOptions(options []elastic.ClientOptionFunc, logLevel string) ([]elastic.ClientOptionFunc, error) {
// Decouple ES logger from the log-level assigned to the parent application's log-level; otherwise, the least
// permissive log-level will dominate.
// e.g. --log-level=info and --es.log-level=debug would mute ES's debug logging and would require --log-level=debug
// to show ES debug logs.
prodConfig := zap.NewProductionConfig()
var lvl zapcore.Level
var setLogger func(logger elastic.Logger) elastic.ClientOptionFunc
switch logLevel {
case "debug":
lvl = zap.DebugLevel
setLogger = elastic.SetTraceLog
case "info":
lvl = zap.InfoLevel
setLogger = elastic.SetInfoLog
case "error":
lvl = zap.ErrorLevel
setLogger = elastic.SetErrorLog
default:
return options, fmt.Errorf("unrecognized log-level: \"%s\"", logLevel)
}
prodConfig.Level.SetLevel(lvl)
esLogger, err := prodConfig.Build()
if err != nil {
return options, err
}
// Elastic client requires a "Printf"-able logger.
l := zapgrpc.NewLogger(esLogger)
options = append(options, setLogger(l))
return options, nil
}
// GetHTTPRoundTripper returns configured http.RoundTripper
func GetHTTPRoundTripper(c *Configuration, logger *zap.Logger) (http.RoundTripper, error) {
if c.TLS.Enabled {
ctlsConfig, err := c.TLS.Config(logger)
if err != nil {
return nil, err
}
return &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: ctlsConfig,
}, nil
}
var transport http.RoundTripper
httpTransport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
// #nosec G402
TLSClientConfig: &tls.Config{InsecureSkipVerify: c.TLS.SkipHostVerify},
}
if c.TLS.CAPath != "" {
ctlsConfig, err := c.TLS.Config(logger)
if err != nil {
return nil, err
}
httpTransport.TLSClientConfig = ctlsConfig
transport = httpTransport
}
token := ""
if c.TokenFilePath != "" {
if c.AllowTokenFromContext {
logger.Warn("Token file and token propagation are both enabled, token from file won't be used")
}
tokenFromFile, err := loadTokenFromFile(c.TokenFilePath)
if err != nil {
return nil, err
}
token = tokenFromFile
}
if token != "" || c.AllowTokenFromContext {
transport = bearertoken.RoundTripper{
Transport: httpTransport,
OverrideFromCtx: c.AllowTokenFromContext,
StaticToken: token,
}
}
return transport, nil
}
func loadTokenFromFile(path string) (string, error) {
b, err := os.ReadFile(filepath.Clean(path))
if err != nil {
return "", err
}
return strings.TrimRight(string(b), "\r\n"), nil
}
func (c *Configuration) Validate() error {
_, err := govalidator.ValidateStruct(c)
return err
}