id.go 1014 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package docker
  2. import (
  3. "bufio"
  4. "bytes"
  5. "errors"
  6. "io"
  7. "os"
  8. "regexp"
  9. )
  10. var (
  11. _containerdId string
  12. nameFeature = []byte("1:name")
  13. errNotMatch = errors.New("not match")
  14. containerdIDMatcher = regexp.MustCompile(`^[0-9a-zA-Z]+$`)
  15. )
  16. const (
  17. ContainerdIDLength = 64
  18. )
  19. func parseContainerID(r io.Reader) (id string, err error) {
  20. var (
  21. pos int
  22. p []byte
  23. )
  24. br := bufio.NewReader(r)
  25. for {
  26. if p, _, err = br.ReadLine(); err != nil {
  27. break
  28. }
  29. if !bytes.HasPrefix(p, nameFeature) {
  30. continue
  31. }
  32. if len(p) > ContainerdIDLength {
  33. pos = len(p) - ContainerdIDLength
  34. if containerdIDMatcher.Match(p[pos:]) {
  35. return string(p[pos:]), nil
  36. }
  37. }
  38. }
  39. return "", errNotMatch
  40. }
  41. func SelfContainerID() (did string, err error) {
  42. if _containerdId != "" {
  43. return _containerdId, nil
  44. }
  45. var (
  46. fp *os.File
  47. )
  48. if fp, err = os.Open("/proc/self/cgroup"); err != nil {
  49. return
  50. }
  51. defer func() {
  52. _ = fp.Close()
  53. }()
  54. _containerdId, err = parseContainerID(fp)
  55. return _containerdId, err
  56. }