-
Notifications
You must be signed in to change notification settings - Fork 4
/
container_linux.go
108 lines (91 loc) · 2.08 KB
/
container_linux.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
//go:build linux
// +build linux
package system
import (
"bufio"
"os"
"strings"
)
// Inspiration taken from https://github.com/elastic/apm/blob/main/specs/agents/metadata.md#containerkubernetes-metadata
// and https://github.com/elastic/apm-agent-go/blob/main/internal/apmhostutil/container_linux.go
func detectContainer() (*Container, error) {
f, err := os.Open("/proc/self/cgroup")
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
defer f.Close()
s := bufio.NewScanner(f)
for s.Scan() {
p := strings.SplitN(s.Text(), ":", 3)
if len(p) != 3 {
continue
}
path := p[2]
idx := strings.LastIndex(path, ":")
if idx == -1 {
if idx = strings.LastIndex(path, "/"); idx == -1 {
continue
}
}
dirname, basename := path[:idx], path[idx+1:]
if strings.HasSuffix(basename, ".scope") {
basename = basename[:len(basename)-6]
if hyp := strings.Index(basename, "-"); hyp != -1 {
basename = basename[hyp+1:]
}
}
if match := podUIDRegex.FindStringSubmatch(dirname); match != nil {
hostname, _ := os.Hostname()
uid := match[1]
if uid == "" {
uid = strings.ReplaceAll(match[2], "_", "-")
}
return &Container{
ID: basename,
Kubernetes: &Kubernetes{
PodUID: uid,
PodName: hostname,
Namespace: os.Getenv("KUBERNETES_NAMESPACE"),
NodeName: os.Getenv("KUBERNETES_NODE_NAME"),
},
}, nil
} else if containerIDRegex.MatchString(basename) {
return &Container{
ID: basename,
}, nil
}
}
return nil, nil
}
func detectContainerV2() (*Container, error) {
f, err := os.Open("/proc/self/mountinfo")
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
defer f.Close()
s := bufio.NewScanner(f)
for s.Scan() {
p := strings.Split(s.Text(), " ")
if len(p) < 4 {
continue
}
i := strings.Index(p[3], "/docker/containers/")
if i == -1 {
continue
}
id, _, _ := strings.Cut(p[3][i+len("/docker/containers/"):], "/")
if !containerIDRegex.MatchString(id) {
continue
}
return &Container{
ID: id,
}, nil
}
return nil, nil
}