-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
docker.go
400 lines (348 loc) · 9.96 KB
/
docker.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
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you 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
//
// http://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.
//go:build linux || darwin || windows
// +build linux darwin windows
package docker
import (
"errors"
"fmt"
"strconv"
"time"
"github.com/gofrs/uuid"
"github.com/elastic/beats/v7/libbeat/autodiscover"
"github.com/elastic/beats/v7/libbeat/autodiscover/template"
"github.com/elastic/beats/v7/libbeat/common"
"github.com/elastic/elastic-agent-autodiscover/bus"
"github.com/elastic/elastic-agent-autodiscover/docker"
"github.com/elastic/elastic-agent-autodiscover/utils"
"github.com/elastic/elastic-agent-libs/config"
"github.com/elastic/elastic-agent-libs/keystore"
"github.com/elastic/elastic-agent-libs/logp"
"github.com/elastic/elastic-agent-libs/mapstr"
"github.com/elastic/elastic-agent-libs/safemapstr"
)
func init() {
_ = autodiscover.Registry.AddProvider("docker", AutodiscoverBuilder)
}
// Provider implements autodiscover provider for docker containers
type Provider struct {
config *Config
bus bus.Bus
uuid uuid.UUID
builders autodiscover.Builders
appenders autodiscover.Appenders
watcher docker.Watcher
templates template.Mapper
stop chan interface{}
startListener bus.Listener
stopListener bus.Listener
stoppers map[string]*time.Timer
stopTrigger chan *dockerContainerMetadata
logger *logp.Logger
}
// AutodiscoverBuilder builds and returns an autodiscover provider
func AutodiscoverBuilder(
beatName string,
bus bus.Bus,
uuid uuid.UUID,
c *config.C,
keystore keystore.Keystore,
) (autodiscover.Provider, error) {
logger := logp.NewLogger("docker")
errWrap := func(err error) error {
return fmt.Errorf("error setting up docker autodiscover provider: %w", err)
}
config := defaultConfig()
err := c.Unpack(&config)
if err != nil {
return nil, errWrap(err)
}
watcher, err := docker.NewWatcher(logger, config.Host, config.TLS, false)
if err != nil {
return nil, errWrap(err)
}
mapper, err := template.NewConfigMapper(config.Templates, keystore, nil)
if err != nil {
return nil, errWrap(err)
}
if len(mapper.ConditionMaps) == 0 && !config.Hints.Enabled() {
return nil, errWrap(fmt.Errorf("no configs or hints defined for autodiscover provider"))
}
builders, err := autodiscover.NewBuilders(config.Builders, config.Hints, nil)
if err != nil {
return nil, errWrap(err)
}
appenders, err := autodiscover.NewAppenders(config.Appenders)
if err != nil {
return nil, errWrap(err)
}
start := watcher.ListenStart()
stop := watcher.ListenStop()
if err := watcher.Start(); err != nil {
return nil, errWrap(err)
}
return &Provider{
config: config,
bus: bus,
uuid: uuid,
builders: builders,
appenders: appenders,
templates: mapper,
watcher: watcher,
stop: make(chan interface{}),
startListener: start,
stopListener: stop,
stoppers: make(map[string]*time.Timer),
stopTrigger: make(chan *dockerContainerMetadata),
logger: logger,
}, nil
}
// Start the autodiscover process
func (d *Provider) Start() {
go func() {
for {
select {
case <-d.stop:
d.startListener.Stop()
d.stopListener.Stop()
// Stop all timers before closing the channel
for _, stopper := range d.stoppers {
stopper.Stop()
}
close(d.stopTrigger)
return
case event := <-d.startListener.Events():
d.startContainer(event)
case event := <-d.stopListener.Events():
d.scheduleStopContainer(event)
case target := <-d.stopTrigger:
d.stopContainer(target.container, target.metadata)
}
}
}()
}
type dockerContainerMetadata struct {
container *docker.Container
metadata *dockerMetadata
}
type dockerMetadata struct {
// Old selectors [Deprecated]
Docker mapstr.M
// New ECS-based selectors
Container mapstr.M
// Metadata used to enrich events, like ECS-based selectors but can
// have modifications like dedotting
Metadata mapstr.M
}
func (d *Provider) generateMetaDocker(event bus.Event) (*docker.Container, *dockerMetadata) {
container, ok := event["container"].(*docker.Container)
if !ok {
d.logger.Error(errors.New("couldn't get a container from watcher event"))
return nil, nil
}
// Don't dedot selectors, dedot only metadata used for events enrichment
labelMap := mapstr.M{}
metaLabelMap := mapstr.M{}
for k, v := range container.Labels {
err := safemapstr.Put(labelMap, k, v)
if err != nil {
d.logger.Debugf("error adding k:v (%v:%v): %v", k, v, err)
}
if d.config.Dedot {
label := common.DeDot(k)
_, err := metaLabelMap.Put(label, v)
if err != nil {
d.logger.Debugf("error adding value (%v): %v", v, err)
}
} else {
err := safemapstr.Put(metaLabelMap, k, v)
if err != nil {
d.logger.Debugf("error adding k:v (%v:%v): %v", k, v, err)
}
}
}
meta := &dockerMetadata{
Docker: mapstr.M{
"container": mapstr.M{
"id": container.ID,
"name": container.Name,
"image": container.Image,
"labels": labelMap,
},
},
Container: mapstr.M{
"id": container.ID,
"name": container.Name,
"image": mapstr.M{
"name": container.Image,
},
"labels": labelMap,
},
Metadata: mapstr.M{
"container": mapstr.M{
"id": container.ID,
"name": container.Name,
"image": mapstr.M{
"name": container.Image,
},
},
"docker": mapstr.M{
"container": mapstr.M{
"labels": metaLabelMap,
},
},
},
}
return container, meta
}
func (d *Provider) startContainer(event bus.Event) {
container, meta := d.generateMetaDocker(event)
if container == nil || meta == nil {
return
}
if stopper, ok := d.stoppers[container.ID]; ok {
d.logger.Debugf("Container %s is restarting, aborting pending stop", container.ID)
stopper.Stop()
delete(d.stoppers, container.ID)
return
}
d.emitContainer(container, meta, "start")
}
func (d *Provider) scheduleStopContainer(event bus.Event) {
container, meta := d.generateMetaDocker(event)
if container == nil || meta == nil {
return
}
if d.config.CleanupTimeout <= 0 {
d.stopContainer(container, meta)
return
}
stopper := time.AfterFunc(d.config.CleanupTimeout, func() {
d.stopTrigger <- &dockerContainerMetadata{
container: container,
metadata: meta,
}
})
d.stoppers[container.ID] = stopper
}
func (d *Provider) stopContainer(container *docker.Container, meta *dockerMetadata) {
delete(d.stoppers, container.ID)
d.emitContainer(container, meta, "stop")
}
func (d *Provider) emitContainer(container *docker.Container, meta *dockerMetadata, flag string) {
var host string
var ports mapstr.M
if len(container.IPAddresses) > 0 {
host = container.IPAddresses[0]
}
events := make([]bus.Event, 0)
// Without this check there would be overlapping configurations with and without ports.
if len(container.Ports) == 0 {
event := bus.Event{
"provider": d.uuid,
"id": container.ID,
flag: true,
"host": host,
"docker": meta.Docker,
"container": meta.Container,
"meta": meta.Metadata,
}
events = append(events, event)
} else {
ports = mapstr.M{}
for _, port := range container.Ports {
ports[strconv.FormatUint(uint64(port.PrivatePort), 10)] = port.PublicPort
}
}
// Emit container container and port information
for _, port := range container.Ports {
event := bus.Event{
"provider": d.uuid,
"id": container.ID,
flag: true,
"host": host,
"port": port.PrivatePort,
"ports": ports,
"docker": meta.Docker,
"container": meta.Container,
"meta": meta.Metadata,
}
events = append(events, event)
}
d.publish(events)
}
func (d *Provider) publish(events []bus.Event) {
if len(events) == 0 {
return
}
configs := make([]*config.C, 0)
for _, event := range events {
// Try to match a config
if config := d.templates.GetConfig(event); config != nil {
configs = append(configs, config...)
} else {
// If there isn't a default template then attempt to use builders
e := d.generateHints(event)
if config := d.builders.GetConfig(e); config != nil {
configs = append(configs, config...)
}
}
}
// Since all the events belong to the same event ID pick on and add in all the configs
event := bus.Event(mapstr.M(events[0]).Clone())
// Remove the port to avoid ambiguity during debugging
delete(event, "port")
delete(event, "ports")
event["config"] = configs
// Call all appenders to append any extra configuration
d.appenders.Append(event)
d.bus.Publish(event)
}
func (d *Provider) generateHints(event bus.Event) bus.Event {
// Try to build a config with enabled builders. Send a provider agnostic payload.
// Builders are Beat specific.
e := bus.Event{}
var dockerMeta mapstr.M
var ok bool
if rawDocker, err := mapstr.M(event).GetValue("docker.container"); err == nil {
dockerMeta, ok = rawDocker.(mapstr.M)
if ok {
e["container"] = dockerMeta
}
}
if host, ok := event["host"]; ok {
e["host"] = host
}
if port, ok := event["port"]; ok {
e["port"] = port
}
if ports, ok := event["ports"]; ok {
e["ports"] = ports
}
if labels, err := dockerMeta.GetValue("labels"); err == nil {
hints := utils.GenerateHints(labels.(mapstr.M), "", d.config.Prefix)
e["hints"] = hints
}
return e
}
// Stop the autodiscover process
func (d *Provider) Stop() {
close(d.stop)
}
func (d *Provider) String() string {
return "docker"
}