|
@@ -1,22 +1,50 @@
|
|
|
package docker
|
|
|
|
|
|
import (
|
|
|
+ "bufio"
|
|
|
"bytes"
|
|
|
- "os/exec"
|
|
|
+ "errors"
|
|
|
+ "os"
|
|
|
)
|
|
|
|
|
|
var (
|
|
|
- _dockerId string
|
|
|
+ _dockerId string
|
|
|
+ dockerFeature = []byte("docker/")
|
|
|
+
|
|
|
+ errNotMatch = errors.New("not match")
|
|
|
)
|
|
|
|
|
|
-func SelfContainerID() (string, error) {
|
|
|
+func SelfContainerID() (did string, err error) {
|
|
|
if _dockerId != "" {
|
|
|
return _dockerId, nil
|
|
|
}
|
|
|
- if buf, err := exec.Command("/bin/sh", "-c", "cat /proc/self/cgroup | grep -o -e \"docker/.*\"| head -n 1 |sed \"s/docker\\/\\(.*\\)/\\\\1/\"").CombinedOutput(); err != nil {
|
|
|
- return "", err
|
|
|
- } else {
|
|
|
- _dockerId = string(bytes.TrimSpace(buf))
|
|
|
- return _dockerId, nil
|
|
|
+ var (
|
|
|
+ pos int
|
|
|
+ p []byte
|
|
|
+ fp *os.File
|
|
|
+ )
|
|
|
+ if fp, err = os.Open("/proc/self/cgroup"); err != nil {
|
|
|
+ return
|
|
|
+ }
|
|
|
+ defer func() {
|
|
|
+ _ = fp.Close()
|
|
|
+ }()
|
|
|
+ br := bufio.NewReader(fp)
|
|
|
+ for {
|
|
|
+ if p, _, err = br.ReadLine(); err != nil {
|
|
|
+ break
|
|
|
+ }
|
|
|
+ if pos = bytes.Index(p, dockerFeature); pos == -1 {
|
|
|
+ continue
|
|
|
+ }
|
|
|
+ p = bytes.TrimSpace(p[pos+len(dockerFeature):])
|
|
|
+ if pos = bytes.LastIndexByte(p, '/'); pos == -1 {
|
|
|
+ _dockerId = string(p)
|
|
|
+ return _dockerId, nil
|
|
|
+ } else {
|
|
|
+ _dockerId = string(p[pos+1:])
|
|
|
+ return _dockerId, nil
|
|
|
+ }
|
|
|
}
|
|
|
+ return "", errNotMatch
|
|
|
}
|