github.com/lacework-dev/go-moby@v20.10.12+incompatible/pkg/parsers/operatingsystem/operatingsystem_linux.go (about) 1 // Package operatingsystem provides helper function to get the operating system 2 // name for different platforms. 3 package operatingsystem // import "github.com/docker/docker/pkg/parsers/operatingsystem" 4 5 import ( 6 "bufio" 7 "bytes" 8 "fmt" 9 "io/ioutil" 10 "os" 11 "strings" 12 ) 13 14 var ( 15 // file to use to detect if the daemon is running in a container 16 proc1Cgroup = "/proc/1/cgroup" 17 18 // file to check to determine Operating System 19 etcOsRelease = "/etc/os-release" 20 21 // used by stateless systems like Clear Linux 22 altOsRelease = "/usr/lib/os-release" 23 ) 24 25 // GetOperatingSystem gets the name of the current operating system. 26 func GetOperatingSystem() (string, error) { 27 if prettyName, err := getValueFromOsRelease("PRETTY_NAME"); err != nil { 28 return "", err 29 } else if prettyName != "" { 30 return prettyName, nil 31 } 32 33 // If not set, defaults to PRETTY_NAME="Linux" 34 // c.f. http://www.freedesktop.org/software/systemd/man/os-release.html 35 return "Linux", nil 36 } 37 38 // GetOperatingSystemVersion gets the version of the current operating system, as a string. 39 func GetOperatingSystemVersion() (string, error) { 40 return getValueFromOsRelease("VERSION_ID") 41 } 42 43 // parses the os-release file and returns the value associated with `key` 44 func getValueFromOsRelease(key string) (string, error) { 45 osReleaseFile, err := os.Open(etcOsRelease) 46 if err != nil { 47 if !os.IsNotExist(err) { 48 return "", fmt.Errorf("Error opening %s: %v", etcOsRelease, err) 49 } 50 osReleaseFile, err = os.Open(altOsRelease) 51 if err != nil { 52 return "", fmt.Errorf("Error opening %s: %v", altOsRelease, err) 53 } 54 } 55 defer osReleaseFile.Close() 56 57 var value string 58 keyWithTrailingEqual := key + "=" 59 scanner := bufio.NewScanner(osReleaseFile) 60 for scanner.Scan() { 61 line := scanner.Text() 62 if strings.HasPrefix(line, keyWithTrailingEqual) { 63 data := strings.SplitN(line, "=", 2) 64 value = strings.Trim(data[1], `"' `) // remove leading/trailing quotes and whitespace 65 } 66 } 67 68 return value, nil 69 } 70 71 // IsContainerized returns true if we are running inside a container. 72 func IsContainerized() (bool, error) { 73 b, err := ioutil.ReadFile(proc1Cgroup) 74 if err != nil { 75 return false, err 76 } 77 for _, line := range bytes.Split(b, []byte{'\n'}) { 78 if len(line) > 0 && !bytes.HasSuffix(line, []byte(":/")) && !bytes.HasSuffix(line, []byte(":/init.scope")) { 79 return true, nil 80 } 81 } 82 return false, nil 83 }