github.com/getong/docker@v1.13.1/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
     4  
     5  import (
     6  	"bufio"
     7  	"bytes"
     8  	"fmt"
     9  	"io/ioutil"
    10  	"os"
    11  	"strings"
    12  
    13  	"github.com/mattn/go-shellwords"
    14  )
    15  
    16  var (
    17  	// file to use to detect if the daemon is running in a container
    18  	proc1Cgroup = "/proc/1/cgroup"
    19  
    20  	// file to check to determine Operating System
    21  	etcOsRelease = "/etc/os-release"
    22  
    23  	// used by stateless systems like Clear Linux
    24  	altOsRelease = "/usr/lib/os-release"
    25  )
    26  
    27  // GetOperatingSystem gets the name of the current operating system.
    28  func GetOperatingSystem() (string, error) {
    29  	osReleaseFile, err := os.Open(etcOsRelease)
    30  	if err != nil {
    31  		if !os.IsNotExist(err) {
    32  			return "", fmt.Errorf("Error opening %s: %v", etcOsRelease, err)
    33  		}
    34  		osReleaseFile, err = os.Open(altOsRelease)
    35  		if err != nil {
    36  			return "", fmt.Errorf("Error opening %s: %v", altOsRelease, err)
    37  		}
    38  	}
    39  	defer osReleaseFile.Close()
    40  
    41  	var prettyName string
    42  	scanner := bufio.NewScanner(osReleaseFile)
    43  	for scanner.Scan() {
    44  		line := scanner.Text()
    45  		if strings.HasPrefix(line, "PRETTY_NAME=") {
    46  			data := strings.SplitN(line, "=", 2)
    47  			prettyNames, err := shellwords.Parse(data[1])
    48  			if err != nil {
    49  				return "", fmt.Errorf("PRETTY_NAME is invalid: %s", err.Error())
    50  			}
    51  			if len(prettyNames) != 1 {
    52  				return "", fmt.Errorf("PRETTY_NAME needs to be enclosed by quotes if they have spaces: %s", data[1])
    53  			}
    54  			prettyName = prettyNames[0]
    55  		}
    56  	}
    57  	if prettyName != "" {
    58  		return prettyName, nil
    59  	}
    60  	// If not set, defaults to PRETTY_NAME="Linux"
    61  	// c.f. http://www.freedesktop.org/software/systemd/man/os-release.html
    62  	return "Linux", nil
    63  }
    64  
    65  // IsContainerized returns true if we are running inside a container.
    66  func IsContainerized() (bool, error) {
    67  	b, err := ioutil.ReadFile(proc1Cgroup)
    68  	if err != nil {
    69  		return false, err
    70  	}
    71  	for _, line := range bytes.Split(b, []byte{'\n'}) {
    72  		if len(line) > 0 && !bytes.HasSuffix(line, []byte{'/'}) && !bytes.HasSuffix(line, []byte("init.scope")) {
    73  			return true, nil
    74  		}
    75  	}
    76  	return false, nil
    77  }