-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathclient.go
77 lines (62 loc) · 1.87 KB
/
client.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
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package es
import (
"context"
"fmt"
"net/http"
"runtime"
"go.elastic.co/apm/module/apmelasticsearch/v2"
"github.com/elastic/fleet-server/v7/internal/pkg/build"
"github.com/elastic/fleet-server/v7/internal/pkg/config"
"github.com/rs/zerolog"
"github.com/elastic/go-elasticsearch/v8"
)
type ConfigOption func(config *elasticsearch.Config)
func NewClient(ctx context.Context, cfg *config.Config, longPoll bool, opts ...ConfigOption) (*elasticsearch.Client, error) {
escfg, err := cfg.Output.Elasticsearch.ToESConfig(longPoll)
if err != nil {
return nil, err
}
addr := cfg.Output.Elasticsearch.Hosts
mcph := cfg.Output.Elasticsearch.MaxConnPerHost
// Apply configuration options
for _, opt := range opts {
opt(&escfg)
}
zlog := zerolog.Ctx(ctx).With().
Strs("cluster.addr", addr).
Int("cluster.maxConnsPersHost", mcph).
Logger()
zlog.Debug().Msg("init es")
es, err := elasticsearch.NewClient(escfg)
if err != nil {
zlog.Error().Err(err).Msg("fail elasticsearch init")
return nil, err
}
return es, nil
}
func WithUserAgent(name string, bi build.Info) ConfigOption {
return func(config *elasticsearch.Config) {
ua := userAgent(name, bi)
// Set User-Agent header
if config.Header == nil {
config.Header = http.Header{}
}
config.Header.Set("User-Agent", ua)
}
}
func InstrumentRoundTripper() ConfigOption {
return func(config *elasticsearch.Config) {
config.Transport = apmelasticsearch.WrapRoundTripper(
config.Transport,
)
}
}
func userAgent(name string, bi build.Info) string {
return fmt.Sprintf("Elastic-%s/%s (%s; %s; %s; %s)",
name,
bi.Version, runtime.GOOS, runtime.GOARCH,
bi.Commit, bi.BuildTime)
}