Merge pull request #2428 from dims/drop-dependency-on-operatingsytem-package-in-docker/docker

Drop dependency on operatingsytem package in docker/docker
This commit is contained in:
David Ashpole 2020-03-16 09:37:43 -07:00 committed by GitHub
commit 133da87ea0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 110 additions and 480 deletions

View File

@ -21,7 +21,6 @@ import (
"path/filepath"
"strings"
"github.com/docker/docker/pkg/parsers/operatingsystem"
"github.com/google/cadvisor/fs"
info "github.com/google/cadvisor/info/v1"
"github.com/google/cadvisor/utils/cloudinfo"
@ -145,7 +144,7 @@ func Info(sysFs sysfs.SysFs, fsInfo fs.FsInfo, inHostNamespace bool) (*info.Mach
}
func ContainerOsVersion() string {
os, err := operatingsystem.GetOperatingSystem()
os, err := getOperatingSystem()
if err != nil {
os = "Unknown"
}

View File

@ -0,0 +1,55 @@
// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build freebsd darwin linux
package machine
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"regexp"
"runtime"
"strings"
)
var rex = regexp.MustCompile("(PRETTY_NAME)=(.*)")
// getOperatingSystem gets the name of the current operating system.
func getOperatingSystem() (string, error) {
if runtime.GOOS == "darwin" || runtime.GOOS == "freebsd" {
cmd := exec.Command("uname", "-s")
osName, err := cmd.Output()
if err != nil {
return "", err
}
return string(osName), nil
} else {
bytes, err := ioutil.ReadFile("/etc/os-release")
if err != nil && os.IsNotExist(err) {
// /usr/lib/os-release in stateless systems like Clear Linux
bytes, err = ioutil.ReadFile("/usr/lib/os-release")
}
if err != nil {
return "", fmt.Errorf("error opening file : %v", err)
}
line := rex.FindAllStringSubmatch(string(bytes), -1)
if len(line) > 0 {
return strings.Trim(line[0][2], "\""), nil
}
return "Linux", nil
}
}

View File

@ -0,0 +1,54 @@
// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package machine
import (
"fmt"
"golang.org/x/sys/windows/registry"
)
func getOperatingSystem() (string, error) {
system := "Windows"
k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE)
if err != nil {
return system, err
}
defer k.Close()
productName, _, err := k.GetStringValue("ProductName")
if err != nil {
return system, nil
}
releaseId, _, err := k.GetStringValue("ReleaseId")
if err != nil {
return system, err
}
currentBuildNumber, _, err := k.GetStringValue("CurrentBuildNumber")
if err != nil {
return system, err
}
revision, _, err := k.GetIntegerValue("UBR")
if err != nil {
return system, err
}
system = fmt.Sprintf("%s Version %s (OS Build %s.%d)",
productName, releaseId, currentBuildNumber, revision)
return system, nil
}

View File

@ -1,77 +0,0 @@
// Package operatingsystem provides helper function to get the operating system
// name for different platforms.
package operatingsystem // import "github.com/docker/docker/pkg/parsers/operatingsystem"
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/mattn/go-shellwords"
)
var (
// file to use to detect if the daemon is running in a container
proc1Cgroup = "/proc/1/cgroup"
// file to check to determine Operating System
etcOsRelease = "/etc/os-release"
// used by stateless systems like Clear Linux
altOsRelease = "/usr/lib/os-release"
)
// GetOperatingSystem gets the name of the current operating system.
func GetOperatingSystem() (string, error) {
osReleaseFile, err := os.Open(etcOsRelease)
if err != nil {
if !os.IsNotExist(err) {
return "", fmt.Errorf("Error opening %s: %v", etcOsRelease, err)
}
osReleaseFile, err = os.Open(altOsRelease)
if err != nil {
return "", fmt.Errorf("Error opening %s: %v", altOsRelease, err)
}
}
defer osReleaseFile.Close()
var prettyName string
scanner := bufio.NewScanner(osReleaseFile)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "PRETTY_NAME=") {
data := strings.SplitN(line, "=", 2)
prettyNames, err := shellwords.Parse(data[1])
if err != nil {
return "", fmt.Errorf("PRETTY_NAME is invalid: %s", err.Error())
}
if len(prettyNames) != 1 {
return "", fmt.Errorf("PRETTY_NAME needs to be enclosed by quotes if they have spaces: %s", data[1])
}
prettyName = prettyNames[0]
}
}
if prettyName != "" {
return prettyName, nil
}
// If not set, defaults to PRETTY_NAME="Linux"
// c.f. http://www.freedesktop.org/software/systemd/man/os-release.html
return "Linux", nil
}
// IsContainerized returns true if we are running inside a container.
func IsContainerized() (bool, error) {
b, err := ioutil.ReadFile(proc1Cgroup)
if err != nil {
return false, err
}
for _, line := range bytes.Split(b, []byte{'\n'}) {
if len(line) > 0 && !bytes.HasSuffix(line, []byte{'/'}) && !bytes.HasSuffix(line, []byte("init.scope")) {
return true, nil
}
}
return false, nil
}

View File

@ -1,25 +0,0 @@
// +build freebsd darwin
package operatingsystem // import "github.com/docker/docker/pkg/parsers/operatingsystem"
import (
"errors"
"os/exec"
)
// GetOperatingSystem gets the name of the current operating system.
func GetOperatingSystem() (string, error) {
cmd := exec.Command("uname", "-s")
osName, err := cmd.Output()
if err != nil {
return "", err
}
return string(osName), nil
}
// IsContainerized returns true if we are running inside a container.
// No-op on FreeBSD and Darwin, always returns false.
func IsContainerized() (bool, error) {
// TODO: Implement jail detection for freeBSD
return false, errors.New("Cannot detect if we are in container")
}

View File

@ -1,51 +0,0 @@
package operatingsystem // import "github.com/docker/docker/pkg/parsers/operatingsystem"
import (
"fmt"
"golang.org/x/sys/windows/registry"
)
// GetOperatingSystem gets the name of the current operating system.
func GetOperatingSystem() (string, error) {
// Default return value
ret := "Unknown Operating System"
k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE)
if err != nil {
return ret, err
}
defer k.Close()
pn, _, err := k.GetStringValue("ProductName")
if err != nil {
return ret, err
}
ret = pn
ri, _, err := k.GetStringValue("ReleaseId")
if err != nil {
return ret, err
}
ret = fmt.Sprintf("%s Version %s", ret, ri)
cbn, _, err := k.GetStringValue("CurrentBuildNumber")
if err != nil {
return ret, err
}
ubr, _, err := k.GetIntegerValue("UBR")
if err != nil {
return ret, err
}
ret = fmt.Sprintf("%s (OS Build %s.%d)", ret, cbn, ubr)
return ret, nil
}
// IsContainerized returns true if we are running inside a container.
// No-op on Windows, always returns false.
func IsContainerized() (bool, error) {
return false, nil
}

View File

@ -1,8 +0,0 @@
language: go
go:
- tip
before_install:
- go get github.com/mattn/goveralls
- go get golang.org/x/tools/cmd/cover
script:
- $HOME/gopath/bin/goveralls -repotoken 2FMhp57u8LcstKL9B190fLTcEnBtAAiEL

View File

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2017 Yasuhiro Matsumoto
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,47 +0,0 @@
# go-shellwords
[![Coverage Status](https://coveralls.io/repos/mattn/go-shellwords/badge.png?branch=master)](https://coveralls.io/r/mattn/go-shellwords?branch=master)
[![Build Status](https://travis-ci.org/mattn/go-shellwords.svg?branch=master)](https://travis-ci.org/mattn/go-shellwords)
Parse line as shell words.
## Usage
```go
args, err := shellwords.Parse("./foo --bar=baz")
// args should be ["./foo", "--bar=baz"]
```
```go
os.Setenv("FOO", "bar")
p := shellwords.NewParser()
p.ParseEnv = true
args, err := p.Parse("./foo $FOO")
// args should be ["./foo", "bar"]
```
```go
p := shellwords.NewParser()
p.ParseBacktick = true
args, err := p.Parse("./foo `echo $SHELL`")
// args should be ["./foo", "/bin/bash"]
```
```go
shellwords.ParseBacktick = true
p := shellwords.NewParser()
args, err := p.Parse("./foo `echo $SHELL`")
// args should be ["./foo", "/bin/bash"]
```
# Thanks
This is based on cpan module [Parse::CommandLine](https://metacpan.org/pod/Parse::CommandLine).
# License
under the MIT License: http://mattn.mit-license.org/2017
# Author
Yasuhiro Matsumoto (a.k.a mattn)

View File

@ -1,178 +0,0 @@
package shellwords
import (
"errors"
"os"
"regexp"
)
var (
ParseEnv bool = false
ParseBacktick bool = false
)
var envRe = regexp.MustCompile(`\$({[a-zA-Z0-9_]+}|[a-zA-Z0-9_]+)`)
func isSpace(r rune) bool {
switch r {
case ' ', '\t', '\r', '\n':
return true
}
return false
}
func replaceEnv(s string) string {
return envRe.ReplaceAllStringFunc(s, func(s string) string {
s = s[1:]
if s[0] == '{' {
s = s[1 : len(s)-1]
}
return os.Getenv(s)
})
}
type Parser struct {
ParseEnv bool
ParseBacktick bool
Position int
}
func NewParser() *Parser {
return &Parser{ParseEnv, ParseBacktick, 0}
}
func (p *Parser) Parse(line string) ([]string, error) {
args := []string{}
buf := ""
var escaped, doubleQuoted, singleQuoted, backQuote, dollarQuote bool
backtick := ""
pos := -1
got := false
loop:
for i, r := range line {
if escaped {
buf += string(r)
escaped = false
continue
}
if r == '\\' {
if singleQuoted {
buf += string(r)
} else {
escaped = true
}
continue
}
if isSpace(r) {
if singleQuoted || doubleQuoted || backQuote || dollarQuote {
buf += string(r)
backtick += string(r)
} else if got {
if p.ParseEnv {
buf = replaceEnv(buf)
}
args = append(args, buf)
buf = ""
got = false
}
continue
}
switch r {
case '`':
if !singleQuoted && !doubleQuoted && !dollarQuote {
if p.ParseBacktick {
if backQuote {
out, err := shellRun(backtick)
if err != nil {
return nil, err
}
buf = out
}
backtick = ""
backQuote = !backQuote
continue
}
backtick = ""
backQuote = !backQuote
}
case ')':
if !singleQuoted && !doubleQuoted && !backQuote {
if p.ParseBacktick {
if dollarQuote {
out, err := shellRun(backtick)
if err != nil {
return nil, err
}
buf = out
}
backtick = ""
dollarQuote = !dollarQuote
continue
}
backtick = ""
dollarQuote = !dollarQuote
}
case '(':
if !singleQuoted && !doubleQuoted && !backQuote {
if !dollarQuote && len(buf) > 0 && buf == "$" {
dollarQuote = true
buf += "("
continue
} else {
return nil, errors.New("invalid command line string")
}
}
case '"':
if !singleQuoted && !dollarQuote {
doubleQuoted = !doubleQuoted
continue
}
case '\'':
if !doubleQuoted && !dollarQuote {
singleQuoted = !singleQuoted
continue
}
case ';', '&', '|', '<', '>':
if !(escaped || singleQuoted || doubleQuoted || backQuote) {
if r == '>' {
if c := buf[0]; '0' <= c && c <= '9' {
i -= 1
got = false
}
}
pos = i
break loop
}
}
got = true
buf += string(r)
if backQuote || dollarQuote {
backtick += string(r)
}
}
if got {
if p.ParseEnv {
buf = replaceEnv(buf)
}
args = append(args, buf)
}
if escaped || singleQuoted || doubleQuoted || backQuote || dollarQuote {
return nil, errors.New("invalid command line string")
}
p.Position = pos
return args, nil
}
func Parse(line string) ([]string, error) {
return NewParser().Parse(line)
}

View File

@ -1,24 +0,0 @@
// +build !go1.6
package shellwords
import (
"os"
"os/exec"
"runtime"
"strings"
)
func shellRun(line string) (string, error) {
var b []byte
var err error
if runtime.GOOS == "windows" {
b, err = exec.Command(os.Getenv("COMSPEC"), "/c", line).Output()
} else {
b, err = exec.Command(os.Getenv("SHELL"), "-c", line).Output()
}
if err != nil {
return "", err
}
return strings.TrimSpace(string(b)), nil
}

View File

@ -1,22 +0,0 @@
// +build !windows,go1.6
package shellwords
import (
"errors"
"os"
"os/exec"
"strings"
)
func shellRun(line string) (string, error) {
shell := os.Getenv("SHELL")
b, err := exec.Command(shell, "-c", line).Output()
if err != nil {
if eerr, ok := err.(*exec.ExitError); ok {
b = eerr.Stderr
}
return "", errors.New(err.Error() + ":" + string(b))
}
return strings.TrimSpace(string(b)), nil
}

View File

@ -1,22 +0,0 @@
// +build windows,go1.6
package shellwords
import (
"errors"
"os"
"os/exec"
"strings"
)
func shellRun(line string) (string, error) {
shell := os.Getenv("COMSPEC")
b, err := exec.Command(shell, "/c", line).Output()
if err != nil {
if eerr, ok := err.(*exec.ExitError); ok {
b = eerr.Stderr
}
return "", errors.New(err.Error() + ":" + string(b))
}
return strings.TrimSpace(string(b)), nil
}

3
vendor/modules.txt vendored
View File

@ -93,7 +93,6 @@ github.com/docker/docker/api/types/versions
github.com/docker/docker/api/types/volume
github.com/docker/docker/client
github.com/docker/docker/errdefs
github.com/docker/docker/pkg/parsers/operatingsystem
# github.com/docker/go-connections v0.3.0
github.com/docker/go-connections/nat
github.com/docker/go-connections/sockets
@ -145,8 +144,6 @@ github.com/konsorten/go-windows-terminal-sequences
github.com/kr/pretty
# github.com/kr/text v0.0.0-20130911015532-6807e777504f
github.com/kr/text
# github.com/mattn/go-shellwords v1.0.4-0.20180201004752-39dbbfa24bbc
github.com/mattn/go-shellwords
# github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369
github.com/matttproud/golang_protobuf_extensions/pbutil
# github.com/mesos/mesos-go v0.0.7-0.20180413204204-29de6ff97b48