diff --git a/context.go b/context.go index 80a6bd7d..71e126b5 100644 --- a/context.go +++ b/context.go @@ -5,7 +5,7 @@ import ( "os" "regexp" "sync" - + "fmt" "github.com/fsouza/go-dockerclient" ) @@ -159,24 +159,25 @@ type Docker struct { } func GetCurrentContainerID() string { - file, err := os.Open("/proc/self/cgroup") - - if err != nil { - return "" - } + filepaths := []string{"/proc/self/cgroup", "/proc/self/mountinfo"} - reader := bufio.NewReader(file) - scanner := bufio.NewScanner(reader) - scanner.Split(bufio.ScanLines) - - for scanner.Scan() { - _, lines, err := bufio.ScanLines([]byte(scanner.Text()), true) - if err == nil { - strLines := string(lines) - if id := matchDockerCurrentContainerID(strLines); id != "" { - return id - } else if id := matchECSCurrentContainerID(strLines); id != "" { - return id + for _, filepath := range filepaths { + file, err := os.Open(filepath) + if err != nil { + continue + } + reader := bufio.NewReader(file) + scanner := bufio.NewScanner(reader) + scanner.Split(bufio.ScanLines) + for scanner.Scan() { + _, lines, err := bufio.ScanLines([]byte(scanner.Text()), true) + if err == nil { + strLines := string(lines) + if id := matchDockerCurrentContainerID(strLines); id != "" { + return id + } else if id := matchECSCurrentContainerID(strLines); id != "" { + return id + } } } } @@ -185,7 +186,8 @@ func GetCurrentContainerID() string { } func matchDockerCurrentContainerID(lines string) string { - regex := "/docker[/-]([[:alnum:]]{64})(\\.scope)?$" + hostname := os.Getenv("HOSTNAME") + regex := fmt.Sprintf("(%s[[:alnum:]]{52})", hostname) re := regexp.MustCompilePOSIX(regex) if re.MatchString(lines) {