forked from lucaslorentz/caddy-docker-proxy
/
utils.go
74 lines (65 loc) · 1.91 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package docker
import (
"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) {
var containerID string
var err error
if runtime.GOOS == "linux" {
if containerID == "" && err == nil {
containerID, err = wrapper.getCurrentContainerIDFromCGroup()
}
if containerID == "" && err == nil {
containerID, err = wrapper.getCurrentContainerIDFromMountInfo()
}
}
if containerID == "" && err == nil {
containerID, err = os.Hostname()
}
return containerID, err
}
func (wrapper *dockerUtils) getCurrentContainerIDFromMountInfo() (string, error) {
bytes, err := ioutil.ReadFile("/proc/self/mountinfo")
if err != nil {
return "", err
}
containerID := wrapper.extractContainerIDFromMountInfo(string(bytes))
return containerID, nil
}
func (wrapper *dockerUtils) getCurrentContainerIDFromCGroup() (string, error) {
bytes, err := ioutil.ReadFile("/proc/self/cgroup")
if err != nil {
return "", err
}
containerID := wrapper.extractContainerIDFromCGroups(string(bytes))
return containerID, nil
}
func (wrapper *dockerUtils) extractContainerIDFromMountInfo(cgroups string) string {
idRegex := regexp.MustCompile(`containers/([[:alnum:]]{64})/`)
matches := idRegex.FindStringSubmatch(cgroups)
if len(matches) == 0 {
return ""
}
return matches[len(matches)-1]
}
func (wrapper *dockerUtils) extractContainerIDFromCGroups(cgroups string) string {
idRegex := regexp.MustCompile(`(?im)^[^:]*:[^:]*:.*\b([[:alnum:]]{64})\b`)
matches := idRegex.FindStringSubmatch(cgroups)
if len(matches) == 0 {
return ""
}
return matches[len(matches)-1]
}