-
Notifications
You must be signed in to change notification settings - Fork 178
/
utils.go
51 lines (40 loc) · 1.1 KB
/
utils.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
package docker
import (
"errors"
"fmt"
"io/ioutil"
"os"
"regexp"
"runtime"
)
// Utils is an interface with docker utilities
type Utils interface {
GetCurrentContainerID() (string, error)
}
type dockerUtils struct{}
// CreateUtils creates a new instance of docker utils
func CreateUtils() Utils {
return &dockerUtils{}
}
// GetCurrentContainerID returns the id of the container running this application
func (wrapper *dockerUtils) GetCurrentContainerID() (string, error) {
if runtime.GOOS == "windows" {
return os.Hostname()
}
bytes, err := ioutil.ReadFile("/proc/self/cgroup")
if err != nil {
return "", err
}
if len(bytes) == 0 {
return "", errors.New("Cannot read /proc/self/cgroup")
}
return wrapper.ExtractContainerID(string(bytes))
}
func (wrapper *dockerUtils) ExtractContainerID(cgroups string) (string, error) {
idRegex := regexp.MustCompile(`(?i):[^:]*\bcpu\b[^:]*:[^/]*/.*([[:alnum:]]{64}).*`)
matches := idRegex.FindStringSubmatch(cgroups)
if len(matches) == 0 {
return "", fmt.Errorf("Cannot find container id in cgroups: %v", cgroups)
}
return matches[len(matches)-1], nil
}