forked from open-telemetry/opentelemetry-collector-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
203 lines (167 loc) · 6.11 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
// Copyright The OpenTelemetry Authors
//
// 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
//
// https://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 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"
"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 {
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)
}
// 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
}
var _ elasticsearchClient = (*defaultElasticsearchClient)(nil)
func newElasticsearchClient(settings component.TelemetrySettings, c Config, h component.Host) (*defaultElasticsearchClient, error) {
client, err := c.HTTPClientSettings.ToClient(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, c.Password)
authb64 := base64.StdEncoding.EncodeToString([]byte(userPass))
authHeader = fmt.Sprintf("Basic %s", authb64)
}
return &defaultElasticsearchClient{
client: client,
authHeader: authHeader,
endpoint: endpoint,
logger: settings.Logger,
}, nil
}
// nodeStatsMetrics is a comma separated list of metrics that will be gathered from NodeStats.
// The available metrics are documented here for Elasticsearch 7.9:
// https://www.elastic.co/guide/en/elasticsearch/reference/7.9/cluster-nodes-stats.html#cluster-nodes-stats-api-path-params
const nodeStatsMetrics = "breaker,indices,process,jvm,thread_pool,transport,http,fs,indexing_pressure,ingest,indices,adaptive_selection,discovery,script,os"
// nodeStatsIndexMetrics is a comma separated list of index metrics that will be gathered from NodeStats.
const nodeStatsIndexMetrics = "store,docs,indexing,get,search,merge,refresh,flush,warmer,query_cache,fielddata,translog"
const indexStatsMetrics = "search"
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"
}
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)
return &versionResponse, 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)
}
}