forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 9
/
helper.go
62 lines (51 loc) · 1.31 KB
/
helper.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
package docker
import (
"strings"
"github.com/elastic/beats/libbeat/common"
"github.com/fsouza/go-dockerclient"
)
type Container struct {
ID string
Name string
Labels common.MapStr
}
func (c *Container) ToMapStr() common.MapStr {
m := common.MapStr{
"id": c.ID,
"name": c.Name,
}
if len(c.Labels) > 0 {
m["labels"] = c.Labels
}
return m
}
func NewContainer(container *docker.APIContainers) *Container {
return &Container{
ID: container.ID,
Name: ExtractContainerName(container.Names),
Labels: DeDotLabels(container.Labels),
}
}
func ExtractContainerName(names []string) string {
output := names[0]
if len(names) > 1 {
for _, name := range names {
if strings.Count(output, "/") > strings.Count(name, "/") {
output = name
}
}
}
return strings.Trim(output, "/")
}
// DeDotLabels returns a new common.MapStr containing a copy of the labels
// where the dots in each label name have been changed to an underscore.
func DeDotLabels(labels map[string]string) common.MapStr {
outputLabels := common.MapStr{}
for k, v := range labels {
// This is necessary so that ES does not interpret '.' fields as new
// nested JSON objects, and also makes this compatible with ES 2.x.
label := strings.Replace(k, ".", "_", -1)
outputLabels.Put(label, v)
}
return outputLabels
}