-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
clusteragent.go
480 lines (409 loc) · 15.9 KB
/
clusteragent.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
package clusteragent
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"google.golang.org/protobuf/proto"
"github.com/DataDog/datadog-agent/pkg/api/security"
apiv1 "github.com/DataDog/datadog-agent/pkg/clusteragent/api/v1"
"github.com/DataDog/datadog-agent/pkg/clusteragent/clusterchecks/types"
"github.com/DataDog/datadog-agent/pkg/config"
"github.com/DataDog/datadog-agent/pkg/errors"
pbgo "github.com/DataDog/datadog-agent/pkg/proto/pbgo/process"
"github.com/DataDog/datadog-agent/pkg/util/log"
"github.com/DataDog/datadog-agent/pkg/util/retry"
"github.com/DataDog/datadog-agent/pkg/version"
)
/*
Client to query the Datadog Cluster Agent (DCA) API.
*/
const (
authorizationHeaderKey = "Authorization"
// RealIPHeader refers to the cluster level check runner ip passed in the request headers
RealIPHeader = "X-Real-Ip"
languageDetectionPath = "api/v1/languagedetection"
)
var globalClusterAgentClient *DCAClient
type metadataNames []string
// DCAClientInterface is required to query the API of Datadog cluster agent
type DCAClientInterface interface {
Version() version.Version
ClusterAgentAPIEndpoint() string
GetVersion() (version.Version, error)
GetNodeLabels(nodeName string) (map[string]string, error)
GetNodeAnnotations(nodeName string) (map[string]string, error)
GetNamespaceLabels(nsName string) (map[string]string, error)
GetPodsMetadataForNode(nodeName string) (apiv1.NamespacesPodsStringsSet, error)
GetKubernetesMetadataNames(nodeName, ns, podName string) ([]string, error)
GetCFAppsMetadataForNode(nodename string) (map[string][]string, error)
PostClusterCheckStatus(ctx context.Context, nodeName string, status types.NodeStatus) (types.StatusResponse, error)
GetClusterCheckConfigs(ctx context.Context, nodeName string) (types.ConfigResponse, error)
GetEndpointsCheckConfigs(ctx context.Context, nodeName string) (types.ConfigResponse, error)
GetKubernetesClusterID() (string, error)
PostLanguageMetadata(ctx context.Context, data *pbgo.ParentLanguageAnnotationRequest) error
}
// DCAClient is required to query the API of Datadog cluster agent
type DCAClient struct {
// used to setup the DCAClient
initRetry retry.Retrier
clusterAgentAPIEndpoint string // ${SCHEME}://${clusterAgentHost}:${PORT}
clusterAgentAPIRequestHeaders http.Header
clusterAgentClientLock sync.RWMutex
clusterAgentVersion version.Version // Version of the cluster-agent we're connected to
clusterAgentAPIClient *http.Client
leaderClient *leaderClient
}
// resetGlobalClusterAgentClient is a helper to remove the current DCAClient global
// It is ONLY to be used for tests
func resetGlobalClusterAgentClient() {
globalClusterAgentClient = nil
}
// GetClusterAgentClient returns or init the DCAClient
func GetClusterAgentClient() (DCAClientInterface, error) {
if globalClusterAgentClient == nil {
globalClusterAgentClient = &DCAClient{}
globalClusterAgentClient.initRetry.SetupRetrier(&retry.Config{ //nolint:errcheck
Name: "clusterAgentClient",
AttemptMethod: globalClusterAgentClient.init,
Strategy: retry.Backoff,
InitialRetryDelay: 1 * time.Second,
MaxRetryDelay: 5 * time.Minute,
})
}
if err := globalClusterAgentClient.initRetry.TriggerRetry(); err != nil {
log.Debugf("Cluster Agent init error: %v", err)
return nil, err
}
return globalClusterAgentClient, nil
}
func (c *DCAClient) init() error {
var err error
c.clusterAgentAPIEndpoint, err = GetClusterAgentEndpoint()
if err != nil {
return err
}
authToken, err := security.GetClusterAgentAuthToken(config.Datadog)
if err != nil {
return err
}
c.clusterAgentAPIRequestHeaders = http.Header{}
c.clusterAgentAPIRequestHeaders.Set(authorizationHeaderKey, fmt.Sprintf("Bearer %s", authToken))
podIP := config.Datadog.GetString("clc_runner_host")
c.clusterAgentAPIRequestHeaders.Set(RealIPHeader, podIP)
if err := c.initHTTPClient(); err != nil {
return err
}
// Run DCA connection refresh
c.startReconnectHandler(time.Duration(config.Datadog.GetInt64("cluster_agent.client_reconnect_period_seconds")) * time.Second)
log.Infof("Successfully connected to the Datadog Cluster Agent %s", c.clusterAgentVersion.String())
return nil
}
func (c *DCAClient) startReconnectHandler(reconnectPeriod time.Duration) {
if reconnectPeriod <= 0 {
return
}
t := time.NewTicker(reconnectPeriod)
go func() {
for {
<-t.C
err := c.initHTTPClient()
if err != nil {
log.Infof("Failed to re-create HTTP Connection, err: %v", err)
}
}
}()
}
func (c *DCAClient) initHTTPClient() error {
var err error
// Copy of http.DefaulTransport with adapted settings
clusterAgentAPIClient := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 1 * time.Second,
KeepAlive: 20 * time.Second,
}).DialContext,
ForceAttemptHTTP2: false,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
TLSHandshakeTimeout: 5 * time.Second,
MaxConnsPerHost: 1,
MaxIdleConnsPerHost: 1,
IdleConnTimeout: 60 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
ResponseHeaderTimeout: 3 * time.Second,
},
Timeout: 10 * time.Second,
}
// We need to have a client to perform `GetVersion`, only happens during the first call
if c.clusterAgentAPIClient == nil {
c.clusterAgentAPIClient = clusterAgentAPIClient
}
// Validate the cluster-agent client by checking the version
clusterAgentVersion, err := c.GetVersion()
if err != nil {
return err
}
c.clusterAgentClientLock.Lock()
defer c.clusterAgentClientLock.Unlock()
c.clusterAgentAPIClient = clusterAgentAPIClient
c.clusterAgentVersion = clusterAgentVersion
// Before DCA 1.21, we cannot rely on DCA follower forwarding, creating a leaderClient in this case
// TODO: Remove when we drop compatibility
if c.clusterAgentVersion.Major == 1 && c.clusterAgentVersion.Minor < 21 {
log.Warnf("You're using an older Cluster Agent version. Newer Agent versions work best with Cluster Agent >= 1.21")
c.initLeaderClient()
}
return nil
}
func (c *DCAClient) initLeaderClient() {
c.leaderClient = newLeaderClient(c.clusterAgentAPIClient, c.clusterAgentAPIEndpoint)
}
// GetClusterAgentEndpoint provides a validated https endpoint from configuration keys in datadog.yaml:
// 1st. configuration key "cluster_agent.url" (or the DD_CLUSTER_AGENT_URL environment variable),
//
// add the https prefix if the scheme isn't specified
//
// 2nd. environment variables associated with "cluster_agent.kubernetes_service_name"
//
// ${dcaServiceName}_SERVICE_HOST and ${dcaServiceName}_SERVICE_PORT
func GetClusterAgentEndpoint() (string, error) {
const configDcaURL = "cluster_agent.url"
const configDcaSvcName = "cluster_agent.kubernetes_service_name"
dcaURL := config.Datadog.GetString(configDcaURL)
if dcaURL != "" {
if strings.HasPrefix(dcaURL, "http://") {
return "", fmt.Errorf("cannot get cluster agent endpoint, not a https scheme: %s", dcaURL)
}
if !strings.Contains(dcaURL, "://") {
log.Tracef("Adding https scheme to %s: https://%s", dcaURL, dcaURL)
dcaURL = fmt.Sprintf("https://%s", dcaURL)
}
u, err := url.Parse(dcaURL)
if err != nil {
return "", err
}
if u.Scheme != "https" {
return "", fmt.Errorf("cannot get cluster agent endpoint, not a https scheme: %s", u.Scheme)
}
log.Debugf("Connecting to the configured URL for the Datadog Cluster Agent: %s", dcaURL)
return u.String(), nil
}
// Construct the URL with the Kubernetes service environment variables
// *_SERVICE_HOST and *_SERVICE_PORT
dcaSvc := config.Datadog.GetString(configDcaSvcName)
log.Debugf("Identified service for the Datadog Cluster Agent: %s", dcaSvc)
if dcaSvc == "" {
return "", fmt.Errorf("cannot get a cluster agent endpoint, both %s and %s are empty", configDcaURL, configDcaSvcName)
}
dcaSvc = strings.ToUpper(dcaSvc)
dcaSvc = strings.Replace(dcaSvc, "-", "_", -1) // Kubernetes replaces "-" with "_" in the service names injected in the env var.
// host
dcaSvcHostEnv := fmt.Sprintf("%s_SERVICE_HOST", dcaSvc)
dcaSvcHost := os.Getenv(dcaSvcHostEnv)
if dcaSvcHost == "" {
return "", fmt.Errorf("cannot get a cluster agent endpoint for kubernetes service %s, env %s is empty", dcaSvc, dcaSvcHostEnv)
}
// port
dcaSvcPort := os.Getenv(fmt.Sprintf("%s_SERVICE_PORT", dcaSvc))
if dcaSvcPort == "" {
return "", fmt.Errorf("cannot get a cluster agent endpoint for kubernetes service %s, env %s is empty", dcaSvc, dcaSvcPort)
}
// validate the URL
dcaURL = fmt.Sprintf("https://%s:%s", dcaSvcHost, dcaSvcPort)
u, err := url.Parse(dcaURL)
if err != nil {
return "", err
}
return u.String(), nil
}
// Version returns ClusterAgentVersion already stored in the DCAClient
func (c *DCAClient) Version() version.Version {
c.clusterAgentClientLock.RLock()
defer c.clusterAgentClientLock.RUnlock()
return c.clusterAgentVersion
}
// ClusterAgentAPIEndpoint returns the Agent API Endpoint URL as a string
func (c *DCAClient) ClusterAgentAPIEndpoint() string {
return c.clusterAgentAPIEndpoint
}
// TODO: remove when we drop compatibility with older Agents, see end of `init()`
func (c *DCAClient) buildURL(useLeaderClient bool, path string) string {
if useLeaderClient && c.leaderClient != nil {
return c.leaderClient.buildURL(path)
}
return c.clusterAgentAPIEndpoint + "/" + path
}
// TODO: remove when we drop compatibility with older Agents, see end of `init()`
func (c *DCAClient) httpClient(useLeaderClient bool) *http.Client {
c.clusterAgentClientLock.RLock()
defer c.clusterAgentClientLock.RUnlock()
if useLeaderClient && c.leaderClient != nil {
return &c.leaderClient.Client
}
return c.clusterAgentAPIClient
}
// TODO: remove the client parameter when we drop compatibility with older Agents, see end of `init()`
func (c *DCAClient) doQuery(ctx context.Context, path, method string, body io.Reader, readResponseBody, useLeaderClient bool) ([]byte, error) {
url := c.buildURL(useLeaderClient, path)
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, fmt.Errorf("unable to build request during query to: %s, err: %w", url, err)
}
req.Header = c.clusterAgentAPIRequestHeaders
client := c.httpClient(useLeaderClient)
resp, err := client.Do(req)
if err != nil {
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
err = errors.NewTimeoutError(url, err)
}
return nil, errors.NewRemoteServiceError(url, err.Error())
}
defer resp.Body.Close()
if readResponseBody && resp.StatusCode == http.StatusOK {
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.NewRemoteServiceError(url, err.Error())
}
return respBody, nil
}
// Make sure we read always body, required to re-use HTTP Connections
_, _ = io.Copy(io.Discard, resp.Body)
if resp.StatusCode != http.StatusOK {
return nil, errors.NewRemoteServiceError(url, resp.Status)
}
return nil, nil
}
func (c *DCAClient) doJSONQuery(ctx context.Context, path, method string, body io.Reader, obj interface{}, useLeaderClient bool) error {
respBody, err := c.doQuery(ctx, path, method, body, true, useLeaderClient)
if err != nil {
return err
}
err = json.Unmarshal(respBody, obj)
if err != nil {
return fmt.Errorf("failed to unmarshal JSON from URL: %s, err: %w, raw message: %q", path, err, respBody)
}
return nil
}
// TODO: remove when we drop compatibility with older Agents, see end of `init()`
func (c *DCAClient) doJSONQueryToLeader(ctx context.Context, path, method string, body io.Reader, obj interface{}) error {
if c.leaderClient == nil {
return c.doJSONQuery(ctx, path, method, body, obj, false)
}
willRetry := c.leaderClient.hasLeader()
err := c.doJSONQuery(ctx, path, method, body, obj, true)
if err != nil && willRetry {
log.Debugf("Got error on leader, retrying via the service: %v", err)
c.leaderClient.resetURL()
err = c.doJSONQuery(ctx, path, method, body, obj, true)
}
return err
}
// GetVersion fetches the version of the Cluster Agent. Used in the agent status command.
func (c *DCAClient) GetVersion() (version.Version, error) {
var version version.Version
err := c.doJSONQuery(context.TODO(), "version", "GET", nil, &version, false)
return version, err
}
// GetNodeLabels returns the node labels from the Cluster Agent.
func (c *DCAClient) GetNodeLabels(nodeName string) (map[string]string, error) {
var result map[string]string
err := c.doJSONQuery(context.TODO(), "api/v1/tags/node/"+nodeName, "GET", nil, &result, false)
return result, err
}
// GetNamespaceLabels returns the namespace labels from the Cluster Agent.
func (c *DCAClient) GetNamespaceLabels(nsName string) (map[string]string, error) {
var result map[string]string
err := c.doJSONQuery(context.TODO(), "api/v1/tags/namespace/"+nsName, "GET", nil, &result, false)
return result, err
}
// GetNodeAnnotations returns the node annotations from the Cluster Agent.
func (c *DCAClient) GetNodeAnnotations(nodeName string) (map[string]string, error) {
var result map[string]string
err := c.doJSONQuery(context.TODO(), "api/v1/annotations/node/"+nodeName, "GET", nil, &result, false)
return result, err
}
// GetCFAppsMetadataForNode returns the CF application tags from the Cluster Agent.
func (c *DCAClient) GetCFAppsMetadataForNode(nodename string) (map[string][]string, error) {
var result map[string][]string
err := c.doJSONQuery(context.TODO(), "api/v1/tags/cf/apps/"+nodename, "GET", nil, &result, false)
return result, err
}
// GetPodsMetadataForNode queries the datadog cluster agent to get nodeName registered
// Kubernetes pods metadata.
func (c *DCAClient) GetPodsMetadataForNode(nodeName string) (apiv1.NamespacesPodsStringsSet, error) {
/* https://host:port/api/v1/tags/pod/{nodeName}
response example:
{
"Nodes": {
"node1": {
"services": {
"default": {
"datadog-monitoring-cluster-agent-58f45b9b44-pkxrv": {
"datadog-monitoring-cluster-agent": {},
"datadog-monitoring-cluster-agent-metrics-api": {}
}
},
"kube-system": {
"kube-dns-6b98c9c9bf-ts7gc": {
"kube-dns": {}
}
}
}
}
}
}
*/
metadataPodPayload := apiv1.NewMetadataResponse()
err := c.doJSONQuery(context.TODO(), "api/v1/tags/pod/"+nodeName, "GET", nil, metadataPodPayload, false)
if err != nil {
return nil, err
}
if _, ok := metadataPodPayload.Nodes[nodeName]; !ok {
return nil, fmt.Errorf("cluster agent didn't return pods metadata for node: %s", nodeName)
}
return metadataPodPayload.Nodes[nodeName].Services, nil
}
// GetKubernetesMetadataNames queries the datadog cluster agent to get nodeName/podName registered
// Kubernetes metadata.
func (c *DCAClient) GetKubernetesMetadataNames(nodeName, ns, podName string) ([]string, error) {
var metadataNames metadataNames
err := c.doJSONQuery(context.TODO(), fmt.Sprintf("api/v1/tags/pod/%s/%s/%s", nodeName, ns, podName), "GET", nil, &metadataNames, false)
if err != nil {
return nil, err
}
return metadataNames, nil
}
// GetKubernetesClusterID queries the datadog cluster agent to get the Kubernetes cluster ID
// Prefer calling clustername.GetClusterID which has a cached response
func (c *DCAClient) GetKubernetesClusterID() (string, error) {
var clusterID string
err := c.doJSONQuery(context.TODO(), "api/v1/cluster/id", "GET", nil, &clusterID, false)
if err != nil {
return "", err
}
return clusterID, nil
}
// PostLanguageMetadata is called by the core-agent's language detection client
func (c *DCAClient) PostLanguageMetadata(ctx context.Context, data *pbgo.ParentLanguageAnnotationRequest) error {
queryBody, err := proto.Marshal(data)
if err != nil {
return err
}
// query https://host:port/api/v1/languagedetection without expecting a response
_, err = c.doQuery(ctx, languageDetectionPath, "POST", bytes.NewBuffer(queryBody), false, false)
return err
}