|
@@ -4,47 +4,61 @@ import (
|
|
|
"bufio"
|
|
|
"bytes"
|
|
|
"errors"
|
|
|
+ "io"
|
|
|
"os"
|
|
|
+ "regexp"
|
|
|
)
|
|
|
|
|
|
var (
|
|
|
- _dockerId string
|
|
|
- dockerFeature = []byte("docker/")
|
|
|
+ _containerdId string
|
|
|
+
|
|
|
+ nameFeature = []byte("1:name")
|
|
|
|
|
|
errNotMatch = errors.New("not match")
|
|
|
+
|
|
|
+ containerdIDMatcher = regexp.MustCompile(`^[0-9a-zA-Z]+$`)
|
|
|
)
|
|
|
|
|
|
-func SelfContainerID() (did string, err error) {
|
|
|
- if _dockerId != "" {
|
|
|
- return _dockerId, nil
|
|
|
- }
|
|
|
+const (
|
|
|
+ ContainerdIDLength = 64
|
|
|
+)
|
|
|
+
|
|
|
+func parseContainerID(r io.Reader) (id string, err error) {
|
|
|
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)
|
|
|
+ br := bufio.NewReader(r)
|
|
|
for {
|
|
|
if p, _, err = br.ReadLine(); err != nil {
|
|
|
break
|
|
|
}
|
|
|
- if pos = bytes.Index(p, dockerFeature); pos == -1 {
|
|
|
+ if !bytes.HasPrefix(p, nameFeature) {
|
|
|
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
|
|
|
+ if len(p) > ContainerdIDLength {
|
|
|
+ pos = len(p) - ContainerdIDLength
|
|
|
+ if containerdIDMatcher.Match(p[pos:]) {
|
|
|
+ return string(p[pos:]), nil
|
|
|
+ }
|
|
|
}
|
|
|
}
|
|
|
return "", errNotMatch
|
|
|
}
|
|
|
+
|
|
|
+func SelfContainerID() (did string, err error) {
|
|
|
+ if _containerdId != "" {
|
|
|
+ return _containerdId, nil
|
|
|
+ }
|
|
|
+ var (
|
|
|
+ fp *os.File
|
|
|
+ )
|
|
|
+ if fp, err = os.Open("/proc/self/cgroup"); err != nil {
|
|
|
+ return
|
|
|
+ }
|
|
|
+ defer func() {
|
|
|
+ _ = fp.Close()
|
|
|
+ }()
|
|
|
+ _containerdId, err = parseContainerID(fp)
|
|
|
+ return _containerdId, err
|
|
|
+}
|