watchtower/pkg/container/cgroup_id.go

30 lines
729 B
Go
Raw Normal View History

2022-09-07 14:59:26 +02:00
package container
import (
"fmt"
"os"
"regexp"
"github.com/containrrr/watchtower/pkg/types"
)
var dockerContainerPattern = regexp.MustCompile(`[0-9]+:.*:/docker/([a-f|0-9]{64})`)
2022-09-17 12:34:02 +02:00
// GetRunningContainerID tries to resolve the current container ID from the current process cgroup information
2022-09-07 14:59:26 +02:00
func GetRunningContainerID() (cid types.ContainerID, err error) {
file, err := os.ReadFile(fmt.Sprintf("/proc/%d/cgroup", os.Getpid()))
if err != nil {
return
}
2022-09-17 12:34:35 +02:00
return getRunningContainerIDFromString(string(file)), nil
}
func getRunningContainerIDFromString(s string) types.ContainerID {
matches := dockerContainerPattern.FindStringSubmatch(s)
2022-09-07 14:59:26 +02:00
if len(matches) < 2 {
2022-09-17 12:34:35 +02:00
return ""
2022-09-07 14:59:26 +02:00
}
2022-09-17 12:34:35 +02:00
return types.ContainerID(matches[1])
2022-09-07 14:59:26 +02:00
}