-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcontainer.go
47 lines (39 loc) · 992 Bytes
/
container.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
package container
import (
"bufio"
"errors"
"io"
"os"
"strings"
)
const (
dockerPrefix = "/docker/"
kubepodsPrefix = "/kubepods/"
)
// ErrNotInContainerEnv is returned when the GetID function is
// called in a non container environment
var ErrNotInContainerEnv = errors.New("not in a container environment")
func getContainerIDFromReader(f io.Reader) (string, error) {
s := bufio.NewScanner(f)
for s.Scan() {
if err := s.Err(); err != nil {
return "", err
}
group := strings.SplitN(s.Text(), ":", 3)[2]
if strings.HasPrefix(group, dockerPrefix) {
return group[len(dockerPrefix):], nil
} else if strings.HasPrefix(group, kubepodsPrefix) {
return group[len(kubepodsPrefix):], nil
}
}
return "", ErrNotInContainerEnv
}
// GetID returns the container ID when in a containerized environment.
func GetID() (string, error) {
f, err := os.Open("/proc/self/cgroup")
if err != nil {
return "", err
}
defer f.Close()
return getContainerIDFromReader(f)
}