fix(docker): get container id by /proc/self/mountinfo

This commit is contained in:
Jacky 2025-05-03 08:51:03 +00:00
parent 1396cbf096
commit 7b642eb12c
No known key found for this signature in database
GPG key ID: 215C21B10DF38B4D
21 changed files with 1208 additions and 1046 deletions

View file

@ -0,0 +1,42 @@
package docker
import (
"bufio"
"os"
"regexp"
"strings"
)
// GetContainerID retrieves the Docker container ID by parsing /proc/self/mountinfo
func GetContainerID() (string, error) {
// Open the mountinfo file
file, err := os.Open("/proc/self/mountinfo")
if err != nil {
return "", err
}
defer file.Close()
// Regular expression to extract container ID from paths like:
// /var/lib/docker/containers/bd4bd482f7e28566389fe7e4ce6b168e93b372c3fc18091c37923588664ca950/resolv.conf
containerIDPattern := regexp.MustCompile(`/var/lib/docker/containers/([a-f0-9]{64})/`)
// Scan the file line by line
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
// Look for container ID in the line
if strings.Contains(line, "/var/lib/docker/containers/") {
matches := containerIDPattern.FindStringSubmatch(line)
if len(matches) >= 2 {
return matches[1], nil
}
}
}
if err := scanner.Err(); err != nil {
return "", err
}
return "", os.ErrNotExist
}

View file

@ -12,7 +12,7 @@ var (
ErrContainerStatusUnknown = e.New(500006, "container status unknown")
ErrInspectContainer = e.New(500007, "failed to inspect container: {0}")
ErrNginxNotRunningInAnotherContainer = e.New(500008, "nginx is not running in another container")
ErrFailedToGetHostname = e.New(500009, "failed to get hostname: {0}")
ErrFailedToGetContainerID = e.New(500009, "failed to get container id: {0}")
ErrFailedToPullImage = e.New(500010, "failed to pull image: {0}")
ErrFailedToInspectCurrentContainer = e.New(500011, "failed to inspect current container: {0}")
ErrFailedToCreateTempContainer = e.New(500012, "failed to create temp container: {0}")

View file

@ -143,11 +143,11 @@ func UpgradeStepOne(channel string, progressChan chan<- float64) (err error) {
tempContainerName := getTimestampedTempName()
// Get current container name
hostname, err := os.Hostname()
containerID, err := GetContainerID()
if err != nil {
return cosy.WrapErrorWithParams(ErrFailedToGetHostname, err.Error())
return cosy.WrapErrorWithParams(ErrFailedToGetContainerID, err.Error())
}
containerInfo, err := cli.ContainerInspect(ctx, hostname)
containerInfo, err := cli.ContainerInspect(ctx, containerID)
if err != nil {
return cosy.WrapErrorWithParams(ErrFailedToInspectCurrentContainer, err.Error())
}