forked from open-telemetry/opentelemetry-collector-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
266 lines (217 loc) · 7.65 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
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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package elasticsearchreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/elasticsearchreceiver"
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/hashicorp/go-version"
"go.opentelemetry.io/collector/component"
"go.uber.org/zap"
"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/elasticsearchreceiver/internal/model"
)
var (
errUnauthenticated = errors.New("status 401, unauthenticated")
errUnauthorized = errors.New("status 403, unauthorized")
)
// elasticsearchClient defines the interface to retrieve metrics from an Elasticsearch cluster.
type elasticsearchClient interface {
Nodes(ctx context.Context, nodes []string) (*model.Nodes, error)
NodeStats(ctx context.Context, nodes []string) (*model.NodeStats, error)
ClusterHealth(ctx context.Context) (*model.ClusterHealth, error)
IndexStats(ctx context.Context, indices []string) (*model.IndexStats, error)
ClusterMetadata(ctx context.Context) (*model.ClusterMetadataResponse, error)
ClusterStats(ctx context.Context, nodes []string) (*model.ClusterStats, error)
}
// defaultElasticsearchClient is the main implementation of elasticsearchClient.
// It retrieves the required metrics from Elasticsearch's REST api.
type defaultElasticsearchClient struct {
client *http.Client
endpoint *url.URL
authHeader string
logger *zap.Logger
version *version.Version
}
var _ elasticsearchClient = (*defaultElasticsearchClient)(nil)
func newElasticsearchClient(ctx context.Context, settings component.TelemetrySettings, c Config, h component.Host) (*defaultElasticsearchClient, error) {
client, err := c.ClientConfig.ToClient(ctx, h, settings)
if err != nil {
return nil, err
}
endpoint, err := url.Parse(c.Endpoint)
if err != nil {
return nil, err
}
var authHeader string
if c.Username != "" && c.Password != "" {
userPass := fmt.Sprintf("%s:%s", c.Username, string(c.Password))
authb64 := base64.StdEncoding.EncodeToString([]byte(userPass))
authHeader = fmt.Sprintf("Basic %s", authb64)
}
esClient := defaultElasticsearchClient{
client: client,
authHeader: authHeader,
endpoint: endpoint,
logger: settings.Logger,
}
// Try update es version
_, _ = esClient.ClusterMetadata(context.Background())
return &esClient, nil
}
var (
es7_9 = func() *version.Version {
v, _ := version.NewVersion("7.9")
return v
}()
)
const (
// A comma separated list of metrics that will be gathered from NodeStats.
// https://www.elastic.co/guide/en/elasticsearch/reference/7.9/cluster-nodes-stats.html#cluster-nodes-stats-api-path-params
defaultNodeStatsMetrics = "breaker,indices,process,jvm,thread_pool,transport,http,fs,ingest,indices,adaptive_selection,discovery,script,os"
// Extra NodeStats Metrics that are only supported on and after 7.9
nodeStatsMetricsAfter7_9 = ",indexing_pressure"
// A comma separated list of metrics that will be gathered from Nodes.
// The available metrics are documented here for Elasticsearch 7.9:
// https://www.elastic.co/guide/en/elasticsearch/reference/7.9/cluster-nodes-info.html
// Note: This constant should remain empty as the receiver will only retrieve metadata from the /_nodes endpoint, not metrics.
nodesMetrics = ""
// A comma separated list of index metrics that will be gathered from NodeStats.
nodeStatsIndexMetrics = "store,docs,indexing,get,search,merge,refresh,flush,warmer,query_cache,fielddata,translog"
// A comma separated list of metrics that will be gathered from IndexStats.
indexStatsMetrics = "_all"
)
func (c defaultElasticsearchClient) Nodes(ctx context.Context, nodeIDs []string) (*model.Nodes, error) {
var nodeSpec string
if len(nodeIDs) > 0 {
nodeSpec = strings.Join(nodeIDs, ",")
} else {
nodeSpec = "_all"
}
nodesPath := fmt.Sprintf("_nodes/%s/%s", nodeSpec, nodesMetrics)
body, err := c.doRequest(ctx, nodesPath)
if err != nil {
return nil, err
}
nodes := model.Nodes{}
err = json.Unmarshal(body, &nodes)
return &nodes, err
}
func (c defaultElasticsearchClient) NodeStats(ctx context.Context, nodes []string) (*model.NodeStats, error) {
var nodeSpec string
if len(nodes) > 0 {
nodeSpec = strings.Join(nodes, ",")
} else {
nodeSpec = "_all"
}
nodeStatsMetrics := defaultNodeStatsMetrics
if c.version != nil && c.version.GreaterThanOrEqual(es7_9) {
nodeStatsMetrics += nodeStatsMetricsAfter7_9
}
nodeStatsPath := fmt.Sprintf("_nodes/%s/stats/%s/%s", nodeSpec, nodeStatsMetrics, nodeStatsIndexMetrics)
body, err := c.doRequest(ctx, nodeStatsPath)
if err != nil {
return nil, err
}
nodeStats := model.NodeStats{}
err = json.Unmarshal(body, &nodeStats)
return &nodeStats, err
}
func (c defaultElasticsearchClient) ClusterHealth(ctx context.Context) (*model.ClusterHealth, error) {
body, err := c.doRequest(ctx, "_cluster/health")
if err != nil {
return nil, err
}
clusterHealth := model.ClusterHealth{}
err = json.Unmarshal(body, &clusterHealth)
return &clusterHealth, err
}
func (c defaultElasticsearchClient) IndexStats(ctx context.Context, indices []string) (*model.IndexStats, error) {
var indexSpec string
if len(indices) > 0 {
indexSpec = strings.Join(indices, ",")
} else {
indexSpec = "_all"
}
indexStatsPath := fmt.Sprintf("%s/_stats/%s", indexSpec, indexStatsMetrics)
body, err := c.doRequest(ctx, indexStatsPath)
if err != nil {
return nil, err
}
indexStats := model.IndexStats{}
err = json.Unmarshal(body, &indexStats)
return &indexStats, err
}
func (c *defaultElasticsearchClient) ClusterMetadata(ctx context.Context) (*model.ClusterMetadataResponse, error) {
body, err := c.doRequest(ctx, "")
if err != nil {
return nil, err
}
versionResponse := model.ClusterMetadataResponse{}
err = json.Unmarshal(body, &versionResponse)
if c.version == nil {
c.version, _ = version.NewVersion(versionResponse.Version.Number)
}
return &versionResponse, err
}
func (c defaultElasticsearchClient) ClusterStats(ctx context.Context, nodes []string) (*model.ClusterStats, error) {
var nodesSpec string
if len(nodes) > 0 {
nodesSpec = strings.Join(nodes, ",")
} else {
nodesSpec = "_all"
}
clusterStatsPath := fmt.Sprintf("_cluster/stats/nodes/%s", nodesSpec)
body, err := c.doRequest(ctx, clusterStatsPath)
if err != nil {
return nil, err
}
clusterStats := model.ClusterStats{}
err = json.Unmarshal(body, &clusterStats)
return &clusterStats, err
}
func (c defaultElasticsearchClient) doRequest(ctx context.Context, path string) ([]byte, error) {
endpoint, err := c.endpoint.Parse(path)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, "GET", endpoint.String(), nil)
if err != nil {
return nil, err
}
if c.authHeader != "" {
req.Header.Add("Authorization", c.authHeader)
}
// See https://www.elastic.co/guide/en/elasticsearch/reference/8.0/api-conventions.html#api-compatibility
// the compatible-with=7 should signal to newer version of Elasticsearch to use the v7.x API format
req.Header.Add("Accept", "application/vnd.elasticsearch+json; compatible-with=7")
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
return io.ReadAll(resp.Body)
}
body, err := io.ReadAll(resp.Body)
c.logger.Debug(
"Failed to make request to Elasticsearch",
zap.String("path", path),
zap.Int("status_code", resp.StatusCode),
zap.ByteString("body", body),
zap.NamedError("body_read_error", err),
)
switch resp.StatusCode {
case 401:
return nil, errUnauthenticated
case 403:
return nil, errUnauthorized
default:
return nil, fmt.Errorf("got non 200 status code %d", resp.StatusCode)
}
}