container_id.go 1008 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package docker
  2. import (
  3. "bufio"
  4. "os"
  5. "regexp"
  6. "strings"
  7. )
  8. // GetContainerID retrieves the Docker container ID by parsing /proc/self/mountinfo
  9. func GetContainerID() (string, error) {
  10. // Open the mountinfo file
  11. file, err := os.Open("/proc/self/mountinfo")
  12. if err != nil {
  13. return "", err
  14. }
  15. defer file.Close()
  16. // Regular expression to extract container ID from paths like:
  17. // /var/lib/docker/containers/bd4bd482f7e28566389fe7e4ce6b168e93b372c3fc18091c37923588664ca950/resolv.conf
  18. containerIDPattern := regexp.MustCompile(`/var/lib/docker/containers/([a-f0-9]{64})/`)
  19. // Scan the file line by line
  20. scanner := bufio.NewScanner(file)
  21. for scanner.Scan() {
  22. line := scanner.Text()
  23. // Look for container ID in the line
  24. if strings.Contains(line, "/var/lib/docker/containers/") {
  25. matches := containerIDPattern.FindStringSubmatch(line)
  26. if len(matches) >= 2 {
  27. return matches[1], nil
  28. }
  29. }
  30. }
  31. if err := scanner.Err(); err != nil {
  32. return "", err
  33. }
  34. return "", os.ErrNotExist
  35. }