-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
pod.go
493 lines (423 loc) · 15.2 KB
/
pod.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
481
482
483
484
485
486
487
488
489
490
491
492
493
// 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 !aix
package kubernetes
import (
"fmt"
"sync"
"time"
"github.com/gofrs/uuid"
k8s "k8s.io/client-go/kubernetes"
"github.com/elastic/elastic-agent-autodiscover/bus"
"github.com/elastic/elastic-agent-autodiscover/kubernetes"
"github.com/elastic/elastic-agent-autodiscover/kubernetes/metadata"
"github.com/elastic/elastic-agent-autodiscover/utils"
conf "github.com/elastic/elastic-agent-libs/config"
"github.com/elastic/elastic-agent-libs/logp"
"github.com/elastic/elastic-agent-libs/mapstr"
)
type pod struct {
uuid uuid.UUID
config *Config
metagen metadata.MetaGen
logger *logp.Logger
publishFunc func([]bus.Event)
watcher kubernetes.Watcher
nodeWatcher kubernetes.Watcher
namespaceWatcher kubernetes.Watcher
replicasetWatcher kubernetes.Watcher
jobWatcher kubernetes.Watcher
// Mutex used by configuration updates not triggered by the main watcher,
// to avoid race conditions between cross updates and deletions.
// Other updaters must use a write lock.
crossUpdate sync.RWMutex
}
// NewPodEventer creates an eventer that can discover and process pod objects
func NewPodEventer(uuid uuid.UUID, cfg *conf.C, client k8s.Interface, publish func(event []bus.Event)) (Eventer, error) {
logger := logp.NewLogger("autodiscover.pod")
var replicaSetWatcher, jobWatcher kubernetes.Watcher
config := defaultConfig()
err := cfg.Unpack(&config)
if err != nil {
return nil, err
}
// Ensure that node is set correctly whenever the scope is set to "node". Make sure that node is empty
// when cluster scope is enforced.
if config.Scope == "node" {
nd := &kubernetes.DiscoverKubernetesNodeParams{
ConfigHost: config.Node,
Client: client,
IsInCluster: kubernetes.IsInCluster(config.KubeConfig),
HostUtils: &kubernetes.DefaultDiscoveryUtils{},
}
config.Node, err = kubernetes.DiscoverKubernetesNode(logger, nd)
if err != nil {
return nil, fmt.Errorf("couldn't discover kubernetes node due to error %w", err)
}
} else {
config.Node = ""
}
logger.Debugf("Initializing a new Kubernetes watcher using node: %v", config.Node)
watcher, err := kubernetes.NewNamedWatcher("pod", client, &kubernetes.Pod{}, kubernetes.WatchOptions{
SyncTimeout: config.SyncPeriod,
Node: config.Node,
Namespace: config.Namespace,
HonorReSyncs: true,
}, nil)
if err != nil {
return nil, fmt.Errorf("couldn't create watcher for %T due to error %w", &kubernetes.Pod{}, err)
}
options := kubernetes.WatchOptions{
SyncTimeout: config.SyncPeriod,
Node: config.Node,
Namespace: config.Namespace,
}
metaConf := config.AddResourceMetadata
nodeWatcher, err := kubernetes.NewNamedWatcher("node", client, &kubernetes.Node{}, options, nil)
if err != nil {
logger.Errorf("couldn't create watcher for %T due to error %+v", &kubernetes.Node{}, err)
}
namespaceWatcher, err := kubernetes.NewNamedWatcher("namespace", client, &kubernetes.Namespace{}, kubernetes.WatchOptions{
SyncTimeout: config.SyncPeriod,
}, nil)
if err != nil {
logger.Errorf("couldn't create watcher for %T due to error %+v", &kubernetes.Namespace{}, err)
}
// Resource is Pod so we need to create watchers for Replicasets and Jobs that it might belongs to
// in order to be able to retrieve 2nd layer Owner metadata like in case of:
// Deployment -> Replicaset -> Pod
// CronJob -> job -> Pod
if metaConf.Deployment {
replicaSetWatcher, err = kubernetes.NewNamedWatcher("resource_metadata_enricher_rs", client, &kubernetes.ReplicaSet{}, kubernetes.WatchOptions{
SyncTimeout: config.SyncPeriod,
}, nil)
if err != nil {
logger.Errorf("Error creating watcher for %T due to error %+v", &kubernetes.ReplicaSet{}, err)
}
}
if metaConf.CronJob {
jobWatcher, err = kubernetes.NewNamedWatcher("resource_metadata_enricher_job", client, &kubernetes.Job{}, kubernetes.WatchOptions{
SyncTimeout: config.SyncPeriod,
}, nil)
if err != nil {
logger.Errorf("Error creating watcher for %T due to error %+v", &kubernetes.Job{}, err)
}
}
metaGen := metadata.GetPodMetaGen(cfg, watcher, nodeWatcher, namespaceWatcher, replicaSetWatcher, jobWatcher, metaConf)
p := &pod{
config: config,
uuid: uuid,
publishFunc: publish,
metagen: metaGen,
logger: logger,
watcher: watcher,
nodeWatcher: nodeWatcher,
namespaceWatcher: namespaceWatcher,
replicasetWatcher: replicaSetWatcher,
jobWatcher: jobWatcher,
}
watcher.AddEventHandler(p)
if nodeWatcher != nil && (config.Hints.Enabled() || metaConf.Node.Enabled()) {
updater := kubernetes.NewNodePodUpdater(p.unlockedUpdate, watcher.Store(), &p.crossUpdate)
nodeWatcher.AddEventHandler(updater)
}
if namespaceWatcher != nil && (config.Hints.Enabled() || metaConf.Namespace.Enabled()) {
updater := kubernetes.NewNamespacePodUpdater(p.unlockedUpdate, watcher.Store(), &p.crossUpdate)
namespaceWatcher.AddEventHandler(updater)
}
return p, nil
}
// OnAdd ensures processing of pod objects that are newly added.
func (p *pod) OnAdd(obj interface{}) {
p.crossUpdate.RLock()
defer p.crossUpdate.RUnlock()
p.logger.Debugf("Watcher Pod add: %+v", obj)
p.emit(obj.(*kubernetes.Pod), "start")
}
// OnUpdate handles events for pods that have been updated.
func (p *pod) OnUpdate(obj interface{}) {
p.crossUpdate.RLock()
defer p.crossUpdate.RUnlock()
p.unlockedUpdate(obj)
}
func (p *pod) unlockedUpdate(obj interface{}) {
p.logger.Debugf("Watcher Pod update: %+v", obj)
p.emit(obj.(*kubernetes.Pod), "stop")
p.emit(obj.(*kubernetes.Pod), "start")
}
// OnDelete stops pod objects that are deleted.
func (p *pod) OnDelete(obj interface{}) {
p.crossUpdate.RLock()
defer p.crossUpdate.RUnlock()
p.logger.Debugf("Watcher Pod delete: %+v", obj)
p.emit(obj.(*kubernetes.Pod), "stop")
}
// GenerateHints creates hints needed for hints builder.
func (p *pod) 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 kubeMeta, container mapstr.M
annotations := make(mapstr.M, 0)
rawMeta, ok := event["kubernetes"]
if ok {
kubeMeta = rawMeta.(mapstr.M)
// The builder base config can configure any of the field values of kubernetes if need be.
e["kubernetes"] = kubeMeta
if rawAnn, ok := kubeMeta["annotations"]; ok {
anns, _ := rawAnn.(mapstr.M)
if len(anns) != 0 {
annotations = anns.Clone()
}
}
// Look at all the namespace level default annotations and do a merge with priority going to the pod annotations.
if rawNsAnn, ok := kubeMeta["namespace_annotations"]; ok {
namespaceAnnotations, _ := rawNsAnn.(mapstr.M)
if len(namespaceAnnotations) != 0 {
annotations.DeepUpdateNoOverwrite(namespaceAnnotations)
}
}
}
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 rawCont, ok := kubeMeta["container"]; ok {
container = rawCont.(mapstr.M)
// This would end up adding a runtime entry into the event. This would make sure
// that there is not an attempt to spin up a docker input for a rkt container and when a
// rkt input exists it would be natively supported.
e["container"] = container
}
cname := utils.GetContainerName(container)
// Generate hints based on the cumulative of both namespace and pod annotations.
hints := utils.GenerateHints(annotations, cname, p.config.Prefix)
p.logger.Debugf("Generated hints %+v", hints)
if len(hints) != 0 {
e["hints"] = hints
}
p.logger.Debugf("Generated builder event %+v", e)
return e
}
// Start starts the eventer
func (p *pod) Start() error {
if p.nodeWatcher != nil {
err := p.nodeWatcher.Start()
if err != nil {
return err
}
}
if p.namespaceWatcher != nil {
if err := p.namespaceWatcher.Start(); err != nil {
return err
}
}
if p.replicasetWatcher != nil {
err := p.replicasetWatcher.Start()
if err != nil {
return err
}
}
if p.jobWatcher != nil {
err := p.jobWatcher.Start()
if err != nil {
return err
}
}
return p.watcher.Start()
}
// Stop stops the eventer
func (p *pod) Stop() {
p.watcher.Stop()
if p.namespaceWatcher != nil {
p.namespaceWatcher.Stop()
}
if p.nodeWatcher != nil {
p.nodeWatcher.Stop()
}
if p.replicasetWatcher != nil {
p.replicasetWatcher.Stop()
}
if p.jobWatcher != nil {
p.jobWatcher.Stop()
}
}
// emit emits the events for the given pod according to its state and
// the given flag.
// It emits a pod event if the pod has at least a running container,
// and a container event for each one of the ports defined in each
// container.
// If a container doesn't have any defined port, it emits a single
// container event with "port" set to 0.
// "start" events are only generated for containers that have an id.
// "stop" events are always generated to ensure that configurations are
// deleted.
// If the pod is terminated, "stop" events are delayed during the grace
// period defined in `CleanupTimeout`.
// Network information is only included in events for running containers
// and for pods with at least one running container.
func (p *pod) emit(pod *kubernetes.Pod, flag string) {
annotations := kubernetes.PodAnnotations(pod)
labels := kubernetes.PodLabels(pod)
namespaceAnnotations := kubernetes.PodNamespaceAnnotations(pod, p.namespaceWatcher)
eventList := make([][]bus.Event, 0)
portsMap := mapstr.M{}
containers := kubernetes.GetContainersInPod(pod)
anyContainerRunning := false
for _, c := range containers {
if c.Status.State.Running != nil {
anyContainerRunning = true
}
events, ports := p.containerPodEvents(flag, pod, c, annotations, namespaceAnnotations, labels)
if len(events) != 0 {
eventList = append(eventList, events)
}
if len(ports) > 0 {
portsMap.DeepUpdate(ports)
}
}
if len(eventList) != 0 {
event := p.podEvent(flag, pod, portsMap, anyContainerRunning, annotations, namespaceAnnotations, labels)
// Ensure that the pod level event is published first to avoid
// pod metadata overriding a valid container metadata.
eventList = append([][]bus.Event{{event}}, eventList...)
}
delay := (flag == "stop" && kubernetes.PodTerminated(pod, containers))
p.publishAll(eventList, delay)
}
// containerPodEvents creates the events for a container in a pod
// One event is created for each configured port. If there is no
// configured port, a single event is created, with the port set to 0.
// Host and port information is only included if the container is
// running.
// If the container ID is unknown, only "stop" events are generated.
// It also returns a map with the named ports.
func (p *pod) containerPodEvents(flag string, pod *kubernetes.Pod, c *kubernetes.ContainerInPod, annotations, namespaceAnnotations, labels mapstr.M) ([]bus.Event, mapstr.M) {
if c.ID == "" && flag != "stop" {
return nil, nil
}
// This must be an id that doesn't depend on the state of the container
// so it works also on `stop` if containers have been already deleted.
eventID := fmt.Sprintf("%s.%s", pod.GetObjectMeta().GetUID(), c.Spec.Name)
meta := p.metagen.Generate(pod, metadata.WithFields("container.name", c.Spec.Name))
cmeta := mapstr.M{
"id": c.ID,
"runtime": c.Runtime,
"image": mapstr.M{
"name": c.Spec.Image,
},
}
// Information that can be used in discovering a workload
kubemetaMap, _ := meta.GetValue("kubernetes")
kubemeta, _ := kubemetaMap.(mapstr.M)
kubemeta = kubemeta.Clone()
kubemeta["annotations"] = annotations
kubemeta["labels"] = labels
kubemeta["container"] = mapstr.M{
"id": c.ID,
"name": c.Spec.Name,
"image": c.Spec.Image,
"runtime": c.Runtime,
}
if len(namespaceAnnotations) != 0 {
kubemeta["namespace_annotations"] = namespaceAnnotations
}
ports := c.Spec.Ports
if len(ports) == 0 {
// Ensure that at least one event is generated for this container.
// Set port to zero to signify that the event is from a container
// and not from a pod.
ports = []kubernetes.ContainerPort{{ContainerPort: 0}}
}
var events []bus.Event
portsMap := mapstr.M{}
ShouldPut(meta, "container", cmeta, p.logger)
for _, port := range ports {
event := bus.Event{
"provider": p.uuid,
"id": eventID,
flag: true,
"kubernetes": kubemeta,
// Actual metadata that will enrich the event.
"meta": meta,
}
// Include network information only if the container is running,
// so templates that need network don't generate a config.
if c.Status.State.Running != nil {
if port.Name != "" && port.ContainerPort != 0 {
portsMap[port.Name] = port.ContainerPort
}
event["host"] = pod.Status.PodIP
event["port"] = port.ContainerPort
}
events = append(events, event)
}
return events, portsMap
}
// podEvent creates an event for a pod.
// It only includes network information if `includeNetwork` is true.
func (p *pod) podEvent(flag string, pod *kubernetes.Pod, ports mapstr.M, includeNetwork bool, annotations, namespaceAnnotations, labels mapstr.M) bus.Event {
meta := p.metagen.Generate(pod)
// Information that can be used in discovering a workload
kubemetaMap, _ := meta.GetValue("kubernetes")
kubemeta, _ := kubemetaMap.(mapstr.M)
kubemeta = kubemeta.Clone()
kubemeta["annotations"] = annotations
kubemeta["labels"] = labels
if len(namespaceAnnotations) != 0 {
kubemeta["namespace_annotations"] = namespaceAnnotations
}
// Don't set a port on the event
event := bus.Event{
"provider": p.uuid,
"id": fmt.Sprint(pod.GetObjectMeta().GetUID()),
flag: true,
"kubernetes": kubemeta,
"meta": meta,
}
// Include network information only if the pod has an IP and there is any
// running container that could handle requests.
if pod.Status.PodIP != "" && includeNetwork {
event["host"] = pod.Status.PodIP
if len(ports) > 0 {
event["ports"] = ports
}
}
return event
}
// publishAll publishes all events in the event list in the same order. If delay is true
// publishAll schedules the publication of the events after the configured `CleanupPeriod`
// and returns inmediatelly.
// Order of published events matters, so this function will always publish a given eventList
// in the same goroutine.
func (p *pod) publishAll(eventList [][]bus.Event, delay bool) {
if delay && p.config.CleanupTimeout > 0 {
p.logger.Debug("Publish will wait for the cleanup timeout")
time.AfterFunc(p.config.CleanupTimeout, func() {
p.publishAll(eventList, false)
})
return
}
for _, events := range eventList {
p.publishFunc(events)
}
}