forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
metadata.go
93 lines (76 loc) · 2.21 KB
/
metadata.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
package kubernetes
import "github.com/elastic/beats/libbeat/common"
// MetaGenerator builds metadata objects for pods and containers
type MetaGenerator interface {
// PodMetadata generates metadata for the given pod taking to account certain filters
PodMetadata(pod *Pod) common.MapStr
// Containermetadata generates metadata for the given container of a pod
ContainerMetadata(pod *Pod, container string) common.MapStr
}
type metaGenerator struct {
annotations []string
labels []string
labelsExclude []string
}
// NewMetaGenerator initializes and returns a new kubernetes metadata generator
func NewMetaGenerator(annotations, labels, labelsExclude []string) MetaGenerator {
return &metaGenerator{
annotations: annotations,
labels: labels,
labelsExclude: labelsExclude,
}
}
// PodMetadata generates metadata for the given pod taking to account certain filters
func (g *metaGenerator) PodMetadata(pod *Pod) common.MapStr {
labelMap := common.MapStr{}
if len(g.labels) == 0 {
for k, v := range pod.Metadata.Labels {
labelMap[k] = v
}
} else {
labelMap = generateMapSubset(pod.Metadata.Labels, g.labels)
}
// Exclude any labels that are present in the exclude_labels config
for _, label := range g.labelsExclude {
delete(labelMap, label)
}
annotationsMap := generateMapSubset(pod.Metadata.Annotations, g.annotations)
meta := common.MapStr{
"pod": common.MapStr{
"name": pod.Metadata.Name,
},
"node": common.MapStr{
"name": pod.Spec.NodeName,
},
"namespace": pod.Metadata.Namespace,
}
if len(labelMap) != 0 {
meta["labels"] = labelMap
}
if len(annotationsMap) != 0 {
meta["annotations"] = annotationsMap
}
return meta
}
// Containermetadata generates metadata for the given container of a pod
func (g *metaGenerator) ContainerMetadata(pod *Pod, container string) common.MapStr {
podMeta := g.PodMetadata(pod)
// Add container details
podMeta["container"] = common.MapStr{
"name": container,
}
return podMeta
}
func generateMapSubset(input map[string]string, keys []string) common.MapStr {
output := common.MapStr{}
if input == nil {
return output
}
for _, key := range keys {
value, ok := input[key]
if ok {
output[key] = value
}
}
return output
}