-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
generic.go
256 lines (211 loc) · 6.9 KB
/
generic.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
// 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 remote implements a generic workloadmeta Collector that receives
// events from a remote workloadmeta server.
package remote
import (
"context"
"crypto/tls"
"fmt"
"io"
"net"
"time"
"github.com/cenkalti/backoff"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"github.com/DataDog/datadog-agent/comp/core/workloadmeta"
"github.com/DataDog/datadog-agent/comp/core/workloadmeta/telemetry"
"github.com/DataDog/datadog-agent/pkg/api/security"
pkgconfig "github.com/DataDog/datadog-agent/pkg/config"
grpcutil "github.com/DataDog/datadog-agent/pkg/util/grpc"
"github.com/DataDog/datadog-agent/pkg/util/log"
)
const (
noTimeout = 0 * time.Minute
streamRecvTimeout = 10 * time.Minute
)
var errWorkloadmetaStreamNotStarted = errors.New("workloadmeta stream not started")
// GrpcClient interface that represents a gRPC client for the remote workloadmeta.
type GrpcClient interface {
// StreamEntites establishes the stream between the client and the remote gRPC server.
StreamEntities(ctx context.Context, opts ...grpc.CallOption) (Stream, error)
}
// Stream is an interface that represents a gRPC stream.
type Stream interface {
// Recv returns a response of the gRPC server
Recv() (interface{}, error)
}
// StreamHandler is an interface that defines a gRPC stream handler.
type StreamHandler interface {
// Port returns the targeted port
Port() int
// IsEnabled returns if the feature is enabled
IsEnabled() bool
// NewClient returns a client to connect to a remote gRPC server.
NewClient(cc grpc.ClientConnInterface) GrpcClient
// HandleResponse handles a response from the remote gRPC server.
HandleResponse(response interface{}) ([]workloadmeta.CollectorEvent, error)
// HandleResync is called on resynchronization.
HandleResync(store workloadmeta.Component, events []workloadmeta.CollectorEvent)
}
// GenericCollector is a generic remote workloadmeta collector with resync mechanisms.
type GenericCollector struct {
CollectorID string
Catalog workloadmeta.AgentType
StreamHandler StreamHandler
store workloadmeta.Component
resyncNeeded bool
client GrpcClient
stream Stream
streamCtx context.Context
streamCancel context.CancelFunc
ctx context.Context
cancel context.CancelFunc
Insecure bool // for testing
}
// Start starts the generic collector
func (c *GenericCollector) Start(ctx context.Context, store workloadmeta.Component) error {
if !c.StreamHandler.IsEnabled() {
return fmt.Errorf("collector %s is not enabled", c.CollectorID)
}
c.store = store
c.ctx, c.cancel = context.WithCancel(ctx)
opts := []grpc.DialOption{grpc.WithContextDialer(func(ctx context.Context, url string) (net.Conn, error) {
return net.Dial("tcp", url)
})}
if c.Insecure {
// for test purposes
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
} else {
// NOTE: we're using InsecureSkipVerify because the gRPC server only
// persists its TLS certs in memory, and we currently have no
// infrastructure to make them available to clients. This is NOT
// equivalent to grpc.WithInsecure(), since that assumes a non-TLS
// connection.
creds := credentials.NewTLS(&tls.Config{
InsecureSkipVerify: true,
})
opts = append(opts, grpc.WithTransportCredentials(creds))
}
conn, err := grpc.DialContext(
c.ctx,
fmt.Sprintf(":%v", c.StreamHandler.Port()),
opts...,
)
if err != nil {
return err
}
c.client = c.StreamHandler.NewClient(conn)
log.Info("remote workloadmeta initialized successfully")
go c.Run()
return nil
}
// Pull does nothing in workloadmeta collectors.
func (c *GenericCollector) Pull(context.Context) error {
return nil
}
func (c *GenericCollector) startWorkloadmetaStream(maxElapsed time.Duration) error {
expBackoff := backoff.NewExponentialBackOff()
expBackoff.InitialInterval = 500 * time.Millisecond
expBackoff.MaxInterval = 5 * time.Minute
expBackoff.MaxElapsedTime = maxElapsed
return backoff.Retry(func() error {
select {
case <-c.ctx.Done():
return &backoff.PermanentError{Err: errWorkloadmetaStreamNotStarted}
default:
}
token, err := security.FetchAuthToken(pkgconfig.Datadog)
if err != nil {
err = fmt.Errorf("unable to fetch authentication token: %w", err)
log.Warnf("unable to establish entity stream between agents, will possibly retry: %s", err)
return err
}
c.streamCtx, c.streamCancel = context.WithCancel(
metadata.NewOutgoingContext(
c.ctx,
metadata.MD{
"authorization": []string{
fmt.Sprintf("Bearer %s", token),
},
},
),
)
c.stream, err = c.client.StreamEntities(c.streamCtx)
if err != nil {
log.Infof("unable to establish stream, will possibly retry: %s", err)
return err
}
log.Info("workloadmeta stream established successfully")
return nil
}, expBackoff)
}
// Run will run the generic collector streaming loop
func (c *GenericCollector) Run() {
recvWithoutTimeout := pkgconfig.Datadog.GetBool("workloadmeta.remote.recv_without_timeout")
for {
select {
case <-c.ctx.Done():
return
default:
}
if c.stream == nil {
if err := c.startWorkloadmetaStream(noTimeout); err != nil {
log.Warnf("error received trying to start stream: %s", err)
continue
}
}
var (
response interface{}
err error
)
if recvWithoutTimeout {
response, err = c.stream.Recv()
} else {
err = grpcutil.DoWithTimeout(func() error {
var err error
response, err = c.stream.Recv()
return err
}, streamRecvTimeout)
}
if err != nil {
// at the end of stream, but its OK
if errors.Is(err, io.EOF) {
continue
}
c.streamCancel()
telemetry.RemoteClientErrors.Inc(c.CollectorID)
// when Recv() returns an error, the stream is aborted and the
// contents of our store are considered out of sync. The stream must
// be re-established. No events are notified to the store until the
// connection is re-established.
c.stream = nil
c.resyncNeeded = true
log.Warnf("error received from remote workloadmeta: %s", err)
continue
}
collectorEvents, err := c.StreamHandler.HandleResponse(response)
if err != nil {
log.Warnf("error processing event received from remote workloadmeta: %s", err)
continue
}
if c.resyncNeeded {
c.StreamHandler.HandleResync(c.store, collectorEvents)
c.resyncNeeded = false
}
c.store.Notify(collectorEvents)
}
}
// GetID gets the identifier for the generic collector
func (c *GenericCollector) GetID() string {
return c.CollectorID
}
// GetTargetCatalog gets the catalog this collector should target
func (c *GenericCollector) GetTargetCatalog() workloadmeta.AgentType {
return c.Catalog
}