Skip to content

Commit c696358

Browse files
Rename CurrentContainer{Name => ID} and rework GetCurrentContainerID function
1 parent dc155e1 commit c696358

File tree

2 files changed

+29
-21
lines changed

2 files changed

+29
-21
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,7 @@ type Docker struct {
280280
GoVersion string
281281
OperatingSystem string
282282
Architecture string
283-
CurrentContainerName string
283+
CurrentContainerID string
284284
}
285285

286286
// Host environment variables accessible from root in templates as .Env

context.go

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
package dockergen
22

33
import (
4-
"io/ioutil"
4+
"bufio"
5+
"log"
56
"os"
67
"regexp"
7-
"strings"
88
"sync"
99

1010
"github.com/fsouza/go-dockerclient"
@@ -40,8 +40,7 @@ func SetServerInfo(d *docker.Env) {
4040
GoVersion: dockerEnv.Get("GoVersion"),
4141
OperatingSystem: dockerEnv.Get("Os"),
4242
Architecture: dockerEnv.Get("Arch"),
43-
CurrentContainerName: GetCurrentContainerName(),
44-
43+
CurrentContainerID: GetCurrentContainerID(),
4544
}
4645
}
4746

@@ -152,27 +151,36 @@ type Docker struct {
152151
GoVersion string
153152
OperatingSystem string
154153
Architecture string
155-
CurrentContainerName string
154+
CurrentContainerID string
156155
}
157156

158-
func GetCurrentContainerName() string {
159-
contents, err := ioutil.ReadFile("/proc/self/cgroup")
160-
if err != nil {
161-
println("No /proc/self/cgroup file. Fail to detect current container ID")
157+
func GetCurrentContainerID() string {
158+
file, err := os.Open("/proc/self/cgroup")
159+
160+
if os.IsNotExist(err) {
161+
return ""
162+
} else if err != nil {
163+
log.Printf("Fail to open /proc/self/cgroup: %s\n", err)
162164
return ""
163165
}
164-
165-
lines := strings.Split(string(contents), "\n")
166-
re := regexp.MustCompilePOSIX("^1")
167-
168-
for _, line := range lines {
169-
if re.MatchString(line) == true {
170-
splited := strings.SplitN(line, "/docker-", 2)
171-
splited = strings.SplitN(splited[len(splited) - 1], ".scope", 2)
172-
173-
return splited[0]
166+
167+
reader := bufio.NewReader(file)
168+
scanner := bufio.NewScanner(reader)
169+
scanner.Split(bufio.ScanLines)
170+
171+
172+
for scanner.Scan() {
173+
_, lines, err := bufio.ScanLines([]byte(scanner.Text()), true)
174+
if err == nil {
175+
re := regexp.MustCompilePOSIX("/docker-([[:alnum:]]{64}).scope$")
176+
if re.MatchString(string(lines)) {
177+
submatches := re.FindStringSubmatch(string(lines))
178+
containerID := submatches[1]
179+
180+
return containerID
181+
}
174182
}
175-
}
183+
}
176184

177185
return ""
178186
}

0 commit comments

Comments
 (0)