11package dockergen
22
33import (
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