-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
client.go
306 lines (273 loc) · 7.3 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
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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package kubelet // import "github.com/open-telemetry/opentelemetry-collector-contrib/internal/kubelet"
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"go.uber.org/zap"
"k8s.io/client-go/rest"
"k8s.io/client-go/transport"
"github.com/open-telemetry/opentelemetry-collector-contrib/internal/common/sanitize"
"github.com/open-telemetry/opentelemetry-collector-contrib/internal/k8sconfig"
)
const (
svcAcctCACertPath = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"
svcAcctTokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token" // #nosec
defaultSecurePort = "10250"
defaultReadOnlyPort = "10255"
)
type Client interface {
Get(path string) ([]byte, error)
}
func NewClientProvider(endpoint string, cfg *ClientConfig, logger *zap.Logger) (ClientProvider, error) {
switch cfg.APIConfig.AuthType {
case k8sconfig.AuthTypeTLS:
return &tlsClientProvider{
endpoint: endpoint,
cfg: cfg,
logger: logger,
}, nil
case k8sconfig.AuthTypeServiceAccount:
return &saClientProvider{
endpoint: endpoint,
caCertPath: svcAcctCACertPath,
tokenPath: svcAcctTokenPath,
insecureSkipVerify: cfg.InsecureSkipVerify,
logger: logger,
}, nil
case k8sconfig.AuthTypeNone:
return &readOnlyClientProvider{
endpoint: endpoint,
logger: logger,
}, nil
case k8sconfig.AuthTypeKubeConfig:
return &kubeConfigClientProvider{
endpoint: endpoint,
cfg: cfg,
logger: logger,
}, nil
default:
return nil, fmt.Errorf("AuthType [%s] not supported", cfg.APIConfig.AuthType)
}
}
type ClientProvider interface {
BuildClient() (Client, error)
}
type kubeConfigClientProvider struct {
endpoint string
cfg *ClientConfig
logger *zap.Logger
}
func (p *kubeConfigClientProvider) BuildClient() (Client, error) {
authConf, err := k8sconfig.CreateRestConfig(p.cfg.APIConfig)
if err != nil {
return nil, err
}
if p.cfg.InsecureSkipVerify {
// Override InsecureSkipVerify from kubeconfig
authConf.TLSClientConfig.CAFile = ""
authConf.TLSClientConfig.CAData = nil
authConf.TLSClientConfig.Insecure = true
}
client, err := rest.HTTPClientFor(authConf)
if err != nil {
return nil, err
}
joinPath, err := url.JoinPath(authConf.Host, "/api/v1/nodes/", p.endpoint, "/proxy/")
if err != nil {
return nil, err
}
return &clientImpl{
baseURL: joinPath,
httpClient: *client,
tok: nil,
logger: p.logger,
}, nil
}
type readOnlyClientProvider struct {
endpoint string
logger *zap.Logger
}
func (p *readOnlyClientProvider) BuildClient() (Client, error) {
tr := defaultTransport()
endpoint, err := buildEndpoint(p.endpoint, false, p.logger)
if err != nil {
return nil, err
}
return &clientImpl{
baseURL: endpoint,
httpClient: http.Client{Transport: tr},
tok: nil,
logger: p.logger,
}, nil
}
type tlsClientProvider struct {
endpoint string
cfg *ClientConfig
logger *zap.Logger
}
func (p *tlsClientProvider) BuildClient() (Client, error) {
rootCAs, err := systemCertPoolPlusPath(p.cfg.CAFile)
if err != nil {
return nil, err
}
clientCert, err := tls.LoadX509KeyPair(p.cfg.CertFile, p.cfg.KeyFile)
if err != nil {
return nil, err
}
return defaultTLSClient(
p.endpoint,
p.cfg.InsecureSkipVerify,
rootCAs,
[]tls.Certificate{clientCert},
nil,
p.logger,
)
}
type saClientProvider struct {
endpoint string
caCertPath string
tokenPath string
insecureSkipVerify bool
logger *zap.Logger
}
func (p *saClientProvider) BuildClient() (Client, error) {
rootCAs, err := systemCertPoolPlusPath(p.caCertPath)
if err != nil {
return nil, err
}
tok, err := os.ReadFile(p.tokenPath)
if err != nil {
return nil, fmt.Errorf("unable to read token file %s: %w", p.tokenPath, err)
}
tr := defaultTransport()
tr.TLSClientConfig = &tls.Config{
RootCAs: rootCAs,
InsecureSkipVerify: p.insecureSkipVerify,
}
endpoint, err := buildEndpoint(p.endpoint, true, p.logger)
if err != nil {
return nil, err
}
rt, err := transport.NewBearerAuthWithRefreshRoundTripper(string(tok), p.tokenPath, tr)
if err != nil {
return nil, err
}
return &clientImpl{
baseURL: endpoint,
httpClient: http.Client{
Transport: rt,
},
tok: nil,
logger: p.logger,
}, nil
}
func defaultTLSClient(
endpoint string,
insecureSkipVerify bool,
rootCAs *x509.CertPool,
certificates []tls.Certificate,
tok []byte,
logger *zap.Logger,
) (*clientImpl, error) {
tr := defaultTransport()
tr.TLSClientConfig = &tls.Config{
RootCAs: rootCAs,
Certificates: certificates,
InsecureSkipVerify: insecureSkipVerify,
}
endpoint, err := buildEndpoint(endpoint, true, logger)
if err != nil {
return nil, err
}
return &clientImpl{
baseURL: endpoint,
httpClient: http.Client{Transport: tr},
tok: tok,
logger: logger,
}, nil
}
// buildEndpoint builds a kubelet endpoint based on value provided by user and whether secure or read-only endpoint
// should be used.
func buildEndpoint(endpoint string, useSecurePort bool, logger *zap.Logger) (string, error) {
if endpoint == "" {
// This will work if hostNetwork is turned on, in which case the pod has access
// to the node's loopback device.
// https://kubernetes.io/docs/concepts/policy/pod-security-policy/#host-namespaces
host, err := os.Hostname()
if err != nil {
return "", fmt.Errorf("unable to get hostname for default endpoint: %w", err)
}
if useSecurePort {
endpoint = fmt.Sprintf("https://%s:%s", host, defaultSecurePort)
} else {
endpoint = fmt.Sprintf("http://%s:%s", host, defaultReadOnlyPort)
}
logger.Warn("Kubelet endpoint not defined, using default endpoint " + endpoint)
return endpoint, nil
}
if !strings.HasPrefix(endpoint, "http://") && !strings.HasPrefix(endpoint, "https://") {
if useSecurePort {
return "https://" + endpoint, nil
}
return "http://" + endpoint, nil
}
return endpoint, nil
}
func defaultTransport() *http.Transport {
return http.DefaultTransport.(*http.Transport).Clone()
}
// clientImpl
var _ Client = (*clientImpl)(nil)
type clientImpl struct {
baseURL string
httpClient http.Client
logger *zap.Logger
tok []byte
}
func (c *clientImpl) Get(path string) ([]byte, error) {
req, err := c.buildReq(path)
if err != nil {
return nil, err
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer func() {
closeErr := resp.Body.Close()
if closeErr != nil {
c.logger.Warn("failed to close response body", zap.Error(closeErr))
}
}()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read Kubelet response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("kubelet request GET %s failed - %q, response: %q",
sanitize.URL(req.URL), resp.Status, string(body))
}
return body, nil
}
func (c *clientImpl) buildReq(p string) (*http.Request, error) {
reqURL, err := url.JoinPath(c.baseURL, p)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodGet, reqURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
if c.tok != nil {
req.Header.Set("Authorization", fmt.Sprintf("bearer %s", c.tok))
}
return req, nil
}