diff --git a/Dockerfile b/Dockerfile index cb5b6143..d24b4040 100644 --- a/Dockerfile +++ b/Dockerfile @@ -43,13 +43,12 @@ RUN mkdir -p /usr/src/criu \ && rm -rf /usr/src/criu # Install runc -# TODO: This should actually be v1.0.0-rc3 but we first need to switch to -# v1.0.0-rc5 runtime config generation. -ENV RUNC_COMMIT 31980a53ae7887b2c8f8715d13c3eb486c27b6cf +ENV RUNC_COMMIT v1.0.0-rc3 RUN set -x \ && export GOPATH="$(mktemp -d)" \ && git clone https://github.com/opencontainers/runc.git "$GOPATH/src/github.com/opencontainers/runc" \ && cd "$GOPATH/src/github.com/opencontainers/runc" \ + && git fetch origin --tags \ && git checkout -q "$RUNC_COMMIT" \ && make static BUILDTAGS="seccomp selinux" \ && cp runc /usr/local/bin/runc \ diff --git a/lock.json b/lock.json index a5417241..f2c449d6 100644 --- a/lock.json +++ b/lock.json @@ -1,5 +1,5 @@ { - "memo": "1290be673a75036ce5bea81021073dd7041dc3f421446912b6b7ae0ed511fe93", + "memo": "0d3077faf280e4e13e18e56f085053d4ced593c2fcfcb09d7df1aea8f0bba403", "projects": [ { "name": "github.com/BurntSushi/toml", @@ -35,6 +35,14 @@ "." ] }, + { + "name": "github.com/blang/semver", + "version": "v3.5.0", + "revision": "b38d23b8782a487059e8fc8773e9a5b228a77cb6", + "packages": [ + "." + ] + }, { "name": "github.com/containernetworking/cni", "version": "v0.4.0", @@ -325,8 +333,8 @@ }, { "name": "github.com/opencontainers/runtime-spec", - "branch": "master", - "revision": "bb6925ea99f0e366a3f7d1c975f6577475ca25f0", + "version": "v1.0.0-rc5", + "revision": "035da1dca3dfbb00d752eb58b0b158d6129f3776", "packages": [ "specs-go" ] @@ -334,10 +342,11 @@ { "name": "github.com/opencontainers/runtime-tools", "branch": "master", - "revision": "2d92f6557e64d4f9a0e799a75fdf153cec13dffa", + "revision": "18a122b45a71765b09c6a451008a63687040b74a", "packages": [ "generate", - "generate/seccomp" + "generate/seccomp", + "validate" ] }, { diff --git a/manifest.json b/manifest.json index fdb0f75c..19ef4861 100644 --- a/manifest.json +++ b/manifest.json @@ -22,6 +22,9 @@ "branch": "master" }, "github.com/opencontainers/runtime-spec": { + "version": "v1.0.0-rc5" + }, + "github.com/opencontainers/runtime-tools": { "branch": "master" }, "github.com/opencontainers/selinux": { diff --git a/server/container_create.go b/server/container_create.go index c1880575..fdfe1ba2 100644 --- a/server/container_create.go +++ b/server/container_create.go @@ -365,7 +365,7 @@ func (s *Server) createSandboxContainer(ctx context.Context, containerID string, cpuQuota := resources.CpuQuota if cpuQuota != 0 { - specgen.SetLinuxResourcesCPUQuota(uint64(cpuQuota)) + specgen.SetLinuxResourcesCPUQuota(cpuQuota) } cpuShares := resources.CpuShares diff --git a/server/seccomp/seccomp.go b/server/seccomp/seccomp.go index 17f86195..79c1b3fe 100644 --- a/server/seccomp/seccomp.go +++ b/server/seccomp/seccomp.go @@ -75,7 +75,7 @@ func setupSeccomp(config *Seccomp, specgen *generate.Generator) error { } customspec := specgen.Spec() - customspec.Linux.Seccomp = &specs.Seccomp{} + customspec.Linux.Seccomp = &specs.LinuxSeccomp{} // if config.Architectures == 0 then libseccomp will figure out the architecture to use if len(config.Architectures) != 0 { @@ -99,7 +99,7 @@ func setupSeccomp(config *Seccomp, specgen *generate.Generator) error { } } - customspec.Linux.Seccomp.DefaultAction = specs.Action(config.DefaultAction) + customspec.Linux.Seccomp.DefaultAction = specs.LinuxSeccompAction(config.DefaultAction) Loop: // Loop through all syscall blocks and convert them to libcontainer format after filtering them @@ -111,7 +111,7 @@ Loop: } if len(call.Excludes.Caps) > 0 { for _, c := range call.Excludes.Caps { - if stringutils.InSlice(customspec.Process.Capabilities, c) { + if stringutils.InSlice(customspec.Process.Capabilities.Permitted, c) { continue Loop } } @@ -123,7 +123,7 @@ Loop: } if len(call.Includes.Caps) > 0 { for _, c := range call.Includes.Caps { - if !stringutils.InSlice(customspec.Process.Capabilities, c) { + if !stringutils.InSlice(customspec.Process.Capabilities.Permitted, c) { continue Loop } } @@ -145,19 +145,19 @@ Loop: return nil } -func createSpecsSyscall(name string, action Action, args []*Arg) specs.Syscall { - newCall := specs.Syscall{ - Name: name, - Action: specs.Action(action), +func createSpecsSyscall(name string, action Action, args []*Arg) specs.LinuxSyscall { + newCall := specs.LinuxSyscall{ + Names: []string{name}, + Action: specs.LinuxSeccompAction(action), } // Loop through all the arguments of the syscall and convert them for _, arg := range args { - newArg := specs.Arg{ + newArg := specs.LinuxSeccompArg{ Index: arg.Index, Value: arg.Value, ValueTwo: arg.ValueTwo, - Op: specs.Operator(arg.Op), + Op: specs.LinuxSeccompOperator(arg.Op), } newCall.Args = append(newCall.Args, newArg) diff --git a/vendor/github.com/blang/semver/.gx/lastpubver b/vendor/github.com/blang/semver/.gx/lastpubver new file mode 100644 index 00000000..073ce1ef --- /dev/null +++ b/vendor/github.com/blang/semver/.gx/lastpubver @@ -0,0 +1 @@ +3.4.0: QmZTgGMg34JKEvF1hjr7wwYESvFhg9Khv2WFibDAi5dhno diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/LICENSE b/vendor/github.com/blang/semver/LICENSE similarity index 100% rename from vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/LICENSE rename to vendor/github.com/blang/semver/LICENSE diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/README.md b/vendor/github.com/blang/semver/README.md similarity index 100% rename from vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/README.md rename to vendor/github.com/blang/semver/README.md diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/examples/main.go b/vendor/github.com/blang/semver/examples/main.go similarity index 100% rename from vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/examples/main.go rename to vendor/github.com/blang/semver/examples/main.go diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/json.go b/vendor/github.com/blang/semver/json.go similarity index 100% rename from vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/json.go rename to vendor/github.com/blang/semver/json.go diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/json_test.go b/vendor/github.com/blang/semver/json_test.go similarity index 90% rename from vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/json_test.go rename to vendor/github.com/blang/semver/json_test.go index 039117da..c635dea1 100644 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/json_test.go +++ b/vendor/github.com/blang/semver/json_test.go @@ -42,4 +42,8 @@ func TestJSONUnmarshal(t *testing.T) { if err := json.Unmarshal([]byte(badVersionString), &v); err == nil { t.Fatal("expected JSON unmarshal error, got nil") } + + if err := json.Unmarshal([]byte("3.1"), &v); err == nil { + t.Fatal("expected JSON unmarshal error, got nil") + } } diff --git a/vendor/github.com/blang/semver/package.json b/vendor/github.com/blang/semver/package.json new file mode 100644 index 00000000..568be8d9 --- /dev/null +++ b/vendor/github.com/blang/semver/package.json @@ -0,0 +1,17 @@ +{ + "author": "blang", + "bugs": { + "URL": "https://github.com/blang/semver/issues", + "url": "https://github.com/blang/semver/issues" + }, + "gx": { + "dvcsimport": "github.com/blang/semver" + }, + "gxVersion": "0.10.0", + "language": "go", + "license": "MIT", + "name": "semver", + "releaseCmd": "git commit -a -m \"gx publish $VERSION\"", + "version": "3.4.0" +} + diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/range.go b/vendor/github.com/blang/semver/range.go similarity index 51% rename from vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/range.go rename to vendor/github.com/blang/semver/range.go index 0a8eaa1c..fca406d4 100644 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/range.go +++ b/vendor/github.com/blang/semver/range.go @@ -2,10 +2,33 @@ package semver import ( "fmt" + "strconv" "strings" "unicode" ) +type wildcardType int + +const ( + noneWildcard wildcardType = iota + majorWildcard wildcardType = 1 + minorWildcard wildcardType = 2 + patchWildcard wildcardType = 3 +) + +func wildcardTypefromInt(i int) wildcardType { + switch i { + case 1: + return majorWildcard + case 2: + return minorWildcard + case 3: + return patchWildcard + default: + return noneWildcard + } +} + type comparator func(Version, Version) bool var ( @@ -92,8 +115,12 @@ func ParseRange(s string) (Range, error) { if err != nil { return nil, err } + expandedParts, err := expandWildcardVersion(orParts) + if err != nil { + return nil, err + } var orFn Range - for _, p := range orParts { + for _, p := range expandedParts { var andFn Range for _, ap := range p { opStr, vStr, err := splitComparatorVersion(ap) @@ -164,20 +191,39 @@ func buildVersionRange(opStr, vStr string) (*versionRange, error) { } -// splitAndTrim splits a range string by spaces and cleans leading and trailing spaces +// inArray checks if a byte is contained in an array of bytes +func inArray(s byte, list []byte) bool { + for _, el := range list { + if el == s { + return true + } + } + return false +} + +// splitAndTrim splits a range string by spaces and cleans whitespaces func splitAndTrim(s string) (result []string) { last := 0 + var lastChar byte + excludeFromSplit := []byte{'>', '<', '='} for i := 0; i < len(s); i++ { - if s[i] == ' ' { + if s[i] == ' ' && !inArray(lastChar, excludeFromSplit) { if last < i-1 { result = append(result, s[last:i]) } last = i + 1 + } else if s[i] != ' ' { + lastChar = s[i] } } if last < len(s)-1 { result = append(result, s[last:]) } + + for i, v := range result { + result[i] = strings.Replace(v, " ", "", -1) + } + // parts := strings.Split(s, " ") // for _, x := range parts { // if s := strings.TrimSpace(x); len(s) != 0 { @@ -188,7 +234,6 @@ func splitAndTrim(s string) (result []string) { } // splitComparatorVersion splits the comparator from the version. -// Spaces between the comparator and the version are not allowed. // Input must be free of leading or trailing spaces. func splitComparatorVersion(s string) (string, string, error) { i := strings.IndexFunc(s, unicode.IsDigit) @@ -198,6 +243,144 @@ func splitComparatorVersion(s string) (string, string, error) { return strings.TrimSpace(s[0:i]), s[i:], nil } +// getWildcardType will return the type of wildcard that the +// passed version contains +func getWildcardType(vStr string) wildcardType { + parts := strings.Split(vStr, ".") + nparts := len(parts) + wildcard := parts[nparts-1] + + possibleWildcardType := wildcardTypefromInt(nparts) + if wildcard == "x" { + return possibleWildcardType + } + + return noneWildcard +} + +// createVersionFromWildcard will convert a wildcard version +// into a regular version, replacing 'x's with '0's, handling +// special cases like '1.x.x' and '1.x' +func createVersionFromWildcard(vStr string) string { + // handle 1.x.x + vStr2 := strings.Replace(vStr, ".x.x", ".x", 1) + vStr2 = strings.Replace(vStr2, ".x", ".0", 1) + parts := strings.Split(vStr2, ".") + + // handle 1.x + if len(parts) == 2 { + return vStr2 + ".0" + } + + return vStr2 +} + +// incrementMajorVersion will increment the major version +// of the passed version +func incrementMajorVersion(vStr string) (string, error) { + parts := strings.Split(vStr, ".") + i, err := strconv.Atoi(parts[0]) + if err != nil { + return "", err + } + parts[0] = strconv.Itoa(i + 1) + + return strings.Join(parts, "."), nil +} + +// incrementMajorVersion will increment the minor version +// of the passed version +func incrementMinorVersion(vStr string) (string, error) { + parts := strings.Split(vStr, ".") + i, err := strconv.Atoi(parts[1]) + if err != nil { + return "", err + } + parts[1] = strconv.Itoa(i + 1) + + return strings.Join(parts, "."), nil +} + +// expandWildcardVersion will expand wildcards inside versions +// following these rules: +// +// * when dealing with patch wildcards: +// >= 1.2.x will become >= 1.2.0 +// <= 1.2.x will become < 1.3.0 +// > 1.2.x will become >= 1.3.0 +// < 1.2.x will become < 1.2.0 +// != 1.2.x will become < 1.2.0 >= 1.3.0 +// +// * when dealing with minor wildcards: +// >= 1.x will become >= 1.0.0 +// <= 1.x will become < 2.0.0 +// > 1.x will become >= 2.0.0 +// < 1.0 will become < 1.0.0 +// != 1.x will become < 1.0.0 >= 2.0.0 +// +// * when dealing with wildcards without +// version operator: +// 1.2.x will become >= 1.2.0 < 1.3.0 +// 1.x will become >= 1.0.0 < 2.0.0 +func expandWildcardVersion(parts [][]string) ([][]string, error) { + var expandedParts [][]string + for _, p := range parts { + var newParts []string + for _, ap := range p { + if strings.Index(ap, "x") != -1 { + opStr, vStr, err := splitComparatorVersion(ap) + if err != nil { + return nil, err + } + + versionWildcardType := getWildcardType(vStr) + flatVersion := createVersionFromWildcard(vStr) + + var resultOperator string + var shouldIncrementVersion bool + switch opStr { + case ">": + resultOperator = ">=" + shouldIncrementVersion = true + case ">=": + resultOperator = ">=" + case "<": + resultOperator = "<" + case "<=": + resultOperator = "<" + shouldIncrementVersion = true + case "", "=", "==": + newParts = append(newParts, ">="+flatVersion) + resultOperator = "<" + shouldIncrementVersion = true + case "!=", "!": + newParts = append(newParts, "<"+flatVersion) + resultOperator = ">=" + shouldIncrementVersion = true + } + + var resultVersion string + if shouldIncrementVersion { + switch versionWildcardType { + case patchWildcard: + resultVersion, _ = incrementMinorVersion(flatVersion) + case minorWildcard: + resultVersion, _ = incrementMajorVersion(flatVersion) + } + } else { + resultVersion = flatVersion + } + + ap = resultOperator + resultVersion + } + newParts = append(newParts, ap) + } + expandedParts = append(expandedParts, newParts) + } + + return expandedParts, nil +} + func parseComparator(s string) comparator { switch s { case "==": @@ -222,3 +405,12 @@ func parseComparator(s string) comparator { return nil } + +// MustParseRange is like ParseRange but panics if the range cannot be parsed. +func MustParseRange(s string) Range { + r, err := ParseRange(s) + if err != nil { + panic(`semver: ParseRange(` + s + `): ` + err.Error()) + } + return r +} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/range_test.go b/vendor/github.com/blang/semver/range_test.go similarity index 73% rename from vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/range_test.go rename to vendor/github.com/blang/semver/range_test.go index 5a745a9a..83ee9c78 100644 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/range_test.go +++ b/vendor/github.com/blang/semver/range_test.go @@ -6,6 +6,11 @@ import ( "testing" ) +type wildcardTypeTest struct { + input string + wildcardType wildcardType +} + type comparatorTest struct { input string comparator func(comparator) bool @@ -75,7 +80,8 @@ func TestSplitAndTrim(t *testing.T) { s []string }{ {"1.2.3 1.2.3", []string{"1.2.3", "1.2.3"}}, - {" 1.2.3 1.2.3 ", []string{"1.2.3", "1.2.3"}}, // Spaces + {" 1.2.3 1.2.3 ", []string{"1.2.3", "1.2.3"}}, // Spaces + {" >= 1.2.3 <= 1.2.3 ", []string{">=1.2.3", "<=1.2.3"}}, // Spaces between operator and version {"1.2.3 || >=1.2.3 <1.2.3", []string{"1.2.3", "||", ">=1.2.3", "<1.2.3"}}, {" 1.2.3 || >=1.2.3 <1.2.3 ", []string{"1.2.3", "||", ">=1.2.3", "<1.2.3"}}, } @@ -191,6 +197,103 @@ func TestSplitORParts(t *testing.T) { } } +func TestGetWildcardType(t *testing.T) { + wildcardTypeTests := []wildcardTypeTest{ + {"x", majorWildcard}, + {"1.x", minorWildcard}, + {"1.2.x", patchWildcard}, + {"fo.o.b.ar", noneWildcard}, + } + + for _, tc := range wildcardTypeTests { + o := getWildcardType(tc.input) + if o != tc.wildcardType { + t.Errorf("Invalid for case: %q: Expected %q, got: %q", tc.input, tc.wildcardType, o) + } + } +} + +func TestCreateVersionFromWildcard(t *testing.T) { + tests := []struct { + i string + s string + }{ + {"1.2.x", "1.2.0"}, + {"1.x", "1.0.0"}, + } + + for _, tc := range tests { + p := createVersionFromWildcard(tc.i) + if p != tc.s { + t.Errorf("Invalid for case %q: Expected %q, got: %q", tc.i, tc.s, p) + } + } +} + +func TestIncrementMajorVersion(t *testing.T) { + tests := []struct { + i string + s string + }{ + {"1.2.3", "2.2.3"}, + {"1.2", "2.2"}, + {"foo.bar", ""}, + } + + for _, tc := range tests { + p, _ := incrementMajorVersion(tc.i) + if p != tc.s { + t.Errorf("Invalid for case %q: Expected %q, got: %q", tc.i, tc.s, p) + } + } +} + +func TestIncrementMinorVersion(t *testing.T) { + tests := []struct { + i string + s string + }{ + {"1.2.3", "1.3.3"}, + {"1.2", "1.3"}, + {"foo.bar", ""}, + } + + for _, tc := range tests { + p, _ := incrementMinorVersion(tc.i) + if p != tc.s { + t.Errorf("Invalid for case %q: Expected %q, got: %q", tc.i, tc.s, p) + } + } +} + +func TestExpandWildcardVersion(t *testing.T) { + tests := []struct { + i [][]string + o [][]string + }{ + {[][]string{[]string{"foox"}}, nil}, + {[][]string{[]string{">=1.2.x"}}, [][]string{[]string{">=1.2.0"}}}, + {[][]string{[]string{"<=1.2.x"}}, [][]string{[]string{"<1.3.0"}}}, + {[][]string{[]string{">1.2.x"}}, [][]string{[]string{">=1.3.0"}}}, + {[][]string{[]string{"<1.2.x"}}, [][]string{[]string{"<1.2.0"}}}, + {[][]string{[]string{"!=1.2.x"}}, [][]string{[]string{"<1.2.0", ">=1.3.0"}}}, + {[][]string{[]string{">=1.x"}}, [][]string{[]string{">=1.0.0"}}}, + {[][]string{[]string{"<=1.x"}}, [][]string{[]string{"<2.0.0"}}}, + {[][]string{[]string{">1.x"}}, [][]string{[]string{">=2.0.0"}}}, + {[][]string{[]string{"<1.x"}}, [][]string{[]string{"<1.0.0"}}}, + {[][]string{[]string{"!=1.x"}}, [][]string{[]string{"<1.0.0", ">=2.0.0"}}}, + {[][]string{[]string{"1.2.x"}}, [][]string{[]string{">=1.2.0", "<1.3.0"}}}, + {[][]string{[]string{"1.x"}}, [][]string{[]string{">=1.0.0", "<2.0.0"}}}, + } + + for _, tc := range tests { + o, _ := expandWildcardVersion(tc.i) + if !reflect.DeepEqual(tc.o, o) { + t.Errorf("Invalid for case %q: Expected %q, got: %q", tc.i, tc.o, o) + } + } +} + func TestVersionRangeToRange(t *testing.T) { vr := versionRange{ v: MustParse("1.2.3"), @@ -310,7 +413,7 @@ func TestParseRange(t *testing.T) { {"1.0", nil}, {"string", nil}, {"", nil}, - + {"fo.ob.ar.x", nil}, // AND Expressions {">1.2.2 <1.2.4", []tv{ {"1.2.2", false}, @@ -346,6 +449,18 @@ func TestParseRange(t *testing.T) { {"1.2.3", false}, {"1.2.4", false}, }}, + // Wildcard expressions + {">1.x", []tv{ + {"0.1.9", false}, + {"1.2.6", false}, + {"1.9.0", false}, + {"2.0.0", true}, + }}, + {">1.2.x", []tv{ + {"1.1.9", false}, + {"1.2.6", false}, + {"1.3.0", true}, + }}, // Combined Expressions {">1.2.2 <1.2.4 || >=2.0.0", []tv{ {"1.2.2", false}, @@ -354,6 +469,13 @@ func TestParseRange(t *testing.T) { {"2.0.0", true}, {"2.0.1", true}, }}, + {"1.x || >=2.0.x <2.2.x", []tv{ + {"0.9.2", false}, + {"1.2.2", true}, + {"2.0.0", true}, + {"2.1.8", true}, + {"2.2.0", false}, + }}, {">1.2.2 <1.2.4 || >=2.0.0 <3.0.0", []tv{ {"1.2.2", false}, {"1.2.3", true}, @@ -381,6 +503,23 @@ func TestParseRange(t *testing.T) { } } +func TestMustParseRange(t *testing.T) { + testCase := ">1.2.2 <1.2.4 || >=2.0.0 <3.0.0" + r := MustParseRange(testCase) + if !r(MustParse("1.2.3")) { + t.Errorf("Unexpected range behavior on MustParseRange") + } +} + +func TestMustParseRange_panic(t *testing.T) { + defer func() { + if recover() == nil { + t.Errorf("Should have panicked") + } + }() + _ = MustParseRange("invalid version") +} + func BenchmarkRangeParseSimple(b *testing.B) { const VERSION = ">1.0.0" b.ReportAllocs() diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/semver.go b/vendor/github.com/blang/semver/semver.go similarity index 91% rename from vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/semver.go rename to vendor/github.com/blang/semver/semver.go index bbf85ce9..8ee0842e 100644 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/semver.go +++ b/vendor/github.com/blang/semver/semver.go @@ -200,6 +200,29 @@ func Make(s string) (Version, error) { return Parse(s) } +// ParseTolerant allows for certain version specifications that do not strictly adhere to semver +// specs to be parsed by this library. It does so by normalizing versions before passing them to +// Parse(). It currently trims spaces, removes a "v" prefix, and adds a 0 patch number to versions +// with only major and minor components specified +func ParseTolerant(s string) (Version, error) { + s = strings.TrimSpace(s) + s = strings.TrimPrefix(s, "v") + + // Split into major.minor.(patch+pr+meta) + parts := strings.SplitN(s, ".", 3) + if len(parts) < 3 { + if strings.ContainsAny(parts[len(parts)-1], "+-") { + return Version{}, errors.New("Short version cannot contain PreRelease/Build meta data") + } + for len(parts) < 3 { + parts = append(parts, "0") + } + s = strings.Join(parts, ".") + } + + return Parse(s) +} + // Parse parses version string and returns a validated Version or error func Parse(s string) (Version, error) { if len(s) == 0 { diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/semver_test.go b/vendor/github.com/blang/semver/semver_test.go similarity index 90% rename from vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/semver_test.go rename to vendor/github.com/blang/semver/semver_test.go index e56ebce0..b3e1fd43 100644 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/semver_test.go +++ b/vendor/github.com/blang/semver/semver_test.go @@ -30,6 +30,13 @@ var formatTests = []formatTest{ {Version{1, 2, 3, []PRVersion{prstr("alpha"), prstr("b-eta")}, nil}, "1.2.3-alpha.b-eta"}, } +var tolerantFormatTests = []formatTest{ + {Version{1, 2, 3, nil, nil}, "v1.2.3"}, + {Version{1, 2, 3, nil, nil}, " 1.2.3 "}, + {Version{1, 2, 0, nil, nil}, "1.2"}, + {Version{1, 0, 0, nil, nil}, "1"}, +} + func TestStringer(t *testing.T) { for _, test := range formatTests { if res := test.v.String(); res != test.result { @@ -50,6 +57,18 @@ func TestParse(t *testing.T) { } } +func TestParseTolerant(t *testing.T) { + for _, test := range tolerantFormatTests { + if v, err := ParseTolerant(test.result); err != nil { + t.Errorf("Error parsing %q: %q", test.result, err) + } else if comp := v.Compare(test.v); comp != 0 { + t.Errorf("Parsing, expected %q but got %q, comp: %d ", test.v, v, comp) + } else if err := v.Validate(); err != nil { + t.Errorf("Error validating parsed version %q: %q", test.v, err) + } + } +} + func TestMustParse(t *testing.T) { _ = MustParse("32.2.1-alpha") } @@ -184,6 +203,19 @@ func TestWrongFormat(t *testing.T) { } } +var wrongTolerantFormatTests = []wrongformatTest{ + {nil, "1.0+abc"}, + {nil, "1.0-rc.1"}, +} + +func TestWrongTolerantFormat(t *testing.T) { + for _, test := range wrongTolerantFormatTests { + if res, err := ParseTolerant(test.str); err == nil { + t.Errorf("Parsing wrong format version %q, expected error but got %q", test.str, res) + } + } +} + func TestCompareHelper(t *testing.T) { v := Version{1, 0, 0, []PRVersion{prstr("alpha")}, nil} v1 := Version{1, 0, 0, nil, nil} @@ -319,6 +351,15 @@ func BenchmarkParseAverage(b *testing.B) { } } +func BenchmarkParseTolerantAverage(b *testing.B) { + l := len(tolerantFormatTests) + b.ReportAllocs() + b.ResetTimer() + for n := 0; n < b.N; n++ { + ParseTolerant(tolerantFormatTests[n%l].result) + } +} + func BenchmarkStringSimple(b *testing.B) { const VERSION = "0.0.1" v, _ := Parse(VERSION) diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/sort.go b/vendor/github.com/blang/semver/sort.go similarity index 100% rename from vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/sort.go rename to vendor/github.com/blang/semver/sort.go diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/sort_test.go b/vendor/github.com/blang/semver/sort_test.go similarity index 100% rename from vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/sort_test.go rename to vendor/github.com/blang/semver/sort_test.go diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/sql.go b/vendor/github.com/blang/semver/sql.go similarity index 100% rename from vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/sql.go rename to vendor/github.com/blang/semver/sql.go diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/sql_test.go b/vendor/github.com/blang/semver/sql_test.go similarity index 100% rename from vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/blang/semver/sql_test.go rename to vendor/github.com/blang/semver/sql_test.go diff --git a/vendor/github.com/opencontainers/runtime-spec/.gitignore b/vendor/github.com/opencontainers/runtime-spec/.gitignore index 0e195001..f9663c92 100644 --- a/vendor/github.com/opencontainers/runtime-spec/.gitignore +++ b/vendor/github.com/opencontainers/runtime-spec/.gitignore @@ -1,4 +1,3 @@ output schema/validate -code-of-conduct.md version.md diff --git a/vendor/github.com/opencontainers/runtime-spec/.pullapprove.yml b/vendor/github.com/opencontainers/runtime-spec/.pullapprove.yml index d9572bde..49cb34b5 100644 --- a/vendor/github.com/opencontainers/runtime-spec/.pullapprove.yml +++ b/vendor/github.com/opencontainers/runtime-spec/.pullapprove.yml @@ -3,6 +3,8 @@ approve_regex: ^LGTM reject_regex: ^Rejected reset_on_push: true author_approval: ignored +signed_off_by: + required: true reviewers: teams: - runtime-spec-maintainers diff --git a/vendor/github.com/opencontainers/runtime-spec/.travis.yml b/vendor/github.com/opencontainers/runtime-spec/.travis.yml index 707efcfd..7f6c11f1 100644 --- a/vendor/github.com/opencontainers/runtime-spec/.travis.yml +++ b/vendor/github.com/opencontainers/runtime-spec/.travis.yml @@ -1,7 +1,8 @@ language: go go: - - 1.6 - - 1.5.3 + - 1.7 + - 1.6.3 + - 1.5.4 sudo: required @@ -15,7 +16,9 @@ before_install: install: true script: + - env | grep TRAVIS_ - make .govet - make .golint - - make .gitvalidation + - echo "${TRAVIS_COMMIT_RANGE} -> ${TRAVIS_COMMIT_RANGE/.../..} (travis-ci/travis-ci#4596)" + - TRAVIS_COMMIT_RANGE="${TRAVIS_COMMIT_RANGE/.../..}" make .gitvalidation - make docs diff --git a/vendor/github.com/opencontainers/runtime-spec/ChangeLog b/vendor/github.com/opencontainers/runtime-spec/ChangeLog index 157b39d3..99ffe630 100644 --- a/vendor/github.com/opencontainers/runtime-spec/ChangeLog +++ b/vendor/github.com/opencontainers/runtime-spec/ChangeLog @@ -1,5 +1,133 @@ OpenContainers Specifications +Changes with v1.0.0-rc4: + Additions: + + * config-linux: Allow negative values for some resources (#648) + * config-linux: Lift no-tweaking namespace restriction (#649) + + Removals and increased restrictions: + + * config: Rlimit types must be unique (#607) + * config: Forbid empty-string keys in 'annotations' (#645, #654) + * config-linux: Require runtime errors for pre-existing devices + (#647) + * runtime: Only require 'pid' in the state for created/running + statuses (#664) + * schema: Add 'consoleSize' and update requirements (#646) + * schema: Remove string pointers (#656) + * schema/config-linux: Remove blockIODeviceThrottle and other + pointers (#545) + + Breaking Go changes: + + * specs-go/config: Remove string pointers (#653) + * specs-go/config: Make Spec.Hooks a pointer (#427) + * specs-go/config: Convert some resources from unsigned integers + to signed integers (#648) + + Minor fixes and documentation: + + * config: Explicitly list 'hooks' as optional and cite POSIX for + 'env' and 'args' (#427) + * runtime: Replace "process is stopped" with "process exits" + (#465) + * schema/config-linux: Add missing kernelTCP (#655) + * schema/validate: Allow schema identifiers to contain a URL + scheme (#490) + * .travis: Fix git-validation commit ranges (#216) + * *: Add anchor tags to a number of spec locations (#612, #636, + #637, #638, #639, #640) + * *: Typo fixes and polishing (#643, #650, #652, #656, #660, #665) + +Changes with v1.0.0-rc3: + Additions: + + * config: Add support for Windows-based containers (#565, #573) + * config: Add process.consoleSize (#563) + * config: Explicitly allow unknown extensions and document + annotations key conventions (#510) + * config: Define mounts entries for Solaris (#588) + + Removals and increased restrictions: + + * config: Require absolute paths for mount destinations (#609) + * config-linux: Require absolute path for maskedPaths and + readonlyPaths (#587) + * config-linux: Only require /dev/console when process.terminal is + true. Also require /dev/console to be provided by a bind mount + (#518) + * runtime: Require runtimes to generate errors when the container + specified in config.json cannot be created (#559) + + Breaking Go changes: + + * specs-go/config: Aggressive namespacing (#567) + * specs-go/config: Remove pointers from LinuxHugepageLimit, + LinuxInterfacePriority, and LinuxPids properties (#586) + * specs-go/state: Rename version to ociVersion (#633) + LinuxInterfacePriority, and LinuxPids properties (#586) + + Minor fixes and documentation: + + * spec: Separate the spec from project scaffolding (#626) + * README: Define "unspecified", "undefined", and + "implementation-defined" (#575) + * config: Clarify absolue and relative values for root.path (#558) + * config: Clarify ociVersion covering the configuration <-> + runtime API (#523) + * config-linux: Forbid duplicated namespaces with same `type` + (#597) + * glossary: Make objects explicitly unordered and forbid duplicate + names (#584) + * specs-go/config: Add platform tags to Rlimits and + NoNewPRivileges (#564) + * schema/defs-linux: Use int64 for major/minor types (#610) + * Makefile: Add support for Go 1.7 (#547) + * Makefile: Require Go >= 1.6 for golint (#589) + * Makefile: Use a POSIX-compatible test ('==' -> '=') (#542) + * implementations: Rename ocitools -> runtime-tools (#585) + * *: Typo fixes and polishing (#556, #566, #568, #569, #571, #572, + #574, #595, #596, #599, #600, #601, #603, #605, #608, #613, #617, + #619, #621, #622, #623, #624, #625, #627, #629) + +Changes with v1.0.0-rc2: + Additions: + + * config-linux: Add new architectures from libseccomp 2.3.0 (#505) + * schema: Add JSON Schema for state JSON and move schema.json to + config-schema.json and similar (#481, #498, #519) + + Minor fixes and documentation: + + * Add compliance language for platforms and architectures (#527) + * Remove "unconditionally compliant" language (#553) + * bundle: Remove distribution references (#487) + * runtime: Fix sub-bullet indentation (#495) + * config: Replace Arch fstab reference with mount(8) (#443) + * config: Synchronize comments between Markdown and Go (#525) + * config: Drop v0.x compatibility statement (#488) + * config-linux: RFC 2119 wording for cgroupsPath (#493) + * config-linux: Make linux.devices and linux.resources.devices + optional (#526) + * config-linux: Extend no-tweak requirement to runtime namespaces (#538) + * schema: Add hook.timeout (#544) + * schema: Add missing '"type": "object"' (#528) + * schema: Run 'make fmt' and remove duplicates (#546, #551) + * schema/config: Make 'hostname' optional (#491) + * schema/config-linux: Add linux.resources.devices (#550) + * specs-go/config: Add Solaris tags to User properties (#496) + * specs-go/config: Make Linux and Solaris omitempty again (#502) + * specs-go/config: Make KernelTCP and ClassID omitempty (#531) + * specs-go/config: Fix "specified" typo for ApparmorProfile (#503) + * Makefile: Remove code-of-conduct.md and version.md when clean (#541) + * implementations: Mention cc-oci-runtime (#539) + * Use filesystem instead of file system (#529) + * .pullapprove: Add DCO check via PullApprove + * GOVERNANCE: Add governance and release process docs (#521) + * README: Change meeting time from 10am to 2pm Pacific (#524) + * README: Update conference-call phone number (#512, #515) + Changes with v1.0.0-rc1: Breaking changes: diff --git a/vendor/github.com/opencontainers/runtime-spec/GOVERNANCE.md b/vendor/github.com/opencontainers/runtime-spec/GOVERNANCE.md new file mode 100644 index 00000000..e5224fbf --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-spec/GOVERNANCE.md @@ -0,0 +1,70 @@ +# Project governance + +The [OCI charter][charter] §5.b.viii tasks an OCI Project's maintainers (listed in the repository's MAINTAINERS file and sometimes referred to as "the TDC", [§5.e][charter]) with: + +> Creating, maintaining and enforcing governance guidelines for the TDC, approved by the maintainers, and which shall be posted visibly for the TDC. + +This section describes generic rules and procedures for fulfilling that mandate. + +## Proposing a motion + +A maintainer SHOULD propose a motion on the dev@opencontainers.org mailing list (except [security issues](#security-issues)) with another maintainer as a co-sponsor. + +## Voting + +Voting on a proposed motion SHOULD happen on the dev@opencontainers.org mailing list (except [security issues](#security-issues)) with maintainers posting LGTM or REJECT. +Maintainers MAY also explicitly not vote by posting ABSTAIN (which is useful to revert a previous vote). +Maintainers MAY post multiple times (e.g. as they revise their position based on feeback), but only their final post counts in the tally. +A proposed motion is adopted if two-thirds of votes cast, a quorum having voted, are in favor of the release. + +Voting SHOULD remain open for a week to collect feedback from the wider community and allow the maintainers to digest the proposed motion. +Under exceptional conditions (e.g. non-major security fix releases) proposals which reach quorum with unanimous support MAY be adopted earlier. + +A maintainer MAY choose to reply with REJECT. +A maintainer posting a REJECT MUST include a list of concerns or links to written documentation for those concerns (e.g. GitHub issues or mailing-list threads). +The maintainers SHOULD try to resolve the concerns and wait for the rejecting maintainer to change their opinion to LGTM. +However, a motion MAY be adopted with REJECTs, as outlined in the previous paragraphs. + +## Quorum + +A quorum is established when at least two-thirds of maintainers have voted. + +For projects that are not specifications, a [motion to release](#release-approval) MAY be adopted if the tally is at least three LGTMs and no REJECTs, even if three votes does not meet the usual two-thirds quorum. + +## Security issues + +Motions with sensitive security implications MUST be proposed on the security@opencontainers.org mailing list instead of dev@opencontainers.org, but should otherwise follow the standard [proposal](#proposing-a-motion) process. +The security@opencontainers.org mailing list includes all members of the TOB. +The TOB will contact the project maintainers and provide a channel for discussing and voting on the motion, but voting will otherwise follow the standard [voting](#voting) and [quorum](#quorum) rules. +The TOB and project maintainers will work together to notify affected parties before making an adopted motion public. + +## Amendments + +The [project governance](#project-governance) rules and procedures MAY be amended or replaced using the procedures themselves. +The MAINTAINERS of this project governance document is the total set of MAINTAINERS from all Open Containers projects (runC, runtime-spec, and image-spec). + +## Subject templates + +Maintainers are busy and get lots of email. +To make project proposals recognizable, proposed motions SHOULD use the following subject templates. + +### Proposing a motion + +> [{project} VOTE]: {motion description} (closes {end of voting window}) + +For example: + +> [runtime-spec VOTE]: Tag 0647920 as 1.0.0-rc (closes 2016-06-03 20:00 UTC) + +### Tallying results + +After voting closes, a maintainer SHOULD post a tally to the motion thread with a subject template like: + +> [{project} {status}]: {motion description} (+{LGTMs} -{REJECTs} #{ABSTAINs}) + +Where `{status}` is either `adopted` or `rejected`. +For example: + +> [runtime-spec adopted]: Tag 0647920 as 1.0.0-rc (+6 -0 #3) + +[charter]: https://www.opencontainers.org/about/governance diff --git a/vendor/github.com/opencontainers/runtime-spec/Makefile b/vendor/github.com/opencontainers/runtime-spec/Makefile index a35e2fac..1d540182 100644 --- a/vendor/github.com/opencontainers/runtime-spec/Makefile +++ b/vendor/github.com/opencontainers/runtime-spec/Makefile @@ -1,8 +1,7 @@ EPOCH_TEST_COMMIT := 78e6667ae2d67aad100b28ee9580b41b7a24e667 -OUTPUT_DIRNAME ?= output/ +OUTPUT_DIRNAME ?= output DOC_FILENAME ?= oci-runtime-spec -SHELL ?= $(shell command -v bash 2>/dev/null) DOCKER ?= $(shell command -v docker 2>/dev/null) PANDOC ?= $(shell command -v pandoc 2>/dev/null) ifeq "$(strip $(PANDOC))" '' @@ -22,13 +21,8 @@ endif # These docs are in an order that determines how they show up in the PDF/HTML docs. DOC_FILES := \ version.md \ - README.md \ - code-of-conduct.md \ + spec.md \ principles.md \ - style.md \ - ROADMAP.md \ - implementations.md \ - project.md \ bundle.md \ runtime.md \ runtime-linux.md \ @@ -55,28 +49,23 @@ $(OUTPUT_DIRNAME)/$(DOC_FILENAME).html: $(DOC_FILES) $(PANDOC) -f markdown_github -t html5 -o $(PANDOC_DST)$@ $(patsubst %,$(PANDOC_SRC)%,$(DOC_FILES)) endif -code-of-conduct.md: - curl -o $@ https://raw.githubusercontent.com/opencontainers/tob/d2f9d68c1332870e40693fe077d311e0742bc73d/code-of-conduct.md - version.md: ./specs-go/version.go go run ./.tool/version-doc.go > $@ HOST_GOLANG_VERSION = $(shell go version | cut -d ' ' -f3 | cut -c 3-) # this variable is used like a function. First arg is the minimum version, Second arg is the version to be checked. -ALLOWED_GO_VERSION = $(shell test '$(shell /bin/echo -e "$(1)\n$(2)" | sort -V | head -n1)' == '$(1)' && echo 'true') +ALLOWED_GO_VERSION = $(shell test '$(shell /bin/echo -e "$(1)\n$(2)" | sort -V | head -n1)' = '$(1)' && echo 'true') .PHONY: test .govet .golint .gitvalidation test: .govet .golint .gitvalidation -# `go get golang.org/x/tools/cmd/vet` .govet: - @go tool | grep -qw vet || (echo "ERROR: 'go vet' not found. Consider 'make install.tools' target" && false) go vet -x ./... # `go get github.com/golang/lint/golint` .golint: -ifeq ($(call ALLOWED_GO_VERSION,1.5,$(HOST_GOLANG_VERSION)),true) +ifeq ($(call ALLOWED_GO_VERSION,1.6,$(HOST_GOLANG_VERSION)),true) @which golint > /dev/null 2>/dev/null || (echo "ERROR: golint not found. Consider 'make install.tools' target" && false) golint ./... endif @@ -85,7 +74,7 @@ endif # When this is running in travis, it will only check the travis commit range .gitvalidation: @which git-validation > /dev/null 2>/dev/null || (echo "ERROR: git-validation not found. Consider 'make install.tools' target" && false) -ifeq ($(TRAVIS),true) +ifdef TRAVIS_COMMIT_RANGE git-validation -q -run DCO,short-subject,dangling-whitespace else git-validation -v -run DCO,short-subject,dangling-whitespace -range $(EPOCH_TEST_COMMIT)..HEAD @@ -93,25 +82,20 @@ endif .PHONY: install.tools -install.tools: .install.golint .install.govet .install.gitvalidation +install.tools: .install.golint .install.gitvalidation -# golint does not even build for =go1.5, so no need to get it. -.install.govet: -ifeq ($(call ALLOWED_GO_VERSION,1.5,$(HOST_GOLANG_VERSION)),true) - go get golang.org/x/tools/cmd/vet +ifeq ($(call ALLOWED_GO_VERSION,1.6,$(HOST_GOLANG_VERSION)),true) + go get -u github.com/golang/lint/golint endif .install.gitvalidation: - go get github.com/vbatts/git-validation + go get -u github.com/vbatts/git-validation .PHONY: clean clean: rm -rf $(OUTPUT_DIRNAME) *~ + rm -f version.md diff --git a/vendor/github.com/opencontainers/runtime-spec/README.md b/vendor/github.com/opencontainers/runtime-spec/README.md index 6835d82c..6da5f6de 100644 --- a/vendor/github.com/opencontainers/runtime-spec/README.md +++ b/vendor/github.com/opencontainers/runtime-spec/README.md @@ -1,68 +1,53 @@ -# Open Container Runtime Specification +# Open Container Initiative Runtime Specification -The [Open Container Initiative](http://www.opencontainers.org/) develops specifications for standards on Operating System process and application containers. +The [Open Container Initiative][oci] develops specifications for standards on Operating System process and application containers. +The specification can be found [here](spec.md). -Table of Contents +## Table of Contents -- [Introduction](README.md) - - [Code of Conduct](#code-of-conduct) - - [Container Principles](principles.md) - - [Style and Conventions](style.md) - - [Roadmap](ROADMAP.md) - - [Implementations](implementations.md) - - [project](project.md) -- [Filesystem Bundle](bundle.md) -- Runtime and Lifecycle - - [General Runtime and Lifecycle](runtime.md) - - [Linux-specific Runtime and Lifecycle](runtime-linux.md) -- Configuration - - [General Configuration](config.md) - - [Linux-specific Configuration](config-linux.md) - - [Solaris-specific Configuration](config-solaris.md) -- [Glossary](glossary.md) +Additional documentation about how this group operates: -In the specifications in the above table of contents, the keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" are to be interpreted as described in [RFC 2119](http://tools.ietf.org/html/rfc2119) (Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, March 1997). +- [Code of Conduct][code-of-conduct] +- [Style and Conventions](style.md) +- [Roadmap](ROADMAP.md) +- [Implementations](implementations.md) +- [Releases](RELEASES.md) +- [project](project.md) +- [charter][charter] -An implementation is not compliant if it fails to satisfy one or more of the MUST or REQUIRED requirements for the protocols it implements. -An implementation that satisfies all the MUST or REQUIRED and all the SHOULD requirements for its protocols is said to be "unconditionally compliant". - -# Use Cases +## Use Cases To provide context for users the following section gives example use cases for each part of the spec. -#### Application Bundle Builders +### Application Bundle Builders Application bundle builders can create a [bundle](bundle.md) directory that includes all of the files required for launching an application as a container. -The bundle contains an OCI [configuration file](config.md) where the builder can specify host-independent details such as [which executable to launch](config.md#process-configuration) and host-specific settings such as [mount](config.md#mounts) locations, [hook](config.md#hooks) paths, Linux [namespaces](config-linux.md#namespaces) and [cgroups](config-linux.md#control-groups). +The bundle contains an OCI [configuration file](config.md) where the builder can specify host-independent details such as [which executable to launch](config.md#process) and host-specific settings such as [mount](config.md#mounts) locations, [hook](config.md#hooks) paths, Linux [namespaces](config-linux.md#namespaces) and [cgroups](config-linux.md#control-groups). Because the configuration includes host-specific settings, application bundle directories copied between two hosts may require configuration adjustments. -#### Hook Developers +### Hook Developers [Hook](config.md#hooks) developers can extend the functionality of an OCI-compliant runtime by hooking into a container's lifecycle with an external application. Example use cases include sophisticated network configuration, volume garbage collection, etc. -#### Runtime Developers +### Runtime Developers Runtime developers can build runtime implementations that run OCI-compliant bundles and container configuration, containing low-level OS and host specific details, on a particular platform. -# Releases +## Releases There is a loose [Road Map](./ROADMAP.md). During the `0.x` series of OCI releases we make no backwards compatibility guarantees and intend to break the schema during this series. -# Contributing +## Contributing Development happens on GitHub for the spec. Issues are used for bugs and actionable items and longer discussions can happen on the [mailing list](#mailing-list). The specification and code is licensed under the Apache 2.0 license found in the [LICENSE](./LICENSE) file. -## Code of Conduct - -Participation in the OpenContainers community is governed by [OpenContainer's Code of Conduct](https://github.com/opencontainers/tob/blob/d2f9d68c1332870e40693fe077d311e0742bc73d/code-of-conduct.md). - -## Discuss your design +### Discuss your design The project welcomes submissions, but please let everyone know what you are working on. @@ -73,27 +58,27 @@ It also guarantees that the design is sound before code is written; a GitHub pul Typos and grammatical errors can go straight to a pull-request. When in doubt, start on the [mailing-list](#mailing-list). -## Weekly Call +### Weekly Call -The contributors and maintainers of all OCI projects have a weekly meeting Wednesdays at 10:00 AM (USA Pacific.) -Everyone is welcome to participate via [UberConference web][UberConference] or audio-only: 415-968-0849 (no PIN needed.) +The contributors and maintainers of all OCI projects have a weekly meeting Wednesdays at 2:00 PM (USA Pacific). +Everyone is welcome to participate via [UberConference web][uberconference] or audio-only: 415-968-0849 (no PIN needed.) An initial agenda will be posted to the [mailing list](#mailing-list) earlier in the week, and everyone is welcome to propose additional topics or suggest other agenda alterations there. -Minutes are posted to the [mailing list](#mailing-list) and minutes from past calls are archived to the [wiki](https://github.com/opencontainers/runtime-spec/wiki) for those who are unable to join the call. +Minutes are posted to the [mailing list](#mailing-list) and minutes from past calls are archived to the [wiki][runtime-wiki]. -## Mailing List +### Mailing List -You can subscribe and join the mailing list on [Google Groups](https://groups.google.com/a/opencontainers.org/forum/#!forum/dev). +You can subscribe and join the mailing list on [Google Groups][dev-list]. -## IRC +### IRC OCI discussion happens on #opencontainers on Freenode ([logs][irc-logs]). -## Git commit +### Git commit -### Sign your work +#### Sign your work The sign-off is a simple line at the end of the explanation for the patch, which certifies that you wrote it or otherwise have the right to pass it on as an open-source patch. -The rules are pretty simple: if you can certify the below (from [developercertificate.org](http://developercertificate.org/)): +The rules are pretty simple: if you can certify the below (from http://developercertificate.org): ``` Developer Certificate of Origin @@ -142,10 +127,10 @@ using your real name (sorry, no pseudonyms or anonymous contributions.) You can add the sign off when creating the git commit via `git commit -s`. -### Commit Style +#### Commit Style Simple house-keeping for clean git history. -Read more on [How to Write a Git Commit Message](http://chris.beams.io/posts/git-commit/) or the Discussion section of [`git-commit(1)`](http://git-scm.com/docs/git-commit). +Read more on [How to Write a Git Commit Message][how-to-git-commit] or the Discussion section of [git-commit(1)][git-commit.1]. 1. Separate the subject from body with a blank line 2. Limit the subject line to 50 characters @@ -157,5 +142,14 @@ Read more on [How to Write a Git Commit Message](http://chris.beams.io/posts/git * If there was important/useful/essential conversation or information, copy or include a reference 8. When possible, one keyword to scope the change in the subject (i.e. "README: ...", "runtime: ...") -[UberConference]: https://www.uberconference.com/opencontainers + +[charter]: https://www.opencontainers.org/about/governance +[code-of-conduct]: https://github.com/opencontainers/tob/blob/master/code-of-conduct.md +[dev-list]: https://groups.google.com/a/opencontainers.org/forum/#!forum/dev +[how-to-git-commit]: http://chris.beams.io/posts/git-commit [irc-logs]: http://ircbot.wl.linuxfoundation.org/eavesdrop/%23opencontainers/ +[oci]: https://www.opencontainers.org +[runtime-wiki]: https://github.com/opencontainers/runtime-spec/wiki +[uberconference]: https://www.uberconference.com/opencontainers + +[git-commit.1]: http://git-scm.com/docs/git-commit diff --git a/vendor/github.com/opencontainers/runtime-spec/RELEASES.md b/vendor/github.com/opencontainers/runtime-spec/RELEASES.md new file mode 100644 index 00000000..e220042c --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-spec/RELEASES.md @@ -0,0 +1,51 @@ +# Releases + +The release process hopes to encourage early, consistent consensus-building during project development. +The mechanisms used are regular community communication on the mailing list about progress, scheduled meetings for issue resolution and release triage, and regularly paced and communicated releases. +Releases are proposed and adopted or rejected using the usual [project governance](GOVERNANCE.md) rules and procedures. + +An anti-pattern that we want to avoid is heavy development or discussions "late cycle" around major releases. +We want to build a community that is involved and communicates consistently through all releases instead of relying on "silent periods" as a judge of stability. + +## Parallel releases + +A single project MAY consider several motions to release in parallel. +However each motion to release after the initial 0.1.0 MUST be based on a previous release that has already landed. + +For example, runtime-spec maintainers may propose a v1.0.0-rc2 on the 1st of the month and a v0.9.1 bugfix on the 2nd of the month. +They may not propose a v1.0.0-rc3 until the v1.0.0-rc2 is accepted (on the 7th if the vote initiated on the 1st passes). + +## Specifications + +The OCI maintains three categories of projects: specifications, applications, and conformance-testing tools. +However, specification releases have special restrictions in the [OCI charter][charter]: + +* They are the target of backwards compatibility (§7.g), and +* They are subject to the OFWa patent grant (§8.d and e). + +To avoid unfortunate side effects (onerous backwards compatibity requirements or Member resignations), the following additional procedures apply to specification releases: + +### Planning a release + +Every OCI specification project SHOULD hold meetings that involve maintainers reviewing pull requests, debating outstanding issues, and planning releases. +This meeting MUST be advertised on the project README and MAY happen on a phone call, video conference, or on IRC. +Maintainers MUST send updates to the dev@opencontainers.org with results of these meetings. + +Before the specification reaches v1.0.0, the meetings SHOULD be weekly. +Once a specification has reached v1.0.0, the maintainers may alter the cadence, but a meeting MUST be held within four weeks of the previous meeting. + +The release plans, corresponding milestones and estimated due dates MUST be published on GitHub (e.g. https://github.com/opencontainers/runtime-spec/milestones). +GitHub milestones and issues are only used for community organization and all releases MUST follow the [project governance](GOVERNANCE.md) rules and procedures. + +### Timelines + +Specifications have a variety of different timelines in their lifecycle. + +* Pre-v1.0.0 specifications SHOULD release on a monthly cadence to garner feedback. +* Major specification releases MUST release at least three release candidates spaced a minimum of one week apart. + This means a major release like a v1.0.0 or v2.0.0 release will take 1 month at minimum: one week for rc1, one week for rc2, one week for rc3, and one week for the major release itself. + Maintainers SHOULD strive to make zero breaking changes during this cycle of release candidates and SHOULD restart the three-candidate count when a breaking change is introduced. + For example if a breaking change is introduced in v1.0.0-rc2 then the series would end with v1.0.0-rc4 and v1.0.0. +- Minor and patch releases SHOULD be made on an as-needed basis. + +[charter]: https://www.opencontainers.org/about/governance diff --git a/vendor/github.com/opencontainers/runtime-spec/ROADMAP.md b/vendor/github.com/opencontainers/runtime-spec/ROADMAP.md index 89e5a499..6199b9b8 100644 --- a/vendor/github.com/opencontainers/runtime-spec/ROADMAP.md +++ b/vendor/github.com/opencontainers/runtime-spec/ROADMAP.md @@ -6,7 +6,7 @@ The items in the 1.0 roadmap can be broken down into smaller milestones that are The topics below are broad and small working groups will be needed for each to define scope and requirements or if the feature is required at all for the OCI level. Topics listed in the roadmap do not mean that they will be implemented or added but are areas that need discussion to see if they fit in to the goals of the OCI. -Listed topics may defer to the [project wiki](https://github.com/opencontainers/runtime-spec/wiki/RoadMap:) for collaboration. +Listed topics may defer to the [project wiki][runtime-wiki] for collaboration. ## 1.0 @@ -18,14 +18,6 @@ Could be solved by lifecycle/ops and create/start split discussions *Owner:* vishh & duglin -### Live Container Updates - -Should we allow dynamic container updates to runtime options? - -Proposal: make it an optional feature - -*Owner:* hqhq (was vishh) robdolinms, bcorrie - ### Version Schema Decide on a robust versioning schema for the spec as it evolves. @@ -40,9 +32,9 @@ Ensure that the base configuration format is viable for various platforms. Systems: +* Linux * Solaris * Windows -* Linux *Owner:* robdolinms as lead coordinator @@ -53,3 +45,6 @@ Ensure that we have lifecycle hooks in the correct places with full coverage ove Will probably go away with Vish's work on splitting create and start, and if we have exec. *Owner:* + + +[runtime-wiki]: https://github.com/opencontainers/runtime-spec/wiki/RoadMap diff --git a/vendor/github.com/opencontainers/runtime-spec/bundle.md b/vendor/github.com/opencontainers/runtime-spec/bundle.md index d77db89b..d0fd1259 100644 --- a/vendor/github.com/opencontainers/runtime-spec/bundle.md +++ b/vendor/github.com/opencontainers/runtime-spec/bundle.md @@ -1,22 +1,24 @@ -# Filesystem Bundle +# Filesystem Bundle -## Container Format +## Container Format This section defines a format for encoding a container as a *filesystem bundle* - a set of files organized in a certain way, and containing all the necessary data and metadata for any compliant runtime to perform all standard operations against it. -See also [OS X application bundles](http://en.wikipedia.org/wiki/Bundle_%28OS_X%29) for a similar use of the term *bundle*. +See also [MacOS application bundles][macos_bundle] for a similar use of the term *bundle*. -The definition of a bundle is only concerned with how a container, and its configuration data, are stored on a local file system so that it can be consumed by a compliant runtime. +The definition of a bundle is only concerned with how a container, and its configuration data, are stored on a local filesystem so that it can be consumed by a compliant runtime. A Standard Container bundle contains all the information needed to load and run a container. This MUST include the following artifacts: -1. `config.json` : contains configuration data. +1. `config.json`: contains configuration data. This REQUIRED file MUST reside in the root of the bundle directory and MUST be named `config.json`. See [`config.json`](config.md) for more details. -2. A directory representing the root filesystem of the container. +2. A directory representing the root filesystem of the container. While the name of this REQUIRED directory may be arbitrary, users should consider using a conventional name, such as `rootfs`. This directory MUST be referenced from within the `config.json` file. While these artifacts MUST all be present in a single directory on the local filesystem, that directory itself is not part of the bundle. In other words, a tar archive of a *bundle* will have these artifacts at the root of the archive, not nested within a top-level directory. + +[macos_bundle]: https://en.wikipedia.org/wiki/Bundle_%28macOS%29 diff --git a/vendor/github.com/opencontainers/runtime-spec/config-linux.md b/vendor/github.com/opencontainers/runtime-spec/config-linux.md index b206fa04..8f5f70a3 100644 --- a/vendor/github.com/opencontainers/runtime-spec/config-linux.md +++ b/vendor/github.com/opencontainers/runtime-spec/config-linux.md @@ -1,32 +1,32 @@ -# Linux-specific Container Configuration +# Linux Container Configuration This document describes the schema for the [Linux-specific section](config.md#platform-specific-configuration) of the [container configuration](config.md). -The Linux container specification uses various kernel features like namespaces, cgroups, capabilities, LSM, and file system jails to fulfill the spec. +The Linux container specification uses various kernel features like namespaces, cgroups, capabilities, LSM, and filesystem jails to fulfill the spec. -## Default File Systems +## Default Filesystems The Linux ABI includes both syscalls and several special file paths. -Applications expecting a Linux environment will very likely expect these files paths to be setup correctly. +Applications expecting a Linux environment will very likely expect these file paths to be setup correctly. -The following filesystems MUST be made available in each application's filesystem +The following filesystems SHOULD be made available in each container's filesystem: -| Path | Type | +| Path | Type | | -------- | ------ | -| /proc | [procfs](https://www.kernel.org/doc/Documentation/filesystems/proc.txt) | -| /sys | [sysfs](https://www.kernel.org/doc/Documentation/filesystems/sysfs.txt) | -| /dev/pts | [devpts](https://www.kernel.org/doc/Documentation/filesystems/devpts.txt) | -| /dev/shm | [tmpfs](https://www.kernel.org/doc/Documentation/filesystems/tmpfs.txt) | +| /proc | [procfs][procfs] | +| /sys | [sysfs][sysfs] | +| /dev/pts | [devpts][devpts] | +| /dev/shm | [tmpfs][tmpfs] | -## Namespaces +## Namespaces A namespace wraps a global system resource in an abstraction that makes it appear to the processes within the namespace that they have their own isolated instance of the global resource. Changes to the global resource are visible to other processes that are members of the namespace, but are invisible to other processes. -For more information, see [the man page](http://man7.org/linux/man-pages/man7/namespaces.7.html). +For more information, see the [namespaces(7)][namespaces.7_2] man page. Namespaces are specified as an array of entries inside the `namespaces` root field. The following parameters can be specified to setup namespaces: -* **`type`** *(string, required)* - namespace type. The following namespaces types are supported: +* **`type`** *(string, REQUIRED)* - namespace type. The following namespace types are supported: * **`pid`** processes inside the container will only be able to see other processes inside the same container. * **`network`** the container will have its own network stack. * **`mount`** the container will have an isolated mount table. @@ -35,10 +35,11 @@ The following parameters can be specified to setup namespaces: * **`user`** the container will be able to remap user and group IDs from the host to local users and groups within the container. * **`cgroup`** the container will have an isolated view of the cgroup hierarchy. -* **`path`** *(string, optional)* - path to namespace file in the [runtime mount namespace](glossary.md#runtime-namespace) +* **`path`** *(string, OPTIONAL)* - path to namespace file in the [runtime mount namespace](glossary.md#runtime-namespace) If a path is specified, that particular file is used to join that type of namespace. -Also, when a path is specified, a runtime MUST assume that the setup for that particular namespace has already been done and error out if the config specifies anything else related to that namespace. +If a namespace type is not specified in the `namespaces` array, the container MUST inherit the [runtime namespace](glossary.md#runtime-namespace) of that type. +If a `namespaces` field contains duplicated namespaces with same `type`, the runtime MUST error out. ###### Example @@ -70,7 +71,19 @@ Also, when a path is specified, a runtime MUST assume that the setup for that pa ] ``` -## User namespace mappings +## User namespace mappings + +**`uidMappings`** (array of objects, OPTIONAL) describes the user namespace uid mappings from the host to the container. +**`gidMappings`** (array of objects, OPTIONAL) describes the user namespace gid mappings from the host to the container. + +Each entry has the following structure: + +* **`hostID`** *(uint32, REQUIRED)* - is the starting uid/gid on the host to be mapped to *containerID*. +* **`containerID`** *(uint32, REQUIRED)* - is the starting uid/gid in the container. +* **`size`** *(uint32, REQUIRED)* - is the number of ids to be mapped. + +The runtime SHOULD NOT modify the ownership of referenced filesystems to realize the mapping. +Note that the number of mapping entries MAY be limited by the [kernel][user-namespaces]. ###### Example @@ -79,38 +92,36 @@ Also, when a path is specified, a runtime MUST assume that the setup for that pa { "hostID": 1000, "containerID": 0, - "size": 10 + "size": 32000 } ], "gidMappings": [ { "hostID": 1000, "containerID": 0, - "size": 10 + "size": 32000 } ] ``` -uid/gid mappings describe the user namespace mappings from the host to the container. -The runtime SHOULD NOT modify the ownership of referenced filesystems to realize the mapping. -*hostID* is the starting uid/gid on the host to be mapped to *containerID* which is the starting uid/gid in the container and *size* refers to the number of ids to be mapped. -There is a limit of 5 mappings which is the Linux kernel hard limit. +## Devices -## Devices - -`devices` is an array specifying the list of devices that MUST be available in the container. +**`devices`** (array of objects, OPTIONAL) lists devices that MUST be available in the container. The runtime may supply them however it likes (with [mknod][mknod.2], by bind mounting from the runtime mount namespace, etc.). -The following parameters can be specified: +Each entry has the following structure: -* **`type`** *(string, required)* - type of device: `c`, `b`, `u` or `p`. +* **`type`** *(string, REQUIRED)* - type of device: `c`, `b`, `u` or `p`. More info in [mknod(1)][mknod.1]. -* **`path`** *(string, required)* - full path to device inside container. -* **`major, minor`** *(int64, required unless **`type`** is `p`)* - [major, minor numbers][devices] for the device. -* **`fileMode`** *(uint32, optional)* - file mode for the device. +* **`path`** *(string, REQUIRED)* - full path to device inside container. + If a [file][file.1] already exists at `path` that does not match the requested device, the runtime MUST generate an error. +* **`major, minor`** *(int64, REQUIRED unless `type` is `p`)* - [major, minor numbers][devices] for the device. +* **`fileMode`** *(uint32, OPTIONAL)* - file mode for the device. You can also control access to devices [with cgroups](#device-whitelist). -* **`uid`** *(uint32, optional)* - id of device owner. -* **`gid`** *(uint32, optional)* - id of device group. +* **`uid`** *(uint32, OPTIONAL)* - id of device owner. +* **`gid`** *(uint32, OPTIONAL)* - id of device group. + +The same `type`, `major` and `minor` SHOULD NOT be used for multiple devices. ###### Example @@ -137,7 +148,7 @@ The following parameters can be specified: ] ``` -###### Default Devices +###### Default Devices In addition to any devices configured with this setting, the runtime MUST also supply: @@ -147,49 +158,68 @@ In addition to any devices configured with this setting, the runtime MUST also s * [`/dev/random`][random.4] * [`/dev/urandom`][random.4] * [`/dev/tty`][tty.4] -* [`/dev/console`][console.4] +* [`/dev/console`][console.4] is setup if terminal is enabled in the config by bind mounting the pseudoterminal slave to /dev/console. * [`/dev/ptmx`][pts.4]. A [bind-mount or symlink of the container's `/dev/pts/ptmx`][devpts]. -## Control groups +## Control groups Also known as cgroups, they are used to restrict resource usage for a container and handle device access. -cgroups provide controls to restrict cpu, memory, IO, pids and network for the container. +cgroups provide controls (through controllers) to restrict cpu, memory, IO, pids and network for the container. For more information, see the [kernel cgroups documentation][cgroup-v1]. The path to the cgroups can be specified in the Spec via `cgroupsPath`. -`cgroupsPath` is expected to be relative to the cgroups mount point. -If `cgroupsPath` is not specified, implementations can define the default cgroup path. +`cgroupsPath` can be used to either control the cgroup hierarchy for containers or to run a new process in an existing container. +If `cgroupsPath` is: +* ... an absolute path (starting with `/`), the runtime MUST take the path to be relative to the cgroup mount point. +* ... a relative path (not starting with `/`), the runtime MAY interpret the path relative to a runtime-determined location in the cgroup hierarchy. +* ... not specified, the runtime MAY define the default cgroup path. +Runtimes MAY consider certain `cgroupsPath` values to be invalid, and MUST generate an error if this is the case. +If a `cgroupsPath` value is specified, the runtime MUST consistently attach to the same place in the cgroup hierarchy given the same value of `cgroupsPath`. + Implementations of the Spec can choose to name cgroups in any manner. The Spec does not include naming schema for cgroups. -The Spec does not support [split hierarchy][cgroup-v2]. +The Spec does not support per-controller paths for the reasons discussed in the [cgroupv2 documentation][cgroup-v2]. The cgroups will be created if they don't exist. -###### Example - -```json - "cgroupsPath": "/myRuntime/myContainer" -``` - -`cgroupsPath` can be used to either control the cgroups hierarchy for containers or to run a new process in an existing container. - You can configure a container's cgroups via the `resources` field of the Linux configuration. Do not specify `resources` unless limits have to be updated. For example, to run a new process in an existing container without updating limits, `resources` need not be specified. -#### Device whitelist +A runtime MUST at least use the minimum set of cgroup controllers required to fulfill the `resources` settings. +However, a runtime MAY attach the container process to additional cgroup controllers supported by the system. -`devices` is an array of entries to control the [device whitelist][cgroup-v1-devices]. +###### Example + +```json + "cgroupsPath": "/myRuntime/myContainer", + "resources": { + "memory": { + "limit": 100000, + "reservation": 200000 + }, + "devices": [ + { + "allow": false, + "access": "rwm" + } + ] + } +``` + +#### Device whitelist + +**`devices`** (array of objects, OPTIONAL) configures the [device whitelist][cgroup-v1-devices]. The runtime MUST apply entries in the listed order. -The following parameters can be specified: +Each entry has the following structure: -* **`allow`** *(boolean, required)* - whether the entry is allowed or denied. -* **`type`** *(string, optional)* - type of device: `a` (all), `c` (char), or `b` (block). +* **`allow`** *(boolean, REQUIRED)* - whether the entry is allowed or denied. +* **`type`** *(string, OPTIONAL)* - type of device: `a` (all), `c` (char), or `b` (block). `null` or unset values mean "all", mapping to `a`. -* **`major, minor`** *(int64, optional)* - [major, minor numbers][devices] for the device. +* **`major, minor`** *(int64, OPTIONAL)* - [major, minor numbers][devices] for the device. `null` or unset values mean "all", mapping to [`*` in the filesystem API][cgroup-v1-devices]. -* **`access`** *(string, optional)* - cgroup permissions for device. +* **`access`** *(string, OPTIONAL)* - cgroup permissions for device. A composition of `r` (read), `w` (write), and `m` (mknod). ###### Example @@ -217,7 +247,7 @@ The following parameters can be specified: ] ``` -#### Disable out-of-memory killer +#### Disable out-of-memory killer `disableOOMKiller` contains a boolean (`true` or `false`) that enables or disables the Out of Memory killer for a cgroup. If enabled (`false`), tasks that attempt to consume more memory than they are allowed are immediately killed by the OOM killer. @@ -225,7 +255,7 @@ The OOM killer is enabled by default in every cgroup using the `memory` subsyste To disable it, specify a value of `true`. For more information, see [the memory cgroup man page][cgroup-v1-memory]. -* **`disableOOMKiller`** *(bool, optional)* - enables or disables the OOM killer +* **`disableOOMKiller`** *(bool, OPTIONAL)* - enables or disables the OOM killer ###### Example @@ -233,14 +263,14 @@ For more information, see [the memory cgroup man page][cgroup-v1-memory]. "disableOOMKiller": false ``` -#### Set oom_score_adj +#### Set oom_score_adj `oomScoreAdj` sets heuristic regarding how the process is evaluated by the kernel during memory pressure. -For more information, see [the proc filesystem documentation section 3.1](https://www.kernel.org/doc/Documentation/filesystems/proc.txt). +For more information, see [the proc filesystem documentation section 3.1][procfs]. This is a kernel/system level setting, where as `disableOOMKiller` is scoped for a memory cgroup. For more information on how these two settings work together, see [the memory cgroup documentation section 10. OOM Contol][cgroup-v1-memory]. -* **`oomScoreAdj`** *(int, optional)* - adjust the oom-killer score +* **`oomScoreAdj`** *(int, OPTIONAL)* - adjust the oom-killer score ###### Example @@ -248,24 +278,24 @@ For more information on how these two settings work together, see [the memory cg "oomScoreAdj": 100 ``` -#### Memory +#### Memory -`memory` represents the cgroup subsystem `memory` and it's used to set limits on the container's memory usage. +**`memory`** (object, OPTIONAL) represents the cgroup subsystem `memory` and it's used to set limits on the container's memory usage. For more information, see [the memory cgroup man page][cgroup-v1-memory]. The following parameters can be specified to setup the controller: -* **`limit`** *(uint64, optional)* - sets limit of memory usage in bytes +* **`limit`** *(uint64, OPTIONAL)* - sets limit of memory usage in bytes -* **`reservation`** *(uint64, optional)* - sets soft limit of memory usage in bytes +* **`reservation`** *(uint64, OPTIONAL)* - sets soft limit of memory usage in bytes -* **`swap`** *(uint64, optional)* - sets limit of memory+Swap usage +* **`swap`** *(uint64, OPTIONAL)* - sets limit of memory+Swap usage -* **`kernel`** *(uint64, optional)* - sets hard limit for kernel memory +* **`kernel`** *(uint64, OPTIONAL)* - sets hard limit for kernel memory -* **`kernelTCP`** *(uint64, optional)* - sets hard limit in bytes for kernel TCP buffer memory +* **`kernelTCP`** *(uint64, OPTIONAL)* - sets hard limit in bytes for kernel TCP buffer memory -* **`swappiness`** *(uint64, optional)* - sets swappiness parameter of vmscan (See sysctl's vm.swappiness) +* **`swappiness`** *(uint64, OPTIONAL)* - sets swappiness parameter of vmscan (See sysctl's vm.swappiness) ###### Example @@ -280,26 +310,26 @@ The following parameters can be specified to setup the controller: } ``` -#### CPU +#### CPU -`cpu` represents the cgroup subsystems `cpu` and `cpusets`. +**`cpu`** (object, OPTIONAL) represents the cgroup subsystems `cpu` and `cpusets`. For more information, see [the cpusets cgroup man page][cgroup-v1-cpusets]. The following parameters can be specified to setup the controller: -* **`shares`** *(uint64, optional)* - specifies a relative share of CPU time available to the tasks in a cgroup +* **`shares`** *(uint64, OPTIONAL)* - specifies a relative share of CPU time available to the tasks in a cgroup -* **`quota`** *(uint64, optional)* - specifies the total amount of time in microseconds for which all tasks in a cgroup can run during one period (as defined by **`period`** below) +* **`quota`** *(int64, OPTIONAL)* - specifies the total amount of time in microseconds for which all tasks in a cgroup can run during one period (as defined by **`period`** below) -* **`period`** *(uint64, optional)* - specifies a period of time in microseconds for how regularly a cgroup's access to CPU resources should be reallocated (CFS scheduler only) +* **`period`** *(uint64, OPTIONAL)* - specifies a period of time in microseconds for how regularly a cgroup's access to CPU resources should be reallocated (CFS scheduler only) -* **`realtimeRuntime`** *(uint64, optional)* - specifies a period of time in microseconds for the longest continuous period in which the tasks in a cgroup have access to CPU resources +* **`realtimeRuntime`** *(int64, OPTIONAL)* - specifies a period of time in microseconds for the longest continuous period in which the tasks in a cgroup have access to CPU resources -* **`realtimePeriod`** *(uint64, optional)* - same as **`period`** but applies to realtime scheduler only +* **`realtimePeriod`** *(uint64, OPTIONAL)* - same as **`period`** but applies to realtime scheduler only -* **`cpus`** *(string, optional)* - list of CPUs the container will run in +* **`cpus`** *(string, OPTIONAL)* - list of CPUs the container will run in -* **`mems`** *(string, optional)* - list of Memory Nodes the container will run in +* **`mems`** *(string, OPTIONAL)* - list of Memory Nodes the container will run in ###### Example @@ -315,27 +345,28 @@ The following parameters can be specified to setup the controller: } ``` -#### Block IO Controller +#### Block IO -`blockIO` represents the cgroup subsystem `blkio` which implements the block io controller. +**`blockIO`** (object, OPTIONAL) represents the cgroup subsystem `blkio` which implements the block IO controller. For more information, see [the kernel cgroups documentation about blkio][cgroup-v1-blkio]. The following parameters can be specified to setup the controller: -* **`blkioWeight`** *(uint16, optional)* - specifies per-cgroup weight. This is default weight of the group on all devices until and unless overridden by per-device rules. The range is from 10 to 1000. +* **`blkioWeight`** *(uint16, OPTIONAL)* - specifies per-cgroup weight. This is default weight of the group on all devices until and unless overridden by per-device rules. The range is from 10 to 1000. -* **`blkioLeafWeight`** *(uint16, optional)* - equivalents of `blkioWeight` for the purpose of deciding how much weight tasks in the given cgroup has while competing with the cgroup's child cgroups. The range is from 10 to 1000. +* **`blkioLeafWeight`** *(uint16, OPTIONAL)* - equivalents of `blkioWeight` for the purpose of deciding how much weight tasks in the given cgroup has while competing with the cgroup's child cgroups. The range is from 10 to 1000. -* **`blkioWeightDevice`** *(array, optional)* - specifies the list of devices which will be bandwidth rate limited. The following parameters can be specified per-device: - * **`major, minor`** *(int64, required)* - major, minor numbers for device. More info in `man mknod`. - * **`weight`** *(uint16, optional)* - bandwidth rate for the device, range is from 10 to 1000 - * **`leafWeight`** *(uint16, optional)* - bandwidth rate for the device while competing with the cgroup's child cgroups, range is from 10 to 1000, CFQ scheduler only +* **`blkioWeightDevice`** *(array, OPTIONAL)* - specifies the list of devices which will be bandwidth rate limited. The following parameters can be specified per-device: + * **`major, minor`** *(int64, REQUIRED)* - major, minor numbers for device. More info in `man mknod`. + * **`weight`** *(uint16, OPTIONAL)* - bandwidth rate for the device, range is from 10 to 1000 + * **`leafWeight`** *(uint16, OPTIONAL)* - bandwidth rate for the device while competing with the cgroup's child cgroups, range is from 10 to 1000, CFQ scheduler only You must specify at least one of `weight` or `leafWeight` in a given entry, and can specify both. -* **`blkioThrottleReadBpsDevice`**, **`blkioThrottleWriteBpsDevice`**, **`blkioThrottleReadIOPSDevice`**, **`blkioThrottleWriteIOPSDevice`** *(array, optional)* - specify the list of devices which will be IO rate limited. The following parameters can be specified per-device: - * **`major, minor`** *(int64, required)* - major, minor numbers for device. More info in `man mknod`. - * **`rate`** *(uint64, required)* - IO rate limit for the device +* **`blkioThrottleReadBpsDevice`**, **`blkioThrottleWriteBpsDevice`**, **`blkioThrottleReadIOPSDevice`**, **`blkioThrottleWriteIOPSDevice`** *(array, OPTIONAL)* - specify the list of devices which will be IO rate limited. + The following parameters can be specified per-device: + * **`major, minor`** *(int64, REQUIRED)* - major, minor numbers for device. More info in `man mknod`. + * **`rate`** *(uint64, REQUIRED)* - IO rate limit for the device ###### Example @@ -373,17 +404,17 @@ The following parameters can be specified to setup the controller: } ``` -#### Huge page limits +#### Huge page limits -`hugepageLimits` represents the `hugetlb` controller which allows to limit the +**`hugepageLimits`** (array of objects, OPTIONAL) represents the `hugetlb` controller which allows to limit the HugeTLB usage per control group and enforces the controller limit during page fault. For more information, see the [kernel cgroups documentation about HugeTLB][cgroup-v1-hugetlb]. -`hugepageLimits` is an array of entries, each having the following structure: +Each entry has the following structure: -* **`pageSize`** *(string, required)* - hugepage size +* **`pageSize`** *(string, REQUIRED)* - hugepage size -* **`limit`** *(uint64, required)* - limit in bytes of *hugepagesize* HugeTLB usage +* **`limit`** *(uint64, REQUIRED)* - limit in bytes of *hugepagesize* HugeTLB usage ###### Example @@ -391,24 +422,24 @@ For more information, see the [kernel cgroups documentation about HugeTLB][cgrou "hugepageLimits": [ { "pageSize": "2MB", - "limit": 9223372036854771712 + "limit": 209715200 } ] ``` -#### Network +#### Network -`network` represents the cgroup subsystems `net_cls` and `net_prio`. +**`network`** (object, OPTIONAL) represents the cgroup subsystems `net_cls` and `net_prio`. For more information, see [the net\_cls cgroup man page][cgroup-v1-net-cls] and [the net\_prio cgroup man page][cgroup-v1-net-prio]. -The following parameters can be specified to setup these cgroup controllers: +The following parameters can be specified to setup the controller: -* **`classID`** *(uint32, optional)* - is the network class identifier the cgroup's network packets will be tagged with +* **`classID`** *(uint32, OPTIONAL)* - is the network class identifier the cgroup's network packets will be tagged with -* **`priorities`** *(array, optional)* - specifies a list of objects of the priorities assigned to traffic originating from -processes in the group and egressing the system on various interfaces. The following parameters can be specified per-priority: - * **`name`** *(string, required)* - interface name - * **`priority`** *(uint32, required)* - priority applied to the interface +* **`priorities`** *(array, OPTIONAL)* - specifies a list of objects of the priorities assigned to traffic originating from processes in the group and egressing the system on various interfaces. + The following parameters can be specified per-priority: + * **`name`** *(string, REQUIRED)* - interface name + * **`priority`** *(uint32, REQUIRED)* - priority applied to the interface ###### Example @@ -428,14 +459,14 @@ processes in the group and egressing the system on various interfaces. The follo } ``` -#### PIDs +#### PIDs -`pids` represents the cgroup subsystem `pids`. +**`pids`** (object, OPTIONAL) represents the cgroup subsystem `pids`. For more information, see [the pids cgroup man page][cgroup-v1-pids]. The following parameters can be specified to setup the controller: -* **`limit`** *(int64, required)* - specifies the maximum number of tasks in the cgroup +* **`limit`** *(int64, REQUIRED)* - specifies the maximum number of tasks in the cgroup ###### Example @@ -445,10 +476,10 @@ The following parameters can be specified to setup the controller: } ``` -## Sysctl +## Sysctl -`sysctl` allows kernel parameters to be modified at runtime for the container. -For more information, see [the man page](http://man7.org/linux/man-pages/man8/sysctl.8.html) +**`sysctl`** (object, OPTIONAL) allows kernel parameters to be modified at runtime for the container. +For more information, see the [sysctl(8)][sysctl.8] man page. ###### Example @@ -459,13 +490,13 @@ For more information, see [the man page](http://man7.org/linux/man-pages/man8/sy } ``` -## seccomp +## Seccomp Seccomp provides application sandboxing mechanism in the Linux kernel. Seccomp configuration allows one to configure actions to take for matched syscalls and furthermore also allows matching on values passed as arguments to syscalls. -For more information about Seccomp, see [Seccomp kernel documentation](https://www.kernel.org/doc/Documentation/prctl/seccomp_filter.txt) -The actions, architectures, and operators are strings that match the definitions in seccomp.h from [libseccomp](https://github.com/seccomp/libseccomp) and are translated to corresponding values. -A valid list of constants as of libseccomp v2.3.0 is shown below. +For more information about Seccomp, see [Seccomp][seccomp] kernel documentation. +The actions, architectures, and operators are strings that match the definitions in seccomp.h from [libseccomp][] and are translated to corresponding values. +A valid list of constants as of libseccomp v2.3.2 is shown below. Architecture Constants * `SCMP_ARCH_X86` @@ -484,6 +515,8 @@ Architecture Constants * `SCMP_ARCH_PPC64LE` * `SCMP_ARCH_S390` * `SCMP_ARCH_S390X` +* `SCMP_ARCH_PARISC` +* `SCMP_ARCH_PARISC64` Action Constants: * `SCMP_ACT_KILL` @@ -507,22 +540,27 @@ Operator Constants: "seccomp": { "defaultAction": "SCMP_ACT_ALLOW", "architectures": [ - "SCMP_ARCH_X86" + "SCMP_ARCH_X86", + "SCMP_ARCH_X32" ], "syscalls": [ { - "name": "getcwd", - "action": "SCMP_ACT_ERRNO" + "names": [ + "getcwd", + "chmod" + ], + "action": "SCMP_ACT_ERRNO", + "comment": "stop exploit x" } ] } ``` -## Rootfs Mount Propagation +## Rootfs Mount Propagation -`rootfsPropagation` sets the rootfs's mount propagation. +**`rootfsPropagation`** (string, OPTIONAL) sets the rootfs's mount propagation. Its value is either slave, private, or shared. -[The kernel doc](https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt) has more information about mount propagation. +The [Shared Subtrees][sharedsubtree] article in the kernel documentation has more information about mount propagation. ###### Example @@ -530,9 +568,10 @@ Its value is either slave, private, or shared. "rootfsPropagation": "slave", ``` -## Masked Paths +## Masked Paths -`maskedPaths` will mask over the provided paths inside the container so that they cannot be read. +**`maskedPaths`** (array of strings, OPTIONAL) will mask over the provided paths inside the container so that they cannot be read. +The values MUST be absolute paths in the [container namespace][container-namespace2]. ###### Example @@ -542,9 +581,10 @@ Its value is either slave, private, or shared. ] ``` -## Readonly Paths +## Readonly Paths -`readonlyPaths` will set the provided paths as readonly inside the container. +**`readonlyPaths`** (array of strings, OPTIONAL) will set the provided paths as readonly inside the container. +The values MUST be absolute paths in the [container namespace][container-namespace2]. ###### Example @@ -554,9 +594,9 @@ Its value is either slave, private, or shared. ] ``` -## Mount Label +## Mount Label -`mountLabel` will set the Selinux context for the mounts in the container. +**`mountLabel`** (string, OPTIONAL) will set the Selinux context for the mounts in the container. ###### Example @@ -564,6 +604,9 @@ Its value is either slave, private, or shared. "mountLabel": "system_u:object_r:svirt_sandbox_file_t:s0:c715,c811" ``` + +[container-namespace2]: glossary.md#container_namespace + [cgroup-v1]: https://www.kernel.org/doc/Documentation/cgroup-v1/cgroups.txt [cgroup-v1-blkio]: https://www.kernel.org/doc/Documentation/cgroup-v1/blkio-controller.txt [cgroup-v1-cpusets]: https://www.kernel.org/doc/Documentation/cgroup-v1/cpusets.txt @@ -576,13 +619,23 @@ Its value is either slave, private, or shared. [cgroup-v2]: https://www.kernel.org/doc/Documentation/cgroup-v2.txt [devices]: https://www.kernel.org/doc/Documentation/devices.txt [devpts]: https://www.kernel.org/doc/Documentation/filesystems/devpts.txt +[file]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_164 +[libseccomp]: https://github.com/seccomp/libseccomp +[procfs]: https://www.kernel.org/doc/Documentation/filesystems/proc.txt +[seccomp]: https://www.kernel.org/doc/Documentation/prctl/seccomp_filter.txt +[sharedsubtree]: https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt +[sysfs]: https://www.kernel.org/doc/Documentation/filesystems/sysfs.txt +[tmpfs]: https://www.kernel.org/doc/Documentation/filesystems/tmpfs.txt -[mknod.1]: http://man7.org/linux/man-pages/man1/mknod.1.html -[mknod.2]: http://man7.org/linux/man-pages/man2/mknod.2.html [console.4]: http://man7.org/linux/man-pages/man4/console.4.html [full.4]: http://man7.org/linux/man-pages/man4/full.4.html +[mknod.1]: http://man7.org/linux/man-pages/man1/mknod.1.html +[mknod.2]: http://man7.org/linux/man-pages/man2/mknod.2.html +[namespaces.7_2]: http://man7.org/linux/man-pages/man7/namespaces.7.html [null.4]: http://man7.org/linux/man-pages/man4/null.4.html [pts.4]: http://man7.org/linux/man-pages/man4/pts.4.html [random.4]: http://man7.org/linux/man-pages/man4/random.4.html +[sysctl.8]: http://man7.org/linux/man-pages/man8/sysctl.8.html [tty.4]: http://man7.org/linux/man-pages/man4/tty.4.html [zero.4]: http://man7.org/linux/man-pages/man4/zero.4.html +[user-namespaces]: http://man7.org/linux/man-pages/man7/user_namespaces.7.html diff --git a/vendor/github.com/opencontainers/runtime-spec/config-solaris.md b/vendor/github.com/opencontainers/runtime-spec/config-solaris.md index 06311253..fb28a66e 100644 --- a/vendor/github.com/opencontainers/runtime-spec/config-solaris.md +++ b/vendor/github.com/opencontainers/runtime-spec/config-solaris.md @@ -1,49 +1,48 @@ -# Solaris Application Container Configuration +# Solaris Application Container Configuration -Solaris application containers can be configured using the following properties, all of the below properties have mappings to properties specified under zonecfg(1M) man page, except milestone. -The Solaris specification is entirely optional. +Solaris application containers can be configured using the following properties, all of the below properties have mappings to properties specified under [zonecfg(1M)][zonecfg.1m_2] man page, except milestone. -## milestone +## milestone The SMF(Service Management Facility) FMRI which should go to "online" state before we start the desired process within the container. -**`milestone`** *(string, optional)* +**`milestone`** *(string, OPTIONAL)* ### Example ```json "milestone": "svc:/milestone/container:default" ``` -## limitpriv +## limitpriv The maximum set of privileges any process in this container can obtain. -The property should consist of a comma-separated privilege set specification as described in priv_str_to_set(3C) man page for the respective release of Solaris. +The property should consist of a comma-separated privilege set specification as described in [priv_str_to_set(3C)][priv-str-to-set.3c] man page for the respective release of Solaris. -**`limitpriv`** *(string, optional)* +**`limitpriv`** *(string, OPTIONAL)* ### Example ```json "limitpriv": "default" ``` -## maxShmMemory +## maxShmMemory The maximum amount of shared memory allowed for this application container. A scale (K, M, G, T) can be applied to the value for each of these numbers (for example, 1M is one megabyte). -Mapped to max-shm-memory in zonecfg(1M) man page. +Mapped to `max-shm-memory` in [zonecfg(1M)][zonecfg.1m] man page. -**`maxShmMemory`** *(string, optional)* +**`maxShmMemory`** *(string, OPTIONAL)* ### Example ```json "maxShmMemory": "512m" ``` -## cappedCPU +## cappedCPU Sets a limit on the amount of CPU time that can be used by a container. The unit used translates to the percentage of a single CPU that can be used by all user threads in a container, expressed as a fraction (for example, .75) or a mixed number (whole number and fraction, for example, 1.25). An ncpu value of 1 means 100% of a CPU, a value of 1.25 means 125%, .75 mean 75%, and so forth. When projects within a capped container have their own caps, the minimum value takes precedence. -cappedCPU is mapped to capped-cpu in zonecfg(1M) man page. +cappedCPU is mapped to `capped-cpu` in [zonecfg(1M)][zonecfg.1m] man page. -* **`ncpus`** *(string, optional)* +* **`ncpus`** *(string, OPTIONAL)* ### Example ```json @@ -52,13 +51,13 @@ cappedCPU is mapped to capped-cpu in zonecfg(1M) man page. } ``` -## cappedMemory +## cappedMemory The physical and swap caps on the memory that can be used by this application container. A scale (K, M, G, T) can be applied to the value for each of these numbers (for example, 1M is one megabyte). -cappedMemory is mapped to capped-memory in zonecfg(1M) man page. +cappedMemory is mapped to `capped-memory` in [zonecfg(1M)][zonecfg.1m] man page. -* **`physical`** *(string, optional)* -* **`swap`** *(string, optional)* +* **`physical`** *(string, OPTIONAL)* +* **`swap`** *(string, OPTIONAL)* ### Example ```json @@ -68,37 +67,37 @@ cappedMemory is mapped to capped-memory in zonecfg(1M) man page. } ``` -## Network +## Network -### Automatic Network (anet) +### Automatic Network (anet) anet is specified as an array that is used to setup networking for Solaris application containers. The anet resource represents the automatic creation of a network resource for an application container. The zones administration daemon, zoneadmd, is the primary process for managing the container's virtual platform. -One of the daemons is responsibilities is creation and teardown of the networks for the container. -For more information on the daemon check the zoneadmd(1M) man page. +One of the daemon's responsibilities is creation and teardown of the networks for the container. +For more information on the daemon see the [zoneadmd(1M)][zoneadmd.1m] man page. When such a container is started, a temporary VNIC(Virtual NIC) is automatically created for the container. The VNIC is deleted when the container is torn down. The following properties can be used to setup automatic networks. -For additional information on properties check zonecfg(1M) man page for the respective release of Solaris. +For additional information on properties, check the [zonecfg(1M)][zonecfg.1m] man page for the respective release of Solaris. -* **`linkname`** *(string, optional)* Specify a name for the automatically created VNIC datalink. -* **`lowerLink`** *(string, optional)* Specify the link over which the VNIC will be created. -Mapped to lower-link in the zonecfg(1M) man page. -* **`allowedAddress`** *(string, optional)* The set of IP addresses that the container can use might be constrained by specifying the allowedAddress property. +* **`linkname`** *(string, OPTIONAL)* Specify a name for the automatically created VNIC datalink. +* **`lowerLink`** *(string, OPTIONAL)* Specify the link over which the VNIC will be created. +Mapped to `lower-link` in the [zonecfg(1M)][zonecfg.1m] man page. +* **`allowedAddress`** *(string, OPTIONAL)* The set of IP addresses that the container can use might be constrained by specifying the allowedAddress property. If allowedAddress has not been specified, then they can use any IP address on the associated physical interface for the network resource. Otherwise, when allowedAddress is specified, the container cannot use IP addresses that are not in the allowedAddress list for the physical address. -Mapped to allowed-address in the zonecfg(1M) man page. -* **`configureAllowedAddress`** *(string, optional)* If configureAllowedAddress is set to true, the addresses specified by allowedAddress are automatically configured on the interface each time the container starts. +Mapped to `allowed-address` in the [zonecfg(1M)][zonecfg.1m] man page. +* **`configureAllowedAddress`** *(string, OPTIONAL)* If configureAllowedAddress is set to true, the addresses specified by allowedAddress are automatically configured on the interface each time the container starts. When it is set to false, the allowedAddress will not be configured on container start. -Mapped to configure-allowed-address in the zonecfg(1M) man page. -* **`defrouter`** *(string, optional)* The value for the optional default router. -* **`macAddress`** *(string, optional)* Set the VNIC's MAC addresses based on the specified value or keyword. +Mapped to `configure-allowed-address` in the [zonecfg(1M)][zonecfg.1m] man page. +* **`defrouter`** *(string, OPTIONAL)* The value for the OPTIONAL default router. +* **`macAddress`** *(string, OPTIONAL)* Set the VNIC`s MAC addresses based on the specified value or keyword. If not a keyword, it is interpreted as a unicast MAC address. -For a list of the supported keywords please refer to the zonecfg(1M) man page of the respective Solaris release. -Mapped to mac-address in the zonecfg(1M) man page. -* **`linkProtection`** *(string, optional)* Enables one or more types of link protection using comma-separated values. +For a list of the supported keywords please refer to the [zonecfg(1M)][zonecfg.1m] man page of the respective Solaris release. +Mapped to `mac-address` in the [zonecfg(1M)][zonecfg.1m] man page. +* **`linkProtection`** *(string, OPTIONAL)* Enables one or more types of link protection using comma-separated values. See the protection property in dladm(8) for supported values in respective release of Solaris. -Mapped to link-protection in the zonecfg(1M) man page. +Mapped to `link-protection` in the [zonecfg(1M)][zonecfg.1m] man page. #### Example ```json @@ -114,3 +113,8 @@ Mapped to link-protection in the zonecfg(1M) man page. } ] ``` + + +[priv-str-to-set.3c]: http://docs.oracle.com/cd/E53394_01/html/E54766/priv-str-to-set-3c.html +[zoneadmd.1m]: http://docs.oracle.com/cd/E53394_01/html/E54764/zoneadmd-1m.html +[zonecfg.1m_2]: http://docs.oracle.com/cd/E53394_01/html/E54764/zonecfg-1m.html diff --git a/vendor/github.com/opencontainers/runtime-spec/config-windows.md b/vendor/github.com/opencontainers/runtime-spec/config-windows.md new file mode 100644 index 00000000..883998fb --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-spec/config-windows.md @@ -0,0 +1,99 @@ +# Windows-specific Container Configuration + +This document describes the schema for the [Windows-specific section](config.md#platform-specific-configuration) of the [container configuration](config.md). +The Windows container specification uses APIs provided by the Windows Host Compute Service (HCS) to fulfill the spec. + +## Resources + +You can configure a container's resource limits via the OPTIONAL `resources` field of the Windows configuration. + +### Memory + +`memory` is an OPTIONAL configuration for the container's memory usage. + +The following parameters can be specified: + +* **`limit`** *(uint64, OPTIONAL)* - sets limit of memory usage in bytes. + +* **`reservation`** *(uint64, OPTIONAL)* - sets the guaranteed minimum amount of memory for a container in bytes. + +#### Example + +```json + "windows": { + "resources": { + "memory": { + "limit": 2097152, + "reservation": 524288 + } + } + } +``` + +### CPU + +`cpu` is an OPTIONAL configuration for the container's CPU usage. + +The following parameters can be specified: + +* **`count`** *(uint64, OPTIONAL)* - specifies the number of CPUs available to the container. + +* **`shares`** *(uint16, OPTIONAL)* - specifies the relative weight to other containers with CPU shares. The range is from 1 to 10000. + +* **`percent`** *(uint, OPTIONAL)* - specifies the percentage of available CPUs usable by the container. + +#### Example + +```json + "windows": { + "resources": { + "cpu": { + "percent": 50 + } + } + } +``` + +### Storage + +`storage` is an OPTIONAL configuration for the container's storage usage. + +The following parameters can be specified: + +* **`iops`** *(uint64, OPTIONAL)* - specifies the maximum IO operations per second for the system drive of the container. + +* **`bps`** *(uint64, OPTIONAL)* - specifies the maximum bytes per second for the system drive of the container. + +* **`sandboxSize`** *(uint64, OPTIONAL)* - specifies the minimum size of the system drive in bytes. + +#### Example + +```json + "windows": { + "resources": { + "storage": { + "iops": 50 + } + } + } +``` + +### Network + +`network` is an OPTIONAL configuration for the container's network usage. + +The following parameters can be specified: + +* **`egressBandwidth`** *(uint64, OPTIONAL)* - specified the maximum egress bandwidth in bytes per second for the container. + +#### Example + +```json + "windows": { + "resources": { + "network": { + "egressBandwidth": 1048577 + } + } + } +``` diff --git a/vendor/github.com/opencontainers/runtime-spec/config.md b/vendor/github.com/opencontainers/runtime-spec/config.md index e2532824..92cad0ba 100644 --- a/vendor/github.com/opencontainers/runtime-spec/config.md +++ b/vendor/github.com/opencontainers/runtime-spec/config.md @@ -1,18 +1,23 @@ -# Container Configuration file +# Container Configuration file The container's top-level directory MUST contain a configuration file called `config.json`. The canonical schema is defined in this document, but there is a JSON Schema in [`schema/config-schema.json`](schema/config-schema.json) and Go bindings in [`specs-go/config.go`](specs-go/config.go). +[Platform](spec.md#platforms)-specific configuration schema are defined in the [platform-specific documents](#platform-specific-configuration) linked below. +For properties that are only defined for some [platforms](spec.md#platforms), the Go property has a `platform` tag listing those protocols (e.g. `platform:"linux,solaris"`). The configuration file contains metadata necessary to implement standard operations against the container. This includes the process to run, environment variables to inject, sandboxing features to use, etc. -Below is a detailed description of each field defined in the configuration format. +Below is a detailed description of each field defined in the configuration format and valid values are specified. +Platform-specific fields are identified as such. +For all platform-specific configuration values, the scope defined below in the [Platform-specific configuration](#platform-specific-configuration) section applies. -## Specification version -* **`ociVersion`** (string, required) MUST be in [SemVer v2.0.0](http://semver.org/spec/v2.0.0.html) format and specifies the version of the OpenContainer specification with which the bundle complies. -The OpenContainer spec follows semantic versioning and retains forward and backward compatibility within major versions. -For example, if an implementation is compliant with version 1.0.1 of the spec, it is compatible with the complete 1.x series. +## Specification version + +* **`ociVersion`** (string, REQUIRED) MUST be in [SemVer v2.0.0][semver-v2.0.0] format and specifies the version of the Open Container Runtime Specification with which the bundle complies. +The Open Container Runtime Specification follows semantic versioning and retains forward and backward compatibility within major versions. +For example, if a configuration is compliant with version 1.1 of this specification, it is compatible with all runtimes that support any 1.1 or later release of this specification, but is not compatible with a runtime that supports 1.0 and not 1.1. ### Example @@ -20,12 +25,15 @@ For example, if an implementation is compliant with version 1.0.1 of the spec, i "ociVersion": "0.1.0" ``` -## Root Configuration +## Root -Each container has exactly one *root filesystem*, specified in the *root* object: +**`root`** (object, REQUIRED) specifies the container's root filesystem. -* **`path`** (string, required) Specifies the path to the root filesystem for the container. A directory MUST exist at the path declared by the field. -* **`readonly`** (bool, optional) If true then the root filesystem MUST be read-only inside the container. Defaults to false. +* **`path`** (string, REQUIRED) Specifies the path to the root filesystem for the container. + The path is either an absolute path or a relative path to the bundle. + On Linux, for example, with a bundle at `/to/bundle` and a root filesystem at `/to/bundle/rootfs`, the `path` value can be either `/to/bundle/rootfs` or `rootfs`. + A directory MUST exist at the path declared by the field. +* **`readonly`** (bool, OPTIONAL) If true then the root filesystem MUST be read-only inside the container, defaults to false. ### Example @@ -36,17 +44,29 @@ Each container has exactly one *root filesystem*, specified in the *root* object } ``` -## Mounts +## Mounts -You MAY add array of mount points inside container as `mounts`. +**`mounts`** (array, OPTIONAL) specifies additional mounts beyond [`root`](#root-configuration). The runtime MUST mount entries in the listed order. -The parameters are similar to the ones in [the Linux mount system call](http://man7.org/linux/man-pages/man2/mount.2.html). +For Linux, the parameters are as documented in [mount(2)][mount.2] system call man page. +For Solaris, the mount entry corresponds to the 'fs' resource in the [zonecfg(1M)][zonecfg.1m] man page. +For Windows, see [mountvol][mountvol] and [SetVolumeMountPoint][set-volume-mountpoint] for details. -* **`destination`** (string, required) Destination of mount point: path inside container. -For the Windows operating system, one mount destination MUST NOT be nested within another mount. (Ex: c:\\foo and c:\\foo\\bar). -* **`type`** (string, required) Linux, *filesystemtype* argument supported by the kernel are listed in */proc/filesystems* (e.g., "minix", "ext2", "ext3", "jfs", "xfs", "reiserfs", "msdos", "proc", "nfs", "iso9660"). Windows: ntfs -* **`source`** (string, required) a device name, but can also be a directory name or a dummy. Windows, the volume name that is the target of the mount point. \\?\Volume\{GUID}\ (on Windows source is called target) -* **`options`** (list of strings, optional) in the fstab format [https://wiki.archlinux.org/index.php/Fstab](https://wiki.archlinux.org/index.php/Fstab). + +* **`destination`** (string, REQUIRED) Destination of mount point: path inside container. + This value MUST be an absolute path. + * Windows: one mount destination MUST NOT be nested within another mount (e.g., c:\\foo and c:\\foo\\bar). + * Solaris: corresponds to "dir" of the fs resource in [zonecfg(1M)][zonecfg.1m]. +* **`type`** (string, OPTIONAL) The filesystem type of the filesystem to be mounted. + * Linux: valid *filesystemtype* supported by the kernel as listed in */proc/filesystems* (e.g., "minix", "ext2", "ext3", "jfs", "xfs", "reiserfs", "msdos", "proc", "nfs", "iso9660"). + * Windows: the type of file system on the volume, e.g. "ntfs". + * Solaris: corresponds to "type" of the fs resource in [zonecfg(1M)][zonecfg.1m]. +* **`source`** (string, OPTIONAL) A device name, but can also be a directory name or a dummy. + * Windows: the volume name that is the target of the mount point, \\?\Volume\{GUID}\ (on Windows source is called target). + * Solaris: corresponds to "special" of the fs resource in [zonecfg(1M)][zonecfg.1m]. +* **`options`** (list of strings, OPTIONAL) Mount options of the filesystem to be used. + * Linux: supported options are listed in the [mount(8)][mount.8] man page. Note both [filesystem-independent][mount.8-filesystem-independent] and [filesystem-specific][mount.8-filesystem-specific] options are listed. + * Solaris: corresponds to "options" of the fs resource in [zonecfg(1M)][zonecfg.1m]. ### Example (Linux) @@ -80,51 +100,87 @@ For the Windows operating system, one mount destination MUST NOT be nested withi ] ``` -See links for details about [mountvol](http://ss64.com/nt/mountvol.html) and [SetVolumeMountPoint](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365561(v=vs.85).aspx) in Windows. +### Example (Solaris) +```json +"mounts": [ + { + "destination": "/opt/local", + "type": "lofs", + "source": "/usr/local", + "options": ["ro","nodevices"] + }, + { + "destination": "/opt/sfw", + "type": "lofs", + "source": "/opt/sfw" + } +] +``` -## Process configuration +## Process -* **`terminal`** (bool, optional) specifies whether you want a terminal attached to that process. Defaults to false. -* **`cwd`** (string, required) is the working directory that will be set for the executable. This value MUST be an absolute path. -* **`env`** (array of strings, optional) contains a list of variables that will be set in the process's environment prior to execution. Elements in the array are specified as Strings in the form "KEY=value". The left hand side MUST consist solely of letters, digits, and underscores `_` as outlined in [IEEE Std 1003.1-2001](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html). -* **`args`** (array of strings, required) executable to launch and any flags as an array. The executable is the first element and MUST be available at the given path inside of the rootfs. If the executable path is not an absolute path then the search $PATH is interpreted to find the executable. +**`process`** (object, REQUIRED) specifies the container process. -For Linux-based systems the process structure supports the following process specific fields: +* **`terminal`** (bool, OPTIONAL) specifies whether a terminal is attached to that process, defaults to false. + As an example, if set to true on Linux a pseudoterminal pair is allocated for the container process and the pseudoterminal slave is duplicated on the container process's [standard streams][stdin.3]. +* **`consoleSize`** (object, OPTIONAL) specifies the console size of the terminal if attached, containing the following properties: + * **`height`** (uint, REQUIRED) + * **`width`** (uint, REQUIRED) +* **`cwd`** (string, REQUIRED) is the working directory that will be set for the executable. + This value MUST be an absolute path. +* **`env`** (array of strings, OPTIONAL) with the same semantics as [IEEE Std 1003.1-2001's `environ`][ieee-1003.1-2001-xbd-c8.1]. +* **`args`** (array of strings, REQUIRED) with similar semantics to [IEEE Std 1003.1-2001 `execvp`'s *argv*][ieee-1003.1-2001-xsh-exec]. + This specification extends the IEEE standard in that at least one entry is REQUIRED, and that entry is used with the same semantics as `execvp`'s *file*. +* **`capabilities`** (object, OPTIONAL) is an object containing arrays that specifies the sets of capabilities for the process(es) inside the container. Valid values are platform-specific. For example, valid values for Linux are defined in the [capabilities(7)][capabilities.7] man page. + capabilities contains the following properties: + * **`effective`** (array of strings, OPTIONAL) - the `effective` field is an array of effective capabilities that are kept for the process. + * **`bounding`** (array of strings, OPTIONAL) - the `bounding` field is an array of bounding capabilities that are kept for the process. + * **`inheritable`** (array of strings, OPTIONAL) - the `inheritable` field is an array of inheritable capabilities that are kept for the process. + * **`permitted`** (array of strings, OPTIONAL) - the `permitted` field is an array of permitted capabilities that are kept for the process. + * **`ambient`** (array of strings, OPTIONAL) - the `ambient` field is an array of ambient capabilities that are kept for the process. +* **`rlimits`** (array of objects, OPTIONAL) allows setting resource limits for a process inside the container. + Each entry has the following structure: -* **`capabilities`** (array of strings, optional) capabilities is an array that specifies Linux capabilities that can be provided to the process inside the container. -Valid values are the strings for capabilities defined in [the man page](http://man7.org/linux/man-pages/man7/capabilities.7.html) -* **`rlimits`** (array of rlimits, optional) rlimits is an array of rlimits that allows setting resource limits for a process inside the container. -The kernel enforces the `soft` limit for a resource while the `hard` limit acts as a ceiling for that value that could be set by an unprivileged process. -Valid values for the 'type' field are the resources defined in [the man page](http://man7.org/linux/man-pages/man2/setrlimit.2.html). -* **`apparmorProfile`** (string, optional) apparmor profile specifies the name of the apparmor profile that will be used for the container. -For more information about Apparmor, see [Apparmor documentation](https://wiki.ubuntu.com/AppArmor) -* **`selinuxLabel`** (string, optional) SELinux process label specifies the label with which the processes in a container are run. -For more information about SELinux, see [Selinux documentation](http://selinuxproject.org/page/Main_Page) -* **`noNewPrivileges`** (bool, optional) setting `noNewPrivileges` to true prevents the processes in the container from gaining additional privileges. -[The kernel doc](https://www.kernel.org/doc/Documentation/prctl/no_new_privs.txt) has more information on how this is achieved using a prctl system call. + * **`type`** (string, REQUIRED) - the platform resource being limited, for example on Linux as defined in the [setrlimit(2)][setrlimit.2] man page. + * **`soft`** (uint64, REQUIRED) - the value of the limit enforced for the corresponding resource. + * **`hard`** (uint64, REQUIRED) - the ceiling for the soft limit that could be set by an unprivileged process. Only a privileged process (e.g. under Linux: one with the CAP_SYS_RESOURCE capability) can raise a hard limit. -### User + If `rlimits` contains duplicated entries with same `type`, the runtime MUST error out. + +* **`noNewPrivileges`** (bool, OPTIONAL) setting `noNewPrivileges` to true prevents the processes in the container from gaining additional privileges. + As an example, the ['no_new_privs'][no-new-privs] article in the kernel documentation has information on how this is achieved using a prctl system call on Linux. + +For Linux-based systems the process structure supports the following process specific fields. + +* **`apparmorProfile`** (string, OPTIONAL) specifies the name of the AppArmor profile to be applied to processes in the container. + For more information about AppArmor, see [AppArmor documentation][apparmor]. +* **`selinuxLabel`** (string, OPTIONAL) specifies the SELinux label to be applied to the processes in the container. + For more information about SELinux, see [SELinux documentation][selinux]. + +### User The user for the process is a platform-specific structure that allows specific control over which user the process runs as. -#### Linux and Solaris User +#### Linux and Solaris User For Linux and Solaris based systems the user structure has the following fields: -* **`uid`** (int, required) specifies the user ID in the [container namespace][container-namespace]. -* **`gid`** (int, required) specifies the group ID in the [container namespace][container-namespace]. -* **`additionalGids`** (array of ints, optional) specifies additional group IDs (in the [container namespace][container-namespace]) to be added to the process. +* **`uid`** (int, REQUIRED) specifies the user ID in the [container namespace](glossary.md#container-namespace). +* **`gid`** (int, REQUIRED) specifies the group ID in the [container namespace](glossary.md#container-namespace). +* **`additionalGids`** (array of ints, OPTIONAL) specifies additional group IDs (in the [container namespace](glossary.md#container-namespace) to be added to the process. _Note: symbolic name for uid and gid, such as uname and gname respectively, are left to upper levels to derive (i.e. `/etc/passwd` parsing, NSS, etc)_ -_Note: For Solaris, uid and gid specify the uid and gid of the process inside the container and need not be same as in the host._ - ### Example (Linux) ```json "process": { "terminal": true, + "consoleSize": { + "height": 25, + "width": 80 + }, "user": { "uid": 1, "gid": 1, @@ -141,11 +197,30 @@ _Note: For Solaris, uid and gid specify the uid and gid of the process inside th "apparmorProfile": "acme_secure_profile", "selinuxLabel": "system_u:system_r:svirt_lxc_net_t:s0:c124,c675", "noNewPrivileges": true, - "capabilities": [ - "CAP_AUDIT_WRITE", - "CAP_KILL", - "CAP_NET_BIND_SERVICE" - ], + "capabilities": { + "bounding": [ + "CAP_AUDIT_WRITE", + "CAP_KILL", + "CAP_NET_BIND_SERVICE" + ], + "permitted": [ + "CAP_AUDIT_WRITE", + "CAP_KILL", + "CAP_NET_BIND_SERVICE" + ], + "inheritable": [ + "CAP_AUDIT_WRITE", + "CAP_KILL", + "CAP_NET_BIND_SERVICE" + ], + "effective": [ + "CAP_AUDIT_WRITE", + "CAP_KILL", + ], + "ambient": [ + "CAP_NET_BIND_SERVICE" + ] + }, "rlimits": [ { "type": "RLIMIT_NOFILE", @@ -160,6 +235,10 @@ _Note: For Solaris, uid and gid specify the uid and gid of the process inside th ```json "process": { "terminal": true, + "consoleSize": { + "height": 25, + "width": 80 + }, "user": { "uid": 1, "gid": 1, @@ -172,14 +251,40 @@ _Note: For Solaris, uid and gid specify the uid and gid of the process inside th "cwd": "/root", "args": [ "/usr/bin/bash" + ] +} +``` + +#### Windows User + +For Windows based systems the user structure has the following fields: + +* **`username`** (string, OPTIONAL) specifies the user name for the process. + +### Example (Windows) + +```json +"process": { + "terminal": true, + "user": { + "username": "containeradministrator" + }, + "env": [ + "VARIABLE=1" ], + "cwd": "c:\\foo", + "args": [ + "someapp.exe", + ] } ``` -## Hostname +## Hostname -* **`hostname`** (string, optional) as it is accessible to processes running inside. On Linux, you can only set this if your bundle creates a new [UTS namespace][uts-namespace]. +* **`hostname`** (string, OPTIONAL) specifies the container's hostname as seen by processes running inside the container. + On Linux, for example, this will change the hostname in the [container](glossary.md#container-namespace) [UTS namespace][uts-namespace.7]. + Depending on your [namespace configuration](config-linux.md#namespaces), the container UTS namespace may be the [runtime UTS namespace](glossary.md#runtime-namespace). ### Example @@ -187,14 +292,16 @@ _Note: For Solaris, uid and gid specify the uid and gid of the process inside th "hostname": "mrsdalloway" ``` -## Platform +## Platform -* **`os`** (string, required) specifies the operating system family this image targets. - The runtime MUST generate an error if it does not support the configured **`os`**. +**`platform`** (object, REQUIRED) specifies the configuration's target platform. + +* **`os`** (string, REQUIRED) specifies the operating system family of the container configuration's specified [`root`](#root-configuration) file system bundle. + The runtime MUST generate an error if it does not support the specified **`os`**. Bundles SHOULD use, and runtimes SHOULD understand, **`os`** entries listed in the Go Language document for [`$GOOS`][go-environment]. If an operating system is not included in the `$GOOS` documentation, it SHOULD be submitted to this specification for standardization. -* **`arch`** (string, required) specifies the instruction set for which the binaries in the image have been compiled. - The runtime MUST generate an error if it does not support the configured **`arch`**. +* **`arch`** (string, REQUIRED) specifies the instruction set for which the binaries in the specified [`root`](#root-configuration) file system bundle have been compiled. + The runtime MUST generate an error if it does not support the specified **`arch`**. Values for **`arch`** SHOULD use, and runtimes SHOULD understand, **`arch`** entries listed in the Go Language document for [`$GOARCH`][go-environment]. If an architecture is not included in the `$GOARCH` documentation, it SHOULD be submitted to this specification for standardization. @@ -207,14 +314,18 @@ _Note: For Solaris, uid and gid specify the uid and gid of the process inside th } ``` -## Platform-specific configuration +## Platform-specific configuration -[**`platform.os`**](#platform) is used to lookup further platform-specific configuration. +[**`platform.os`**](#platform) is used to specify platform-specific configuration. +Runtime implementations MAY support any valid values for platform-specific fields as part of this configuration. +Implementations MUST error out when invalid values are encountered and MUST generate an error message and error out when encountering valid values it chooses to not support. -* **`linux`** (object, optional) [Linux-specific configuration](config-linux.md). - This SHOULD only be set if **`platform.os`** is `linux`. -* **`solaris`** (object, optional) [Solaris-specific configuration](config-solaris.md). - This SHOULD only be set if **`platform.os`** is `solaris`. +* **`linux`** (object, OPTIONAL) [Linux-specific configuration](config-linux.md). + This MAY be set if **`platform.os`** is `linux` and MUST NOT be set otherwise. +* **`windows`** (object, OPTIONAL) [Windows-specific configuration](config-windows.md). + This MAY be set if **`platform.os`** is `windows` and MUST NOT be set otherwise. +* **`solaris`** (object, OPTIONAL) [Solaris-specific configuration](config-solaris.md). + This MAY be set if **`platform.os`** is `solaris` and MUST NOT be set otherwise. ### Example (Linux) @@ -234,46 +345,46 @@ _Note: For Solaris, uid and gid specify the uid and gid of the process inside th } ``` -## Hooks +## Hooks -Lifecycle hooks allow custom events for different points in a container's runtime. -Presently there are `Prestart`, `Poststart` and `Poststop`. +Hooks allow for the configuration of custom actions related to the [lifecycle](runtime.md#lifecycle) of the container. -* [`Prestart`](#prestart) is a list of hooks to be run before the container process is executed -* [`Poststart`](#poststart) is a list of hooks to be run immediately after the container process is started -* [`Poststop`](#poststop) is a list of hooks to be run after the container process exits +* **`hooks`** (object, OPTIONAL) MAY contain any of the following properties: + * **`prestart`** (array, OPTIONAL) is an array of [pre-start hooks](#prestart). + Entries in the array contain the following properties: + * **`path`** (string, REQUIRED) with similar semantics to [IEEE Std 1003.1-2001 `execv`'s *path*][ieee-1003.1-2001-xsh-exec]. + This specification extends the IEEE standard in that **`path`** MUST be absolute. + * **`args`** (array of strings, OPTIONAL) with the same semantics as [IEEE Std 1003.1-2001 `execv`'s *argv*][ieee-1003.1-2001-xsh-exec]. + * **`env`** (array of strings, OPTIONAL) with the same semantics as [IEEE Std 1003.1-2001's `environ`][ieee-1003.1-2001-xbd-c8.1]. + * **`timeout`** (int, OPTIONAL) is the number of seconds before aborting the hook. + * **`poststart`** (array, OPTIONAL) is an array of [post-start hooks](#poststart). + Entries in the array have the same schema as pre-start entries. + * **`poststop`** (array, OPTIONAL) is an array of [post-stop hooks](#poststop). + Entries in the array have the same schema as pre-start entries. -Hooks allow one to run code before/after various lifecycle events of the container. +Hooks allow users to specify programs to run before or after various lifecycle events. Hooks MUST be called in the listed order. -The state of the container is passed to the hooks over stdin, so the hooks could get the information they need to do their work. +The [state](runtime.md#state) of the container MUST be passed to hooks over stdin so that they may do work appropriate to the current state of the container. -Hook paths are absolute and are executed from the host's filesystem in the [runtime namespace][runtime-namespace]. +### Prestart -### Prestart +The pre-start hooks MUST be called after the [`start`](runtime.md#start) operation is called but [before the user-specified program command is executed](runtime.md#lifecycle). +On Linux, for example, they are called after the container namespaces are created, so they provide an opportunity to customize the container (e.g. the network namespace could be specified in this hook). -The pre-start hooks are called after the container process is spawned, but before the user supplied command is executed. -They are called after the container namespaces are created on Linux, so they provide an opportunity to customize the container. -In Linux, for e.g., the network namespace could be configured in this hook. +### Poststart -If a hook returns a non-zero exit code, then an error including the exit code and the stderr is returned to the caller and the container is torn down. +The post-start hooks MUST be called [after the user-specified process is executed](runtime#lifecycle) but before the [`start`](runtime.md#start) operation returns. +For example, this hook can notify the user that the container process is spawned. -### Poststart +### Poststop -The post-start hooks are called after the user process is started. -For example this hook can notify user that real process is spawned. - -If a hook returns a non-zero exit code, then an error is logged and the remaining hooks are executed. - -### Poststop - -The post-stop hooks are called after the container process is stopped. -Cleanup or debugging could be performed in such a hook. -If a hook returns a non-zero exit code, then an error is logged and the remaining hooks are executed. +The post-stop hooks MUST be called [after the container is deleted](runtime#lifecycle) but before the [`delete`](runtime.md#delete) operation returns. +Cleanup or debugging functions are examples of such a hook. ### Example ```json - "hooks" : { + "hooks": { "prestart": [ { "path": "/usr/bin/fix-mounts", @@ -299,24 +410,33 @@ If a hook returns a non-zero exit code, then an error is logged and the remainin } ``` -`path` is required for a hook. -`args` and `env` are optional. -`timeout` is the number of seconds before aborting the hook. -The semantics are the same as `Path`, `Args` and `Env` in [golang Cmd](https://golang.org/pkg/os/exec/#Cmd). +## Annotations -## Annotations - -This OPTIONAL property contains arbitrary metadata for the container. +**`annotations`** (object, OPTIONAL) contains arbitrary metadata for the container. This information MAY be structured or unstructured. -Annotations are key-value maps. +Annotations MUST be a key-value map. +If there are no annotations then this property MAY either be absent or an empty map. + +Keys MUST be strings. +Keys MUST be unique within this map. +Keys MUST NOT be an empty string. +Keys SHOULD be named using a reverse domain notation - e.g. `com.example.myKey`. +Keys using the `org.opencontainers` namespace are reserved and MUST NOT be used by subsequent specifications. +Implementations that are reading/processing this configuration file MUST NOT generate an error if they encounter an unknown annotation key. + +Values MUST be strings. +Values MAY be an empty string. ```json "annotations": { - "key1" : "value1", - "key2" : "value2" + "com.example.gpu-cores": "2" } ``` +## Extensibility +Implementations that are reading/processing this configuration file MUST NOT generate an error if they encounter an unknown property. +Instead they MUST ignore unknown properties. + ## Configuration Schema Example Here is a full example `config.json` for reference. @@ -346,11 +466,30 @@ Here is a full example `config.json` for reference. "TERM=xterm" ], "cwd": "/", - "capabilities": [ - "CAP_AUDIT_WRITE", - "CAP_KILL", - "CAP_NET_BIND_SERVICE" - ], + "capabilities": { + "bounding": [ + "CAP_AUDIT_WRITE", + "CAP_KILL", + "CAP_NET_BIND_SERVICE" + ], + "permitted": [ + "CAP_AUDIT_WRITE", + "CAP_KILL", + "CAP_NET_BIND_SERVICE" + ], + "inheritable": [ + "CAP_AUDIT_WRITE", + "CAP_KILL", + "CAP_NET_BIND_SERVICE" + ], + "effective": [ + "CAP_AUDIT_WRITE", + "CAP_KILL", + ], + "ambient": [ + "CAP_NET_BIND_SERVICE" + ] + }, "rlimits": [ { "type": "RLIMIT_CORE", @@ -618,12 +757,17 @@ Here is a full example `config.json` for reference. "seccomp": { "defaultAction": "SCMP_ACT_ALLOW", "architectures": [ - "SCMP_ARCH_X86" + "SCMP_ARCH_X86", + "SCMP_ARCH_X32" ], "syscalls": [ { - "name": "getcwd", - "action": "SCMP_ACT_ERRNO" + "names": [ + "getcwd", + "chmod" + ], + "action": "SCMP_ACT_ERRNO", + "comment": "stop exploit x" } ] }, @@ -667,13 +811,29 @@ Here is a full example `config.json` for reference. "mountLabel": "system_u:object_r:svirt_sandbox_file_t:s0:c715,c811" }, "annotations": { - "key1": "value1", - "key2": "value2" + "com.example.key1": "value1", + "com.example.key2": "value2" } } ``` -[container-namespace]: glossary.md#container-namespace + +[apparmor]: https://wiki.ubuntu.com/AppArmor +[selinux]:http://selinuxproject.org/page/Main_Page +[no-new-privs]: https://www.kernel.org/doc/Documentation/prctl/no_new_privs.txt +[semver-v2.0.0]: http://semver.org/spec/v2.0.0.html [go-environment]: https://golang.org/doc/install/source#environment -[runtime-namespace]: glossary.md#runtime-namespace -[uts-namespace]: http://man7.org/linux/man-pages/man7/namespaces.7.html +[ieee-1003.1-2001-xbd-c8.1]: http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html#tag_08_01 +[ieee-1003.1-2001-xsh-exec]: http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html +[mountvol]: http://ss64.com/nt/mountvol.html +[set-volume-mountpoint]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365561(v=vs.85).aspx + +[capabilities.7]: http://man7.org/linux/man-pages/man7/capabilities.7.html +[mount.2]: http://man7.org/linux/man-pages/man2/mount.2.html +[mount.8]: http://man7.org/linux/man-pages/man8/mount.8.html +[mount.8-filesystem-independent]: http://man7.org/linux/man-pages/man8/mount.8.html#FILESYSTEM-INDEPENDENT_MOUNT%20OPTIONS +[mount.8-filesystem-specific]: http://man7.org/linux/man-pages/man8/mount.8.html#FILESYSTEM-SPECIFIC_MOUNT%20OPTIONS +[setrlimit.2]: http://man7.org/linux/man-pages/man2/setrlimit.2.html +[stdin.3]: http://man7.org/linux/man-pages/man3/stdin.3.html +[uts-namespace.7]: http://man7.org/linux/man-pages/man7/namespaces.7.html +[zonecfg.1m]: http://docs.oracle.com/cd/E53394_01/html/E54764/zonecfg-1m.html diff --git a/vendor/github.com/opencontainers/runtime-spec/glossary.md b/vendor/github.com/opencontainers/runtime-spec/glossary.md index 6b6eb594..09f80e42 100644 --- a/vendor/github.com/opencontainers/runtime-spec/glossary.md +++ b/vendor/github.com/opencontainers/runtime-spec/glossary.md @@ -1,36 +1,40 @@ -# Glossary +# Glossary -## Bundle +## Bundle A [directory structure](bundle.md) that is written ahead of time, distributed, and used to seed the runtime for creating a [container](#container) and launching a process within it. -## Configuration +## Configuration The [`config.json`](config.md) file in a [bundle](#bundle) which defines the intended [container](#container) and container process. -## Container +## Container An environment for executing processes with configurable isolation and resource limitations. For example, namespaces, resource limits, and mounts are all part of the container environment. -## Container namespace +## Container namespace -On Linux, a leaf in the [namespace][namespaces.7] hierarchy in which the [configured process](config.md#process-configuration) executes. +On Linux, a leaf in the [namespace][namespaces.7] hierarchy in which the [configured process](config.md#process) executes. -## JSON +## JSON All configuration [JSON][] MUST be encoded in [UTF-8][]. +JSON objects MUST NOT include duplicate names. +The order of entries in JSON objects is not significant. -## Runtime +## Runtime An implementation of this specification. It reads the [configuration files](#configuration) from a [bundle](#bundle), uses that information to create a [container](#container), launches a process inside the container, and performs other [lifecycle actions](runtime.md). -## Runtime namespace +## Runtime namespace On Linux, a leaf in the [namespace][namespaces.7] hierarchy from which the [runtime](#runtime) process is executed. New container namespaces will be created as children of the runtime namespaces. -[JSON]: http://json.org/ + +[JSON]: https://tools.ietf.org/html/rfc7159 [UTF-8]: http://www.unicode.org/versions/Unicode8.0.0/ch03.pdf + [namespaces.7]: http://man7.org/linux/man-pages/man7/namespaces.7.html diff --git a/vendor/github.com/opencontainers/runtime-spec/implementations.md b/vendor/github.com/opencontainers/runtime-spec/implementations.md index 1a6d7542..1631073b 100644 --- a/vendor/github.com/opencontainers/runtime-spec/implementations.md +++ b/vendor/github.com/opencontainers/runtime-spec/implementations.md @@ -1,18 +1,27 @@ -# Implementations +# Implementations The following sections link to associated projects, some of which are maintained by the OCI and some of which are maintained by external organizations. If you know of any associated projects that are not listed here, please file a pull request adding a link to that project. -## Runtime (Container) +## Runtime (Container) -* [opencontainers/runc](https://github.com/opencontainers/runc) - Reference implementation of OCI runtime +* [opencontainers/runc][runc] - Reference implementation of OCI runtime -## Runtime (Virtual Machine) +## Runtime (Virtual Machine) -* [hyperhq/runv](https://github.com/hyperhq/runv) - Hypervisor-based runtime for OCI +* [hyperhq/runv][runv] - Hypervisor-based runtime for OCI +* [01org/cc-oci-runtime][cc-oci] - Hypervisor-based OCI runtime for Intel® Architecture -## Testing & Tools +## Testing & Tools -* [kunalkushwaha/octool](https://github.com/kunalkushwaha/octool) - A config linter and validator. -* [opencontainers/ocitools](https://github.com/opencontainers/ocitools) - A config generator and runtime/bundle testing framework. -* [huawei-openlab/oct](https://github.com/huawei-openlab/oct) - Open Container Testing framework for OCI configuration and runtime +* [kunalkushwaha/octool][octool] - A config linter and validator. +* [huawei-openlab/oct][oct] - Open Container Testing framework for OCI configuration and runtime +* [opencontainers/runtime-tools][runtime-tools] - A config generator and runtime/bundle testing framework. + + +[runc]: https://github.com/opencontainers/runc +[runv]: https://github.com/hyperhq/runv +[cc-oci]: https://github.com/01org/cc-oci-runtime +[octool]: https://github.com/kunalkushwaha/octool +[oct]: https://github.com/huawei-openlab/oct +[runtime-tools]: https://github.com/opencontainers/runtime-tools diff --git a/vendor/github.com/opencontainers/runtime-spec/principles.md b/vendor/github.com/opencontainers/runtime-spec/principles.md index 5dbab169..6c769630 100644 --- a/vendor/github.com/opencontainers/runtime-spec/principles.md +++ b/vendor/github.com/opencontainers/runtime-spec/principles.md @@ -1,4 +1,4 @@ -# The 5 principles of Standard Containers +# The 5 principles of Standard Containers Define a unit of software delivery called a Standard Container. The goal of a Standard Container is to encapsulate a software component and all its dependencies in a format that is self-describing and portable, so that any compliant runtime can run it without extra dependencies, regardless of the underlying machine and the contents of the container. @@ -14,22 +14,22 @@ Shipping containers are a fundamental unit of delivery, they can be lifted, stac Irrespective of their contents, by standardizing the container itself it allowed for a consistent, more streamlined and efficient set of processes to be defined. For software Standard Containers offer similar functionality by being the fundamental, standardized, unit of delivery for a software package. -## 1. Standard operations +## 1. Standard operations Standard Containers define a set of STANDARD OPERATIONS. They can be created, started, and stopped using standard container tools; copied and snapshotted using standard filesystem tools; and downloaded and uploaded using standard network tools. -## 2. Content-agnostic +## 2. Content-agnostic Standard Containers are CONTENT-AGNOSTIC: all standard operations have the same effect regardless of the contents. They are started in the same way whether they contain a postgres database, a php application with its dependencies and application server, or Java build artifacts. -## 3. Infrastructure-agnostic +## 3. Infrastructure-agnostic Standard Containers are INFRASTRUCTURE-AGNOSTIC: they can be run in any OCI supported infrastructure. For example, a standard container can be bundled on a laptop, uploaded to cloud storage, downloaded, run and snapshotted by a build server at a fiber hotel in Virginia, uploaded to 10 staging servers in a home-made private cloud cluster, then sent to 30 production instances across 3 public cloud regions. -## 4. Designed for automation +## 4. Designed for automation Standard Containers are DESIGNED FOR AUTOMATION: because they offer the same standard operations regardless of content and infrastructure, Standard Containers, are extremely well-suited for automation. In fact, you could say automation is their secret weapon. @@ -39,7 +39,7 @@ Before Standard Containers, by the time a software component ran in production, Builds failed, libraries conflicted, mirrors crashed, post-it notes were lost, logs were misplaced, cluster updates were half-broken. The process was slow, inefficient and cost a fortune - and was entirely different depending on the language and infrastructure provider. -## 5. Industrial-grade delivery +## 5. Industrial-grade delivery Standard Containers make INDUSTRIAL-GRADE DELIVERY of software a reality. Leveraging all of the properties listed above, Standard Containers are enabling large and small enterprises to streamline and automate their software delivery pipelines. diff --git a/vendor/github.com/opencontainers/runtime-spec/project.md b/vendor/github.com/opencontainers/runtime-spec/project.md index 2f8f0767..3f8a09b9 100644 --- a/vendor/github.com/opencontainers/runtime-spec/project.md +++ b/vendor/github.com/opencontainers/runtime-spec/project.md @@ -1,10 +1,12 @@ -# Project docs +# Project docs -## Release Process +## Release Process * Increment version in [`specs-go/version.go`](specs-go/version.go) * `git commit` version increment * `git tag` the prior commit (preferably signed tag) * `make docs` to produce PDF and HTML copies of the spec -* Make a release on [github.com/opencontainers/runtime-spec](https://github.com/opencontainers/runtime-spec/releases) for the version. Attach the produced docs. +* Make a [release][releases] for the version. Attach the produced docs. + +[releases]: https://github.com/opencontainers/runtime-spec/releases diff --git a/vendor/github.com/opencontainers/runtime-spec/runtime-linux.md b/vendor/github.com/opencontainers/runtime-spec/runtime-linux.md index 388df30a..a47b8969 100644 --- a/vendor/github.com/opencontainers/runtime-spec/runtime-linux.md +++ b/vendor/github.com/opencontainers/runtime-spec/runtime-linux.md @@ -1,14 +1,14 @@ -# Linux Runtime +# Linux Runtime -## File descriptors +## File descriptors By default, only the `stdin`, `stdout` and `stderr` file descriptors are kept open for the application by the runtime. -The runtime MAY pass additional file descriptors to the application to support features such as [socket activation](http://0pointer.de/blog/projects/socket-activated-containers.html). +The runtime MAY pass additional file descriptors to the application to support features such as [socket activation][socket-activated-containers]. Some of the file descriptors MAY be redirected to `/dev/null` even though they are open. -## Dev symbolic links +## Dev symbolic links -After the container has `/proc` mounted, the following standard symlinks MUST be setup within `/dev/` for the io. +After the container has `/proc` mounted, the following standard symlinks MUST be setup within `/dev/` for the IO. | Source | Destination | | --------------- | ----------- | @@ -16,3 +16,6 @@ After the container has `/proc` mounted, the following standard symlinks MUST be | /proc/self/fd/0 | /dev/stdin | | /proc/self/fd/1 | /dev/stdout | | /proc/self/fd/2 | /dev/stderr | + + +[socket-activated-containers]: http://0pointer.de/blog/projects/socket-activated-containers.html diff --git a/vendor/github.com/opencontainers/runtime-spec/runtime.md b/vendor/github.com/opencontainers/runtime-spec/runtime.md index 01bdb9d5..4786848a 100644 --- a/vendor/github.com/opencontainers/runtime-spec/runtime.md +++ b/vendor/github.com/opencontainers/runtime-spec/runtime.md @@ -1,31 +1,35 @@ -# Runtime and Lifecycle +# Runtime and Lifecycle -## Scope of a Container +## Scope of a Container Barring access control concerns, the entity using a runtime to create a container MUST be able to use the operations defined in this specification against that same container. Whether other entities using the same, or other, instance of the runtime can see that container is out of scope of this specification. -## State +## State -The state of a container MUST include, at least, the following properties: +The state of a container includes the following properties: -* **`ociVersion`**: (string) is the OCI specification version used when creating the container. -* **`id`**: (string) is the container's ID. +* **`ociVersion`** (string, REQUIRED) is the OCI specification version used when creating the container. +* **`id`** (string, REQUIRED) is the container's ID. This MUST be unique across all containers on this host. There is no requirement that it be unique across hosts. -* **`status`**: (string) is the runtime state of the container. +* **`status`** (string, REQUIRED) is the runtime state of the container. The value MAY be one of: - * `created` : the container has been created but the user-specified code has not yet been executed - * `running` : the container has been created and the user-specified code is running - * `stopped` : the container has been created and the user-specified code has been executed but is no longer running - Additional values MAY be defined by the runtime, however, they MUST be used to represent new runtime states not defined above. -* **`pid`**: (int) is the ID of the main process within the container, as seen by the host. -* **`bundlePath`**: (string) is the absolute path to the container's bundle directory. + * `creating`: the container is being created (step 2 in the [lifecycle](#lifecycle)) + * `created`: the runtime has finished the [create operation](#create) (after step 2 in the [lifecycle](#lifecycle)), and the container process has neither exited nor executed the user-specified program + * `running`: the container process has executed the user-specified program but has not exited (after step 4 in the [lifecycle](#lifecycle)) + * `stopped`: the container process has exited (step 5 in the [lifecycle](#lifecycle)) + + Additional values MAY be defined by the runtime, however, they MUST be used to represent new runtime states not defined above. +* **`pid`** (int, REQUIRED when `status` is `created` or `running`) is the ID of the container process, as seen by the host. +* **`bundle`** (string, REQUIRED) is the absolute path to the container's bundle directory. This is provided so that consumers can find the container's configuration and root filesystem on the host. -* **`annotations`**: (map) contains the list of annotations associated with the container. +* **`annotations`** (map, OPTIONAL) contains the list of annotations associated with the container. If no annotations were provided then this property MAY either be absent or an empty map. +The state MAY include additional properties. + When serialized in JSON, the format MUST adhere to the following pattern: ```json @@ -34,7 +38,7 @@ When serialized in JSON, the format MUST adhere to the following pattern: "id": "oci-container1", "status": "running", "pid": 4422, - "bundlePath": "/containers/redis", + "bundle": "/containers/redis", "annotations": { "myKey": "myValue" } @@ -43,50 +47,62 @@ When serialized in JSON, the format MUST adhere to the following pattern: See [Query State](#query-state) for information on retrieving the state of a container. -## Lifecycle +## Lifecycle The lifecycle describes the timeline of events that happen from when a container is created to when it ceases to exist. -1. OCI compliant runtime's `create` command is invoked with a reference to the location of the bundle and a unique identifier. +1. OCI compliant runtime's [`create`](runtime.md#create) command is invoked with a reference to the location of the bundle and a unique identifier. 2. The container's runtime environment MUST be created according to the configuration in [`config.json`](config.md). - If the runtime is unable to create the environment specified in the [`config.json`](config.md), it MUST generate an error. - While the resources requested in the [`config.json`](config.md) MUST be created, the user-specified code (from [`process`](config.md#process-configuration) MUST NOT be run at this time. - Any updates to `config.json` after this step MUST NOT affect the container. + If the runtime is unable to create the environment specified in the [`config.json`](config.md), it MUST [generate an error](#errors). + While the resources requested in the [`config.json`](config.md) MUST be created, the user-specified program (from [`process`](config.md#process)) MUST NOT be run at this time. + Any updates to [`config.json`](config.md) after this step MUST NOT affect the container. 3. Once the container is created additional actions MAY be performed based on the features the runtime chooses to support. However, some actions might only be available based on the current state of the container (e.g. only available while it is started). -4. Runtime's `start` command is invoked with the unique identifier of the container. - The runtime MUST run the user-specified code, as specified by [`process`](config.md#process-configuration). -5. The container's process is stopped. - This MAY happen due to them erroring out, exiting, crashing or the runtime's `kill` operation being invoked. -6. Runtime's `delete` command is invoked with the unique identifier of the container. - The container MUST be destroyed by undoing the steps performed during create phase (step 2). +4. Runtime's [`start`](runtime.md#start) command is invoked with the unique identifier of the container. +5. The [prestart hooks](config.md#prestart) MUST be invoked by the runtime. + If any prestart hook fails, the runtime MUST [generate an error](#errors), stop the container, and continue the lifecycle at step 10. +6. The runtime MUST run the user-specified program, as specified by [`process`](config.md#process). +7. The [poststart hooks](config.md#poststart) MUST be invoked by the runtime. + If any poststart hook fails, the runtime MUST [log a warning](#warnings), but the remaining hooks and lifecycle continue as if the hook had succeeded. +8. The container process exits. + This MAY happen due to erroring out, exiting, crashing or the runtime's [`kill`](runtime.md#kill) operation being invoked. +9. Runtime's [`delete`](runtime.md#delete) command is invoked with the unique identifier of the container. +10. The container MUST be destroyed by undoing the steps performed during create phase (step 2). +11. The [poststop hooks](config.md#poststop) MUST be invoked by the runtime. + If any poststop hook fails, the runtime MUST [log a warning](#warnings), but the remaining hooks and lifecycle continue as if the hook had succeeded. -## Errors +## Errors In cases where the specified operation generates an error, this specification does not mandate how, or even if, that error is returned or exposed to the user of an implementation. Unless otherwise stated, generating an error MUST leave the state of the environment as if the operation were never attempted - modulo any possible trivial ancillary changes such as logging. -## Operations +## Warnings + +In cases where the specified operation logs a warning, this specification does not mandate how, or even if, that warning is returned or exposed to the user of an implementation. +Unless otherwise stated, logging a warning does not change the flow of the operation; it MUST continue as if the warning had not been logged. + +## Operations OCI compliant runtimes MUST support the following operations, unless the operation is not supported by the base operating system. -Note: these operations are not specifying any command-line APIs, and the paramenters are inputs for general operations. +Note: these operations are not specifying any command-line APIs, and the parameters are inputs for general operations. -### Query State +### Query State `state ` -This operation MUST generate an error if it is not provided the ID of a container. -Attempting to query a container that does not exist MUST generate an error. +This operation MUST [generate an error](#errors) if it is not provided the ID of a container. +Attempting to query a container that does not exist MUST [generate an error](#errors). This operation MUST return the state of a container as specified in the [State](#state) section. -### Create +### Create `create ` -This operation MUST generate an error if it is not provided a path to the bundle and the container ID to associate with the container. -If the ID provided is not unique across all containers within the scope of the runtime, or is not valid in any other way, the implementation MUST generate an error and a new container MUST not be created. +This operation MUST [generate an error](#errors) if it is not provided a path to the bundle and the container ID to associate with the container. +If the ID provided is not unique across all containers within the scope of the runtime, or is not valid in any other way, the implementation MUST [generate an error](#errors) and a new container MUST NOT be created. Using the data in [`config.json`](config.md), this operation MUST create a new container. -This means that all of the resources associated with the container MUST be created, however, the user-specified code MUST NOT be run at this time. +This means that all of the resources associated with the container MUST be created, however, the user-specified program MUST NOT be run at this time. +If the runtime cannot create the container as specified in [`config.json`](config.md), it MUST [generate an error](#errors) and a new container MUST NOT be created. Upon successful completion of this operation the `status` property of this container MUST be `created`. @@ -95,36 +111,36 @@ Runtime callers who are interested in pre-create validation can run [bundle-vali Any changes made to the [`config.json`](config.md) file after this operation will not have an effect on the container. -### Start +### Start `start ` -This operation MUST generate an error if it is not provided the container ID. -Attempting to start a container that does not exist MUST generate an error. -Attempting to start an already started container MUST have no effect on the container and MUST generate an error. -This operation MUST run the user-specified code as specified by [`process`](config.md#process-configuration). +This operation MUST [generate an error](#errors) if it is not provided the container ID. +Attempting to start a container that does not exist MUST [generate an error](#errors). +Attempting to start an already started container MUST have no effect on the container and MUST [generate an error](#errors). +This operation MUST run the user-specified program as specified by [`process`](config.md#process). Upon successful completion of this operation the `status` property of this container MUST be `running`. -### Kill +### Kill `kill ` -This operation MUST generate an error if it is not provided the container ID. -Attempting to send a signal to a container that is not running MUST have no effect on the container and MUST generate an error. +This operation MUST [generate an error](#errors) if it is not provided the container ID. +Attempting to send a signal to a container that is not running MUST have no effect on the container and MUST [generate an error](#errors). This operation MUST send the specified signal to the process in the container. When the process in the container is stopped, irrespective of it being as a result of a `kill` operation or any other reason, the `status` property of this container MUST be `stopped`. -### Delete +### Delete `delete ` -This operation MUST generate an error if it is not provided the container ID. -Attempting to delete a container that does not exist MUST generate an error. -Attempting to delete a container whose process is still running MUST generate an error. +This operation MUST [generate an error](#errors) if it is not provided the container ID. +Attempting to delete a container that does not exist MUST [generate an error](#errors). +Attempting to delete a container whose process is still running MUST [generate an error](#errors). Deleting a container MUST delete the resources that were created during the `create` step. Note that resources associated with the container, but not created by this container, MUST NOT be deleted. Once a container is deleted its ID MAY be used by a subsequent container. -## Hooks +## Hooks Many of the operations specified in this specification have "hooks" that allow for additional actions to be taken before or after each operation. See [runtime configuration for hooks](./config.md#hooks) for more information. diff --git a/vendor/github.com/opencontainers/runtime-spec/schema/README.md b/vendor/github.com/opencontainers/runtime-spec/schema/README.md index 2c8e2927..345c7dbd 100644 --- a/vendor/github.com/opencontainers/runtime-spec/schema/README.md +++ b/vendor/github.com/opencontainers/runtime-spec/schema/README.md @@ -9,6 +9,7 @@ The layout of the files is as follows: * [config-schema.json](config-schema.json) - the primary entrypoint for the [configuration](../config.md) schema * [config-linux.json](config-linux.json) - the [Linux-specific configuration sub-structure](../config-linux.md) * [config-solaris.json](config-solaris.json) - the [Solaris-specific configuration sub-structure](../config-solaris.md) +* [config-windows.json](config-windows.json) - the [Windows-specific configuration sub-structure](../config-windows.md) * [state-schema.json](state-schema.json) - the primary entrypoint for the [state JSON](../runtime.md#state) schema * [defs.json](defs.json) - definitions for general types * [defs-linux.json](defs-linux.json) - definitions for Linux-specific types @@ -38,3 +39,9 @@ Then use it like: ```bash ./validate config-schema.json /config.json ``` + +Or like: + +```bash +./validate https://raw.githubusercontent.com/opencontainers/runtime-spec/v1.0.0-rc1/schema/schema.json /config.json +``` diff --git a/vendor/github.com/opencontainers/runtime-spec/schema/config-linux.json b/vendor/github.com/opencontainers/runtime-spec/schema/config-linux.json index ed89b8be..d51e5b5d 100644 --- a/vendor/github.com/opencontainers/runtime-spec/schema/config-linux.json +++ b/vendor/github.com/opencontainers/runtime-spec/schema/config-linux.json @@ -6,45 +6,24 @@ "properties": { "devices": { "id": "https://opencontainers.org/schema/bundle/linux/devices", - "oneOf": [ - { - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/Device" - } - }, - { - "type": "null" - } - ] + "type": "array", + "items": { + "$ref": "defs-linux.json#/definitions/Device" + } }, "uidMappings": { "id": "https://opencontainers.org/schema/bundle/linux/uidMappings", - "oneOf": [ - { - "type": "array", - "items": { - "$ref": "defs.json#/definitions/IDMapping" - } - }, - { - "type": "null" - } - ] + "type": "array", + "items": { + "$ref": "defs.json#/definitions/IDMapping" + } }, "gidMappings": { "id": "https://opencontainers.org/schema/bundle/linux/gidMappings", - "oneOf": [ - { - "type": "array", - "items": { - "$ref": "defs.json#/definitions/IDMapping" - } - }, - { - "type": "null" - } - ] + "type": "array", + "items": { + "$ref": "defs.json#/definitions/IDMapping" + } }, "namespaces": { "id": "https://opencontainers.org/schema/bundle/linux/namespaces", @@ -61,6 +40,13 @@ "id": "https://opencontainers.org/schema/bundle/linux/resources", "type": "object", "properties": { + "devices": { + "id": "https://opencontainers.org/schema/bundle/linux/resources/devices", + "type": "array", + "items": { + "$ref": "defs-linux.json#/definitions/DeviceCgroup" + } + }, "oomScoreAdj": { "id": "https://opencontainers.org/schema/bundle/linux/resources/oomScoreAdj", "type": "integer", @@ -69,12 +55,16 @@ }, "pids": { "id": "https://opencontainers.org/schema/bundle/linux/resources/pids", + "type": "object", "properties": { "limit": { "id": "https://opencontainers.org/schema/bundle/linux/resources/pids/limit", "$ref": "defs.json#/definitions/int64" } - } + }, + "required": [ + "limit" + ] }, "blockIO": { "id": "https://opencontainers.org/schema/bundle/linux/resources/blockIO", @@ -82,112 +72,82 @@ "properties": { "blkioWeight": { "id": "https://opencontainers.org/schema/bundle/linux/resources/blockIO/blkioWeight", - "$ref": "defs-linux.json#/definitions/blkioWeightPointer" + "$ref": "defs-linux.json#/definitions/blkioWeight" }, "blkioLeafWeight": { "id": "https://opencontainers.org/schema/bundle/linux/resources/blockIO/blkioLeafWeight", - "$ref": "defs-linux.json#/definitions/blkioWeightPointer" + "$ref": "defs-linux.json#/definitions/blkioWeight" }, "blkioThrottleReadBpsDevice": { "id": "https://opencontainers.org/schema/bundle/linux/resources/blockIO/blkioThrottleReadBpsDevice", - "oneOf": [ - { - "type": "array", - "items": [ - { - "$ref": "defs-linux.json#/definitions/blockIODeviceThrottlePointer" - } - ] - }, - { - "type": "null" - } - ] + "type": "array", + "items": { + "$ref": "defs-linux.json#/definitions/blockIODeviceThrottle" + } }, "blkioThrottleWriteBpsDevice": { "id": "https://opencontainers.org/schema/bundle/linux/resources/blockIO/blkioThrottleWriteBpsDevice", - "oneOf": [ - { - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/blockIODeviceThrottlePointer" - } - }, - { - "type": "null" - } - ] + "type": "array", + "items": { + "$ref": "defs-linux.json#/definitions/blockIODeviceThrottle" + } }, "blkioThrottleReadIopsDevice": { "id": "https://opencontainers.org/schema/bundle/linux/resources/blockIO/blkioThrottleReadIopsDevice", - "oneOf": [ - { - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/blockIODeviceThrottlePointer" - } - }, - { - "type": "null" - } - ] + "type": "array", + "items": { + "$ref": "defs-linux.json#/definitions/blockIODeviceThrottle" + } }, "blkioThrottleWriteIopsDevice": { "id": "https://opencontainers.org/schema/bundle/linux/resources/blockIO/blkioThrottleWriteIopsDevice", - "oneOf": [ - { - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/blockIODeviceThrottlePointer" - } - }, - { - "type": "null" - } - ] + "type": "array", + "items": { + "$ref": "defs-linux.json#/definitions/blockIODeviceThrottle" + } }, "blkioWeightDevice": { "id": "https://opencontainers.org/schema/bundle/linux/resources/blockIO/blkioWeightDevice", "type": "array", "items": { - "$ref": "defs-linux.json#/definitions/blockIODeviceWeightPointer" + "$ref": "defs-linux.json#/definitions/blockIODeviceWeight" } } } }, "cpu": { "id": "https://opencontainers.org/schema/bundle/linux/resources/cpu", + "type": "object", "properties": { "cpus": { "id": "https://opencontainers.org/schema/bundle/linux/resources/cpu/cpus", - "$ref": "defs.json#/definitions/stringPointer" + "type": "string" }, "mems": { "id": "https://opencontainers.org/schema/bundle/linux/resources/cpu/mems", - "$ref": "defs.json#/definitions/stringPointer" + "type": "string" }, "period": { "id": "https://opencontainers.org/schema/bundle/linux/resources/cpu/period", - "$ref": "defs.json#/definitions/uint64Pointer" + "$ref": "defs.json#/definitions/uint64" }, "quota": { "id": "https://opencontainers.org/schema/bundle/linux/resources/cpu/quota", - "$ref": "defs.json#/definitions/uint64Pointer" + "$ref": "defs.json#/definitions/int64" }, "realtimePeriod": { "id": "https://opencontainers.org/schema/bundle/linux/resources/cpu/realtimePeriod", - "$ref": "defs.json#/definitions/uint64Pointer" + "$ref": "defs.json#/definitions/uint64" }, "realtimeRuntime": { "id": "https://opencontainers.org/schema/bundle/linux/resources/cpu/realtimeRuntime", - "$ref": "defs.json#/definitions/uint64Pointer" + "$ref": "defs.json#/definitions/int64" }, "shares": { "id": "https://opencontainers.org/schema/bundle/linux/resources/cpu/shares", - "$ref": "defs.json#/definitions/uint64Pointer" + "$ref": "defs.json#/definitions/uint64" } - }, - "type": "object" + } }, "disableOOMKiller": { "id": "https://opencontainers.org/schema/bundle/linux/resources/disableOOMKiller", @@ -195,25 +155,22 @@ }, "hugepageLimits": { "id": "https://opencontainers.org/schema/bundle/linux/resources/hugepageLimits", - "oneOf": [ - { - "type": "array", - "items": { - "type": "object", - "properties": { - "pageSize": { - "type": "string" - }, - "limit": { - "$ref": "defs.json#/definitions/uint64" - } - } + "type": "array", + "items": { + "type": "object", + "properties": { + "pageSize": { + "type": "string" + }, + "limit": { + "$ref": "defs.json#/definitions/uint64" } }, - { - "type": "null" - } - ] + "required": [ + "pageSize", + "limit" + ] + } }, "memory": { "id": "https://opencontainers.org/schema/bundle/linux/resources/memory", @@ -221,23 +178,27 @@ "properties": { "kernel": { "id": "https://opencontainers.org/schema/bundle/linux/resources/memory/kernel", - "$ref": "defs.json#/definitions/uint64Pointer" + "$ref": "defs.json#/definitions/uint64" + }, + "kernelTCP": { + "id": "https://opencontainers.org/schema/bundle/linux/resources/memory/kernelTCP", + "$ref": "defs.json#/definitions/uint64" }, "limit": { "id": "https://opencontainers.org/schema/bundle/linux/resources/memory/limit", - "$ref": "defs.json#/definitions/uint64Pointer" + "$ref": "defs.json#/definitions/uint64" }, "reservation": { "id": "https://opencontainers.org/schema/bundle/linux/resources/memory/reservation", - "$ref": "defs.json#/definitions/uint64Pointer" + "$ref": "defs.json#/definitions/uint64" }, "swap": { "id": "https://opencontainers.org/schema/bundle/linux/resources/memory/swap", - "$ref": "defs.json#/definitions/uint64Pointer" + "$ref": "defs.json#/definitions/uint64" }, "swappiness": { "id": "https://opencontainers.org/schema/bundle/linux/resources/memory/swappiness", - "$ref": "defs.json#/definitions/uint64Pointer" + "$ref": "defs.json#/definitions/uint64" } } }, @@ -251,31 +212,18 @@ }, "priorities": { "id": "https://opencontainers.org/schema/bundle/linux/resources/network/priorities", - "oneOf": [ - { - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/NetworkInterfacePriority" - } - }, - { - "type": "null" - } - ] + "type": "array", + "items": { + "$ref": "defs-linux.json#/definitions/NetworkInterfacePriority" + } } } } } }, "cgroupsPath": { - "oneOf": [ - { - "type": "null" - }, - { - "type": "string" - } - ] + "id": "https://opencontainers.org/schema/bundle/linux/cgroupsPath", + "type": "string" }, "rootfsPropagation": { "id": "https://opencontainers.org/schema/bundle/linux/rootfsPropagation", @@ -283,6 +231,7 @@ }, "seccomp": { "id": "https://opencontainers.org/schema/bundle/linux/seccomp", + "type": "object", "properties": { "defaultAction": { "id": "https://opencontainers.org/schema/bundle/linux/seccomp/defaultAction", @@ -290,17 +239,10 @@ }, "architectures": { "id": "https://opencontainers.org/schema/bundle/linux/seccomp/architectures", - "oneOf": [ - { - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/SeccompArch" - } - }, - { - "type": "null" - } - ] + "type": "array", + "items": { + "$ref": "defs-linux.json#/definitions/SeccompArch" + } }, "syscalls": { "id": "https://opencontainers.org/schema/bundle/linux/seccomp/syscalls", @@ -309,19 +251,11 @@ "$ref": "defs-linux.json#/definitions/Syscall" } } - }, - "type": "object" + } }, "sysctl": { "id": "https://opencontainers.org/schema/bundle/linux/sysctl", - "oneOf": [ - { - "$ref": "defs.json#/definitions/mapStringString" - }, - { - "type": "null" - } - ] + "$ref": "defs.json#/definitions/mapStringString" }, "maskedPaths": { "id": "https://opencontainers.org/schema/bundle/linux/maskedPaths", diff --git a/vendor/github.com/opencontainers/runtime-spec/schema/config-schema.json b/vendor/github.com/opencontainers/runtime-spec/schema/config-schema.json index 351901ad..87e46dfe 100644 --- a/vendor/github.com/opencontainers/runtime-spec/schema/config-schema.json +++ b/vendor/github.com/opencontainers/runtime-spec/schema/config-schema.json @@ -56,9 +56,12 @@ } }, "root": { - "description": "The path to the root filesystem for the container.", + "description": "Configures the container's root filesystem.", "id": "https://opencontainers.org/schema/bundle/root", "type": "object", + "required": [ + "path" + ], "properties": { "path": { "id": "https://opencontainers.org/schema/bundle/root/path", @@ -82,6 +85,24 @@ "id": "https://opencontainers.org/schema/bundle/process/args", "$ref": "defs.json#/definitions/ArrayOfStrings" }, + "consoleSize": { + "id": "https://opencontainers.org/schema/bundle/process/consoleSize", + "type": "object", + "required": [ + "height", + "width" + ], + "properties": { + "height": { + "id": "https://opencontainers.org/schema/bundle/process/consoleSize/height", + "$ref": "defs.json#/definitions/uint64" + }, + "width": { + "id": "https://opencontainers.org/schema/bundle/process/consoleSize/width", + "$ref": "defs.json#/definitions/uint64" + } + } + }, "cwd": { "id": "https://opencontainers.org/schema/bundle/process/cwd", "type": "string" @@ -114,9 +135,43 @@ }, "capabilities": { "id": "https://opencontainers.org/schema/bundle/process/linux/capabilities", - "type": "array", - "items": { - "$ref": "defs-linux.json#/definitions/Capability" + "type": "object", + "properties": { + "bounding": { + "id": "https://opencontainers.org/schema/bundle/process/linux/capabilities/bounding", + "type": "array", + "items": { + "$ref": "defs-linux.json#/definitions/Capability" + } + }, + "permitted": { + "id": "https://opencontainers.org/schema/bundle/process/linux/capabilities/permitted", + "type": "array", + "items": { + "$ref": "defs-linux.json#/definitions/Capability" + } + }, + "effective": { + "id": "https://opencontainers.org/schema/bundle/process/linux/capabilities/effective", + "type": "array", + "items": { + "$ref": "defs-linux.json#/definitions/Capability" + } + }, + "inheritable": { + "id": "https://opencontainers.org/schema/bundle/process/linux/capabilities/inheritable", + "type": "array", + "items": { + "$ref": "defs-linux.json#/definitions/Capability" + } + }, + "ambient": { + "id": "https://opencontainers.org/schema/bundle/process/linux/capabilities/ambient", + "type": "array", + "items": { + "$ref": "defs-linux.json#/definitions/Capability" + } + } } }, "apparmorProfile": { @@ -137,6 +192,11 @@ "items": { "id": "https://opencontainers.org/schema/bundle/linux/rlimits/0", "type": "object", + "required": [ + "type", + "soft", + "hard" + ], "properties": { "hard": { "id": "https://opencontainers.org/schema/bundle/linux/rlimits/0/hard", @@ -161,14 +221,15 @@ }, "solaris": { "$ref": "config-solaris.json#/solaris" + }, + "windows": { + "$ref": "config-windows.json#/windows" } }, "required": [ "ociVersion", "platform", "process", - "root", - "mounts", - "hooks" + "root" ] } diff --git a/vendor/github.com/opencontainers/runtime-spec/schema/config-windows.json b/vendor/github.com/opencontainers/runtime-spec/schema/config-windows.json new file mode 100644 index 00000000..38f7d604 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-spec/schema/config-windows.json @@ -0,0 +1,75 @@ +{ + "windows": { + "description": "Windows platform-specific configurations", + "id": "https://opencontainers.org/schema/bundle/windows", + "type": "object", + "properties": { + "resources": { + "id": "https://opencontainers.org/schema/bundle/windows/resources", + "type": "object", + "properties": { + "memory": { + "id": "https://opencontainers.org/schema/bundle/windows/resources/memory", + "type": "object", + "properties": { + "limit": { + "id": "https://opencontainers.org/schema/bundle/windows/resources/memory/limit", + "$ref": "defs.json#/definitions/uint64" + }, + "reservation": { + "id": "https://opencontainers.org/schema/bundle/windows/resources/memory/reservation", + "$ref": "defs.json#/definitions/uint64" + } + } + }, + "cpu": { + "id": "https://opencontainers.org/schema/bundle/windows/resources/cpu", + "type": "object", + "properties": { + "count": { + "id": "https://opencontainers.org/schema/bundle/windows/resources/cpu/count", + "$ref": "defs.json#/definitions/uint64" + }, + "shares": { + "id": "https://opencontainers.org/schema/bundle/windows/resources/cpu/shares", + "$ref": "defs-windows.json#/definitions/cpuShares" + }, + "percent": { + "id": "https://opencontainers.org/schema/bundle/windows/resources/cpu/percent", + "$ref": "defs.json#/definitions/percent" + } + } + }, + "storage": { + "id": "https://opencontainers.org/schema/bundle/windows/resources/storage", + "type": "object", + "properties": { + "iops": { + "id": "https://opencontainers.org/schema/bundle/windows/resources/storage/iops", + "$ref": "defs.json#/definitions/uint64" + }, + "bps": { + "id": "https://opencontainers.org/schema/bundle/windows/resources/storage/bps", + "$ref": "defs.json#/definitions/uint64" + }, + "sandboxSize": { + "id": "https://opencontainers.org/schema/bundle/windows/resources/storage/sandboxSize", + "$ref": "defs.json#/definitions/uint64" + } + } + }, + "network": { + "id": "https://opencontainers.org/schema/bundle/windows/resources/network", + "type": "object", + "properties": { + "egressBandwidth": { + "id": "https://opencontainers.org/schema/bundle/windows/resources/network/egressBandwidth", + "$ref": "defs.json#/definitions/uint64" + } + } + } + } + } + } + } +} diff --git a/vendor/github.com/opencontainers/runtime-spec/schema/defs-linux.json b/vendor/github.com/opencontainers/runtime-spec/schema/defs-linux.json index c12cef6e..7548e286 100644 --- a/vendor/github.com/opencontainers/runtime-spec/schema/defs-linux.json +++ b/vendor/github.com/opencontainers/runtime-spec/schema/defs-linux.json @@ -18,7 +18,9 @@ "SCMP_ARCH_PPC64", "SCMP_ARCH_PPC64LE", "SCMP_ARCH_S390", - "SCMP_ARCH_S390X" + "SCMP_ARCH_S390X", + "SCMP_ARCH_PARISC", + "SCMP_ARCH_PARISC64" ] }, "SeccompAction": { @@ -44,6 +46,7 @@ ] }, "SyscallArg": { + "type": "object", "properties": { "index": { "$ref": "defs.json#/definitions/uint32" @@ -60,9 +63,12 @@ } }, "Syscall": { + "type": "object", "properties": { - "name": { - "type": "string" + "names": { + "type": [ + "string" + ] }, "action": { "$ref": "#/definitions/SeccompAction" @@ -76,17 +82,17 @@ } }, "Capability": { - "description": "Linux process permissions", + "description": "Linux process capabilities", "type": "string", "pattern": "^CAP_([A-Z]|_)+$" }, "Major": { "description": "major device number", - "$ref": "defs.json#/definitions/uint16" + "$ref": "defs.json#/definitions/int64" }, "Minor": { "description": "minor device number", - "$ref": "defs.json#/definitions/uint16" + "$ref": "defs.json#/definitions/int64" }, "FileMode": { "description": "File permissions mode (typically an octal value)", @@ -94,22 +100,21 @@ "minimum": 0, "maximum": 512 }, - "FilePermissions": { - "type": "string" - }, "FileType": { "description": "Type of a block or special character device", "type": "string", "pattern": "^[cbup]$" }, "Device": { + "type": "object", + "required": [ + "type", + "path" + ], "properties": { "type": { "$ref": "#/definitions/FileType" }, - "permissions": { - "$ref": "#/definitions/FilePermissions" - }, "path": { "$ref": "defs.json#/definitions/FilePath" }, @@ -135,17 +140,8 @@ "minimum": 10, "maximum": 1000 }, - "blkioWeightPointer": { - "oneOf": [ - { - "$ref": "#/definitions/blkioWeight" - }, - { - "type": "null" - } - ] - }, "blockIODevice": { + "type": "object", "properties": { "major": { "$ref": "#/definitions/Major" @@ -166,52 +162,58 @@ "$ref": "#/definitions/blockIODevice" }, { + "type": "object", "properties": { "weight": { - "$ref": "#/definitions/blkioWeightPointer" + "$ref": "#/definitions/blkioWeight" }, "leafWeight": { - "$ref": "#/definitions/blkioWeightPointer" + "$ref": "#/definitions/blkioWeight" } } } ] }, - "blockIODeviceWeightPointer": { - "oneOf": [ - { - "$ref": "#/definitions/blockIODeviceWeight" - }, - { - "type": "null" - } - ] - }, "blockIODeviceThrottle": { "allOf": [ { "$ref": "#/definitions/blockIODevice" }, { + "type": "object", "properties": { "rate": { - "$ref": "defs.json#/definitions/uint64Pointer" + "$ref": "defs.json#/definitions/uint64" } } } ] }, - "blockIODeviceThrottlePointer": { - "oneOf": [ - { - "$ref": "#/definitions/blockIODeviceThrottle" + "DeviceCgroup": { + "type": "object", + "properties": { + "allow": { + "type": "boolean" }, - { - "type": "null" + "type": { + "type": "string" + }, + "major": { + "$ref": "#/definitions/Major" + }, + "minor": { + "$ref": "#/definitions/Minor" + }, + "access": { + "type": "string" } + }, + "required": [ + "allow" ] }, "NetworkInterfacePriority": { + "type": "object", "properties": { "name": { "type": "string" @@ -219,7 +221,11 @@ "priority": { "$ref": "defs.json#/definitions/uint32" } - } + }, + "required": [ + "name", + "priority" + ] }, "NamespaceType": { "type": "string", @@ -234,6 +240,7 @@ ] }, "NamespaceReference": { + "type": "object", "properties": { "type": { "$ref": "#/definitions/NamespaceType" @@ -241,7 +248,10 @@ "path": { "$ref": "defs.json#/definitions/FilePath" } - } + }, + "required": [ + "type" + ] } } } diff --git a/vendor/github.com/opencontainers/runtime-spec/schema/defs-windows.json b/vendor/github.com/opencontainers/runtime-spec/schema/defs-windows.json new file mode 100644 index 00000000..6296da0a --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-spec/schema/defs-windows.json @@ -0,0 +1,10 @@ +{ + "definitions": { + "cpuShares": { + "description": "Relative weight to other containers with CPU Shares defined", + "type": "integer", + "minimum": 1, + "maximum": 10000 + } + } +} diff --git a/vendor/github.com/opencontainers/runtime-spec/schema/defs.json b/vendor/github.com/opencontainers/runtime-spec/schema/defs.json index 32903184..126e285b 100644 --- a/vendor/github.com/opencontainers/runtime-spec/schema/defs.json +++ b/vendor/github.com/opencontainers/runtime-spec/schema/defs.json @@ -1,5 +1,5 @@ { - "description": "Definitions used throughout the OpenContainer Specification", + "description": "Definitions used throughout the Open Container Runtime Specification", "definitions": { "int8": { "type": "integer", @@ -41,35 +41,10 @@ "minimum": 0, "maximum": 18446744073709552000 }, - "uint16Pointer": { - "oneOf": [ - { - "$ref": "#/definitions/uint16" - }, - { - "type": "null" - } - ] - }, - "uint64Pointer": { - "oneOf": [ - { - "$ref": "#/definitions/uint64" - }, - { - "type": "null" - } - ] - }, - "stringPointer": { - "oneOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] + "percent": { + "type": "integer", + "minimum": 0, + "maximum": 100 }, "mapStringString": { "type": "object", @@ -104,6 +79,7 @@ "$ref": "#/definitions/ArrayOfStrings" }, "Hook": { + "type": "object", "properties": { "path": { "$ref": "#/definitions/FilePath" @@ -113,8 +89,14 @@ }, "env": { "$ref": "#/definitions/Env" + }, + "timeout": { + "type": "integer" } - } + }, + "required": [ + "path" + ] }, "ArrayOfHooks": { "type": "array", @@ -123,6 +105,7 @@ } }, "IDMapping": { + "type": "object", "properties": { "hostID": { "$ref": "#/definitions/uint32" @@ -133,9 +116,15 @@ "size": { "$ref": "#/definitions/uint32" } - } + }, + "required": [ + "hostID", + "containerID", + "size" + ] }, "Mount": { + "type": "object", "properties": { "source": { "$ref": "#/definitions/FilePath" @@ -151,9 +140,7 @@ } }, "required": [ - "destination", - "source", - "type" + "destination" ] }, "ociVersion": { @@ -161,14 +148,7 @@ "type": "string" }, "annotations": { - "oneOf": [ - { - "$ref": "#/definitions/mapStringString" - }, - { - "type": "null" - } - ] + "$ref": "#/definitions/mapStringString" } } } diff --git a/vendor/github.com/opencontainers/runtime-spec/schema/state-schema.json b/vendor/github.com/opencontainers/runtime-spec/schema/state-schema.json index 4a14f89b..74544980 100644 --- a/vendor/github.com/opencontainers/runtime-spec/schema/state-schema.json +++ b/vendor/github.com/opencontainers/runtime-spec/schema/state-schema.json @@ -17,6 +17,7 @@ "id": "https://opencontainers.org/schema/runtime/state/status", "type": "string", "enum": [ + "creating", "created", "running", "stopped" @@ -27,8 +28,8 @@ "type": "integer", "minimum": 0 }, - "bundlePath": { - "id": "https://opencontainers.org/schema/runtime/state/bundlePath", + "bundle": { + "id": "https://opencontainers.org/schema/runtime/state/bundle", "type": "string" }, "annotations": { @@ -40,6 +41,6 @@ "id", "status", "pid", - "bundlePath" + "bundle" ] } diff --git a/vendor/github.com/opencontainers/runtime-spec/schema/validate.go b/vendor/github.com/opencontainers/runtime-spec/schema/validate.go index 34125cef..847d2054 100644 --- a/vendor/github.com/opencontainers/runtime-spec/schema/validate.go +++ b/vendor/github.com/opencontainers/runtime-spec/schema/validate.go @@ -5,29 +5,58 @@ import ( "io/ioutil" "os" "path/filepath" + "strings" "github.com/xeipuuv/gojsonschema" ) +const usage = `Validate is used to check document with specified schema. +You can use validate in following ways: + + 1.specify document file as an argument + validate + + 2.pass document content through a pipe + cat | validate + + 3.input document content manually, ended with ctrl+d(or your self-defined EOF keys) + validate + [INPUT DOCUMENT CONTENT HERE] +` + func main() { nargs := len(os.Args[1:]) if nargs == 0 || nargs > 2 { - fmt.Printf("ERROR: usage is: %s []\n", os.Args[0]) + fmt.Printf("ERROR: invalid arguments number\n\n%s\n", usage) os.Exit(1) } - schemaPath, err := filepath.Abs(os.Args[1]) - if err != nil { - fmt.Println(err) + if os.Args[1] == "help" || + os.Args[1] == "--help" || + os.Args[1] == "-h" { + fmt.Printf("%s\n", usage) os.Exit(1) } - schemaLoader := gojsonschema.NewReferenceLoader("file://" + schemaPath) + + schemaPath := os.Args[1] + if !strings.Contains(schemaPath, "://") { + var err error + schemaPath, err = formatFilePath(schemaPath) + if err != nil { + fmt.Printf("ERROR: invalid schema-file path: %s\n", err) + os.Exit(1) + } + schemaPath = "file://" + schemaPath + } + + schemaLoader := gojsonschema.NewReferenceLoader(schemaPath) + var documentLoader gojsonschema.JSONLoader if nargs > 1 { - documentPath, err := filepath.Abs(os.Args[2]) + documentPath, err := formatFilePath(os.Args[2]) if err != nil { - fmt.Println(err) + fmt.Printf("ERROR: invalid document-file path: %s\n", err) os.Exit(1) } documentLoader = gojsonschema.NewReferenceLoader("file://" + documentPath) @@ -43,7 +72,8 @@ func main() { result, err := gojsonschema.Validate(schemaLoader, documentLoader) if err != nil { - panic(err.Error()) + fmt.Println(err) + os.Exit(1) } if result.Valid() { @@ -56,3 +86,15 @@ func main() { os.Exit(1) } } + +func formatFilePath(path string) (string, error) { + if _, err := os.Stat(path); err != nil { + return "", err + } + + absPath, err := filepath.Abs(path) + if err != nil { + return "", err + } + return absPath, nil +} diff --git a/vendor/github.com/opencontainers/runtime-spec/spec.md b/vendor/github.com/opencontainers/runtime-spec/spec.md new file mode 100644 index 00000000..200f4e90 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-spec/spec.md @@ -0,0 +1,46 @@ +# Open Container Initiative Runtime Specification + +The [Open Container Initiative][oci] develops specifications for standards on Operating System process and application containers. + +# Abstract + +The OCI Runtime Specification aims to specify the configuration, execution environment, and lifecycle a container. + +A container's configuration is specified as the `config.json` for the supported platforms and details the fields that enable the creation of a container. +The execution environment is specified to ensure that applications running inside a container have a consistent environment between runtimes along with common actions defined for the container's lifecycle. + +# Platforms + +Platforms defined by this specification are: + +* `linux`: [runtime.md](runtime.md), [config.md](config.md), [config-linux.md](config-linux.md), and [runtime-linux.md](runtime-linux.md). +* `solaris`: [runtime.md](runtime.md), [config.md](config.md), and [config-solaris.md](config-solaris.md). +* `windows`: [runtime.md](runtime.md), [config.md](config.md), and [config-windows.md](config-windows.md). + +# Table of Contents + +- [Introduction](spec.md) + - [Notational Conventions](#notational-conventions) + - [Container Principles](principles.md) +- [Filesystem Bundle](bundle.md) +- [Runtime and Lifecycle](runtime.md) + - [Linux-specific Runtime and Lifecycle](runtime-linux.md) +- [Configuration](config.md) + - [Linux-specific Configuration](config-linux.md) + - [Solaris-specific Configuration](config-solaris.md) + - [Windows-specific Configuration](config-windows.md) +- [Glossary](glossary.md) + +# Notational Conventions + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" are to be interpreted as described in [RFC 2119][rfc2119]. + +The key words "unspecified", "undefined", and "implementation-defined" are to be interpreted as described in the [rationale for the C99 standard][c99-unspecified]. + +An implementation is not compliant for a given CPU architecture if it fails to satisfy one or more of the MUST, REQUIRED, or SHALL requirements for the [platforms](#platforms) it implements. +An implementation is compliant for a given CPU architecture if it satisfies all the MUST, REQUIRED, and SHALL requirements for the [platforms](#platforms) it implements. + + +[c99-unspecified]: http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf#page=18 +[oci]: http://www.opencontainers.org +[rfc2119]: http://tools.ietf.org/html/rfc2119 diff --git a/vendor/github.com/opencontainers/runtime-spec/specs-go/config.go b/vendor/github.com/opencontainers/runtime-spec/specs-go/config.go index b2ac75eb..bd8e96a8 100644 --- a/vendor/github.com/opencontainers/runtime-spec/specs-go/config.go +++ b/vendor/github.com/opencontainers/runtime-spec/specs-go/config.go @@ -4,33 +4,37 @@ import "os" // Spec is the base configuration for the container. type Spec struct { - // Version is the version of the specification that is supported. + // Version of the Open Container Runtime Specification with which the bundle complies. Version string `json:"ociVersion"` - // Platform is the host information for OS and Arch. + // Platform specifies the configuration's target platform. Platform Platform `json:"platform"` - // Process is the container's main process. + // Process configures the container process. Process Process `json:"process"` - // Root is the root information for the container's filesystem. + // Root configures the container's root filesystem. Root Root `json:"root"` - // Hostname is the container's host name. + // Hostname configures the container's hostname. Hostname string `json:"hostname,omitempty"` - // Mounts profile configuration for adding mounts to the container's filesystem. + // Mounts configures additional mounts (on top of Root). Mounts []Mount `json:"mounts,omitempty"` - // Hooks are the commands run at various lifecycle events of the container. - Hooks Hooks `json:"hooks"` - // Annotations is an unstructured key value map that may be set by external tools to store and retrieve arbitrary metadata. + // Hooks configures callbacks for container lifecycle events. + Hooks *Hooks `json:"hooks,omitempty"` + // Annotations contains arbitrary metadata for the container. Annotations map[string]string `json:"annotations,omitempty"` // Linux is platform specific configuration for Linux based containers. Linux *Linux `json:"linux,omitempty" platform:"linux"` // Solaris is platform specific configuration for Solaris containers. Solaris *Solaris `json:"solaris,omitempty" platform:"solaris"` + // Windows is platform specific configuration for Windows based containers, including Hyper-V containers. + Windows *Windows `json:"windows,omitempty" platform:"windows"` } // Process contains information to start a specific application inside the container. type Process struct { // Terminal creates an interactive terminal for the container. Terminal bool `json:"terminal,omitempty"` + // ConsoleSize specifies the size of the console. + ConsoleSize Box `json:"consoleSize,omitempty"` // User specifies user information for the process. User User `json:"user"` // Args specifies the binary and arguments for the application to execute. @@ -40,28 +44,51 @@ type Process struct { // Cwd is the current working directory for the process and must be // relative to the container's root. Cwd string `json:"cwd"` - // Capabilities are Linux capabilities that are kept for the container. - Capabilities []string `json:"capabilities,omitempty" platform:"linux"` + // Capabilities are Linux capabilities that are kept for the process. + Capabilities *LinuxCapabilities `json:"capabilities,omitempty" platform:"linux"` // Rlimits specifies rlimit options to apply to the process. - Rlimits []Rlimit `json:"rlimits,omitempty"` + Rlimits []LinuxRlimit `json:"rlimits,omitempty" platform:"linux"` // NoNewPrivileges controls whether additional privileges could be gained by processes in the container. - NoNewPrivileges bool `json:"noNewPrivileges,omitempty"` - - // ApparmorProfile specifies the apparmor profile for the container. (this field is platform dependent) + NoNewPrivileges bool `json:"noNewPrivileges,omitempty" platform:"linux"` + // ApparmorProfile specifies the apparmor profile for the container. ApparmorProfile string `json:"apparmorProfile,omitempty" platform:"linux"` - // SelinuxLabel specifies the selinux context that the container process is run as. (this field is platform dependent) + // SelinuxLabel specifies the selinux context that the container process is run as. SelinuxLabel string `json:"selinuxLabel,omitempty" platform:"linux"` } -// User specifies Linux/Solaris specific user and group information for the container's -// main process. +// LinuxCapabilities specifies the whitelist of capabilities that are kept for a process. +// http://man7.org/linux/man-pages/man7/capabilities.7.html +type LinuxCapabilities struct { + // Bounding is the set of capabilities checked by the kernel. + Bounding []string `json:"bounding,omitempty" platform:"linux"` + // Effective is the set of capabilities checked by the kernel. + Effective []string `json:"effective,omitempty" platform:"linux"` + // Inheritable is the capabilities preserved across execve. + Inheritable []string `json:"inheritable,omitempty" platform:"linux"` + // Permitted is the limiting superset for effective capabilities. + Permitted []string `json:"permitted,omitempty" platform:"linux"` + // Ambient is the ambient set of capabilities that are kept. + Ambient []string `json:"ambient,omitempty" platform:"linux"` +} + +// Box specifies dimensions of a rectangle. Used for specifying the size of a console. +type Box struct { + // Height is the vertical dimension of a box. + Height uint `json:"height"` + // Width is the horizontal dimension of a box. + Width uint `json:"width"` +} + +// User specifies specific user (and group) information for the container process. type User struct { - // UID is the user id. (this field is platform dependent) + // UID is the user id. UID uint32 `json:"uid" platform:"linux,solaris"` - // GID is the group id. (this field is platform dependent) + // GID is the group id. GID uint32 `json:"gid" platform:"linux,solaris"` - // AdditionalGids are additional group ids set for the container's process. (this field is platform dependent) + // AdditionalGids are additional group ids set for the container's process. AdditionalGids []uint32 `json:"additionalGids,omitempty" platform:"linux,solaris"` + // Username is the user name. + Username string `json:"username,omitempty" platform:"windows"` } // Root contains information about the container's root filesystem on the host. @@ -86,10 +113,10 @@ type Mount struct { // Destination is the path where the mount will be placed relative to the container's root. The path and child directories MUST exist, a runtime MUST NOT create directories automatically to a mount point. Destination string `json:"destination"` // Type specifies the mount kind. - Type string `json:"type"` + Type string `json:"type,omitempty"` // Source specifies the source path of the mount. In the case of bind mounts on // Linux based systems this would be the file on the host. - Source string `json:"source"` + Source string `json:"source,omitempty"` // Options are fstab style mount options. Options []string `json:"options,omitempty"` } @@ -116,24 +143,24 @@ type Hooks struct { // Linux contains platform specific configuration for Linux based containers. type Linux struct { // UIDMapping specifies user mappings for supporting user namespaces on Linux. - UIDMappings []IDMapping `json:"uidMappings,omitempty"` + UIDMappings []LinuxIDMapping `json:"uidMappings,omitempty"` // GIDMapping specifies group mappings for supporting user namespaces on Linux. - GIDMappings []IDMapping `json:"gidMappings,omitempty"` + GIDMappings []LinuxIDMapping `json:"gidMappings,omitempty"` // Sysctl are a set of key value pairs that are set for the container on start Sysctl map[string]string `json:"sysctl,omitempty"` // Resources contain cgroup information for handling resource constraints // for the container - Resources *Resources `json:"resources,omitempty"` + Resources *LinuxResources `json:"resources,omitempty"` // CgroupsPath specifies the path to cgroups that are created and/or joined by the container. // The path is expected to be relative to the cgroups mountpoint. // If resources are specified, the cgroups at CgroupsPath will be updated based on resources. - CgroupsPath *string `json:"cgroupsPath,omitempty"` + CgroupsPath string `json:"cgroupsPath,omitempty"` // Namespaces contains the namespaces that are created and/or joined by the container - Namespaces []Namespace `json:"namespaces,omitempty"` + Namespaces []LinuxNamespace `json:"namespaces,omitempty"` // Devices are a list of device nodes that are created for the container - Devices []Device `json:"devices,omitempty"` + Devices []LinuxDevice `json:"devices,omitempty"` // Seccomp specifies the seccomp security settings for the container. - Seccomp *Seccomp `json:"seccomp,omitempty"` + Seccomp *LinuxSeccomp `json:"seccomp,omitempty"` // RootfsPropagation is the rootfs mount propagation mode for the container. RootfsPropagation string `json:"rootfsPropagation,omitempty"` // MaskedPaths masks over the provided paths inside the container. @@ -144,21 +171,21 @@ type Linux struct { MountLabel string `json:"mountLabel,omitempty"` } -// Namespace is the configuration for a Linux namespace -type Namespace struct { +// LinuxNamespace is the configuration for a Linux namespace +type LinuxNamespace struct { // Type is the type of Linux namespace - Type NamespaceType `json:"type"` + Type LinuxNamespaceType `json:"type"` // Path is a path to an existing namespace persisted on disk that can be joined // and is of the same type Path string `json:"path,omitempty"` } -// NamespaceType is one of the Linux namespaces -type NamespaceType string +// LinuxNamespaceType is one of the Linux namespaces +type LinuxNamespaceType string const ( // PIDNamespace for isolating process IDs - PIDNamespace NamespaceType = "pid" + PIDNamespace LinuxNamespaceType = "pid" // NetworkNamespace for isolating network devices, stacks, ports, etc NetworkNamespace = "network" // MountNamespace for isolating mount points @@ -173,18 +200,18 @@ const ( CgroupNamespace = "cgroup" ) -// IDMapping specifies UID/GID mappings -type IDMapping struct { - // HostID is the UID/GID of the host user or group +// LinuxIDMapping specifies UID/GID mappings +type LinuxIDMapping struct { + // HostID is the starting UID/GID on the host to be mapped to 'ContainerID' HostID uint32 `json:"hostID"` - // ContainerID is the UID/GID of the container's user or group + // ContainerID is the starting UID/GID in the container ContainerID uint32 `json:"containerID"` - // Size is the length of the range of IDs mapped between the two namespaces + // Size is the number of IDs to be mapped Size uint32 `json:"size"` } -// Rlimit type and restrictions -type Rlimit struct { +// LinuxRlimit type and restrictions +type LinuxRlimit struct { // Type of the rlimit to set Type string `json:"type"` // Hard is the hard limit for the specified type @@ -193,66 +220,66 @@ type Rlimit struct { Soft uint64 `json:"soft"` } -// HugepageLimit structure corresponds to limiting kernel hugepages -type HugepageLimit struct { +// LinuxHugepageLimit structure corresponds to limiting kernel hugepages +type LinuxHugepageLimit struct { // Pagesize is the hugepage size - Pagesize *string `json:"pageSize,omitempty"` + Pagesize string `json:"pageSize"` // Limit is the limit of "hugepagesize" hugetlb usage - Limit *uint64 `json:"limit,omitempty"` + Limit uint64 `json:"limit"` } -// InterfacePriority for network interfaces -type InterfacePriority struct { +// LinuxInterfacePriority for network interfaces +type LinuxInterfacePriority struct { // Name is the name of the network interface Name string `json:"name"` // Priority for the interface Priority uint32 `json:"priority"` } -// blockIODevice holds major:minor format supported in blkio cgroup -type blockIODevice struct { +// linuxBlockIODevice holds major:minor format supported in blkio cgroup +type linuxBlockIODevice struct { // Major is the device's major number. Major int64 `json:"major"` // Minor is the device's minor number. Minor int64 `json:"minor"` } -// WeightDevice struct holds a `major:minor weight` pair for blkioWeightDevice -type WeightDevice struct { - blockIODevice +// LinuxWeightDevice struct holds a `major:minor weight` pair for blkioWeightDevice +type LinuxWeightDevice struct { + linuxBlockIODevice // Weight is the bandwidth rate for the device, range is from 10 to 1000 Weight *uint16 `json:"weight,omitempty"` // LeafWeight is the bandwidth rate for the device while competing with the cgroup's child cgroups, range is from 10 to 1000, CFQ scheduler only LeafWeight *uint16 `json:"leafWeight,omitempty"` } -// ThrottleDevice struct holds a `major:minor rate_per_second` pair -type ThrottleDevice struct { - blockIODevice +// LinuxThrottleDevice struct holds a `major:minor rate_per_second` pair +type LinuxThrottleDevice struct { + linuxBlockIODevice // Rate is the IO rate limit per cgroup per device - Rate *uint64 `json:"rate,omitempty"` + Rate uint64 `json:"rate"` } -// BlockIO for Linux cgroup 'blkio' resource management -type BlockIO struct { +// LinuxBlockIO for Linux cgroup 'blkio' resource management +type LinuxBlockIO struct { // Specifies per cgroup weight, range is from 10 to 1000 Weight *uint16 `json:"blkioWeight,omitempty"` // Specifies tasks' weight in the given cgroup while competing with the cgroup's child cgroups, range is from 10 to 1000, CFQ scheduler only LeafWeight *uint16 `json:"blkioLeafWeight,omitempty"` // Weight per cgroup per device, can override BlkioWeight - WeightDevice []WeightDevice `json:"blkioWeightDevice,omitempty"` + WeightDevice []LinuxWeightDevice `json:"blkioWeightDevice,omitempty"` // IO read rate limit per cgroup per device, bytes per second - ThrottleReadBpsDevice []ThrottleDevice `json:"blkioThrottleReadBpsDevice,omitempty"` + ThrottleReadBpsDevice []LinuxThrottleDevice `json:"blkioThrottleReadBpsDevice,omitempty"` // IO write rate limit per cgroup per device, bytes per second - ThrottleWriteBpsDevice []ThrottleDevice `json:"blkioThrottleWriteBpsDevice,omitempty"` + ThrottleWriteBpsDevice []LinuxThrottleDevice `json:"blkioThrottleWriteBpsDevice,omitempty"` // IO read rate limit per cgroup per device, IO per second - ThrottleReadIOPSDevice []ThrottleDevice `json:"blkioThrottleReadIOPSDevice,omitempty"` + ThrottleReadIOPSDevice []LinuxThrottleDevice `json:"blkioThrottleReadIOPSDevice,omitempty"` // IO write rate limit per cgroup per device, IO per second - ThrottleWriteIOPSDevice []ThrottleDevice `json:"blkioThrottleWriteIOPSDevice,omitempty"` + ThrottleWriteIOPSDevice []LinuxThrottleDevice `json:"blkioThrottleWriteIOPSDevice,omitempty"` } -// Memory for Linux cgroup 'memory' resource management -type Memory struct { +// LinuxMemory for Linux cgroup 'memory' resource management +type LinuxMemory struct { // Memory limit (in bytes). Limit *uint64 `json:"limit,omitempty"` // Memory reservation or soft_limit (in bytes). @@ -262,67 +289,67 @@ type Memory struct { // Kernel memory limit (in bytes). Kernel *uint64 `json:"kernel,omitempty"` // Kernel memory limit for tcp (in bytes) - KernelTCP *uint64 `json:"kernelTCP"` + KernelTCP *uint64 `json:"kernelTCP,omitempty"` // How aggressive the kernel will swap memory pages. Range from 0 to 100. Swappiness *uint64 `json:"swappiness,omitempty"` } -// CPU for Linux cgroup 'cpu' resource management -type CPU struct { +// LinuxCPU for Linux cgroup 'cpu' resource management +type LinuxCPU struct { // CPU shares (relative weight (ratio) vs. other cgroups with cpu shares). Shares *uint64 `json:"shares,omitempty"` // CPU hardcap limit (in usecs). Allowed cpu time in a given period. - Quota *uint64 `json:"quota,omitempty"` + Quota *int64 `json:"quota,omitempty"` // CPU period to be used for hardcapping (in usecs). Period *uint64 `json:"period,omitempty"` // How much time realtime scheduling may use (in usecs). - RealtimeRuntime *uint64 `json:"realtimeRuntime,omitempty"` + RealtimeRuntime *int64 `json:"realtimeRuntime,omitempty"` // CPU period to be used for realtime scheduling (in usecs). RealtimePeriod *uint64 `json:"realtimePeriod,omitempty"` // CPUs to use within the cpuset. Default is to use any CPU available. - Cpus *string `json:"cpus,omitempty"` + Cpus string `json:"cpus,omitempty"` // List of memory nodes in the cpuset. Default is to use any available memory node. - Mems *string `json:"mems,omitempty"` + Mems string `json:"mems,omitempty"` } -// Pids for Linux cgroup 'pids' resource management (Linux 4.3) -type Pids struct { +// LinuxPids for Linux cgroup 'pids' resource management (Linux 4.3) +type LinuxPids struct { // Maximum number of PIDs. Default is "no limit". - Limit *int64 `json:"limit,omitempty"` + Limit int64 `json:"limit"` } -// Network identification and priority configuration -type Network struct { +// LinuxNetwork identification and priority configuration +type LinuxNetwork struct { // Set class identifier for container's network packets - ClassID *uint32 `json:"classID"` + ClassID *uint32 `json:"classID,omitempty"` // Set priority of network traffic for container - Priorities []InterfacePriority `json:"priorities,omitempty"` + Priorities []LinuxInterfacePriority `json:"priorities,omitempty"` } -// Resources has container runtime resource constraints -type Resources struct { - // Devices are a list of device rules for the whitelist controller - Devices []DeviceCgroup `json:"devices"` +// LinuxResources has container runtime resource constraints +type LinuxResources struct { + // Devices configures the device whitelist. + Devices []LinuxDeviceCgroup `json:"devices,omitempty"` // DisableOOMKiller disables the OOM killer for out of memory conditions DisableOOMKiller *bool `json:"disableOOMKiller,omitempty"` // Specify an oom_score_adj for the container. OOMScoreAdj *int `json:"oomScoreAdj,omitempty"` // Memory restriction configuration - Memory *Memory `json:"memory,omitempty"` + Memory *LinuxMemory `json:"memory,omitempty"` // CPU resource restriction configuration - CPU *CPU `json:"cpu,omitempty"` + CPU *LinuxCPU `json:"cpu,omitempty"` // Task resource restriction configuration. - Pids *Pids `json:"pids,omitempty"` + Pids *LinuxPids `json:"pids,omitempty"` // BlockIO restriction configuration - BlockIO *BlockIO `json:"blockIO,omitempty"` + BlockIO *LinuxBlockIO `json:"blockIO,omitempty"` // Hugetlb limit (in bytes) - HugepageLimits []HugepageLimit `json:"hugepageLimits,omitempty"` + HugepageLimits []LinuxHugepageLimit `json:"hugepageLimits,omitempty"` // Network restriction configuration - Network *Network `json:"network,omitempty"` + Network *LinuxNetwork `json:"network,omitempty"` } -// Device represents the mknod information for a Linux special device file -type Device struct { +// LinuxDevice represents the mknod information for a Linux special device file +type LinuxDevice struct { // Path to the device. Path string `json:"path"` // Device type, block, char, etc. @@ -339,25 +366,18 @@ type Device struct { GID *uint32 `json:"gid,omitempty"` } -// DeviceCgroup represents a device rule for the whitelist controller -type DeviceCgroup struct { +// LinuxDeviceCgroup represents a device rule for the whitelist controller +type LinuxDeviceCgroup struct { // Allow or deny Allow bool `json:"allow"` // Device type, block, char, etc. - Type *string `json:"type,omitempty"` + Type string `json:"type,omitempty"` // Major is the device's major number. Major *int64 `json:"major,omitempty"` // Minor is the device's minor number. Minor *int64 `json:"minor,omitempty"` // Cgroup access permissions format, rwm. - Access *string `json:"access,omitempty"` -} - -// Seccomp represents syscall restrictions -type Seccomp struct { - DefaultAction Action `json:"defaultAction"` - Architectures []Arch `json:"architectures"` - Syscalls []Syscall `json:"syscalls,omitempty"` + Access string `json:"access,omitempty"` } // Solaris contains platform specific configuration for Solaris application containers. @@ -369,26 +389,26 @@ type Solaris struct { // The maximum amount of shared memory allowed for this container. MaxShmMemory string `json:"maxShmMemory,omitempty"` // Specification for automatic creation of network resources for this container. - Anet []Anet `json:"anet,omitempty"` + Anet []SolarisAnet `json:"anet,omitempty"` // Set limit on the amount of CPU time that can be used by container. - CappedCPU *CappedCPU `json:"cappedCPU,omitempty"` + CappedCPU *SolarisCappedCPU `json:"cappedCPU,omitempty"` // The physical and swap caps on the memory that can be used by this container. - CappedMemory *CappedMemory `json:"cappedMemory,omitempty"` + CappedMemory *SolarisCappedMemory `json:"cappedMemory,omitempty"` } -// CappedCPU allows users to set limit on the amount of CPU time that can be used by container. -type CappedCPU struct { +// SolarisCappedCPU allows users to set limit on the amount of CPU time that can be used by container. +type SolarisCappedCPU struct { Ncpus string `json:"ncpus,omitempty"` } -// CappedMemory allows users to set the physical and swap caps on the memory that can be used by this container. -type CappedMemory struct { +// SolarisCappedMemory allows users to set the physical and swap caps on the memory that can be used by this container. +type SolarisCappedMemory struct { Physical string `json:"physical,omitempty"` Swap string `json:"swap,omitempty"` } -// Anet provides the specification for automatic creation of network resources for this container. -type Anet struct { +// SolarisAnet provides the specification for automatic creation of network resources for this container. +type SolarisAnet struct { // Specify a name for the automatically created VNIC datalink. Linkname string `json:"linkname,omitempty"` // Specify the link over which the VNIC will be created. @@ -405,6 +425,65 @@ type Anet struct { Macaddress string `json:"macAddress,omitempty"` } +// Windows defines the runtime configuration for Windows based containers, including Hyper-V containers. +type Windows struct { + // Resources contains information for handling resource constraints for the container. + Resources *WindowsResources `json:"resources,omitempty"` +} + +// WindowsResources has container runtime resource constraints for containers running on Windows. +type WindowsResources struct { + // Memory restriction configuration. + Memory *WindowsMemoryResources `json:"memory,omitempty"` + // CPU resource restriction configuration. + CPU *WindowsCPUResources `json:"cpu,omitempty"` + // Storage restriction configuration. + Storage *WindowsStorageResources `json:"storage,omitempty"` + // Network restriction configuration. + Network *WindowsNetworkResources `json:"network,omitempty"` +} + +// WindowsMemoryResources contains memory resource management settings. +type WindowsMemoryResources struct { + // Memory limit in bytes. + Limit *uint64 `json:"limit,omitempty"` + // Memory reservation in bytes. + Reservation *uint64 `json:"reservation,omitempty"` +} + +// WindowsCPUResources contains CPU resource management settings. +type WindowsCPUResources struct { + // Number of CPUs available to the container. + Count *uint64 `json:"count,omitempty"` + // CPU shares (relative weight to other containers with cpu shares). Range is from 1 to 10000. + Shares *uint16 `json:"shares,omitempty"` + // Percent of available CPUs usable by the container. + Percent *uint8 `json:"percent,omitempty"` +} + +// WindowsStorageResources contains storage resource management settings. +type WindowsStorageResources struct { + // Specifies maximum Iops for the system drive. + Iops *uint64 `json:"iops,omitempty"` + // Specifies maximum bytes per second for the system drive. + Bps *uint64 `json:"bps,omitempty"` + // Sandbox size specifies the minimum size of the system drive in bytes. + SandboxSize *uint64 `json:"sandboxSize,omitempty"` +} + +// WindowsNetworkResources contains network resource management settings. +type WindowsNetworkResources struct { + // EgressBandwidth is the maximum egress bandwidth in bytes per second. + EgressBandwidth *uint64 `json:"egressBandwidth,omitempty"` +} + +// LinuxSeccomp represents syscall restrictions +type LinuxSeccomp struct { + DefaultAction LinuxSeccompAction `json:"defaultAction"` + Architectures []Arch `json:"architectures,omitempty"` + Syscalls []LinuxSyscall `json:"syscalls"` +} + // Arch used for additional architectures type Arch string @@ -427,45 +506,48 @@ const ( ArchPPC64LE Arch = "SCMP_ARCH_PPC64LE" ArchS390 Arch = "SCMP_ARCH_S390" ArchS390X Arch = "SCMP_ARCH_S390X" + ArchPARISC Arch = "SCMP_ARCH_PARISC" + ArchPARISC64 Arch = "SCMP_ARCH_PARISC64" ) -// Action taken upon Seccomp rule match -type Action string +// LinuxSeccompAction taken upon Seccomp rule match +type LinuxSeccompAction string // Define actions for Seccomp rules const ( - ActKill Action = "SCMP_ACT_KILL" - ActTrap Action = "SCMP_ACT_TRAP" - ActErrno Action = "SCMP_ACT_ERRNO" - ActTrace Action = "SCMP_ACT_TRACE" - ActAllow Action = "SCMP_ACT_ALLOW" + ActKill LinuxSeccompAction = "SCMP_ACT_KILL" + ActTrap LinuxSeccompAction = "SCMP_ACT_TRAP" + ActErrno LinuxSeccompAction = "SCMP_ACT_ERRNO" + ActTrace LinuxSeccompAction = "SCMP_ACT_TRACE" + ActAllow LinuxSeccompAction = "SCMP_ACT_ALLOW" ) -// Operator used to match syscall arguments in Seccomp -type Operator string +// LinuxSeccompOperator used to match syscall arguments in Seccomp +type LinuxSeccompOperator string // Define operators for syscall arguments in Seccomp const ( - OpNotEqual Operator = "SCMP_CMP_NE" - OpLessThan Operator = "SCMP_CMP_LT" - OpLessEqual Operator = "SCMP_CMP_LE" - OpEqualTo Operator = "SCMP_CMP_EQ" - OpGreaterEqual Operator = "SCMP_CMP_GE" - OpGreaterThan Operator = "SCMP_CMP_GT" - OpMaskedEqual Operator = "SCMP_CMP_MASKED_EQ" + OpNotEqual LinuxSeccompOperator = "SCMP_CMP_NE" + OpLessThan LinuxSeccompOperator = "SCMP_CMP_LT" + OpLessEqual LinuxSeccompOperator = "SCMP_CMP_LE" + OpEqualTo LinuxSeccompOperator = "SCMP_CMP_EQ" + OpGreaterEqual LinuxSeccompOperator = "SCMP_CMP_GE" + OpGreaterThan LinuxSeccompOperator = "SCMP_CMP_GT" + OpMaskedEqual LinuxSeccompOperator = "SCMP_CMP_MASKED_EQ" ) -// Arg used for matching specific syscall arguments in Seccomp -type Arg struct { - Index uint `json:"index"` - Value uint64 `json:"value"` - ValueTwo uint64 `json:"valueTwo"` - Op Operator `json:"op"` +// LinuxSeccompArg used for matching specific syscall arguments in Seccomp +type LinuxSeccompArg struct { + Index uint `json:"index"` + Value uint64 `json:"value"` + ValueTwo uint64 `json:"valueTwo"` + Op LinuxSeccompOperator `json:"op"` } -// Syscall is used to match a syscall in Seccomp -type Syscall struct { - Name string `json:"name"` - Action Action `json:"action"` - Args []Arg `json:"args,omitempty"` +// LinuxSyscall is used to match a syscall in Seccomp +type LinuxSyscall struct { + Names []string `json:"names"` + Action LinuxSeccompAction `json:"action"` + Args []LinuxSeccompArg `json:"args"` + Comment string `json:"comment"` } diff --git a/vendor/github.com/opencontainers/runtime-spec/specs-go/state.go b/vendor/github.com/opencontainers/runtime-spec/specs-go/state.go index 445f8c5c..b5dd3bee 100644 --- a/vendor/github.com/opencontainers/runtime-spec/specs-go/state.go +++ b/vendor/github.com/opencontainers/runtime-spec/specs-go/state.go @@ -3,15 +3,15 @@ package specs // State holds information about the runtime state of the container. type State struct { // Version is the version of the specification that is supported. - Version string `json:"version"` + Version string `json:"ociVersion"` // ID is the container ID ID string `json:"id"` - // Status is the runtime state of the container. + // Status is the runtime status of the container. Status string `json:"status"` - // Pid is the process id for the container's main process. + // Pid is the process ID for the container process. Pid int `json:"pid"` - // BundlePath is the path to the container's bundle directory. - BundlePath string `json:"bundlePath"` - // Annotations are the annotations associated with the container. - Annotations map[string]string `json:"annotations"` + // Bundle is the path to the container's bundle directory. + Bundle string `json:"bundle"` + // Annotations are key values associated with the container. + Annotations map[string]string `json:"annotations,omitempty"` } diff --git a/vendor/github.com/opencontainers/runtime-spec/specs-go/version.go b/vendor/github.com/opencontainers/runtime-spec/specs-go/version.go index 2db1b801..26b34c29 100644 --- a/vendor/github.com/opencontainers/runtime-spec/specs-go/version.go +++ b/vendor/github.com/opencontainers/runtime-spec/specs-go/version.go @@ -11,7 +11,7 @@ const ( VersionPatch = 0 // VersionDev indicates development branch. Releases will be empty string. - VersionDev = "-rc1-dev" + VersionDev = "-rc5" ) // Version is the specification version that the package types support. diff --git a/vendor/github.com/opencontainers/runtime-spec/style.md b/vendor/github.com/opencontainers/runtime-spec/style.md index fc501cfc..124b82a3 100644 --- a/vendor/github.com/opencontainers/runtime-spec/style.md +++ b/vendor/github.com/opencontainers/runtime-spec/style.md @@ -1,29 +1,45 @@ -# Style and conventions +# Style and conventions -## One sentence per line +## One sentence per line To keep consistency throughout the Markdown files in the Open Container spec all files should be formatted one sentence per line. This fixes two things: it makes diffing easier with git and it resolves fights about line wrapping length. For example, this paragraph will span three lines in the Markdown source. -## Traditionally hex settings should use JSON integers, not JSON strings +## Traditionally hex settings should use JSON integers, not JSON strings For example, [`"classID": 1048577`][class-id] instead of `"classID": "0x100001"`. The config JSON isn't enough of a UI to be worth jumping through string <-> integer hoops to support an 0x… form ([source][integer-over-hex]). -## Constant names should keep redundant prefixes +## Constant names should keep redundant prefixes For example, `CAP_KILL` instead of `KILL` in [**`linux.capabilities`**][capabilities]. The redundancy reduction from removing the namespacing prefix is not useful enough to be worth trimming the upstream identifier ([source][keep-prefix]). -## Optional settings should have pointer Go types +## Optional settings should not have pointer Go types -So we have a consistent way to identify unset values ([source][optional-pointer]). -The exceptions are entries where the Go default for the type is a no-op in the spec, in which case `omitempty` is sufficient and no pointer is needed (sources [here][no-pointer-for-slices], [here][no-pointer-for-boolean], and [here][pointer-when-updates-require-changes]). +Because in many cases the Go default for the type is a no-op in the spec (sources [here][no-pointer-for-strings], [here][no-pointer-for-slices], and [here][no-pointer-for-boolean]). +The exceptions are entries where we need to distinguish between “not set” and “set to the Go default for that type” ([source][pointer-when-updates-require-changes]), and this decision should be made on a per-setting case. + +## Links + +Internal links should be [relative links][markdown-relative-links] when linking to content within the repository. +Internal links should be used inline. + +External links should be collected at the bottom of a markdown file and used as referenced links. +See 'Referenced Links' in this [markdown quick reference][markdown-quick-reference]. +The use of referenced links in the markdown body helps to keep files clean and organized. +This also facilitates updates of external link targets on a per-file basis. + +Referenced links should be kept in two alphabetically sorted sets, a general reference section followed by a man page section. +To keep Pandoc happy, duplicate naming of links within pages listed in the Makefile's DOC_FILES variable should be avoided by appending an '_N' to the link tagname, where 'N' is some number not currently in use. +The organization and style of an existing reference section should be maintained unless it violates these style guidelines. + +An exception to these rules is when a URL is needed contextually, for example when showing an explicit link to the reader. ## Examples -### Anchoring +### Anchoring For any given section that provides a notable example, it is ideal to have it denoted with [markdown headers][markdown-headers]. The level of header should be such that it is a subheader of the header it is an example of. @@ -47,7 +63,7 @@ To use Some Topic, ... ``` -### Content +### Content Where necessary, the values in the example can be empty or unset, but accommodate with comments regarding this intention. @@ -86,12 +102,32 @@ Following is a fully populated example (not necessarily for copy/paste use) } ``` +### Links + +The following is an example of different types of links. +This is shown as a complete markdown file, where the referenced links are at the bottom. + +```markdown +The specification repository's [glossary](glossary.md) is where readers can find definitions of commonly used terms. + +Readers may click through to the [Open Containers namespace][open-containers] on [GitHub][github]. + +The URL for the Open Containers link above is: https://github.com/opencontainers + + +[github]: https://github.com +[open-containers]: https://github.com/opencontainers +``` + + [capabilities]: config-linux.md#capabilities [class-id]: config-linux.md#network -[integer-over-hex]: https://github.com/opencontainers/runtime-spec/pull/267#discussion_r48360013 +[integer-over-hex]: https://github.com/opencontainers/runtime-spec/pull/267#r48360013 [keep-prefix]: https://github.com/opencontainers/runtime-spec/pull/159#issuecomment-138728337 -[no-pointer-for-boolean]: https://github.com/opencontainers/runtime-spec/pull/290#discussion_r50296396 -[no-pointer-for-slices]: https://github.com/opencontainers/runtime-spec/pull/316/files#r50782982 -[optional-pointer]: https://github.com/opencontainers/runtime-spec/pull/233#discussion_r47829711 -[pointer-when-updates-require-changes]: https://github.com/opencontainers/runtime-spec/pull/317/files#r50932706 +[no-pointer-for-boolean]: https://github.com/opencontainers/runtime-spec/pull/290#r50296396 +[no-pointer-for-slices]: https://github.com/opencontainers/runtime-spec/pull/316#r50782982 +[no-pointer-for-strings]: https://github.com/opencontainers/runtime-spec/pull/653#issue-200439192 +[pointer-when-updates-require-changes]: https://github.com/opencontainers/runtime-spec/pull/317#r50932706 [markdown-headers]: https://help.github.com/articles/basic-writing-and-formatting-syntax/#headings +[markdown-quick-reference]: https://en.support.wordpress.com/markdown-quick-reference +[markdown-relative-links]: https://help.github.com/articles/basic-writing-and-formatting-syntax/#relative-links diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/Godeps.json b/vendor/github.com/opencontainers/runtime-tools/Godeps/Godeps.json deleted file mode 100644 index 6a514c4b..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/Godeps.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "ImportPath": "github.com/opencontainers/runtime-tools", - "GoVersion": "go1.4", - "GodepVersion": "v75", - "Packages": [ - "./..." - ], - "Deps": [ - { - "ImportPath": "github.com/Sirupsen/logrus", - "Comment": "v0.8.3-3-g07d998d", - "Rev": "07d998d174c4e2dc90e2f1989a20724220bca1ff" - }, - { - "ImportPath": "github.com/blang/semver", - "Comment": "v3.1.0", - "Rev": "aea32c919a18e5ef4537bbd283ff29594b1b0165" - }, - { - "ImportPath": "github.com/hashicorp/errwrap", - "Rev": "7554cd9344cec97297fa6649b055a8c98c2a1e55" - }, - { - "ImportPath": "github.com/hashicorp/go-multierror", - "Rev": "ed905158d87462226a13fe39ddf685ea65f1c11f" - }, - { - "ImportPath": "github.com/mndrix/tap-go", - "Rev": "67c9553625499b7e7ed4ac4f2d8bf1cb8f5ecf52" - }, - { - "ImportPath": "github.com/opencontainers/runtime-spec/specs-go", - "Comment": "v1.0.0-rc1-31-gbb6925e", - "Rev": "bb6925ea99f0e366a3f7d1c975f6577475ca25f0" - }, - { - "ImportPath": "github.com/syndtr/gocapability/capability", - "Rev": "2c00daeb6c3b45114c80ac44119e7b8801fdd852" - }, - { - "ImportPath": "github.com/urfave/cli", - "Comment": "v1.19.1", - "Rev": "0bdeddeeb0f650497d603c4ad7b20cfe685682f6" - } - ] -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/Readme b/vendor/github.com/opencontainers/runtime-tools/Godeps/Readme deleted file mode 100644 index 4cdaa53d..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/Readme +++ /dev/null @@ -1,5 +0,0 @@ -This directory tree is generated automatically by godep. - -Please do not edit. - -See https://github.com/tools/godep for more information. diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/.gitignore b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/.gitignore deleted file mode 100644 index f037d684..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/pkg -/bin diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/.gitignore b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/.gitignore deleted file mode 100644 index 66be63a0..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/.gitignore +++ /dev/null @@ -1 +0,0 @@ -logrus diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/.travis.yml b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/.travis.yml deleted file mode 100644 index 2d8c0866..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: go -go: - - 1.2 - - 1.3 - - 1.4 - - tip -install: - - go get -t ./... diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/CHANGELOG.md b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/CHANGELOG.md deleted file mode 100644 index cf2f0d1c..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/CHANGELOG.md +++ /dev/null @@ -1,29 +0,0 @@ -# 0.8.3 - -logrus/core: fix entry log level (#208) -logrus/core: improve performance of text formatter by 40% -logrus/core: expose `LevelHooks` type -logrus/core: add support for DragonflyBSD and NetBSD -formatter/text: print structs more verbosely - -# 0.8.2 - -logrus: fix more Fatal family functions - -# 0.8.1 - -logrus: fix not exiting on `Fatalf` and `Fatalln` - -# 0.8.0 - -logrus: defaults to stderr instead of stdout -hooks/sentry: add special field for `*http.Request` -formatter/text: ignore Windows for colors - -# 0.7.3 - -formatter/\*: allow configuration of timestamp layout - -# 0.7.2 - -formatter/text: Add configuration option for time format (#158) diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/LICENSE b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/LICENSE deleted file mode 100644 index f090cb42..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Simon Eskildsen - -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. diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/README.md b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/README.md deleted file mode 100644 index bd9ffb6e..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/README.md +++ /dev/null @@ -1,356 +0,0 @@ -# Logrus :walrus: [![Build Status](https://travis-ci.org/Sirupsen/logrus.svg?branch=master)](https://travis-ci.org/Sirupsen/logrus) [![godoc reference](https://godoc.org/github.com/Sirupsen/logrus?status.png)][godoc] - -Logrus is a structured logger for Go (golang), completely API compatible with -the standard library logger. [Godoc][godoc]. **Please note the Logrus API is not -yet stable (pre 1.0). Logrus itself is completely stable and has been used in -many large deployments. The core API is unlikely to change much but please -version control your Logrus to make sure you aren't fetching latest `master` on -every build.** - -Nicely color-coded in development (when a TTY is attached, otherwise just -plain text): - -![Colored](http://i.imgur.com/PY7qMwd.png) - -With `log.Formatter = new(logrus.JSONFormatter)`, for easy parsing by logstash -or Splunk: - -```json -{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the -ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} - -{"level":"warning","msg":"The group's number increased tremendously!", -"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} - -{"animal":"walrus","level":"info","msg":"A giant walrus appears!", -"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} - -{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", -"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} - -{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, -"time":"2014-03-10 19:57:38.562543128 -0400 EDT"} -``` - -With the default `log.Formatter = new(&log.TextFormatter{})` when a TTY is not -attached, the output is compatible with the -[logfmt](http://godoc.org/github.com/kr/logfmt) format: - -```text -time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 -time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 -time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true -time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 -time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 -time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true -exit status 1 -``` - -#### Example - -The simplest way to use Logrus is simply the package-level exported logger: - -```go -package main - -import ( - log "github.com/Sirupsen/logrus" -) - -func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - }).Info("A walrus appears") -} -``` - -Note that it's completely api-compatible with the stdlib logger, so you can -replace your `log` imports everywhere with `log "github.com/Sirupsen/logrus"` -and you'll now have the flexibility of Logrus. You can customize it all you -want: - -```go -package main - -import ( - "os" - log "github.com/Sirupsen/logrus" - "github.com/Sirupsen/logrus/hooks/airbrake" -) - -func init() { - // Log as JSON instead of the default ASCII formatter. - log.SetFormatter(&log.JSONFormatter{}) - - // Use the Airbrake hook to report errors that have Error severity or above to - // an exception tracker. You can create custom hooks, see the Hooks section. - log.AddHook(airbrake.NewHook("https://example.com", "xyz", "development")) - - // Output to stderr instead of stdout, could also be a file. - log.SetOutput(os.Stderr) - - // Only log the warning severity or above. - log.SetLevel(log.WarnLevel) -} - -func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - "size": 10, - }).Info("A group of walrus emerges from the ocean") - - log.WithFields(log.Fields{ - "omg": true, - "number": 122, - }).Warn("The group's number increased tremendously!") - - log.WithFields(log.Fields{ - "omg": true, - "number": 100, - }).Fatal("The ice breaks!") - - // A common pattern is to re-use fields between logging statements by re-using - // the logrus.Entry returned from WithFields() - contextLogger := log.WithFields(log.Fields{ - "common": "this is a common field", - "other": "I also should be logged always", - }) - - contextLogger.Info("I'll be logged with common and other field") - contextLogger.Info("Me too") -} -``` - -For more advanced usage such as logging to multiple locations from the same -application, you can also create an instance of the `logrus` Logger: - -```go -package main - -import ( - "github.com/Sirupsen/logrus" -) - -// Create a new instance of the logger. You can have any number of instances. -var log = logrus.New() - -func main() { - // The API for setting attributes is a little different than the package level - // exported logger. See Godoc. - log.Out = os.Stderr - - log.WithFields(logrus.Fields{ - "animal": "walrus", - "size": 10, - }).Info("A group of walrus emerges from the ocean") -} -``` - -#### Fields - -Logrus encourages careful, structured logging though logging fields instead of -long, unparseable error messages. For example, instead of: `log.Fatalf("Failed -to send event %s to topic %s with key %d")`, you should log the much more -discoverable: - -```go -log.WithFields(log.Fields{ - "event": event, - "topic": topic, - "key": key, -}).Fatal("Failed to send event") -``` - -We've found this API forces you to think about logging in a way that produces -much more useful logging messages. We've been in countless situations where just -a single added field to a log statement that was already there would've saved us -hours. The `WithFields` call is optional. - -In general, with Logrus using any of the `printf`-family functions should be -seen as a hint you should add a field, however, you can still use the -`printf`-family functions with Logrus. - -#### Hooks - -You can add hooks for logging levels. For example to send errors to an exception -tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to -multiple places simultaneously, e.g. syslog. - -Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in -`init`: - -```go -import ( - log "github.com/Sirupsen/logrus" - "github.com/Sirupsen/logrus/hooks/airbrake" - logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog" - "log/syslog" -) - -func init() { - log.AddHook(airbrake.NewHook("https://example.com", "xyz", "development")) - - hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") - if err != nil { - log.Error("Unable to connect to local syslog daemon") - } else { - log.AddHook(hook) - } -} -``` - - -| Hook | Description | -| ----- | ----------- | -| [Airbrake](https://github.com/Sirupsen/logrus/blob/master/hooks/airbrake/airbrake.go) | Send errors to an exception tracking service compatible with the Airbrake API. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. | -| [Papertrail](https://github.com/Sirupsen/logrus/blob/master/hooks/papertrail/papertrail.go) | Send errors to the Papertrail hosted logging service via UDP. | -| [Syslog](https://github.com/Sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. | -| [BugSnag](https://github.com/Sirupsen/logrus/blob/master/hooks/bugsnag/bugsnag.go) | Send errors to the Bugsnag exception tracking service. | -| [Sentry](https://github.com/Sirupsen/logrus/blob/master/hooks/sentry/sentry.go) | Send errors to the Sentry error logging and aggregation service. | -| [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. | -| [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) | -| [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. | -| [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` | -| [Graylog](https://github.com/gemnasium/logrus-hooks/tree/master/graylog) | Hook for logging to [Graylog](http://graylog2.org/) | -| [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) | -| [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem | -| [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger | -| [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail | -| [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar | -| [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd | - -#### Level logging - -Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic. - -```go -log.Debug("Useful debugging information.") -log.Info("Something noteworthy happened!") -log.Warn("You should probably take a look at this.") -log.Error("Something failed but I'm not quitting.") -// Calls os.Exit(1) after logging -log.Fatal("Bye.") -// Calls panic() after logging -log.Panic("I'm bailing.") -``` - -You can set the logging level on a `Logger`, then it will only log entries with -that severity or anything above it: - -```go -// Will log anything that is info or above (warn, error, fatal, panic). Default. -log.SetLevel(log.InfoLevel) -``` - -It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose -environment if your application has that. - -#### Entries - -Besides the fields added with `WithField` or `WithFields` some fields are -automatically added to all logging events: - -1. `time`. The timestamp when the entry was created. -2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after - the `AddFields` call. E.g. `Failed to send event.` -3. `level`. The logging level. E.g. `info`. - -#### Environments - -Logrus has no notion of environment. - -If you wish for hooks and formatters to only be used in specific environments, -you should handle that yourself. For example, if your application has a global -variable `Environment`, which is a string representation of the environment you -could do: - -```go -import ( - log "github.com/Sirupsen/logrus" -) - -init() { - // do something here to set environment depending on an environment variable - // or command-line flag - if Environment == "production" { - log.SetFormatter(&logrus.JSONFormatter{}) - } else { - // The TextFormatter is default, you don't actually have to do this. - log.SetFormatter(&log.TextFormatter{}) - } -} -``` - -This configuration is how `logrus` was intended to be used, but JSON in -production is mostly only useful if you do log aggregation with tools like -Splunk or Logstash. - -#### Formatters - -The built-in logging formatters are: - -* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise - without colors. - * *Note:* to force colored output when there is no TTY, set the `ForceColors` - field to `true`. To force no colored output even if there is a TTY set the - `DisableColors` field to `true` -* `logrus.JSONFormatter`. Logs fields as JSON. -* `logrus_logstash.LogstashFormatter`. Logs fields as Logstash Events (http://logstash.net). - - ```go - logrus.SetFormatter(&logrus_logstash.LogstashFormatter{Type: “application_name"}) - ``` - -Third party logging formatters: - -* [`zalgo`](https://github.com/aybabtme/logzalgo): invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦. - -You can define your formatter by implementing the `Formatter` interface, -requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a -`Fields` type (`map[string]interface{}`) with all your fields as well as the -default ones (see Entries section above): - -```go -type MyJSONFormatter struct { -} - -log.SetFormatter(new(MyJSONFormatter)) - -func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { - // Note this doesn't include Time, Level and Message which are available on - // the Entry. Consult `godoc` on information about those fields or read the - // source of the official loggers. - serialized, err := json.Marshal(entry.Data) - if err != nil { - return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) - } - return append(serialized, '\n'), nil -} -``` - -#### Logger as an `io.Writer` - -Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it. - -```go -w := logger.Writer() -defer w.Close() - -srv := http.Server{ - // create a stdlib log.Logger that writes to - // logrus.Logger. - ErrorLog: log.New(w, "", 0), -} -``` - -Each line written to that writer will be printed the usual way, using formatters -and hooks. The level for those entries is `info`. - -#### Rotation - -Log rotation is not provided with Logrus. Log rotation should be done by an -external program (like `logrotate(8)`) that can compress and delete old log -entries. It should not be a feature of the application-level logger. - - -[godoc]: https://godoc.org/github.com/Sirupsen/logrus diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry.go deleted file mode 100644 index 2a980651..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry.go +++ /dev/null @@ -1,255 +0,0 @@ -package logrus - -import ( - "bytes" - "fmt" - "io" - "os" - "time" -) - -// An entry is the final or intermediate Logrus logging entry. It contains all -// the fields passed with WithField{,s}. It's finally logged when Debug, Info, -// Warn, Error, Fatal or Panic is called on it. These objects can be reused and -// passed around as much as you wish to avoid field duplication. -type Entry struct { - Logger *Logger - - // Contains all the fields set by the user. - Data Fields - - // Time at which the log entry was created - Time time.Time - - // Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic - Level Level - - // Message passed to Debug, Info, Warn, Error, Fatal or Panic - Message string -} - -func NewEntry(logger *Logger) *Entry { - return &Entry{ - Logger: logger, - // Default is three fields, give a little extra room - Data: make(Fields, 5), - Level: logger.Level, - } -} - -// Returns a reader for the entry, which is a proxy to the formatter. -func (entry *Entry) Reader() (*bytes.Buffer, error) { - serialized, err := entry.Logger.Formatter.Format(entry) - return bytes.NewBuffer(serialized), err -} - -// Returns the string representation from the reader and ultimately the -// formatter. -func (entry *Entry) String() (string, error) { - reader, err := entry.Reader() - if err != nil { - return "", err - } - - return reader.String(), err -} - -// Add a single field to the Entry. -func (entry *Entry) WithField(key string, value interface{}) *Entry { - return entry.WithFields(Fields{key: value}) -} - -// Add a map of fields to the Entry. -func (entry *Entry) WithFields(fields Fields) *Entry { - data := Fields{} - for k, v := range entry.Data { - data[k] = v - } - for k, v := range fields { - data[k] = v - } - return &Entry{Logger: entry.Logger, Data: data, Level: entry.Level} -} - -func (entry *Entry) log(level Level, msg string) { - entry.Time = time.Now() - entry.Level = level - entry.Message = msg - - if err := entry.Logger.Hooks.Fire(level, entry); err != nil { - entry.Logger.mu.Lock() - fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err) - entry.Logger.mu.Unlock() - } - - reader, err := entry.Reader() - if err != nil { - entry.Logger.mu.Lock() - fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) - entry.Logger.mu.Unlock() - } - - entry.Logger.mu.Lock() - defer entry.Logger.mu.Unlock() - - _, err = io.Copy(entry.Logger.Out, reader) - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) - } - - // To avoid Entry#log() returning a value that only would make sense for - // panic() to use in Entry#Panic(), we avoid the allocation by checking - // directly here. - if level <= PanicLevel { - panic(entry) - } -} - -func (entry *Entry) Debug(args ...interface{}) { - if entry.Level >= DebugLevel { - entry.log(DebugLevel, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Print(args ...interface{}) { - entry.Info(args...) -} - -func (entry *Entry) Info(args ...interface{}) { - if entry.Level >= InfoLevel { - entry.log(InfoLevel, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Warn(args ...interface{}) { - if entry.Level >= WarnLevel { - entry.log(WarnLevel, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Warning(args ...interface{}) { - entry.Warn(args...) -} - -func (entry *Entry) Error(args ...interface{}) { - if entry.Level >= ErrorLevel { - entry.log(ErrorLevel, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Fatal(args ...interface{}) { - if entry.Level >= FatalLevel { - entry.log(FatalLevel, fmt.Sprint(args...)) - } - os.Exit(1) -} - -func (entry *Entry) Panic(args ...interface{}) { - if entry.Level >= PanicLevel { - entry.log(PanicLevel, fmt.Sprint(args...)) - } - panic(fmt.Sprint(args...)) -} - -// Entry Printf family functions - -func (entry *Entry) Debugf(format string, args ...interface{}) { - if entry.Level >= DebugLevel { - entry.Debug(fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Infof(format string, args ...interface{}) { - if entry.Level >= InfoLevel { - entry.Info(fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Printf(format string, args ...interface{}) { - entry.Infof(format, args...) -} - -func (entry *Entry) Warnf(format string, args ...interface{}) { - if entry.Level >= WarnLevel { - entry.Warn(fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Warningf(format string, args ...interface{}) { - entry.Warnf(format, args...) -} - -func (entry *Entry) Errorf(format string, args ...interface{}) { - if entry.Level >= ErrorLevel { - entry.Error(fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Fatalf(format string, args ...interface{}) { - if entry.Level >= FatalLevel { - entry.Fatal(fmt.Sprintf(format, args...)) - } - os.Exit(1) -} - -func (entry *Entry) Panicf(format string, args ...interface{}) { - if entry.Level >= PanicLevel { - entry.Panic(fmt.Sprintf(format, args...)) - } -} - -// Entry Println family functions - -func (entry *Entry) Debugln(args ...interface{}) { - if entry.Level >= DebugLevel { - entry.Debug(entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Infoln(args ...interface{}) { - if entry.Level >= InfoLevel { - entry.Info(entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Println(args ...interface{}) { - entry.Infoln(args...) -} - -func (entry *Entry) Warnln(args ...interface{}) { - if entry.Level >= WarnLevel { - entry.Warn(entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Warningln(args ...interface{}) { - entry.Warnln(args...) -} - -func (entry *Entry) Errorln(args ...interface{}) { - if entry.Level >= ErrorLevel { - entry.Error(entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Fatalln(args ...interface{}) { - if entry.Level >= FatalLevel { - entry.Fatal(entry.sprintlnn(args...)) - } - os.Exit(1) -} - -func (entry *Entry) Panicln(args ...interface{}) { - if entry.Level >= PanicLevel { - entry.Panic(entry.sprintlnn(args...)) - } -} - -// Sprintlnn => Sprint no newline. This is to get the behavior of how -// fmt.Sprintln where spaces are always added between operands, regardless of -// their type. Instead of vendoring the Sprintln implementation to spare a -// string allocation, we do the simplest thing. -func (entry *Entry) sprintlnn(args ...interface{}) string { - msg := fmt.Sprintln(args...) - return msg[:len(msg)-1] -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry_test.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry_test.go deleted file mode 100644 index f7de400a..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package logrus - -import ( - "bytes" - "fmt" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestEntryPanicln(t *testing.T) { - errBoom := fmt.Errorf("boom time") - - defer func() { - p := recover() - assert.NotNil(t, p) - - switch pVal := p.(type) { - case *Entry: - assert.Equal(t, "kaboom", pVal.Message) - assert.Equal(t, errBoom, pVal.Data["err"]) - default: - t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal) - } - }() - - logger := New() - logger.Out = &bytes.Buffer{} - entry := NewEntry(logger) - entry.WithField("err", errBoom).Panicln("kaboom") -} - -func TestEntryPanicf(t *testing.T) { - errBoom := fmt.Errorf("boom again") - - defer func() { - p := recover() - assert.NotNil(t, p) - - switch pVal := p.(type) { - case *Entry: - assert.Equal(t, "kaboom true", pVal.Message) - assert.Equal(t, errBoom, pVal.Data["err"]) - default: - t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal) - } - }() - - logger := New() - logger.Out = &bytes.Buffer{} - entry := NewEntry(logger) - entry.WithField("err", errBoom).Panicf("kaboom %v", true) -} - -func TestEntryLogLevel(t *testing.T) { - out := &bytes.Buffer{} - logger := New() - logger.Out = out - logger.Level = DebugLevel - entry := NewEntry(logger) - assert.Equal(t, DebugLevel, entry.Level) - entry.Level = WarnLevel - entry.Info("it should not be displayed") - assert.Equal(t, "", out.String()) - entry.Warn("it should be displayed") - assert.Contains(t, out.String(), "it should be displayed") -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/basic/basic.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/basic/basic.go deleted file mode 100644 index a1623ec0..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/basic/basic.go +++ /dev/null @@ -1,50 +0,0 @@ -package main - -import ( - "github.com/Sirupsen/logrus" -) - -var log = logrus.New() - -func init() { - log.Formatter = new(logrus.JSONFormatter) - log.Formatter = new(logrus.TextFormatter) // default - log.Level = logrus.DebugLevel -} - -func main() { - defer func() { - err := recover() - if err != nil { - log.WithFields(logrus.Fields{ - "omg": true, - "err": err, - "number": 100, - }).Fatal("The ice breaks!") - } - }() - - log.WithFields(logrus.Fields{ - "animal": "walrus", - "number": 8, - }).Debug("Started observing beach") - - log.WithFields(logrus.Fields{ - "animal": "walrus", - "size": 10, - }).Info("A group of walrus emerges from the ocean") - - log.WithFields(logrus.Fields{ - "omg": true, - "number": 122, - }).Warn("The group's number increased tremendously!") - - log.WithFields(logrus.Fields{ - "temperature": -4, - }).Debug("Temperature changes") - - log.WithFields(logrus.Fields{ - "animal": "orca", - "size": 9009, - }).Panic("It's over 9000!") -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/hook/hook.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/hook/hook.go deleted file mode 100644 index cb5759a3..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/hook/hook.go +++ /dev/null @@ -1,30 +0,0 @@ -package main - -import ( - "github.com/Sirupsen/logrus" - "github.com/Sirupsen/logrus/hooks/airbrake" -) - -var log = logrus.New() - -func init() { - log.Formatter = new(logrus.TextFormatter) // default - log.Hooks.Add(airbrake.NewHook("https://example.com", "xyz", "development")) -} - -func main() { - log.WithFields(logrus.Fields{ - "animal": "walrus", - "size": 10, - }).Info("A group of walrus emerges from the ocean") - - log.WithFields(logrus.Fields{ - "omg": true, - "number": 122, - }).Warn("The group's number increased tremendously!") - - log.WithFields(logrus.Fields{ - "omg": true, - "number": 100, - }).Fatal("The ice breaks!") -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/exported.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/exported.go deleted file mode 100644 index a67e1b80..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/exported.go +++ /dev/null @@ -1,188 +0,0 @@ -package logrus - -import ( - "io" -) - -var ( - // std is the name of the standard logger in stdlib `log` - std = New() -) - -func StandardLogger() *Logger { - return std -} - -// SetOutput sets the standard logger output. -func SetOutput(out io.Writer) { - std.mu.Lock() - defer std.mu.Unlock() - std.Out = out -} - -// SetFormatter sets the standard logger formatter. -func SetFormatter(formatter Formatter) { - std.mu.Lock() - defer std.mu.Unlock() - std.Formatter = formatter -} - -// SetLevel sets the standard logger level. -func SetLevel(level Level) { - std.mu.Lock() - defer std.mu.Unlock() - std.Level = level -} - -// GetLevel returns the standard logger level. -func GetLevel() Level { - std.mu.Lock() - defer std.mu.Unlock() - return std.Level -} - -// AddHook adds a hook to the standard logger hooks. -func AddHook(hook Hook) { - std.mu.Lock() - defer std.mu.Unlock() - std.Hooks.Add(hook) -} - -// WithField creates an entry from the standard logger and adds a field to -// it. If you want multiple fields, use `WithFields`. -// -// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal -// or Panic on the Entry it returns. -func WithField(key string, value interface{}) *Entry { - return std.WithField(key, value) -} - -// WithFields creates an entry from the standard logger and adds multiple -// fields to it. This is simply a helper for `WithField`, invoking it -// once for each field. -// -// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal -// or Panic on the Entry it returns. -func WithFields(fields Fields) *Entry { - return std.WithFields(fields) -} - -// Debug logs a message at level Debug on the standard logger. -func Debug(args ...interface{}) { - std.Debug(args...) -} - -// Print logs a message at level Info on the standard logger. -func Print(args ...interface{}) { - std.Print(args...) -} - -// Info logs a message at level Info on the standard logger. -func Info(args ...interface{}) { - std.Info(args...) -} - -// Warn logs a message at level Warn on the standard logger. -func Warn(args ...interface{}) { - std.Warn(args...) -} - -// Warning logs a message at level Warn on the standard logger. -func Warning(args ...interface{}) { - std.Warning(args...) -} - -// Error logs a message at level Error on the standard logger. -func Error(args ...interface{}) { - std.Error(args...) -} - -// Panic logs a message at level Panic on the standard logger. -func Panic(args ...interface{}) { - std.Panic(args...) -} - -// Fatal logs a message at level Fatal on the standard logger. -func Fatal(args ...interface{}) { - std.Fatal(args...) -} - -// Debugf logs a message at level Debug on the standard logger. -func Debugf(format string, args ...interface{}) { - std.Debugf(format, args...) -} - -// Printf logs a message at level Info on the standard logger. -func Printf(format string, args ...interface{}) { - std.Printf(format, args...) -} - -// Infof logs a message at level Info on the standard logger. -func Infof(format string, args ...interface{}) { - std.Infof(format, args...) -} - -// Warnf logs a message at level Warn on the standard logger. -func Warnf(format string, args ...interface{}) { - std.Warnf(format, args...) -} - -// Warningf logs a message at level Warn on the standard logger. -func Warningf(format string, args ...interface{}) { - std.Warningf(format, args...) -} - -// Errorf logs a message at level Error on the standard logger. -func Errorf(format string, args ...interface{}) { - std.Errorf(format, args...) -} - -// Panicf logs a message at level Panic on the standard logger. -func Panicf(format string, args ...interface{}) { - std.Panicf(format, args...) -} - -// Fatalf logs a message at level Fatal on the standard logger. -func Fatalf(format string, args ...interface{}) { - std.Fatalf(format, args...) -} - -// Debugln logs a message at level Debug on the standard logger. -func Debugln(args ...interface{}) { - std.Debugln(args...) -} - -// Println logs a message at level Info on the standard logger. -func Println(args ...interface{}) { - std.Println(args...) -} - -// Infoln logs a message at level Info on the standard logger. -func Infoln(args ...interface{}) { - std.Infoln(args...) -} - -// Warnln logs a message at level Warn on the standard logger. -func Warnln(args ...interface{}) { - std.Warnln(args...) -} - -// Warningln logs a message at level Warn on the standard logger. -func Warningln(args ...interface{}) { - std.Warningln(args...) -} - -// Errorln logs a message at level Error on the standard logger. -func Errorln(args ...interface{}) { - std.Errorln(args...) -} - -// Panicln logs a message at level Panic on the standard logger. -func Panicln(args ...interface{}) { - std.Panicln(args...) -} - -// Fatalln logs a message at level Fatal on the standard logger. -func Fatalln(args ...interface{}) { - std.Fatalln(args...) -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter.go deleted file mode 100644 index 104d689f..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter.go +++ /dev/null @@ -1,48 +0,0 @@ -package logrus - -import "time" - -const DefaultTimestampFormat = time.RFC3339 - -// The Formatter interface is used to implement a custom Formatter. It takes an -// `Entry`. It exposes all the fields, including the default ones: -// -// * `entry.Data["msg"]`. The message passed from Info, Warn, Error .. -// * `entry.Data["time"]`. The timestamp. -// * `entry.Data["level"]. The level the entry was logged at. -// -// Any additional fields added with `WithField` or `WithFields` are also in -// `entry.Data`. Format is expected to return an array of bytes which are then -// logged to `logger.Out`. -type Formatter interface { - Format(*Entry) ([]byte, error) -} - -// This is to not silently overwrite `time`, `msg` and `level` fields when -// dumping it. If this code wasn't there doing: -// -// logrus.WithField("level", 1).Info("hello") -// -// Would just silently drop the user provided level. Instead with this code -// it'll logged as: -// -// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} -// -// It's not exported because it's still using Data in an opinionated way. It's to -// avoid code duplication between the two default formatters. -func prefixFieldClashes(data Fields) { - _, ok := data["time"] - if ok { - data["fields.time"] = data["time"] - } - - _, ok = data["msg"] - if ok { - data["fields.msg"] = data["msg"] - } - - _, ok = data["level"] - if ok { - data["fields.level"] = data["level"] - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter_bench_test.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter_bench_test.go deleted file mode 100644 index c6d290c7..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter_bench_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package logrus - -import ( - "fmt" - "testing" - "time" -) - -// smallFields is a small size data set for benchmarking -var smallFields = Fields{ - "foo": "bar", - "baz": "qux", - "one": "two", - "three": "four", -} - -// largeFields is a large size data set for benchmarking -var largeFields = Fields{ - "foo": "bar", - "baz": "qux", - "one": "two", - "three": "four", - "five": "six", - "seven": "eight", - "nine": "ten", - "eleven": "twelve", - "thirteen": "fourteen", - "fifteen": "sixteen", - "seventeen": "eighteen", - "nineteen": "twenty", - "a": "b", - "c": "d", - "e": "f", - "g": "h", - "i": "j", - "k": "l", - "m": "n", - "o": "p", - "q": "r", - "s": "t", - "u": "v", - "w": "x", - "y": "z", - "this": "will", - "make": "thirty", - "entries": "yeah", -} - -var errorFields = Fields{ - "foo": fmt.Errorf("bar"), - "baz": fmt.Errorf("qux"), -} - -func BenchmarkErrorTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{DisableColors: true}, errorFields) -} - -func BenchmarkSmallTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{DisableColors: true}, smallFields) -} - -func BenchmarkLargeTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{DisableColors: true}, largeFields) -} - -func BenchmarkSmallColoredTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{ForceColors: true}, smallFields) -} - -func BenchmarkLargeColoredTextFormatter(b *testing.B) { - doBenchmark(b, &TextFormatter{ForceColors: true}, largeFields) -} - -func BenchmarkSmallJSONFormatter(b *testing.B) { - doBenchmark(b, &JSONFormatter{}, smallFields) -} - -func BenchmarkLargeJSONFormatter(b *testing.B) { - doBenchmark(b, &JSONFormatter{}, largeFields) -} - -func doBenchmark(b *testing.B, formatter Formatter, fields Fields) { - entry := &Entry{ - Time: time.Time{}, - Level: InfoLevel, - Message: "message", - Data: fields, - } - var d []byte - var err error - for i := 0; i < b.N; i++ { - d, err = formatter.Format(entry) - if err != nil { - b.Fatal(err) - } - b.SetBytes(int64(len(d))) - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash.go deleted file mode 100644 index 8ea93ddf..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash.go +++ /dev/null @@ -1,56 +0,0 @@ -package logstash - -import ( - "encoding/json" - "fmt" - - "github.com/Sirupsen/logrus" -) - -// Formatter generates json in logstash format. -// Logstash site: http://logstash.net/ -type LogstashFormatter struct { - Type string // if not empty use for logstash type field. - - // TimestampFormat sets the format used for timestamps. - TimestampFormat string -} - -func (f *LogstashFormatter) Format(entry *logrus.Entry) ([]byte, error) { - entry.Data["@version"] = 1 - - if f.TimestampFormat == "" { - f.TimestampFormat = logrus.DefaultTimestampFormat - } - - entry.Data["@timestamp"] = entry.Time.Format(f.TimestampFormat) - - // set message field - v, ok := entry.Data["message"] - if ok { - entry.Data["fields.message"] = v - } - entry.Data["message"] = entry.Message - - // set level field - v, ok = entry.Data["level"] - if ok { - entry.Data["fields.level"] = v - } - entry.Data["level"] = entry.Level.String() - - // set type field - if f.Type != "" { - v, ok = entry.Data["type"] - if ok { - entry.Data["fields.type"] = v - } - entry.Data["type"] = f.Type - } - - serialized, err := json.Marshal(entry.Data) - if err != nil { - return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) - } - return append(serialized, '\n'), nil -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash_test.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash_test.go deleted file mode 100644 index d8814a0e..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package logstash - -import ( - "bytes" - "encoding/json" - "github.com/Sirupsen/logrus" - "github.com/stretchr/testify/assert" - "testing" -) - -func TestLogstashFormatter(t *testing.T) { - assert := assert.New(t) - - lf := LogstashFormatter{Type: "abc"} - - fields := logrus.Fields{ - "message": "def", - "level": "ijk", - "type": "lmn", - "one": 1, - "pi": 3.14, - "bool": true, - } - - entry := logrus.WithFields(fields) - entry.Message = "msg" - entry.Level = logrus.InfoLevel - - b, _ := lf.Format(entry) - - var data map[string]interface{} - dec := json.NewDecoder(bytes.NewReader(b)) - dec.UseNumber() - dec.Decode(&data) - - // base fields - assert.Equal(json.Number("1"), data["@version"]) - assert.NotEmpty(data["@timestamp"]) - assert.Equal("abc", data["type"]) - assert.Equal("msg", data["message"]) - assert.Equal("info", data["level"]) - - // substituted fields - assert.Equal("def", data["fields.message"]) - assert.Equal("ijk", data["fields.level"]) - assert.Equal("lmn", data["fields.type"]) - - // formats - assert.Equal(json.Number("1"), data["one"]) - assert.Equal(json.Number("3.14"), data["pi"]) - assert.Equal(true, data["bool"]) -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hook_test.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hook_test.go deleted file mode 100644 index 13f34cb6..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hook_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package logrus - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -type TestHook struct { - Fired bool -} - -func (hook *TestHook) Fire(entry *Entry) error { - hook.Fired = true - return nil -} - -func (hook *TestHook) Levels() []Level { - return []Level{ - DebugLevel, - InfoLevel, - WarnLevel, - ErrorLevel, - FatalLevel, - PanicLevel, - } -} - -func TestHookFires(t *testing.T) { - hook := new(TestHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - assert.Equal(t, hook.Fired, false) - - log.Print("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, true) - }) -} - -type ModifyHook struct { -} - -func (hook *ModifyHook) Fire(entry *Entry) error { - entry.Data["wow"] = "whale" - return nil -} - -func (hook *ModifyHook) Levels() []Level { - return []Level{ - DebugLevel, - InfoLevel, - WarnLevel, - ErrorLevel, - FatalLevel, - PanicLevel, - } -} - -func TestHookCanModifyEntry(t *testing.T) { - hook := new(ModifyHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.WithField("wow", "elephant").Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["wow"], "whale") - }) -} - -func TestCanFireMultipleHooks(t *testing.T) { - hook1 := new(ModifyHook) - hook2 := new(TestHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook1) - log.Hooks.Add(hook2) - - log.WithField("wow", "elephant").Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["wow"], "whale") - assert.Equal(t, hook2.Fired, true) - }) -} - -type ErrorHook struct { - Fired bool -} - -func (hook *ErrorHook) Fire(entry *Entry) error { - hook.Fired = true - return nil -} - -func (hook *ErrorHook) Levels() []Level { - return []Level{ - ErrorLevel, - } -} - -func TestErrorHookShouldntFireOnInfo(t *testing.T) { - hook := new(ErrorHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.Info("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, false) - }) -} - -func TestErrorHookShouldFireOnError(t *testing.T) { - hook := new(ErrorHook) - - LogAndAssertJSON(t, func(log *Logger) { - log.Hooks.Add(hook) - log.Error("test") - }, func(fields Fields) { - assert.Equal(t, hook.Fired, true) - }) -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks.go deleted file mode 100644 index 3f151cdc..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks.go +++ /dev/null @@ -1,34 +0,0 @@ -package logrus - -// A hook to be fired when logging on the logging levels returned from -// `Levels()` on your implementation of the interface. Note that this is not -// fired in a goroutine or a channel with workers, you should handle such -// functionality yourself if your call is non-blocking and you don't wish for -// the logging calls for levels returned from `Levels()` to block. -type Hook interface { - Levels() []Level - Fire(*Entry) error -} - -// Internal type for storing the hooks on a logger instance. -type LevelHooks map[Level][]Hook - -// Add a hook to an instance of logger. This is called with -// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. -func (hooks LevelHooks) Add(hook Hook) { - for _, level := range hook.Levels() { - hooks[level] = append(hooks[level], hook) - } -} - -// Fire all the hooks for the passed level. Used by `entry.log` to fire -// appropriate hooks for a log entry. -func (hooks LevelHooks) Fire(level Level, entry *Entry) error { - for _, hook := range hooks[level] { - if err := hook.Fire(entry); err != nil { - return err - } - } - - return nil -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/airbrake/airbrake.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/airbrake/airbrake.go deleted file mode 100644 index b0502c33..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/airbrake/airbrake.go +++ /dev/null @@ -1,54 +0,0 @@ -package airbrake - -import ( - "errors" - "fmt" - - "github.com/Sirupsen/logrus" - "github.com/tobi/airbrake-go" -) - -// AirbrakeHook to send exceptions to an exception-tracking service compatible -// with the Airbrake API. -type airbrakeHook struct { - APIKey string - Endpoint string - Environment string -} - -func NewHook(endpoint, apiKey, env string) *airbrakeHook { - return &airbrakeHook{ - APIKey: apiKey, - Endpoint: endpoint, - Environment: env, - } -} - -func (hook *airbrakeHook) Fire(entry *logrus.Entry) error { - airbrake.ApiKey = hook.APIKey - airbrake.Endpoint = hook.Endpoint - airbrake.Environment = hook.Environment - - var notifyErr error - err, ok := entry.Data["error"].(error) - if ok { - notifyErr = err - } else { - notifyErr = errors.New(entry.Message) - } - - airErr := airbrake.Notify(notifyErr) - if airErr != nil { - return fmt.Errorf("Failed to send error to Airbrake: %s", airErr) - } - - return nil -} - -func (hook *airbrakeHook) Levels() []logrus.Level { - return []logrus.Level{ - logrus.ErrorLevel, - logrus.FatalLevel, - logrus.PanicLevel, - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/airbrake/airbrake_test.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/airbrake/airbrake_test.go deleted file mode 100644 index 058a91e3..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/airbrake/airbrake_test.go +++ /dev/null @@ -1,133 +0,0 @@ -package airbrake - -import ( - "encoding/xml" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/Sirupsen/logrus" -) - -type notice struct { - Error NoticeError `xml:"error"` -} -type NoticeError struct { - Class string `xml:"class"` - Message string `xml:"message"` -} - -type customErr struct { - msg string -} - -func (e *customErr) Error() string { - return e.msg -} - -const ( - testAPIKey = "abcxyz" - testEnv = "development" - expectedClass = "*airbrake.customErr" - expectedMsg = "foo" - unintendedMsg = "Airbrake will not see this string" -) - -var ( - noticeError = make(chan NoticeError, 1) -) - -// TestLogEntryMessageReceived checks if invoking Logrus' log.Error -// method causes an XML payload containing the log entry message is received -// by a HTTP server emulating an Airbrake-compatible endpoint. -func TestLogEntryMessageReceived(t *testing.T) { - log := logrus.New() - ts := startAirbrakeServer(t) - defer ts.Close() - - hook := NewHook(ts.URL, testAPIKey, "production") - log.Hooks.Add(hook) - - log.Error(expectedMsg) - - select { - case received := <-noticeError: - if received.Message != expectedMsg { - t.Errorf("Unexpected message received: %s", received.Message) - } - case <-time.After(time.Second): - t.Error("Timed out; no notice received by Airbrake API") - } -} - -// TestLogEntryMessageReceived confirms that, when passing an error type using -// logrus.Fields, a HTTP server emulating an Airbrake endpoint receives the -// error message returned by the Error() method on the error interface -// rather than the logrus.Entry.Message string. -func TestLogEntryWithErrorReceived(t *testing.T) { - log := logrus.New() - ts := startAirbrakeServer(t) - defer ts.Close() - - hook := NewHook(ts.URL, testAPIKey, "production") - log.Hooks.Add(hook) - - log.WithFields(logrus.Fields{ - "error": &customErr{expectedMsg}, - }).Error(unintendedMsg) - - select { - case received := <-noticeError: - if received.Message != expectedMsg { - t.Errorf("Unexpected message received: %s", received.Message) - } - if received.Class != expectedClass { - t.Errorf("Unexpected error class: %s", received.Class) - } - case <-time.After(time.Second): - t.Error("Timed out; no notice received by Airbrake API") - } -} - -// TestLogEntryWithNonErrorTypeNotReceived confirms that, when passing a -// non-error type using logrus.Fields, a HTTP server emulating an Airbrake -// endpoint receives the logrus.Entry.Message string. -// -// Only error types are supported when setting the 'error' field using -// logrus.WithFields(). -func TestLogEntryWithNonErrorTypeNotReceived(t *testing.T) { - log := logrus.New() - ts := startAirbrakeServer(t) - defer ts.Close() - - hook := NewHook(ts.URL, testAPIKey, "production") - log.Hooks.Add(hook) - - log.WithFields(logrus.Fields{ - "error": expectedMsg, - }).Error(unintendedMsg) - - select { - case received := <-noticeError: - if received.Message != unintendedMsg { - t.Errorf("Unexpected message received: %s", received.Message) - } - case <-time.After(time.Second): - t.Error("Timed out; no notice received by Airbrake API") - } -} - -func startAirbrakeServer(t *testing.T) *httptest.Server { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var notice notice - if err := xml.NewDecoder(r.Body).Decode(¬ice); err != nil { - t.Error(err) - } - r.Body.Close() - - noticeError <- notice.Error - })) - - return ts -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag.go deleted file mode 100644 index d20a0f54..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag.go +++ /dev/null @@ -1,68 +0,0 @@ -package logrus_bugsnag - -import ( - "errors" - - "github.com/Sirupsen/logrus" - "github.com/bugsnag/bugsnag-go" -) - -type bugsnagHook struct{} - -// ErrBugsnagUnconfigured is returned if NewBugsnagHook is called before -// bugsnag.Configure. Bugsnag must be configured before the hook. -var ErrBugsnagUnconfigured = errors.New("bugsnag must be configured before installing this logrus hook") - -// ErrBugsnagSendFailed indicates that the hook failed to submit an error to -// bugsnag. The error was successfully generated, but `bugsnag.Notify()` -// failed. -type ErrBugsnagSendFailed struct { - err error -} - -func (e ErrBugsnagSendFailed) Error() string { - return "failed to send error to Bugsnag: " + e.err.Error() -} - -// NewBugsnagHook initializes a logrus hook which sends exceptions to an -// exception-tracking service compatible with the Bugsnag API. Before using -// this hook, you must call bugsnag.Configure(). The returned object should be -// registered with a log via `AddHook()` -// -// Entries that trigger an Error, Fatal or Panic should now include an "error" -// field to send to Bugsnag. -func NewBugsnagHook() (*bugsnagHook, error) { - if bugsnag.Config.APIKey == "" { - return nil, ErrBugsnagUnconfigured - } - return &bugsnagHook{}, nil -} - -// Fire forwards an error to Bugsnag. Given a logrus.Entry, it extracts the -// "error" field (or the Message if the error isn't present) and sends it off. -func (hook *bugsnagHook) Fire(entry *logrus.Entry) error { - var notifyErr error - err, ok := entry.Data["error"].(error) - if ok { - notifyErr = err - } else { - notifyErr = errors.New(entry.Message) - } - - bugsnagErr := bugsnag.Notify(notifyErr) - if bugsnagErr != nil { - return ErrBugsnagSendFailed{bugsnagErr} - } - - return nil -} - -// Levels enumerates the log levels on which the error should be forwarded to -// bugsnag: everything at or above the "Error" level. -func (hook *bugsnagHook) Levels() []logrus.Level { - return []logrus.Level{ - logrus.ErrorLevel, - logrus.FatalLevel, - logrus.PanicLevel, - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag_test.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag_test.go deleted file mode 100644 index e9ea298d..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package logrus_bugsnag - -import ( - "encoding/json" - "errors" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/Sirupsen/logrus" - "github.com/bugsnag/bugsnag-go" -) - -type notice struct { - Events []struct { - Exceptions []struct { - Message string `json:"message"` - } `json:"exceptions"` - } `json:"events"` -} - -func TestNoticeReceived(t *testing.T) { - msg := make(chan string, 1) - expectedMsg := "foo" - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var notice notice - data, _ := ioutil.ReadAll(r.Body) - if err := json.Unmarshal(data, ¬ice); err != nil { - t.Error(err) - } - _ = r.Body.Close() - - msg <- notice.Events[0].Exceptions[0].Message - })) - defer ts.Close() - - hook := &bugsnagHook{} - - bugsnag.Configure(bugsnag.Configuration{ - Endpoint: ts.URL, - ReleaseStage: "production", - APIKey: "12345678901234567890123456789012", - Synchronous: true, - }) - - log := logrus.New() - log.Hooks.Add(hook) - - log.WithFields(logrus.Fields{ - "error": errors.New(expectedMsg), - }).Error("Bugsnag will not see this string") - - select { - case received := <-msg: - if received != expectedMsg { - t.Errorf("Unexpected message received: %s", received) - } - case <-time.After(time.Second): - t.Error("Timed out; no notice received by Bugsnag API") - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/README.md b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/README.md deleted file mode 100644 index ae61e922..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# Papertrail Hook for Logrus :walrus: - -[Papertrail](https://papertrailapp.com) provides hosted log management. Once stored in Papertrail, you can [group](http://help.papertrailapp.com/kb/how-it-works/groups/) your logs on various dimensions, [search](http://help.papertrailapp.com/kb/how-it-works/search-syntax) them, and trigger [alerts](http://help.papertrailapp.com/kb/how-it-works/alerts). - -In most deployments, you'll want to send logs to Papertrail via their [remote_syslog](http://help.papertrailapp.com/kb/configuration/configuring-centralized-logging-from-text-log-files-in-unix/) daemon, which requires no application-specific configuration. This hook is intended for relatively low-volume logging, likely in managed cloud hosting deployments where installing `remote_syslog` is not possible. - -## Usage - -You can find your Papertrail UDP port on your [Papertrail account page](https://papertrailapp.com/account/destinations). Substitute it below for `YOUR_PAPERTRAIL_UDP_PORT`. - -For `YOUR_APP_NAME`, substitute a short string that will readily identify your application or service in the logs. - -```go -import ( - "log/syslog" - "github.com/Sirupsen/logrus" - "github.com/Sirupsen/logrus/hooks/papertrail" -) - -func main() { - log := logrus.New() - hook, err := logrus_papertrail.NewPapertrailHook("logs.papertrailapp.com", YOUR_PAPERTRAIL_UDP_PORT, YOUR_APP_NAME) - - if err == nil { - log.Hooks.Add(hook) - } -} -``` diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail.go deleted file mode 100644 index c0f10c1b..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail.go +++ /dev/null @@ -1,55 +0,0 @@ -package logrus_papertrail - -import ( - "fmt" - "net" - "os" - "time" - - "github.com/Sirupsen/logrus" -) - -const ( - format = "Jan 2 15:04:05" -) - -// PapertrailHook to send logs to a logging service compatible with the Papertrail API. -type PapertrailHook struct { - Host string - Port int - AppName string - UDPConn net.Conn -} - -// NewPapertrailHook creates a hook to be added to an instance of logger. -func NewPapertrailHook(host string, port int, appName string) (*PapertrailHook, error) { - conn, err := net.Dial("udp", fmt.Sprintf("%s:%d", host, port)) - return &PapertrailHook{host, port, appName, conn}, err -} - -// Fire is called when a log event is fired. -func (hook *PapertrailHook) Fire(entry *logrus.Entry) error { - date := time.Now().Format(format) - msg, _ := entry.String() - payload := fmt.Sprintf("<22> %s %s: %s", date, hook.AppName, msg) - - bytesWritten, err := hook.UDPConn.Write([]byte(payload)) - if err != nil { - fmt.Fprintf(os.Stderr, "Unable to send log line to Papertrail via UDP. Wrote %d bytes before error: %v", bytesWritten, err) - return err - } - - return nil -} - -// Levels returns the available logging levels. -func (hook *PapertrailHook) Levels() []logrus.Level { - return []logrus.Level{ - logrus.PanicLevel, - logrus.FatalLevel, - logrus.ErrorLevel, - logrus.WarnLevel, - logrus.InfoLevel, - logrus.DebugLevel, - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail_test.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail_test.go deleted file mode 100644 index 96318d00..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package logrus_papertrail - -import ( - "fmt" - "testing" - - "github.com/Sirupsen/logrus" - "github.com/stvp/go-udp-testing" -) - -func TestWritingToUDP(t *testing.T) { - port := 16661 - udp.SetAddr(fmt.Sprintf(":%d", port)) - - hook, err := NewPapertrailHook("localhost", port, "test") - if err != nil { - t.Errorf("Unable to connect to local UDP server.") - } - - log := logrus.New() - log.Hooks.Add(hook) - - udp.ShouldReceive(t, "foo", func() { - log.Info("foo") - }) -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/README.md b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/README.md deleted file mode 100644 index 8b1f9a16..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/README.md +++ /dev/null @@ -1,78 +0,0 @@ -# Sentry Hook for Logrus :walrus: - -[Sentry](https://getsentry.com) provides both self-hosted and hosted -solutions for exception tracking. -Both client and server are -[open source](https://github.com/getsentry/sentry). - -## Usage - -Every sentry application defined on the server gets a different -[DSN](https://www.getsentry.com/docs/). In the example below replace -`YOUR_DSN` with the one created for your application. - -```go -import ( - "github.com/Sirupsen/logrus" - "github.com/Sirupsen/logrus/hooks/sentry" -) - -func main() { - log := logrus.New() - hook, err := logrus_sentry.NewSentryHook(YOUR_DSN, []logrus.Level{ - logrus.PanicLevel, - logrus.FatalLevel, - logrus.ErrorLevel, - }) - - if err == nil { - log.Hooks.Add(hook) - } -} -``` - -If you wish to initialize a SentryHook with tags, you can use the `NewWithTagsSentryHook` constructor to provide default tags: - -```go -tags := map[string]string{ - "site": "example.com", -} -levels := []logrus.Level{ - logrus.PanicLevel, - logrus.FatalLevel, - logrus.ErrorLevel, -} -hook, err := logrus_sentry.NewWithTagsSentryHook(YOUR_DSN, tags, levels) - -``` - - -## Special fields - -Some logrus fields have a special meaning in this hook, -these are `server_name`, `logger` and `http_request`. -When logs are sent to sentry these fields are treated differently. -- `server_name` (also known as hostname) is the name of the server which -is logging the event (hostname.example.com) -- `logger` is the part of the application which is logging the event. -In go this usually means setting it to the name of the package. -- `http_request` is the in-coming request(*http.Request). The detailed request data are sent to Sentry. - -## Timeout - -`Timeout` is the time the sentry hook will wait for a response -from the sentry server. - -If this time elapses with no response from -the server an error will be returned. - -If `Timeout` is set to 0 the SentryHook will not wait for a reply -and will assume a correct delivery. - -The SentryHook has a default timeout of `100 milliseconds` when created -with a call to `NewSentryHook`. This can be changed by assigning a value to the `Timeout` field: - -```go -hook, _ := logrus_sentry.NewSentryHook(...) -hook.Timeout = 20*time.Second -``` diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry.go deleted file mode 100644 index 4d184b2f..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry.go +++ /dev/null @@ -1,131 +0,0 @@ -package logrus_sentry - -import ( - "fmt" - "net/http" - "time" - - "github.com/Sirupsen/logrus" - "github.com/getsentry/raven-go" -) - -var ( - severityMap = map[logrus.Level]raven.Severity{ - logrus.DebugLevel: raven.DEBUG, - logrus.InfoLevel: raven.INFO, - logrus.WarnLevel: raven.WARNING, - logrus.ErrorLevel: raven.ERROR, - logrus.FatalLevel: raven.FATAL, - logrus.PanicLevel: raven.FATAL, - } -) - -func getAndDel(d logrus.Fields, key string) (string, bool) { - var ( - ok bool - v interface{} - val string - ) - if v, ok = d[key]; !ok { - return "", false - } - - if val, ok = v.(string); !ok { - return "", false - } - delete(d, key) - return val, true -} - -func getAndDelRequest(d logrus.Fields, key string) (*http.Request, bool) { - var ( - ok bool - v interface{} - req *http.Request - ) - if v, ok = d[key]; !ok { - return nil, false - } - if req, ok = v.(*http.Request); !ok || req == nil { - return nil, false - } - delete(d, key) - return req, true -} - -// SentryHook delivers logs to a sentry server. -type SentryHook struct { - // Timeout sets the time to wait for a delivery error from the sentry server. - // If this is set to zero the server will not wait for any response and will - // consider the message correctly sent - Timeout time.Duration - - client *raven.Client - levels []logrus.Level -} - -// NewSentryHook creates a hook to be added to an instance of logger -// and initializes the raven client. -// This method sets the timeout to 100 milliseconds. -func NewSentryHook(DSN string, levels []logrus.Level) (*SentryHook, error) { - client, err := raven.New(DSN) - if err != nil { - return nil, err - } - return &SentryHook{100 * time.Millisecond, client, levels}, nil -} - -// NewWithTagsSentryHook creates a hook with tags to be added to an instance -// of logger and initializes the raven client. This method sets the timeout to -// 100 milliseconds. -func NewWithTagsSentryHook(DSN string, tags map[string]string, levels []logrus.Level) (*SentryHook, error) { - client, err := raven.NewWithTags(DSN, tags) - if err != nil { - return nil, err - } - return &SentryHook{100 * time.Millisecond, client, levels}, nil -} - -// Called when an event should be sent to sentry -// Special fields that sentry uses to give more information to the server -// are extracted from entry.Data (if they are found) -// These fields are: logger, server_name and http_request -func (hook *SentryHook) Fire(entry *logrus.Entry) error { - packet := &raven.Packet{ - Message: entry.Message, - Timestamp: raven.Timestamp(entry.Time), - Level: severityMap[entry.Level], - Platform: "go", - } - - d := entry.Data - - if logger, ok := getAndDel(d, "logger"); ok { - packet.Logger = logger - } - if serverName, ok := getAndDel(d, "server_name"); ok { - packet.ServerName = serverName - } - if req, ok := getAndDelRequest(d, "http_request"); ok { - packet.Interfaces = append(packet.Interfaces, raven.NewHttp(req)) - } - packet.Extra = map[string]interface{}(d) - - _, errCh := hook.client.Capture(packet, nil) - timeout := hook.Timeout - if timeout != 0 { - timeoutCh := time.After(timeout) - select { - case err := <-errCh: - return err - case <-timeoutCh: - return fmt.Errorf("no response from sentry server in %s", timeout) - } - } - return nil -} - -// Levels returns the available logging levels. -func (hook *SentryHook) Levels() []logrus.Level { - return hook.levels -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry_test.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry_test.go deleted file mode 100644 index 5f59f699..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry_test.go +++ /dev/null @@ -1,132 +0,0 @@ -package logrus_sentry - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "reflect" - "strings" - "testing" - - "github.com/Sirupsen/logrus" - "github.com/getsentry/raven-go" -) - -const ( - message = "error message" - server_name = "testserver.internal" - logger_name = "test.logger" -) - -func getTestLogger() *logrus.Logger { - l := logrus.New() - l.Out = ioutil.Discard - return l -} - -func WithTestDSN(t *testing.T, tf func(string, <-chan *raven.Packet)) { - pch := make(chan *raven.Packet, 1) - s := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - defer req.Body.Close() - d := json.NewDecoder(req.Body) - p := &raven.Packet{} - err := d.Decode(p) - if err != nil { - t.Fatal(err.Error()) - } - - pch <- p - })) - defer s.Close() - - fragments := strings.SplitN(s.URL, "://", 2) - dsn := fmt.Sprintf( - "%s://public:secret@%s/sentry/project-id", - fragments[0], - fragments[1], - ) - tf(dsn, pch) -} - -func TestSpecialFields(t *testing.T) { - WithTestDSN(t, func(dsn string, pch <-chan *raven.Packet) { - logger := getTestLogger() - - hook, err := NewSentryHook(dsn, []logrus.Level{ - logrus.ErrorLevel, - }) - - if err != nil { - t.Fatal(err.Error()) - } - logger.Hooks.Add(hook) - - req, _ := http.NewRequest("GET", "url", nil) - logger.WithFields(logrus.Fields{ - "server_name": server_name, - "logger": logger_name, - "http_request": req, - }).Error(message) - - packet := <-pch - if packet.Logger != logger_name { - t.Errorf("logger should have been %s, was %s", logger_name, packet.Logger) - } - - if packet.ServerName != server_name { - t.Errorf("server_name should have been %s, was %s", server_name, packet.ServerName) - } - }) -} - -func TestSentryHandler(t *testing.T) { - WithTestDSN(t, func(dsn string, pch <-chan *raven.Packet) { - logger := getTestLogger() - hook, err := NewSentryHook(dsn, []logrus.Level{ - logrus.ErrorLevel, - }) - if err != nil { - t.Fatal(err.Error()) - } - logger.Hooks.Add(hook) - - logger.Error(message) - packet := <-pch - if packet.Message != message { - t.Errorf("message should have been %s, was %s", message, packet.Message) - } - }) -} - -func TestSentryTags(t *testing.T) { - WithTestDSN(t, func(dsn string, pch <-chan *raven.Packet) { - logger := getTestLogger() - tags := map[string]string{ - "site": "test", - } - levels := []logrus.Level{ - logrus.ErrorLevel, - } - - hook, err := NewWithTagsSentryHook(dsn, tags, levels) - if err != nil { - t.Fatal(err.Error()) - } - - logger.Hooks.Add(hook) - - logger.Error(message) - packet := <-pch - expected := raven.Tags{ - raven.Tag{ - Key: "site", - Value: "test", - }, - } - if !reflect.DeepEqual(packet.Tags, expected) { - t.Errorf("message should have been %s, was %s", message, packet.Message) - } - }) -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/README.md b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/README.md deleted file mode 100644 index 4dbb8e72..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/README.md +++ /dev/null @@ -1,20 +0,0 @@ -# Syslog Hooks for Logrus :walrus: - -## Usage - -```go -import ( - "log/syslog" - "github.com/Sirupsen/logrus" - logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog" -) - -func main() { - log := logrus.New() - hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") - - if err == nil { - log.Hooks.Add(hook) - } -} -``` diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog.go deleted file mode 100644 index b6fa3746..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog.go +++ /dev/null @@ -1,59 +0,0 @@ -package logrus_syslog - -import ( - "fmt" - "github.com/Sirupsen/logrus" - "log/syslog" - "os" -) - -// SyslogHook to send logs via syslog. -type SyslogHook struct { - Writer *syslog.Writer - SyslogNetwork string - SyslogRaddr string -} - -// Creates a hook to be added to an instance of logger. This is called with -// `hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_DEBUG, "")` -// `if err == nil { log.Hooks.Add(hook) }` -func NewSyslogHook(network, raddr string, priority syslog.Priority, tag string) (*SyslogHook, error) { - w, err := syslog.Dial(network, raddr, priority, tag) - return &SyslogHook{w, network, raddr}, err -} - -func (hook *SyslogHook) Fire(entry *logrus.Entry) error { - line, err := entry.String() - if err != nil { - fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err) - return err - } - - switch entry.Level { - case logrus.PanicLevel: - return hook.Writer.Crit(line) - case logrus.FatalLevel: - return hook.Writer.Crit(line) - case logrus.ErrorLevel: - return hook.Writer.Err(line) - case logrus.WarnLevel: - return hook.Writer.Warning(line) - case logrus.InfoLevel: - return hook.Writer.Info(line) - case logrus.DebugLevel: - return hook.Writer.Debug(line) - default: - return nil - } -} - -func (hook *SyslogHook) Levels() []logrus.Level { - return []logrus.Level{ - logrus.PanicLevel, - logrus.FatalLevel, - logrus.ErrorLevel, - logrus.WarnLevel, - logrus.InfoLevel, - logrus.DebugLevel, - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go deleted file mode 100644 index 42762dc1..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package logrus_syslog - -import ( - "github.com/Sirupsen/logrus" - "log/syslog" - "testing" -) - -func TestLocalhostAddAndPrint(t *testing.T) { - log := logrus.New() - hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") - - if err != nil { - t.Errorf("Unable to connect to local syslog.") - } - - log.Hooks.Add(hook) - - for _, level := range hook.Levels() { - if len(log.Hooks[level]) != 1 { - t.Errorf("SyslogHook was not added. The length of log.Hooks[%v]: %v", level, len(log.Hooks[level])) - } - } - - log.Info("Congratulations!") -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter.go deleted file mode 100644 index 2ad6dc5c..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter.go +++ /dev/null @@ -1,41 +0,0 @@ -package logrus - -import ( - "encoding/json" - "fmt" -) - -type JSONFormatter struct { - // TimestampFormat sets the format used for marshaling timestamps. - TimestampFormat string -} - -func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { - data := make(Fields, len(entry.Data)+3) - for k, v := range entry.Data { - switch v := v.(type) { - case error: - // Otherwise errors are ignored by `encoding/json` - // https://github.com/Sirupsen/logrus/issues/137 - data[k] = v.Error() - default: - data[k] = v - } - } - prefixFieldClashes(data) - - timestampFormat := f.TimestampFormat - if timestampFormat == "" { - timestampFormat = DefaultTimestampFormat - } - - data["time"] = entry.Time.Format(timestampFormat) - data["msg"] = entry.Message - data["level"] = entry.Level.String() - - serialized, err := json.Marshal(data) - if err != nil { - return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) - } - return append(serialized, '\n'), nil -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter_test.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter_test.go deleted file mode 100644 index 1d708732..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package logrus - -import ( - "encoding/json" - "errors" - - "testing" -) - -func TestErrorNotLost(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("error", errors.New("wild walrus"))) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["error"] != "wild walrus" { - t.Fatal("Error field not set") - } -} - -func TestErrorNotLostOnFieldNotNamedError(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("omg", errors.New("wild walrus"))) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["omg"] != "wild walrus" { - t.Fatal("Error field not set") - } -} - -func TestFieldClashWithTime(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("time", "right now!")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["fields.time"] != "right now!" { - t.Fatal("fields.time not set to original time field") - } - - if entry["time"] != "0001-01-01T00:00:00Z" { - t.Fatal("time field not set to current time, was: ", entry["time"]) - } -} - -func TestFieldClashWithMsg(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("msg", "something")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["fields.msg"] != "something" { - t.Fatal("fields.msg not set to original msg field") - } -} - -func TestFieldClashWithLevel(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("level", "something")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - entry := make(map[string]interface{}) - err = json.Unmarshal(b, &entry) - if err != nil { - t.Fatal("Unable to unmarshal formatted entry: ", err) - } - - if entry["fields.level"] != "something" { - t.Fatal("fields.level not set to original level field") - } -} - -func TestJSONEntryEndsWithNewline(t *testing.T) { - formatter := &JSONFormatter{} - - b, err := formatter.Format(WithField("level", "something")) - if err != nil { - t.Fatal("Unable to format entry: ", err) - } - - if b[len(b)-1] != '\n' { - t.Fatal("Expected JSON log entry to end with a newline") - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/logger.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/logger.go deleted file mode 100644 index e4974bfb..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/logger.go +++ /dev/null @@ -1,206 +0,0 @@ -package logrus - -import ( - "io" - "os" - "sync" -) - -type Logger struct { - // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a - // file, or leave it default which is `os.Stdout`. You can also set this to - // something more adventorous, such as logging to Kafka. - Out io.Writer - // Hooks for the logger instance. These allow firing events based on logging - // levels and log entries. For example, to send errors to an error tracking - // service, log to StatsD or dump the core on fatal errors. - Hooks LevelHooks - // All log entries pass through the formatter before logged to Out. The - // included formatters are `TextFormatter` and `JSONFormatter` for which - // TextFormatter is the default. In development (when a TTY is attached) it - // logs with colors, but to a file it wouldn't. You can easily implement your - // own that implements the `Formatter` interface, see the `README` or included - // formatters for examples. - Formatter Formatter - // The logging level the logger should log at. This is typically (and defaults - // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be - // logged. `logrus.Debug` is useful in - Level Level - // Used to sync writing to the log. - mu sync.Mutex -} - -// Creates a new logger. Configuration should be set by changing `Formatter`, -// `Out` and `Hooks` directly on the default logger instance. You can also just -// instantiate your own: -// -// var log = &Logger{ -// Out: os.Stderr, -// Formatter: new(JSONFormatter), -// Hooks: make(LevelHooks), -// Level: logrus.DebugLevel, -// } -// -// It's recommended to make this a global instance called `log`. -func New() *Logger { - return &Logger{ - Out: os.Stderr, - Formatter: new(TextFormatter), - Hooks: make(LevelHooks), - Level: InfoLevel, - } -} - -// Adds a field to the log entry, note that you it doesn't log until you call -// Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry. -// Ff you want multiple fields, use `WithFields`. -func (logger *Logger) WithField(key string, value interface{}) *Entry { - return NewEntry(logger).WithField(key, value) -} - -// Adds a struct of fields to the log entry. All it does is call `WithField` for -// each `Field`. -func (logger *Logger) WithFields(fields Fields) *Entry { - return NewEntry(logger).WithFields(fields) -} - -func (logger *Logger) Debugf(format string, args ...interface{}) { - if logger.Level >= DebugLevel { - NewEntry(logger).Debugf(format, args...) - } -} - -func (logger *Logger) Infof(format string, args ...interface{}) { - if logger.Level >= InfoLevel { - NewEntry(logger).Infof(format, args...) - } -} - -func (logger *Logger) Printf(format string, args ...interface{}) { - NewEntry(logger).Printf(format, args...) -} - -func (logger *Logger) Warnf(format string, args ...interface{}) { - if logger.Level >= WarnLevel { - NewEntry(logger).Warnf(format, args...) - } -} - -func (logger *Logger) Warningf(format string, args ...interface{}) { - if logger.Level >= WarnLevel { - NewEntry(logger).Warnf(format, args...) - } -} - -func (logger *Logger) Errorf(format string, args ...interface{}) { - if logger.Level >= ErrorLevel { - NewEntry(logger).Errorf(format, args...) - } -} - -func (logger *Logger) Fatalf(format string, args ...interface{}) { - if logger.Level >= FatalLevel { - NewEntry(logger).Fatalf(format, args...) - } - os.Exit(1) -} - -func (logger *Logger) Panicf(format string, args ...interface{}) { - if logger.Level >= PanicLevel { - NewEntry(logger).Panicf(format, args...) - } -} - -func (logger *Logger) Debug(args ...interface{}) { - if logger.Level >= DebugLevel { - NewEntry(logger).Debug(args...) - } -} - -func (logger *Logger) Info(args ...interface{}) { - if logger.Level >= InfoLevel { - NewEntry(logger).Info(args...) - } -} - -func (logger *Logger) Print(args ...interface{}) { - NewEntry(logger).Info(args...) -} - -func (logger *Logger) Warn(args ...interface{}) { - if logger.Level >= WarnLevel { - NewEntry(logger).Warn(args...) - } -} - -func (logger *Logger) Warning(args ...interface{}) { - if logger.Level >= WarnLevel { - NewEntry(logger).Warn(args...) - } -} - -func (logger *Logger) Error(args ...interface{}) { - if logger.Level >= ErrorLevel { - NewEntry(logger).Error(args...) - } -} - -func (logger *Logger) Fatal(args ...interface{}) { - if logger.Level >= FatalLevel { - NewEntry(logger).Fatal(args...) - } - os.Exit(1) -} - -func (logger *Logger) Panic(args ...interface{}) { - if logger.Level >= PanicLevel { - NewEntry(logger).Panic(args...) - } -} - -func (logger *Logger) Debugln(args ...interface{}) { - if logger.Level >= DebugLevel { - NewEntry(logger).Debugln(args...) - } -} - -func (logger *Logger) Infoln(args ...interface{}) { - if logger.Level >= InfoLevel { - NewEntry(logger).Infoln(args...) - } -} - -func (logger *Logger) Println(args ...interface{}) { - NewEntry(logger).Println(args...) -} - -func (logger *Logger) Warnln(args ...interface{}) { - if logger.Level >= WarnLevel { - NewEntry(logger).Warnln(args...) - } -} - -func (logger *Logger) Warningln(args ...interface{}) { - if logger.Level >= WarnLevel { - NewEntry(logger).Warnln(args...) - } -} - -func (logger *Logger) Errorln(args ...interface{}) { - if logger.Level >= ErrorLevel { - NewEntry(logger).Errorln(args...) - } -} - -func (logger *Logger) Fatalln(args ...interface{}) { - if logger.Level >= FatalLevel { - NewEntry(logger).Fatalln(args...) - } - os.Exit(1) -} - -func (logger *Logger) Panicln(args ...interface{}) { - if logger.Level >= PanicLevel { - NewEntry(logger).Panicln(args...) - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus.go deleted file mode 100644 index 43ee12e9..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus.go +++ /dev/null @@ -1,94 +0,0 @@ -package logrus - -import ( - "fmt" - "log" -) - -// Fields type, used to pass to `WithFields`. -type Fields map[string]interface{} - -// Level type -type Level uint8 - -// Convert the Level to a string. E.g. PanicLevel becomes "panic". -func (level Level) String() string { - switch level { - case DebugLevel: - return "debug" - case InfoLevel: - return "info" - case WarnLevel: - return "warning" - case ErrorLevel: - return "error" - case FatalLevel: - return "fatal" - case PanicLevel: - return "panic" - } - - return "unknown" -} - -// ParseLevel takes a string level and returns the Logrus log level constant. -func ParseLevel(lvl string) (Level, error) { - switch lvl { - case "panic": - return PanicLevel, nil - case "fatal": - return FatalLevel, nil - case "error": - return ErrorLevel, nil - case "warn", "warning": - return WarnLevel, nil - case "info": - return InfoLevel, nil - case "debug": - return DebugLevel, nil - } - - var l Level - return l, fmt.Errorf("not a valid logrus Level: %q", lvl) -} - -// These are the different logging levels. You can set the logging level to log -// on your instance of logger, obtained with `logrus.New()`. -const ( - // PanicLevel level, highest level of severity. Logs and then calls panic with the - // message passed to Debug, Info, ... - PanicLevel Level = iota - // FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the - // logging level is set to Panic. - FatalLevel - // ErrorLevel level. Logs. Used for errors that should definitely be noted. - // Commonly used for hooks to send errors to an error tracking service. - ErrorLevel - // WarnLevel level. Non-critical entries that deserve eyes. - WarnLevel - // InfoLevel level. General operational entries about what's going on inside the - // application. - InfoLevel - // DebugLevel level. Usually only enabled when debugging. Very verbose logging. - DebugLevel -) - -// Won't compile if StdLogger can't be realized by a log.Logger -var _ StdLogger = &log.Logger{} - -// StdLogger is what your logrus-enabled library should take, that way -// it'll accept a stdlib logger and a logrus logger. There's no standard -// interface, this is the closest we get, unfortunately. -type StdLogger interface { - Print(...interface{}) - Printf(string, ...interface{}) - Println(...interface{}) - - Fatal(...interface{}) - Fatalf(string, ...interface{}) - Fatalln(...interface{}) - - Panic(...interface{}) - Panicf(string, ...interface{}) - Panicln(...interface{}) -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus_test.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus_test.go deleted file mode 100644 index efaacea2..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus_test.go +++ /dev/null @@ -1,301 +0,0 @@ -package logrus - -import ( - "bytes" - "encoding/json" - "strconv" - "strings" - "sync" - "testing" - - "github.com/stretchr/testify/assert" -) - -func LogAndAssertJSON(t *testing.T, log func(*Logger), assertions func(fields Fields)) { - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - log(logger) - - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - assertions(fields) -} - -func LogAndAssertText(t *testing.T, log func(*Logger), assertions func(fields map[string]string)) { - var buffer bytes.Buffer - - logger := New() - logger.Out = &buffer - logger.Formatter = &TextFormatter{ - DisableColors: true, - } - - log(logger) - - fields := make(map[string]string) - for _, kv := range strings.Split(buffer.String(), " ") { - if !strings.Contains(kv, "=") { - continue - } - kvArr := strings.Split(kv, "=") - key := strings.TrimSpace(kvArr[0]) - val := kvArr[1] - if kvArr[1][0] == '"' { - var err error - val, err = strconv.Unquote(val) - assert.NoError(t, err) - } - fields[key] = val - } - assertions(fields) -} - -func TestPrint(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Print("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "info") - }) -} - -func TestInfo(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "info") - }) -} - -func TestWarn(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Warn("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["level"], "warning") - }) -} - -func TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln("test", "test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test test") - }) -} - -func TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln("test", 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test 10") - }) -} - -func TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln(10, 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "10 10") - }) -} - -func TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Infoln(10, 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "10 10") - }) -} - -func TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test", 10) - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test10") - }) -} - -func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.Info("test", "test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "testtest") - }) -} - -func TestWithFieldsShouldAllowAssignments(t *testing.T) { - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - localLog := logger.WithFields(Fields{ - "key1": "value1", - }) - - localLog.WithField("key2", "value2").Info("test") - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - assert.Equal(t, "value2", fields["key2"]) - assert.Equal(t, "value1", fields["key1"]) - - buffer = bytes.Buffer{} - fields = Fields{} - localLog.Info("test") - err = json.Unmarshal(buffer.Bytes(), &fields) - assert.Nil(t, err) - - _, ok := fields["key2"] - assert.Equal(t, false, ok) - assert.Equal(t, "value1", fields["key1"]) -} - -func TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("msg", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - }) -} - -func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("msg", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["msg"], "test") - assert.Equal(t, fields["fields.msg"], "hello") - }) -} - -func TestUserSuppliedTimeFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("time", "hello").Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["fields.time"], "hello") - }) -} - -func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) { - LogAndAssertJSON(t, func(log *Logger) { - log.WithField("level", 1).Info("test") - }, func(fields Fields) { - assert.Equal(t, fields["level"], "info") - assert.Equal(t, fields["fields.level"], 1.0) // JSON has floats only - }) -} - -func TestDefaultFieldsAreNotPrefixed(t *testing.T) { - LogAndAssertText(t, func(log *Logger) { - ll := log.WithField("herp", "derp") - ll.Info("hello") - ll.Info("bye") - }, func(fields map[string]string) { - for _, fieldName := range []string{"fields.level", "fields.time", "fields.msg"} { - if _, ok := fields[fieldName]; ok { - t.Fatalf("should not have prefixed %q: %v", fieldName, fields) - } - } - }) -} - -func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) { - - var buffer bytes.Buffer - var fields Fields - - logger := New() - logger.Out = &buffer - logger.Formatter = new(JSONFormatter) - - llog := logger.WithField("context", "eating raw fish") - - llog.Info("looks delicious") - - err := json.Unmarshal(buffer.Bytes(), &fields) - assert.NoError(t, err, "should have decoded first message") - assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields") - assert.Equal(t, fields["msg"], "looks delicious") - assert.Equal(t, fields["context"], "eating raw fish") - - buffer.Reset() - - llog.Warn("omg it is!") - - err = json.Unmarshal(buffer.Bytes(), &fields) - assert.NoError(t, err, "should have decoded second message") - assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields") - assert.Equal(t, fields["msg"], "omg it is!") - assert.Equal(t, fields["context"], "eating raw fish") - assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry") - -} - -func TestConvertLevelToString(t *testing.T) { - assert.Equal(t, "debug", DebugLevel.String()) - assert.Equal(t, "info", InfoLevel.String()) - assert.Equal(t, "warning", WarnLevel.String()) - assert.Equal(t, "error", ErrorLevel.String()) - assert.Equal(t, "fatal", FatalLevel.String()) - assert.Equal(t, "panic", PanicLevel.String()) -} - -func TestParseLevel(t *testing.T) { - l, err := ParseLevel("panic") - assert.Nil(t, err) - assert.Equal(t, PanicLevel, l) - - l, err = ParseLevel("fatal") - assert.Nil(t, err) - assert.Equal(t, FatalLevel, l) - - l, err = ParseLevel("error") - assert.Nil(t, err) - assert.Equal(t, ErrorLevel, l) - - l, err = ParseLevel("warn") - assert.Nil(t, err) - assert.Equal(t, WarnLevel, l) - - l, err = ParseLevel("warning") - assert.Nil(t, err) - assert.Equal(t, WarnLevel, l) - - l, err = ParseLevel("info") - assert.Nil(t, err) - assert.Equal(t, InfoLevel, l) - - l, err = ParseLevel("debug") - assert.Nil(t, err) - assert.Equal(t, DebugLevel, l) - - l, err = ParseLevel("invalid") - assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error()) -} - -func TestGetSetLevelRace(t *testing.T) { - wg := sync.WaitGroup{} - for i := 0; i < 100; i++ { - wg.Add(1) - go func(i int) { - defer wg.Done() - if i%2 == 0 { - SetLevel(InfoLevel) - } else { - GetLevel() - } - }(i) - - } - wg.Wait() -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_bsd.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_bsd.go deleted file mode 100644 index 71f8d67a..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_bsd.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build darwin freebsd openbsd netbsd dragonfly - -package logrus - -import "syscall" - -const ioctlReadTermios = syscall.TIOCGETA - -type Termios syscall.Termios diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_linux.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_linux.go deleted file mode 100644 index a2c0b40d..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_linux.go +++ /dev/null @@ -1,12 +0,0 @@ -// Based on ssh/terminal: -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package logrus - -import "syscall" - -const ioctlReadTermios = syscall.TCGETS - -type Termios syscall.Termios diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_notwindows.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_notwindows.go deleted file mode 100644 index 4bb53760..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_notwindows.go +++ /dev/null @@ -1,21 +0,0 @@ -// Based on ssh/terminal: -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux darwin freebsd openbsd netbsd dragonfly - -package logrus - -import ( - "syscall" - "unsafe" -) - -// IsTerminal returns true if the given file descriptor is a terminal. -func IsTerminal() bool { - fd := syscall.Stdout - var termios Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_windows.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_windows.go deleted file mode 100644 index 2e09f6f7..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_windows.go +++ /dev/null @@ -1,27 +0,0 @@ -// Based on ssh/terminal: -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package logrus - -import ( - "syscall" - "unsafe" -) - -var kernel32 = syscall.NewLazyDLL("kernel32.dll") - -var ( - procGetConsoleMode = kernel32.NewProc("GetConsoleMode") -) - -// IsTerminal returns true if the given file descriptor is a terminal. -func IsTerminal() bool { - fd := syscall.Stdout - var st uint32 - r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0) - return r != 0 && e == 0 -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter.go deleted file mode 100644 index e25f86cd..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter.go +++ /dev/null @@ -1,158 +0,0 @@ -package logrus - -import ( - "bytes" - "fmt" - "runtime" - "sort" - "strings" - "time" -) - -const ( - nocolor = 0 - red = 31 - green = 32 - yellow = 33 - blue = 34 - gray = 37 -) - -var ( - baseTimestamp time.Time - isTerminal bool -) - -func init() { - baseTimestamp = time.Now() - isTerminal = IsTerminal() -} - -func miniTS() int { - return int(time.Since(baseTimestamp) / time.Second) -} - -type TextFormatter struct { - // Set to true to bypass checking for a TTY before outputting colors. - ForceColors bool - - // Force disabling colors. - DisableColors bool - - // Disable timestamp logging. useful when output is redirected to logging - // system that already adds timestamps. - DisableTimestamp bool - - // Enable logging the full timestamp when a TTY is attached instead of just - // the time passed since beginning of execution. - FullTimestamp bool - - // TimestampFormat to use for display when a full timestamp is printed - TimestampFormat string - - // The fields are sorted by default for a consistent output. For applications - // that log extremely frequently and don't use the JSON formatter this may not - // be desired. - DisableSorting bool -} - -func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { - var keys []string = make([]string, 0, len(entry.Data)) - for k := range entry.Data { - keys = append(keys, k) - } - - if !f.DisableSorting { - sort.Strings(keys) - } - - b := &bytes.Buffer{} - - prefixFieldClashes(entry.Data) - - isColorTerminal := isTerminal && (runtime.GOOS != "windows") - isColored := (f.ForceColors || isColorTerminal) && !f.DisableColors - - if f.TimestampFormat == "" { - f.TimestampFormat = DefaultTimestampFormat - } - if isColored { - f.printColored(b, entry, keys) - } else { - if !f.DisableTimestamp { - f.appendKeyValue(b, "time", entry.Time.Format(f.TimestampFormat)) - } - f.appendKeyValue(b, "level", entry.Level.String()) - f.appendKeyValue(b, "msg", entry.Message) - for _, key := range keys { - f.appendKeyValue(b, key, entry.Data[key]) - } - } - - b.WriteByte('\n') - return b.Bytes(), nil -} - -func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string) { - var levelColor int - switch entry.Level { - case DebugLevel: - levelColor = gray - case WarnLevel: - levelColor = yellow - case ErrorLevel, FatalLevel, PanicLevel: - levelColor = red - default: - levelColor = blue - } - - levelText := strings.ToUpper(entry.Level.String())[0:4] - - if !f.FullTimestamp { - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, miniTS(), entry.Message) - } else { - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(f.TimestampFormat), entry.Message) - } - for _, k := range keys { - v := entry.Data[k] - fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%+v", levelColor, k, v) - } -} - -func needsQuoting(text string) bool { - for _, ch := range text { - if !((ch >= 'a' && ch <= 'z') || - (ch >= 'A' && ch <= 'Z') || - (ch >= '0' && ch <= '9') || - ch == '-' || ch == '.') { - return false - } - } - return true -} - -func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) { - - b.WriteString(key) - b.WriteByte('=') - - switch value := value.(type) { - case string: - if needsQuoting(value) { - b.WriteString(value) - } else { - fmt.Fprintf(b, "%q", value) - } - case error: - errmsg := value.Error() - if needsQuoting(errmsg) { - b.WriteString(errmsg) - } else { - fmt.Fprintf(b, "%q", value) - } - default: - fmt.Fprint(b, value) - } - - b.WriteByte(' ') -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter_test.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter_test.go deleted file mode 100644 index e25a44f6..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package logrus - -import ( - "bytes" - "errors" - "testing" - "time" -) - -func TestQuoting(t *testing.T) { - tf := &TextFormatter{DisableColors: true} - - checkQuoting := func(q bool, value interface{}) { - b, _ := tf.Format(WithField("test", value)) - idx := bytes.Index(b, ([]byte)("test=")) - cont := bytes.Contains(b[idx+5:], []byte{'"'}) - if cont != q { - if q { - t.Errorf("quoting expected for: %#v", value) - } else { - t.Errorf("quoting not expected for: %#v", value) - } - } - } - - checkQuoting(false, "abcd") - checkQuoting(false, "v1.0") - checkQuoting(false, "1234567890") - checkQuoting(true, "/foobar") - checkQuoting(true, "x y") - checkQuoting(true, "x,y") - checkQuoting(false, errors.New("invalid")) - checkQuoting(true, errors.New("invalid argument")) -} - -func TestTimestampFormat(t *testing.T) { - checkTimeStr := func(format string) { - customFormatter := &TextFormatter{DisableColors: true, TimestampFormat: format} - customStr, _ := customFormatter.Format(WithField("test", "test")) - timeStart := bytes.Index(customStr, ([]byte)("time=")) - timeEnd := bytes.Index(customStr, ([]byte)("level=")) - timeStr := customStr[timeStart+5 : timeEnd-1] - if timeStr[0] == '"' && timeStr[len(timeStr)-1] == '"' { - timeStr = timeStr[1 : len(timeStr)-1] - } - if format == "" { - format = time.RFC3339 - } - _, e := time.Parse(format, (string)(timeStr)) - if e != nil { - t.Errorf("time string \"%s\" did not match provided time format \"%s\": %s", timeStr, format, e) - } - } - - checkTimeStr("2006-01-02T15:04:05.000000000Z07:00") - checkTimeStr("Mon Jan _2 15:04:05 2006") - checkTimeStr("") -} - -// TODO add tests for sorting etc., this requires a parser for the text -// formatter output. diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/writer.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/writer.go deleted file mode 100644 index 1e30b1c7..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/Sirupsen/logrus/writer.go +++ /dev/null @@ -1,31 +0,0 @@ -package logrus - -import ( - "bufio" - "io" - "runtime" -) - -func (logger *Logger) Writer() *io.PipeWriter { - reader, writer := io.Pipe() - - go logger.writerScanner(reader) - runtime.SetFinalizer(writer, writerFinalizer) - - return writer -} - -func (logger *Logger) writerScanner(reader *io.PipeReader) { - scanner := bufio.NewScanner(reader) - for scanner.Scan() { - logger.Print(scanner.Text()) - } - if err := scanner.Err(); err != nil { - logger.Errorf("Error while reading from Writer: %s", err) - } - reader.Close() -} - -func writerFinalizer(writer *io.PipeWriter) { - writer.Close() -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/errwrap/LICENSE b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/errwrap/LICENSE deleted file mode 100644 index c33dcc7c..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/errwrap/LICENSE +++ /dev/null @@ -1,354 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. “Contributor” - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. “Contributor Version” - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor’s Contribution. - -1.3. “Contribution” - - means Covered Software of a particular Contributor. - -1.4. “Covered Software” - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. “Incompatible With Secondary Licenses” - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of version - 1.1 or earlier of the License, but not also under the terms of a - Secondary License. - -1.6. “Executable Form” - - means any form of the work other than Source Code Form. - -1.7. “Larger Work” - - means a work that combines Covered Software with other material, in a separate - file or files, that is not Covered Software. - -1.8. “License” - - means this document. - -1.9. “Licensable” - - means having the right to grant, to the maximum extent possible, whether at the - time of the initial grant or subsequently, any and all of the rights conveyed by - this License. - -1.10. “Modifications” - - means any of the following: - - a. any file in Source Code Form that results from an addition to, deletion - from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. “Patent Claims” of a Contributor - - means any patent claim(s), including without limitation, method, process, - and apparatus claims, in any patent Licensable by such Contributor that - would be infringed, but for the grant of the License, by the making, - using, selling, offering for sale, having made, import, or transfer of - either its Contributions or its Contributor Version. - -1.12. “Secondary License” - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. “Source Code Form” - - means the form of the work preferred for making modifications. - -1.14. “You” (or “Your”) - - means an individual or a legal entity exercising rights under this - License. For legal entities, “You” includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, “control” means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or as - part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its Contributions - or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution become - effective for each Contribution on the date the Contributor first distributes - such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under this - License. No additional rights or licenses will be implied from the distribution - or licensing of Covered Software under this License. Notwithstanding Section - 2.1(b) above, no patent license is granted by a Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party’s - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of its - Contributions. - - This License does not grant any rights in the trademarks, service marks, or - logos of any Contributor (except as may be necessary to comply with the - notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this License - (see Section 10.2) or under the terms of a Secondary License (if permitted - under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its Contributions - are its original creation(s) or it has sufficient rights to grant the - rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under applicable - copyright doctrines of fair use, fair dealing, or other equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under the - terms of this License. You must inform recipients that the Source Code Form - of the Covered Software is governed by the terms of this License, and how - they can obtain a copy of this License. You may not attempt to alter or - restrict the recipients’ rights in the Source Code Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this License, - or sublicense it under different terms, provided that the license for - the Executable Form does not attempt to limit or alter the recipients’ - rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for the - Covered Software. If the Larger Work is a combination of Covered Software - with a work governed by one or more Secondary Licenses, and the Covered - Software is not Incompatible With Secondary Licenses, this License permits - You to additionally distribute such Covered Software under the terms of - such Secondary License(s), so that the recipient of the Larger Work may, at - their option, further distribute the Covered Software under the terms of - either this License or such Secondary License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices (including - copyright notices, patent notices, disclaimers of warranty, or limitations - of liability) contained within the Source Code Form of the Covered - Software, except that You may alter any license notices to the extent - required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on behalf - of any Contributor. You must make it absolutely clear that any such - warranty, support, indemnity, or liability obligation is offered by You - alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, judicial - order, or regulation then You must: (a) comply with the terms of this License - to the maximum extent possible; and (b) describe the limitations and the code - they affect. Such description must be placed in a text file included with all - distributions of the Covered Software under this License. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing basis, - if such Contributor fails to notify You of the non-compliance by some - reasonable means prior to 60 days after You have come back into compliance. - Moreover, Your grants from a particular Contributor are reinstated on an - ongoing basis if such Contributor notifies You of the non-compliance by - some reasonable means, this is the first time You have received notice of - non-compliance with this License from such Contributor, and You become - compliant prior to 30 days after Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, counter-claims, - and cross-claims) alleging that a Contributor Version directly or - indirectly infringes any patent, then the rights granted to You by any and - all Contributors for the Covered Software under Section 2.1 of this License - shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an “as is” basis, without - warranty of any kind, either expressed, implied, or statutory, including, - without limitation, warranties that the Covered Software is free of defects, - merchantable, fit for a particular purpose or non-infringing. The entire - risk as to the quality and performance of the Covered Software is with You. - Should any Covered Software prove defective in any respect, You (not any - Contributor) assume the cost of any necessary servicing, repair, or - correction. This disclaimer of warranty constitutes an essential part of this - License. No use of any Covered Software is authorized under this License - except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from such - party’s negligence to the extent applicable law prohibits such limitation. - Some jurisdictions do not allow the exclusion or limitation of incidental or - consequential damages, so this exclusion and limitation may not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts of - a jurisdiction where the defendant maintains its principal place of business - and such litigation shall be governed by laws of that jurisdiction, without - reference to its conflict-of-law provisions. Nothing in this Section shall - prevent a party’s ability to bring cross-claims or counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject matter - hereof. If any provision of this License is held to be unenforceable, such - provision shall be reformed only to the extent necessary to make it - enforceable. Any law or regulation which provides that the language of a - contract shall be construed against the drafter shall not be used to construe - this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version of - the License under which You originally received the Covered Software, or - under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a modified - version of this License if you rename the license and remove any - references to the name of the license steward (except to note that such - modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses - If You choose to distribute Source Code Form that is Incompatible With - Secondary Licenses under the terms of this version of the License, the - notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, then -You may include the notice in a location (such as a LICENSE file in a relevant -directory) where a recipient would be likely to look for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - “Incompatible With Secondary Licenses” Notice - - This Source Code Form is “Incompatible - With Secondary Licenses”, as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/errwrap/README.md b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/errwrap/README.md deleted file mode 100644 index 1c95f597..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/errwrap/README.md +++ /dev/null @@ -1,89 +0,0 @@ -# errwrap - -`errwrap` is a package for Go that formalizes the pattern of wrapping errors -and checking if an error contains another error. - -There is a common pattern in Go of taking a returned `error` value and -then wrapping it (such as with `fmt.Errorf`) before returning it. The problem -with this pattern is that you completely lose the original `error` structure. - -Arguably the _correct_ approach is that you should make a custom structure -implementing the `error` interface, and have the original error as a field -on that structure, such [as this example](http://golang.org/pkg/os/#PathError). -This is a good approach, but you have to know the entire chain of possible -rewrapping that happens, when you might just care about one. - -`errwrap` formalizes this pattern (it doesn't matter what approach you use -above) by giving a single interface for wrapping errors, checking if a specific -error is wrapped, and extracting that error. - -## Installation and Docs - -Install using `go get github.com/hashicorp/errwrap`. - -Full documentation is available at -http://godoc.org/github.com/hashicorp/errwrap - -## Usage - -#### Basic Usage - -Below is a very basic example of its usage: - -```go -// A function that always returns an error, but wraps it, like a real -// function might. -func tryOpen() error { - _, err := os.Open("/i/dont/exist") - if err != nil { - return errwrap.Wrapf("Doesn't exist: {{err}}", err) - } - - return nil -} - -func main() { - err := tryOpen() - - // We can use the Contains helpers to check if an error contains - // another error. It is safe to do this with a nil error, or with - // an error that doesn't even use the errwrap package. - if errwrap.Contains(err, ErrNotExist) { - // Do something - } - if errwrap.ContainsType(err, new(os.PathError)) { - // Do something - } - - // Or we can use the associated `Get` functions to just extract - // a specific error. This would return nil if that specific error doesn't - // exist. - perr := errwrap.GetType(err, new(os.PathError)) -} -``` - -#### Custom Types - -If you're already making custom types that properly wrap errors, then -you can get all the functionality of `errwraps.Contains` and such by -implementing the `Wrapper` interface with just one function. Example: - -```go -type AppError { - Code ErrorCode - Err error -} - -func (e *AppError) WrappedErrors() []error { - return []error{e.Err} -} -``` - -Now this works: - -```go -err := &AppError{Err: fmt.Errorf("an error")} -if errwrap.ContainsType(err, fmt.Errorf("")) { - // This will work! -} -``` diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/errwrap/errwrap.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/errwrap/errwrap.go deleted file mode 100644 index a733bef1..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/errwrap/errwrap.go +++ /dev/null @@ -1,169 +0,0 @@ -// Package errwrap implements methods to formalize error wrapping in Go. -// -// All of the top-level functions that take an `error` are built to be able -// to take any error, not just wrapped errors. This allows you to use errwrap -// without having to type-check and type-cast everywhere. -package errwrap - -import ( - "errors" - "reflect" - "strings" -) - -// WalkFunc is the callback called for Walk. -type WalkFunc func(error) - -// Wrapper is an interface that can be implemented by custom types to -// have all the Contains, Get, etc. functions in errwrap work. -// -// When Walk reaches a Wrapper, it will call the callback for every -// wrapped error in addition to the wrapper itself. Since all the top-level -// functions in errwrap use Walk, this means that all those functions work -// with your custom type. -type Wrapper interface { - WrappedErrors() []error -} - -// Wrap defines that outer wraps inner, returning an error type that -// can be cleanly used with the other methods in this package, such as -// Contains, GetAll, etc. -// -// This function won't modify the error message at all (the outer message -// will be used). -func Wrap(outer, inner error) error { - return &wrappedError{ - Outer: outer, - Inner: inner, - } -} - -// Wrapf wraps an error with a formatting message. This is similar to using -// `fmt.Errorf` to wrap an error. If you're using `fmt.Errorf` to wrap -// errors, you should replace it with this. -// -// format is the format of the error message. The string '{{err}}' will -// be replaced with the original error message. -func Wrapf(format string, err error) error { - outerMsg := "" - if err != nil { - outerMsg = err.Error() - } - - outer := errors.New(strings.Replace( - format, "{{err}}", outerMsg, -1)) - - return Wrap(outer, err) -} - -// Contains checks if the given error contains an error with the -// message msg. If err is not a wrapped error, this will always return -// false unless the error itself happens to match this msg. -func Contains(err error, msg string) bool { - return len(GetAll(err, msg)) > 0 -} - -// ContainsType checks if the given error contains an error with -// the same concrete type as v. If err is not a wrapped error, this will -// check the err itself. -func ContainsType(err error, v interface{}) bool { - return len(GetAllType(err, v)) > 0 -} - -// Get is the same as GetAll but returns the deepest matching error. -func Get(err error, msg string) error { - es := GetAll(err, msg) - if len(es) > 0 { - return es[len(es)-1] - } - - return nil -} - -// GetType is the same as GetAllType but returns the deepest matching error. -func GetType(err error, v interface{}) error { - es := GetAllType(err, v) - if len(es) > 0 { - return es[len(es)-1] - } - - return nil -} - -// GetAll gets all the errors that might be wrapped in err with the -// given message. The order of the errors is such that the outermost -// matching error (the most recent wrap) is index zero, and so on. -func GetAll(err error, msg string) []error { - var result []error - - Walk(err, func(err error) { - if err.Error() == msg { - result = append(result, err) - } - }) - - return result -} - -// GetAllType gets all the errors that are the same type as v. -// -// The order of the return value is the same as described in GetAll. -func GetAllType(err error, v interface{}) []error { - var result []error - - var search string - if v != nil { - search = reflect.TypeOf(v).String() - } - Walk(err, func(err error) { - var needle string - if err != nil { - needle = reflect.TypeOf(err).String() - } - - if needle == search { - result = append(result, err) - } - }) - - return result -} - -// Walk walks all the wrapped errors in err and calls the callback. If -// err isn't a wrapped error, this will be called once for err. If err -// is a wrapped error, the callback will be called for both the wrapper -// that implements error as well as the wrapped error itself. -func Walk(err error, cb WalkFunc) { - if err == nil { - return - } - - switch e := err.(type) { - case *wrappedError: - cb(e.Outer) - Walk(e.Inner, cb) - case Wrapper: - cb(err) - - for _, err := range e.WrappedErrors() { - Walk(err, cb) - } - default: - cb(err) - } -} - -// wrappedError is an implementation of error that has both the -// outer and inner errors. -type wrappedError struct { - Outer error - Inner error -} - -func (w *wrappedError) Error() string { - return w.Outer.Error() -} - -func (w *wrappedError) WrappedErrors() []error { - return []error{w.Outer, w.Inner} -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/.travis.yml b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/.travis.yml deleted file mode 100644 index 4b865d19..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -sudo: false - -language: go - -go: - - 1.6 - -branches: - only: - - master - -script: make test testrace diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/LICENSE b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/LICENSE deleted file mode 100644 index 82b4de97..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/LICENSE +++ /dev/null @@ -1,353 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. “Contributor” - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. “Contributor Version” - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor’s Contribution. - -1.3. “Contribution” - - means Covered Software of a particular Contributor. - -1.4. “Covered Software” - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. “Incompatible With Secondary Licenses” - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of version - 1.1 or earlier of the License, but not also under the terms of a - Secondary License. - -1.6. “Executable Form” - - means any form of the work other than Source Code Form. - -1.7. “Larger Work” - - means a work that combines Covered Software with other material, in a separate - file or files, that is not Covered Software. - -1.8. “License” - - means this document. - -1.9. “Licensable” - - means having the right to grant, to the maximum extent possible, whether at the - time of the initial grant or subsequently, any and all of the rights conveyed by - this License. - -1.10. “Modifications” - - means any of the following: - - a. any file in Source Code Form that results from an addition to, deletion - from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. “Patent Claims” of a Contributor - - means any patent claim(s), including without limitation, method, process, - and apparatus claims, in any patent Licensable by such Contributor that - would be infringed, but for the grant of the License, by the making, - using, selling, offering for sale, having made, import, or transfer of - either its Contributions or its Contributor Version. - -1.12. “Secondary License” - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. “Source Code Form” - - means the form of the work preferred for making modifications. - -1.14. “You” (or “Your”) - - means an individual or a legal entity exercising rights under this - License. For legal entities, “You” includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, “control” means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or as - part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its Contributions - or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution become - effective for each Contribution on the date the Contributor first distributes - such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under this - License. No additional rights or licenses will be implied from the distribution - or licensing of Covered Software under this License. Notwithstanding Section - 2.1(b) above, no patent license is granted by a Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party’s - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of its - Contributions. - - This License does not grant any rights in the trademarks, service marks, or - logos of any Contributor (except as may be necessary to comply with the - notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this License - (see Section 10.2) or under the terms of a Secondary License (if permitted - under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its Contributions - are its original creation(s) or it has sufficient rights to grant the - rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under applicable - copyright doctrines of fair use, fair dealing, or other equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under the - terms of this License. You must inform recipients that the Source Code Form - of the Covered Software is governed by the terms of this License, and how - they can obtain a copy of this License. You may not attempt to alter or - restrict the recipients’ rights in the Source Code Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this License, - or sublicense it under different terms, provided that the license for - the Executable Form does not attempt to limit or alter the recipients’ - rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for the - Covered Software. If the Larger Work is a combination of Covered Software - with a work governed by one or more Secondary Licenses, and the Covered - Software is not Incompatible With Secondary Licenses, this License permits - You to additionally distribute such Covered Software under the terms of - such Secondary License(s), so that the recipient of the Larger Work may, at - their option, further distribute the Covered Software under the terms of - either this License or such Secondary License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices (including - copyright notices, patent notices, disclaimers of warranty, or limitations - of liability) contained within the Source Code Form of the Covered - Software, except that You may alter any license notices to the extent - required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on behalf - of any Contributor. You must make it absolutely clear that any such - warranty, support, indemnity, or liability obligation is offered by You - alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, judicial - order, or regulation then You must: (a) comply with the terms of this License - to the maximum extent possible; and (b) describe the limitations and the code - they affect. Such description must be placed in a text file included with all - distributions of the Covered Software under this License. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing basis, - if such Contributor fails to notify You of the non-compliance by some - reasonable means prior to 60 days after You have come back into compliance. - Moreover, Your grants from a particular Contributor are reinstated on an - ongoing basis if such Contributor notifies You of the non-compliance by - some reasonable means, this is the first time You have received notice of - non-compliance with this License from such Contributor, and You become - compliant prior to 30 days after Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, counter-claims, - and cross-claims) alleging that a Contributor Version directly or - indirectly infringes any patent, then the rights granted to You by any and - all Contributors for the Covered Software under Section 2.1 of this License - shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an “as is” basis, without - warranty of any kind, either expressed, implied, or statutory, including, - without limitation, warranties that the Covered Software is free of defects, - merchantable, fit for a particular purpose or non-infringing. The entire - risk as to the quality and performance of the Covered Software is with You. - Should any Covered Software prove defective in any respect, You (not any - Contributor) assume the cost of any necessary servicing, repair, or - correction. This disclaimer of warranty constitutes an essential part of this - License. No use of any Covered Software is authorized under this License - except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from such - party’s negligence to the extent applicable law prohibits such limitation. - Some jurisdictions do not allow the exclusion or limitation of incidental or - consequential damages, so this exclusion and limitation may not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts of - a jurisdiction where the defendant maintains its principal place of business - and such litigation shall be governed by laws of that jurisdiction, without - reference to its conflict-of-law provisions. Nothing in this Section shall - prevent a party’s ability to bring cross-claims or counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject matter - hereof. If any provision of this License is held to be unenforceable, such - provision shall be reformed only to the extent necessary to make it - enforceable. Any law or regulation which provides that the language of a - contract shall be construed against the drafter shall not be used to construe - this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version of - the License under which You originally received the Covered Software, or - under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a modified - version of this License if you rename the license and remove any - references to the name of the license steward (except to note that such - modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses - If You choose to distribute Source Code Form that is Incompatible With - Secondary Licenses under the terms of this version of the License, the - notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, then -You may include the notice in a location (such as a LICENSE file in a relevant -directory) where a recipient would be likely to look for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - “Incompatible With Secondary Licenses” Notice - - This Source Code Form is “Incompatible - With Secondary Licenses”, as defined by - the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/Makefile b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/Makefile deleted file mode 100644 index b97cd6ed..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -TEST?=./... - -default: test - -# test runs the test suite and vets the code. -test: generate - @echo "==> Running tests..." - @go list $(TEST) \ - | grep -v "/vendor/" \ - | xargs -n1 go test -timeout=60s -parallel=10 ${TESTARGS} - -# testrace runs the race checker -testrace: generate - @echo "==> Running tests (race)..." - @go list $(TEST) \ - | grep -v "/vendor/" \ - | xargs -n1 go test -timeout=60s -race ${TESTARGS} - -# updatedeps installs all the dependencies needed to run and build. -updatedeps: - @sh -c "'${CURDIR}/scripts/deps.sh' '${NAME}'" - -# generate runs `go generate` to build the dynamically generated source files. -generate: - @echo "==> Generating..." - @find . -type f -name '.DS_Store' -delete - @go list ./... \ - | grep -v "/vendor/" \ - | xargs -n1 go generate - -.PHONY: default test testrace updatedeps generate diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/README.md b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/README.md deleted file mode 100644 index ead5830f..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/README.md +++ /dev/null @@ -1,97 +0,0 @@ -# go-multierror - -[![Build Status](http://img.shields.io/travis/hashicorp/go-multierror.svg?style=flat-square)][travis] -[![Go Documentation](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)][godocs] - -[travis]: https://travis-ci.org/hashicorp/go-multierror -[godocs]: https://godoc.org/github.com/hashicorp/go-multierror - -`go-multierror` is a package for Go that provides a mechanism for -representing a list of `error` values as a single `error`. - -This allows a function in Go to return an `error` that might actually -be a list of errors. If the caller knows this, they can unwrap the -list and access the errors. If the caller doesn't know, the error -formats to a nice human-readable format. - -`go-multierror` implements the -[errwrap](https://github.com/hashicorp/errwrap) interface so that it can -be used with that library, as well. - -## Installation and Docs - -Install using `go get github.com/hashicorp/go-multierror`. - -Full documentation is available at -http://godoc.org/github.com/hashicorp/go-multierror - -## Usage - -go-multierror is easy to use and purposely built to be unobtrusive in -existing Go applications/libraries that may not be aware of it. - -**Building a list of errors** - -The `Append` function is used to create a list of errors. This function -behaves a lot like the Go built-in `append` function: it doesn't matter -if the first argument is nil, a `multierror.Error`, or any other `error`, -the function behaves as you would expect. - -```go -var result error - -if err := step1(); err != nil { - result = multierror.Append(result, err) -} -if err := step2(); err != nil { - result = multierror.Append(result, err) -} - -return result -``` - -**Customizing the formatting of the errors** - -By specifying a custom `ErrorFormat`, you can customize the format -of the `Error() string` function: - -```go -var result *multierror.Error - -// ... accumulate errors here, maybe using Append - -if result != nil { - result.ErrorFormat = func([]error) string { - return "errors!" - } -} -``` - -**Accessing the list of errors** - -`multierror.Error` implements `error` so if the caller doesn't know about -multierror, it will work just fine. But if you're aware a multierror might -be returned, you can use type switches to access the list of errors: - -```go -if err := something(); err != nil { - if merr, ok := err.(*multierror.Error); ok { - // Use merr.Errors - } -} -``` - -**Returning a multierror only if there are errors** - -If you build a `multierror.Error`, you can use the `ErrorOrNil` function -to return an `error` implementation only if there are errors to return: - -```go -var result *multierror.Error - -// ... accumulate errors here - -// Return the `error` only if errors were added to the multierror, otherwise -// return nil since there are no errors. -return result.ErrorOrNil() -``` diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/append.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/append.go deleted file mode 100644 index 775b6e75..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/append.go +++ /dev/null @@ -1,41 +0,0 @@ -package multierror - -// Append is a helper function that will append more errors -// onto an Error in order to create a larger multi-error. -// -// If err is not a multierror.Error, then it will be turned into -// one. If any of the errs are multierr.Error, they will be flattened -// one level into err. -func Append(err error, errs ...error) *Error { - switch err := err.(type) { - case *Error: - // Typed nils can reach here, so initialize if we are nil - if err == nil { - err = new(Error) - } - - // Go through each error and flatten - for _, e := range errs { - switch e := e.(type) { - case *Error: - if e != nil { - err.Errors = append(err.Errors, e.Errors...) - } - default: - if e != nil { - err.Errors = append(err.Errors, e) - } - } - } - - return err - default: - newErrs := make([]error, 0, len(errs)+1) - if err != nil { - newErrs = append(newErrs, err) - } - newErrs = append(newErrs, errs...) - - return Append(&Error{}, newErrs...) - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/flatten.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/flatten.go deleted file mode 100644 index aab8e9ab..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/flatten.go +++ /dev/null @@ -1,26 +0,0 @@ -package multierror - -// Flatten flattens the given error, merging any *Errors together into -// a single *Error. -func Flatten(err error) error { - // If it isn't an *Error, just return the error as-is - if _, ok := err.(*Error); !ok { - return err - } - - // Otherwise, make the result and flatten away! - flatErr := new(Error) - flatten(err, flatErr) - return flatErr -} - -func flatten(err error, flatErr *Error) { - switch err := err.(type) { - case *Error: - for _, e := range err.Errors { - flatten(e, flatErr) - } - default: - flatErr.Errors = append(flatErr.Errors, err) - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/format.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/format.go deleted file mode 100644 index 6c7a3cc9..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/format.go +++ /dev/null @@ -1,27 +0,0 @@ -package multierror - -import ( - "fmt" - "strings" -) - -// ErrorFormatFunc is a function callback that is called by Error to -// turn the list of errors into a string. -type ErrorFormatFunc func([]error) string - -// ListFormatFunc is a basic formatter that outputs the number of errors -// that occurred along with a bullet point list of the errors. -func ListFormatFunc(es []error) string { - if len(es) == 1 { - return fmt.Sprintf("1 error occurred:\n\n* %s", es[0]) - } - - points := make([]string, len(es)) - for i, err := range es { - points[i] = fmt.Sprintf("* %s", err) - } - - return fmt.Sprintf( - "%d errors occurred:\n\n%s", - len(es), strings.Join(points, "\n")) -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/multierror.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/multierror.go deleted file mode 100644 index 2ea08273..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/multierror.go +++ /dev/null @@ -1,51 +0,0 @@ -package multierror - -import ( - "fmt" -) - -// Error is an error type to track multiple errors. This is used to -// accumulate errors in cases and return them as a single "error". -type Error struct { - Errors []error - ErrorFormat ErrorFormatFunc -} - -func (e *Error) Error() string { - fn := e.ErrorFormat - if fn == nil { - fn = ListFormatFunc - } - - return fn(e.Errors) -} - -// ErrorOrNil returns an error interface if this Error represents -// a list of errors, or returns nil if the list of errors is empty. This -// function is useful at the end of accumulation to make sure that the value -// returned represents the existence of errors. -func (e *Error) ErrorOrNil() error { - if e == nil { - return nil - } - if len(e.Errors) == 0 { - return nil - } - - return e -} - -func (e *Error) GoString() string { - return fmt.Sprintf("*%#v", *e) -} - -// WrappedErrors returns the list of errors that this Error is wrapping. -// It is an implementatin of the errwrap.Wrapper interface so that -// multierror.Error can be used with that library. -// -// This method is not safe to be called concurrently and is no different -// than accessing the Errors field directly. It is implementd only to -// satisfy the errwrap.Wrapper interface. -func (e *Error) WrappedErrors() []error { - return e.Errors -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/prefix.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/prefix.go deleted file mode 100644 index 5c477abe..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/hashicorp/go-multierror/prefix.go +++ /dev/null @@ -1,37 +0,0 @@ -package multierror - -import ( - "fmt" - - "github.com/hashicorp/errwrap" -) - -// Prefix is a helper function that will prefix some text -// to the given error. If the error is a multierror.Error, then -// it will be prefixed to each wrapped error. -// -// This is useful to use when appending multiple multierrors -// together in order to give better scoping. -func Prefix(err error, prefix string) error { - if err == nil { - return nil - } - - format := fmt.Sprintf("%s {{err}}", prefix) - switch err := err.(type) { - case *Error: - // Typed nils can reach here, so initialize if we are nil - if err == nil { - err = new(Error) - } - - // Wrap each of the errors - for i, e := range err.Errors { - err.Errors[i] = errwrap.Wrapf(format, e) - } - - return err - default: - return errwrap.Wrapf(format, err) - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/mndrix/tap-go/.gitignore b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/mndrix/tap-go/.gitignore deleted file mode 100644 index 9e8d7ca0..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/mndrix/tap-go/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -gopath/pkg -test/*/test -/TAGS diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/mndrix/tap-go/LICENSE b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/mndrix/tap-go/LICENSE deleted file mode 100644 index cf1ab25d..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/mndrix/tap-go/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -This is free and unencumbered software released into the public domain. - -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -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 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. - -For more information, please refer to diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/mndrix/tap-go/Makefile b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/mndrix/tap-go/Makefile deleted file mode 100644 index dda78b2b..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/mndrix/tap-go/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -TESTS = auto check diagnostic known failing writer -GOPATH = $(CURDIR)/gopath - -.PHONY: $(TESTS) - -all: $(foreach t,$(TESTS),test/$(t)/test) - prove -v -e '' test/*/test - -clean: - rm -f test/*/test - -test/%/test: test/%/main.go tap.go - go build -o $@ $< - -$(TESTS): %: test/%/test - prove -v -e '' test/$@/test diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/mndrix/tap-go/README.md b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/mndrix/tap-go/README.md deleted file mode 100644 index f795022d..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/mndrix/tap-go/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Test Anything Protocol for Go - -The [Test Anything Protocol](http://testanything.org/) ("TAP") is a text-based -interface between tests and a test harness. This package helps Go to generate -TAP output. - -Read the [full package documentation](https://godoc.org/github.com/mndrix/tap-go) diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/mndrix/tap-go/tap.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/mndrix/tap-go/tap.go deleted file mode 100644 index 24054263..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/mndrix/tap-go/tap.go +++ /dev/null @@ -1,130 +0,0 @@ -// Package tap provides support for automated Test Anything Protocol ("TAP") -// tests in Go. For example: -// -// package main -// -// import "github.com/mndrix/tap-go" -// -// func main() { -// t := tap.New() -// t.Header(2) -// t.Ok(true, "first test") -// t.Ok(true, "second test") -// } -// -// generates the following output -// -// TAP version 13 -// 1..2 -// ok 1 - first test -// ok 2 - second test -package tap - -import ( - "fmt" - "io" - "os" - "strings" -) -import "testing/quick" - -// T is a type to encapsulate test state. Methods on this type generate TAP -// output. -type T struct { - nextTestNumber int - - // Writer indicates where TAP output should be sent. The default is os.Stdout. - Writer io.Writer -} - -// New creates a new Tap value -func New() *T { - return &T{ - nextTestNumber: 1, - } -} - -func (t *T) w() io.Writer { - if t.Writer == nil { - return os.Stdout - } - return t.Writer -} - -func (t *T) printf(format string, a ...interface{}) { - fmt.Fprintf(t.w(), format, a...) -} - -// Header displays a TAP header including version number and expected -// number of tests to run. For an unknown number of tests, set -// testCount to zero (in which case the plan is not written); this is -// useful with AutoPlan. -func (t *T) Header(testCount int) { - t.printf("TAP version 13\n") - if testCount > 0 { - t.printf("1..%d\n", testCount) - } -} - -// Ok generates TAP output indicating whether a test passed or failed. -func (t *T) Ok(test bool, description string) { - // did the test pass or not? - ok := "ok" - if !test { - ok = "not ok" - } - - t.printf("%s %d - %s\n", ok, t.nextTestNumber, description) - t.nextTestNumber++ -} - -// Fail indicates that a test has failed. This is typically only used when the -// logic is too complex to fit naturally into an Ok() call. -func (t *T) Fail(description string) { - t.Ok(false, description) -} - -// Pass indicates that a test has passed. This is typically only used when the -// logic is too complex to fit naturally into an Ok() call. -func (t *T) Pass(description string) { - t.Ok(true, description) -} - -// Check runs randomized tests against a function just as "testing/quick.Check" -// does. Success or failure generate appropriate TAP output. -func (t *T) Check(function interface{}, description string) { - err := quick.Check(function, nil) - if err == nil { - t.Ok(true, description) - return - } - - t.Diagnostic(err.Error()) - t.Ok(false, description) -} - -// Count returns the number of tests completed so far. -func (t *T) Count() int { - return t.nextTestNumber - 1 -} - -// AutoPlan generates a test plan based on the number of tests that were run. -func (t *T) AutoPlan() { - t.printf("1..%d\n", t.Count()) -} - -func escapeNewlines(s string) string { - return strings.Replace(strings.TrimRight(s, "\n"), "\n", "\n# ", -1) -} - -// Diagnostic generates a diagnostic from the message, -// which may span multiple lines. -func (t *T) Diagnostic(message string) { - t.printf("# %s\n", escapeNewlines(message)) -} - -// Diagnosticf generates a diagnostic from the format string and arguments, -// which may span multiple lines. -func (t *T) Diagnosticf(format string, a ...interface{}) { - t.printf("# "+escapeNewlines(format)+"\n", a...) -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/opencontainers/runtime-spec/LICENSE b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/opencontainers/runtime-spec/LICENSE deleted file mode 100644 index bdc40365..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/opencontainers/runtime-spec/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015 The Linux Foundation. - - 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. diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/opencontainers/runtime-spec/specs-go/config.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/opencontainers/runtime-spec/specs-go/config.go deleted file mode 100644 index b2ac75eb..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/opencontainers/runtime-spec/specs-go/config.go +++ /dev/null @@ -1,471 +0,0 @@ -package specs - -import "os" - -// Spec is the base configuration for the container. -type Spec struct { - // Version is the version of the specification that is supported. - Version string `json:"ociVersion"` - // Platform is the host information for OS and Arch. - Platform Platform `json:"platform"` - // Process is the container's main process. - Process Process `json:"process"` - // Root is the root information for the container's filesystem. - Root Root `json:"root"` - // Hostname is the container's host name. - Hostname string `json:"hostname,omitempty"` - // Mounts profile configuration for adding mounts to the container's filesystem. - Mounts []Mount `json:"mounts,omitempty"` - // Hooks are the commands run at various lifecycle events of the container. - Hooks Hooks `json:"hooks"` - // Annotations is an unstructured key value map that may be set by external tools to store and retrieve arbitrary metadata. - Annotations map[string]string `json:"annotations,omitempty"` - - // Linux is platform specific configuration for Linux based containers. - Linux *Linux `json:"linux,omitempty" platform:"linux"` - // Solaris is platform specific configuration for Solaris containers. - Solaris *Solaris `json:"solaris,omitempty" platform:"solaris"` -} - -// Process contains information to start a specific application inside the container. -type Process struct { - // Terminal creates an interactive terminal for the container. - Terminal bool `json:"terminal,omitempty"` - // User specifies user information for the process. - User User `json:"user"` - // Args specifies the binary and arguments for the application to execute. - Args []string `json:"args"` - // Env populates the process environment for the process. - Env []string `json:"env,omitempty"` - // Cwd is the current working directory for the process and must be - // relative to the container's root. - Cwd string `json:"cwd"` - // Capabilities are Linux capabilities that are kept for the container. - Capabilities []string `json:"capabilities,omitempty" platform:"linux"` - // Rlimits specifies rlimit options to apply to the process. - Rlimits []Rlimit `json:"rlimits,omitempty"` - // NoNewPrivileges controls whether additional privileges could be gained by processes in the container. - NoNewPrivileges bool `json:"noNewPrivileges,omitempty"` - - // ApparmorProfile specifies the apparmor profile for the container. (this field is platform dependent) - ApparmorProfile string `json:"apparmorProfile,omitempty" platform:"linux"` - // SelinuxLabel specifies the selinux context that the container process is run as. (this field is platform dependent) - SelinuxLabel string `json:"selinuxLabel,omitempty" platform:"linux"` -} - -// User specifies Linux/Solaris specific user and group information for the container's -// main process. -type User struct { - // UID is the user id. (this field is platform dependent) - UID uint32 `json:"uid" platform:"linux,solaris"` - // GID is the group id. (this field is platform dependent) - GID uint32 `json:"gid" platform:"linux,solaris"` - // AdditionalGids are additional group ids set for the container's process. (this field is platform dependent) - AdditionalGids []uint32 `json:"additionalGids,omitempty" platform:"linux,solaris"` -} - -// Root contains information about the container's root filesystem on the host. -type Root struct { - // Path is the absolute path to the container's root filesystem. - Path string `json:"path"` - // Readonly makes the root filesystem for the container readonly before the process is executed. - Readonly bool `json:"readonly,omitempty"` -} - -// Platform specifies OS and arch information for the host system that the container -// is created for. -type Platform struct { - // OS is the operating system. - OS string `json:"os"` - // Arch is the architecture - Arch string `json:"arch"` -} - -// Mount specifies a mount for a container. -type Mount struct { - // Destination is the path where the mount will be placed relative to the container's root. The path and child directories MUST exist, a runtime MUST NOT create directories automatically to a mount point. - Destination string `json:"destination"` - // Type specifies the mount kind. - Type string `json:"type"` - // Source specifies the source path of the mount. In the case of bind mounts on - // Linux based systems this would be the file on the host. - Source string `json:"source"` - // Options are fstab style mount options. - Options []string `json:"options,omitempty"` -} - -// Hook specifies a command that is run at a particular event in the lifecycle of a container -type Hook struct { - Path string `json:"path"` - Args []string `json:"args,omitempty"` - Env []string `json:"env,omitempty"` - Timeout *int `json:"timeout,omitempty"` -} - -// Hooks for container setup and teardown -type Hooks struct { - // Prestart is a list of hooks to be run before the container process is executed. - // On Linux, they are run after the container namespaces are created. - Prestart []Hook `json:"prestart,omitempty"` - // Poststart is a list of hooks to be run after the container process is started. - Poststart []Hook `json:"poststart,omitempty"` - // Poststop is a list of hooks to be run after the container process exits. - Poststop []Hook `json:"poststop,omitempty"` -} - -// Linux contains platform specific configuration for Linux based containers. -type Linux struct { - // UIDMapping specifies user mappings for supporting user namespaces on Linux. - UIDMappings []IDMapping `json:"uidMappings,omitempty"` - // GIDMapping specifies group mappings for supporting user namespaces on Linux. - GIDMappings []IDMapping `json:"gidMappings,omitempty"` - // Sysctl are a set of key value pairs that are set for the container on start - Sysctl map[string]string `json:"sysctl,omitempty"` - // Resources contain cgroup information for handling resource constraints - // for the container - Resources *Resources `json:"resources,omitempty"` - // CgroupsPath specifies the path to cgroups that are created and/or joined by the container. - // The path is expected to be relative to the cgroups mountpoint. - // If resources are specified, the cgroups at CgroupsPath will be updated based on resources. - CgroupsPath *string `json:"cgroupsPath,omitempty"` - // Namespaces contains the namespaces that are created and/or joined by the container - Namespaces []Namespace `json:"namespaces,omitempty"` - // Devices are a list of device nodes that are created for the container - Devices []Device `json:"devices,omitempty"` - // Seccomp specifies the seccomp security settings for the container. - Seccomp *Seccomp `json:"seccomp,omitempty"` - // RootfsPropagation is the rootfs mount propagation mode for the container. - RootfsPropagation string `json:"rootfsPropagation,omitempty"` - // MaskedPaths masks over the provided paths inside the container. - MaskedPaths []string `json:"maskedPaths,omitempty"` - // ReadonlyPaths sets the provided paths as RO inside the container. - ReadonlyPaths []string `json:"readonlyPaths,omitempty"` - // MountLabel specifies the selinux context for the mounts in the container. - MountLabel string `json:"mountLabel,omitempty"` -} - -// Namespace is the configuration for a Linux namespace -type Namespace struct { - // Type is the type of Linux namespace - Type NamespaceType `json:"type"` - // Path is a path to an existing namespace persisted on disk that can be joined - // and is of the same type - Path string `json:"path,omitempty"` -} - -// NamespaceType is one of the Linux namespaces -type NamespaceType string - -const ( - // PIDNamespace for isolating process IDs - PIDNamespace NamespaceType = "pid" - // NetworkNamespace for isolating network devices, stacks, ports, etc - NetworkNamespace = "network" - // MountNamespace for isolating mount points - MountNamespace = "mount" - // IPCNamespace for isolating System V IPC, POSIX message queues - IPCNamespace = "ipc" - // UTSNamespace for isolating hostname and NIS domain name - UTSNamespace = "uts" - // UserNamespace for isolating user and group IDs - UserNamespace = "user" - // CgroupNamespace for isolating cgroup hierarchies - CgroupNamespace = "cgroup" -) - -// IDMapping specifies UID/GID mappings -type IDMapping struct { - // HostID is the UID/GID of the host user or group - HostID uint32 `json:"hostID"` - // ContainerID is the UID/GID of the container's user or group - ContainerID uint32 `json:"containerID"` - // Size is the length of the range of IDs mapped between the two namespaces - Size uint32 `json:"size"` -} - -// Rlimit type and restrictions -type Rlimit struct { - // Type of the rlimit to set - Type string `json:"type"` - // Hard is the hard limit for the specified type - Hard uint64 `json:"hard"` - // Soft is the soft limit for the specified type - Soft uint64 `json:"soft"` -} - -// HugepageLimit structure corresponds to limiting kernel hugepages -type HugepageLimit struct { - // Pagesize is the hugepage size - Pagesize *string `json:"pageSize,omitempty"` - // Limit is the limit of "hugepagesize" hugetlb usage - Limit *uint64 `json:"limit,omitempty"` -} - -// InterfacePriority for network interfaces -type InterfacePriority struct { - // Name is the name of the network interface - Name string `json:"name"` - // Priority for the interface - Priority uint32 `json:"priority"` -} - -// blockIODevice holds major:minor format supported in blkio cgroup -type blockIODevice struct { - // Major is the device's major number. - Major int64 `json:"major"` - // Minor is the device's minor number. - Minor int64 `json:"minor"` -} - -// WeightDevice struct holds a `major:minor weight` pair for blkioWeightDevice -type WeightDevice struct { - blockIODevice - // Weight is the bandwidth rate for the device, range is from 10 to 1000 - Weight *uint16 `json:"weight,omitempty"` - // LeafWeight is the bandwidth rate for the device while competing with the cgroup's child cgroups, range is from 10 to 1000, CFQ scheduler only - LeafWeight *uint16 `json:"leafWeight,omitempty"` -} - -// ThrottleDevice struct holds a `major:minor rate_per_second` pair -type ThrottleDevice struct { - blockIODevice - // Rate is the IO rate limit per cgroup per device - Rate *uint64 `json:"rate,omitempty"` -} - -// BlockIO for Linux cgroup 'blkio' resource management -type BlockIO struct { - // Specifies per cgroup weight, range is from 10 to 1000 - Weight *uint16 `json:"blkioWeight,omitempty"` - // Specifies tasks' weight in the given cgroup while competing with the cgroup's child cgroups, range is from 10 to 1000, CFQ scheduler only - LeafWeight *uint16 `json:"blkioLeafWeight,omitempty"` - // Weight per cgroup per device, can override BlkioWeight - WeightDevice []WeightDevice `json:"blkioWeightDevice,omitempty"` - // IO read rate limit per cgroup per device, bytes per second - ThrottleReadBpsDevice []ThrottleDevice `json:"blkioThrottleReadBpsDevice,omitempty"` - // IO write rate limit per cgroup per device, bytes per second - ThrottleWriteBpsDevice []ThrottleDevice `json:"blkioThrottleWriteBpsDevice,omitempty"` - // IO read rate limit per cgroup per device, IO per second - ThrottleReadIOPSDevice []ThrottleDevice `json:"blkioThrottleReadIOPSDevice,omitempty"` - // IO write rate limit per cgroup per device, IO per second - ThrottleWriteIOPSDevice []ThrottleDevice `json:"blkioThrottleWriteIOPSDevice,omitempty"` -} - -// Memory for Linux cgroup 'memory' resource management -type Memory struct { - // Memory limit (in bytes). - Limit *uint64 `json:"limit,omitempty"` - // Memory reservation or soft_limit (in bytes). - Reservation *uint64 `json:"reservation,omitempty"` - // Total memory limit (memory + swap). - Swap *uint64 `json:"swap,omitempty"` - // Kernel memory limit (in bytes). - Kernel *uint64 `json:"kernel,omitempty"` - // Kernel memory limit for tcp (in bytes) - KernelTCP *uint64 `json:"kernelTCP"` - // How aggressive the kernel will swap memory pages. Range from 0 to 100. - Swappiness *uint64 `json:"swappiness,omitempty"` -} - -// CPU for Linux cgroup 'cpu' resource management -type CPU struct { - // CPU shares (relative weight (ratio) vs. other cgroups with cpu shares). - Shares *uint64 `json:"shares,omitempty"` - // CPU hardcap limit (in usecs). Allowed cpu time in a given period. - Quota *uint64 `json:"quota,omitempty"` - // CPU period to be used for hardcapping (in usecs). - Period *uint64 `json:"period,omitempty"` - // How much time realtime scheduling may use (in usecs). - RealtimeRuntime *uint64 `json:"realtimeRuntime,omitempty"` - // CPU period to be used for realtime scheduling (in usecs). - RealtimePeriod *uint64 `json:"realtimePeriod,omitempty"` - // CPUs to use within the cpuset. Default is to use any CPU available. - Cpus *string `json:"cpus,omitempty"` - // List of memory nodes in the cpuset. Default is to use any available memory node. - Mems *string `json:"mems,omitempty"` -} - -// Pids for Linux cgroup 'pids' resource management (Linux 4.3) -type Pids struct { - // Maximum number of PIDs. Default is "no limit". - Limit *int64 `json:"limit,omitempty"` -} - -// Network identification and priority configuration -type Network struct { - // Set class identifier for container's network packets - ClassID *uint32 `json:"classID"` - // Set priority of network traffic for container - Priorities []InterfacePriority `json:"priorities,omitempty"` -} - -// Resources has container runtime resource constraints -type Resources struct { - // Devices are a list of device rules for the whitelist controller - Devices []DeviceCgroup `json:"devices"` - // DisableOOMKiller disables the OOM killer for out of memory conditions - DisableOOMKiller *bool `json:"disableOOMKiller,omitempty"` - // Specify an oom_score_adj for the container. - OOMScoreAdj *int `json:"oomScoreAdj,omitempty"` - // Memory restriction configuration - Memory *Memory `json:"memory,omitempty"` - // CPU resource restriction configuration - CPU *CPU `json:"cpu,omitempty"` - // Task resource restriction configuration. - Pids *Pids `json:"pids,omitempty"` - // BlockIO restriction configuration - BlockIO *BlockIO `json:"blockIO,omitempty"` - // Hugetlb limit (in bytes) - HugepageLimits []HugepageLimit `json:"hugepageLimits,omitempty"` - // Network restriction configuration - Network *Network `json:"network,omitempty"` -} - -// Device represents the mknod information for a Linux special device file -type Device struct { - // Path to the device. - Path string `json:"path"` - // Device type, block, char, etc. - Type string `json:"type"` - // Major is the device's major number. - Major int64 `json:"major"` - // Minor is the device's minor number. - Minor int64 `json:"minor"` - // FileMode permission bits for the device. - FileMode *os.FileMode `json:"fileMode,omitempty"` - // UID of the device. - UID *uint32 `json:"uid,omitempty"` - // Gid of the device. - GID *uint32 `json:"gid,omitempty"` -} - -// DeviceCgroup represents a device rule for the whitelist controller -type DeviceCgroup struct { - // Allow or deny - Allow bool `json:"allow"` - // Device type, block, char, etc. - Type *string `json:"type,omitempty"` - // Major is the device's major number. - Major *int64 `json:"major,omitempty"` - // Minor is the device's minor number. - Minor *int64 `json:"minor,omitempty"` - // Cgroup access permissions format, rwm. - Access *string `json:"access,omitempty"` -} - -// Seccomp represents syscall restrictions -type Seccomp struct { - DefaultAction Action `json:"defaultAction"` - Architectures []Arch `json:"architectures"` - Syscalls []Syscall `json:"syscalls,omitempty"` -} - -// Solaris contains platform specific configuration for Solaris application containers. -type Solaris struct { - // SMF FMRI which should go "online" before we start the container process. - Milestone string `json:"milestone,omitempty"` - // Maximum set of privileges any process in this container can obtain. - LimitPriv string `json:"limitpriv,omitempty"` - // The maximum amount of shared memory allowed for this container. - MaxShmMemory string `json:"maxShmMemory,omitempty"` - // Specification for automatic creation of network resources for this container. - Anet []Anet `json:"anet,omitempty"` - // Set limit on the amount of CPU time that can be used by container. - CappedCPU *CappedCPU `json:"cappedCPU,omitempty"` - // The physical and swap caps on the memory that can be used by this container. - CappedMemory *CappedMemory `json:"cappedMemory,omitempty"` -} - -// CappedCPU allows users to set limit on the amount of CPU time that can be used by container. -type CappedCPU struct { - Ncpus string `json:"ncpus,omitempty"` -} - -// CappedMemory allows users to set the physical and swap caps on the memory that can be used by this container. -type CappedMemory struct { - Physical string `json:"physical,omitempty"` - Swap string `json:"swap,omitempty"` -} - -// Anet provides the specification for automatic creation of network resources for this container. -type Anet struct { - // Specify a name for the automatically created VNIC datalink. - Linkname string `json:"linkname,omitempty"` - // Specify the link over which the VNIC will be created. - Lowerlink string `json:"lowerLink,omitempty"` - // The set of IP addresses that the container can use. - Allowedaddr string `json:"allowedAddress,omitempty"` - // Specifies whether allowedAddress limitation is to be applied to the VNIC. - Configallowedaddr string `json:"configureAllowedAddress,omitempty"` - // The value of the optional default router. - Defrouter string `json:"defrouter,omitempty"` - // Enable one or more types of link protection. - Linkprotection string `json:"linkProtection,omitempty"` - // Set the VNIC's macAddress - Macaddress string `json:"macAddress,omitempty"` -} - -// Arch used for additional architectures -type Arch string - -// Additional architectures permitted to be used for system calls -// By default only the native architecture of the kernel is permitted -const ( - ArchX86 Arch = "SCMP_ARCH_X86" - ArchX86_64 Arch = "SCMP_ARCH_X86_64" - ArchX32 Arch = "SCMP_ARCH_X32" - ArchARM Arch = "SCMP_ARCH_ARM" - ArchAARCH64 Arch = "SCMP_ARCH_AARCH64" - ArchMIPS Arch = "SCMP_ARCH_MIPS" - ArchMIPS64 Arch = "SCMP_ARCH_MIPS64" - ArchMIPS64N32 Arch = "SCMP_ARCH_MIPS64N32" - ArchMIPSEL Arch = "SCMP_ARCH_MIPSEL" - ArchMIPSEL64 Arch = "SCMP_ARCH_MIPSEL64" - ArchMIPSEL64N32 Arch = "SCMP_ARCH_MIPSEL64N32" - ArchPPC Arch = "SCMP_ARCH_PPC" - ArchPPC64 Arch = "SCMP_ARCH_PPC64" - ArchPPC64LE Arch = "SCMP_ARCH_PPC64LE" - ArchS390 Arch = "SCMP_ARCH_S390" - ArchS390X Arch = "SCMP_ARCH_S390X" -) - -// Action taken upon Seccomp rule match -type Action string - -// Define actions for Seccomp rules -const ( - ActKill Action = "SCMP_ACT_KILL" - ActTrap Action = "SCMP_ACT_TRAP" - ActErrno Action = "SCMP_ACT_ERRNO" - ActTrace Action = "SCMP_ACT_TRACE" - ActAllow Action = "SCMP_ACT_ALLOW" -) - -// Operator used to match syscall arguments in Seccomp -type Operator string - -// Define operators for syscall arguments in Seccomp -const ( - OpNotEqual Operator = "SCMP_CMP_NE" - OpLessThan Operator = "SCMP_CMP_LT" - OpLessEqual Operator = "SCMP_CMP_LE" - OpEqualTo Operator = "SCMP_CMP_EQ" - OpGreaterEqual Operator = "SCMP_CMP_GE" - OpGreaterThan Operator = "SCMP_CMP_GT" - OpMaskedEqual Operator = "SCMP_CMP_MASKED_EQ" -) - -// Arg used for matching specific syscall arguments in Seccomp -type Arg struct { - Index uint `json:"index"` - Value uint64 `json:"value"` - ValueTwo uint64 `json:"valueTwo"` - Op Operator `json:"op"` -} - -// Syscall is used to match a syscall in Seccomp -type Syscall struct { - Name string `json:"name"` - Action Action `json:"action"` - Args []Arg `json:"args,omitempty"` -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/opencontainers/runtime-spec/specs-go/state.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/opencontainers/runtime-spec/specs-go/state.go deleted file mode 100644 index 445f8c5c..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/opencontainers/runtime-spec/specs-go/state.go +++ /dev/null @@ -1,17 +0,0 @@ -package specs - -// State holds information about the runtime state of the container. -type State struct { - // Version is the version of the specification that is supported. - Version string `json:"version"` - // ID is the container ID - ID string `json:"id"` - // Status is the runtime state of the container. - Status string `json:"status"` - // Pid is the process id for the container's main process. - Pid int `json:"pid"` - // BundlePath is the path to the container's bundle directory. - BundlePath string `json:"bundlePath"` - // Annotations are the annotations associated with the container. - Annotations map[string]string `json:"annotations"` -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/opencontainers/runtime-spec/specs-go/version.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/opencontainers/runtime-spec/specs-go/version.go deleted file mode 100644 index 2db1b801..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/opencontainers/runtime-spec/specs-go/version.go +++ /dev/null @@ -1,18 +0,0 @@ -package specs - -import "fmt" - -const ( - // VersionMajor is for an API incompatible changes - VersionMajor = 1 - // VersionMinor is for functionality in a backwards-compatible manner - VersionMinor = 0 - // VersionPatch is for backwards-compatible bug fixes - VersionPatch = 0 - - // VersionDev indicates development branch. Releases will be empty string. - VersionDev = "-rc1-dev" -) - -// Version is the specification version that the package types support. -var Version = fmt.Sprintf("%d.%d.%d%s", VersionMajor, VersionMinor, VersionPatch, VersionDev) diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability.go deleted file mode 100644 index c13f4e52..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) 2013, Suryandaru Triandana -// All rights reserved. -// -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Package capability provides utilities for manipulating POSIX capabilities. -package capability - -type Capabilities interface { - // Get check whether a capability present in the given - // capabilities set. The 'which' value should be one of EFFECTIVE, - // PERMITTED, INHERITABLE or BOUNDING. - Get(which CapType, what Cap) bool - - // Empty check whether all capability bits of the given capabilities - // set are zero. The 'which' value should be one of EFFECTIVE, - // PERMITTED, INHERITABLE or BOUNDING. - Empty(which CapType) bool - - // Full check whether all capability bits of the given capabilities - // set are one. The 'which' value should be one of EFFECTIVE, - // PERMITTED, INHERITABLE or BOUNDING. - Full(which CapType) bool - - // Set sets capabilities of the given capabilities sets. The - // 'which' value should be one or combination (OR'ed) of EFFECTIVE, - // PERMITTED, INHERITABLE or BOUNDING. - Set(which CapType, caps ...Cap) - - // Unset unsets capabilities of the given capabilities sets. The - // 'which' value should be one or combination (OR'ed) of EFFECTIVE, - // PERMITTED, INHERITABLE or BOUNDING. - Unset(which CapType, caps ...Cap) - - // Fill sets all bits of the given capabilities kind to one. The - // 'kind' value should be one or combination (OR'ed) of CAPS or - // BOUNDS. - Fill(kind CapType) - - // Clear sets all bits of the given capabilities kind to zero. The - // 'kind' value should be one or combination (OR'ed) of CAPS or - // BOUNDS. - Clear(kind CapType) - - // String return current capabilities state of the given capabilities - // set as string. The 'which' value should be one of EFFECTIVE, - // PERMITTED, INHERITABLE or BOUNDING. - StringCap(which CapType) string - - // String return current capabilities state as string. - String() string - - // Load load actual capabilities value. This will overwrite all - // outstanding changes. - Load() error - - // Apply apply the capabilities settings, so all changes will take - // effect. - Apply(kind CapType) error -} - -// NewPid create new initialized Capabilities object for given pid when it -// is nonzero, or for the current pid if pid is 0 -func NewPid(pid int) (Capabilities, error) { - return newPid(pid) -} - -// NewFile create new initialized Capabilities object for given named file. -func NewFile(name string) (Capabilities, error) { - return newFile(name) -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability_linux.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability_linux.go deleted file mode 100644 index 3dfcd398..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability_linux.go +++ /dev/null @@ -1,608 +0,0 @@ -// Copyright (c) 2013, Suryandaru Triandana -// All rights reserved. -// -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package capability - -import ( - "bufio" - "errors" - "fmt" - "io" - "os" - "strings" - "syscall" -) - -var errUnknownVers = errors.New("unknown capability version") - -const ( - linuxCapVer1 = 0x19980330 - linuxCapVer2 = 0x20071026 - linuxCapVer3 = 0x20080522 -) - -var ( - capVers uint32 - capLastCap Cap -) - -func init() { - var hdr capHeader - capget(&hdr, nil) - capVers = hdr.version - - if initLastCap() == nil { - CAP_LAST_CAP = capLastCap - if capLastCap > 31 { - capUpperMask = (uint32(1) << (uint(capLastCap) - 31)) - 1 - } else { - capUpperMask = 0 - } - } -} - -func initLastCap() error { - if capLastCap != 0 { - return nil - } - - f, err := os.Open("/proc/sys/kernel/cap_last_cap") - if err != nil { - return err - } - defer f.Close() - - var b []byte = make([]byte, 11) - _, err = f.Read(b) - if err != nil { - return err - } - - fmt.Sscanf(string(b), "%d", &capLastCap) - - return nil -} - -func mkStringCap(c Capabilities, which CapType) (ret string) { - for i, first := Cap(0), true; i <= CAP_LAST_CAP; i++ { - if !c.Get(which, i) { - continue - } - if first { - first = false - } else { - ret += ", " - } - ret += i.String() - } - return -} - -func mkString(c Capabilities, max CapType) (ret string) { - ret = "{" - for i := CapType(1); i <= max; i <<= 1 { - ret += " " + i.String() + "=\"" - if c.Empty(i) { - ret += "empty" - } else if c.Full(i) { - ret += "full" - } else { - ret += c.StringCap(i) - } - ret += "\"" - } - ret += " }" - return -} - -func newPid(pid int) (c Capabilities, err error) { - switch capVers { - case linuxCapVer1: - p := new(capsV1) - p.hdr.version = capVers - p.hdr.pid = pid - c = p - case linuxCapVer2, linuxCapVer3: - p := new(capsV3) - p.hdr.version = capVers - p.hdr.pid = pid - c = p - default: - err = errUnknownVers - return - } - err = c.Load() - if err != nil { - c = nil - } - return -} - -type capsV1 struct { - hdr capHeader - data capData -} - -func (c *capsV1) Get(which CapType, what Cap) bool { - if what > 32 { - return false - } - - switch which { - case EFFECTIVE: - return (1< 32 { - continue - } - - if which&EFFECTIVE != 0 { - c.data.effective |= 1 << uint(what) - } - if which&PERMITTED != 0 { - c.data.permitted |= 1 << uint(what) - } - if which&INHERITABLE != 0 { - c.data.inheritable |= 1 << uint(what) - } - } -} - -func (c *capsV1) Unset(which CapType, caps ...Cap) { - for _, what := range caps { - if what > 32 { - continue - } - - if which&EFFECTIVE != 0 { - c.data.effective &= ^(1 << uint(what)) - } - if which&PERMITTED != 0 { - c.data.permitted &= ^(1 << uint(what)) - } - if which&INHERITABLE != 0 { - c.data.inheritable &= ^(1 << uint(what)) - } - } -} - -func (c *capsV1) Fill(kind CapType) { - if kind&CAPS == CAPS { - c.data.effective = 0x7fffffff - c.data.permitted = 0x7fffffff - c.data.inheritable = 0 - } -} - -func (c *capsV1) Clear(kind CapType) { - if kind&CAPS == CAPS { - c.data.effective = 0 - c.data.permitted = 0 - c.data.inheritable = 0 - } -} - -func (c *capsV1) StringCap(which CapType) (ret string) { - return mkStringCap(c, which) -} - -func (c *capsV1) String() (ret string) { - return mkString(c, BOUNDING) -} - -func (c *capsV1) Load() (err error) { - return capget(&c.hdr, &c.data) -} - -func (c *capsV1) Apply(kind CapType) error { - if kind&CAPS == CAPS { - return capset(&c.hdr, &c.data) - } - return nil -} - -type capsV3 struct { - hdr capHeader - data [2]capData - bounds [2]uint32 -} - -func (c *capsV3) Get(which CapType, what Cap) bool { - var i uint - if what > 31 { - i = uint(what) >> 5 - what %= 32 - } - - switch which { - case EFFECTIVE: - return (1< 31 { - i = uint(what) >> 5 - what %= 32 - } - - if which&EFFECTIVE != 0 { - c.data[i].effective |= 1 << uint(what) - } - if which&PERMITTED != 0 { - c.data[i].permitted |= 1 << uint(what) - } - if which&INHERITABLE != 0 { - c.data[i].inheritable |= 1 << uint(what) - } - if which&BOUNDING != 0 { - c.bounds[i] |= 1 << uint(what) - } - } -} - -func (c *capsV3) Unset(which CapType, caps ...Cap) { - for _, what := range caps { - var i uint - if what > 31 { - i = uint(what) >> 5 - what %= 32 - } - - if which&EFFECTIVE != 0 { - c.data[i].effective &= ^(1 << uint(what)) - } - if which&PERMITTED != 0 { - c.data[i].permitted &= ^(1 << uint(what)) - } - if which&INHERITABLE != 0 { - c.data[i].inheritable &= ^(1 << uint(what)) - } - if which&BOUNDING != 0 { - c.bounds[i] &= ^(1 << uint(what)) - } - } -} - -func (c *capsV3) Fill(kind CapType) { - if kind&CAPS == CAPS { - c.data[0].effective = 0xffffffff - c.data[0].permitted = 0xffffffff - c.data[0].inheritable = 0 - c.data[1].effective = 0xffffffff - c.data[1].permitted = 0xffffffff - c.data[1].inheritable = 0 - } - - if kind&BOUNDS == BOUNDS { - c.bounds[0] = 0xffffffff - c.bounds[1] = 0xffffffff - } -} - -func (c *capsV3) Clear(kind CapType) { - if kind&CAPS == CAPS { - c.data[0].effective = 0 - c.data[0].permitted = 0 - c.data[0].inheritable = 0 - c.data[1].effective = 0 - c.data[1].permitted = 0 - c.data[1].inheritable = 0 - } - - if kind&BOUNDS == BOUNDS { - c.bounds[0] = 0 - c.bounds[1] = 0 - } -} - -func (c *capsV3) StringCap(which CapType) (ret string) { - return mkStringCap(c, which) -} - -func (c *capsV3) String() (ret string) { - return mkString(c, BOUNDING) -} - -func (c *capsV3) Load() (err error) { - err = capget(&c.hdr, &c.data[0]) - if err != nil { - return - } - - var status_path string - - if c.hdr.pid == 0 { - status_path = fmt.Sprintf("/proc/self/status") - } else { - status_path = fmt.Sprintf("/proc/%d/status", c.hdr.pid) - } - - f, err := os.Open(status_path) - if err != nil { - return - } - b := bufio.NewReader(f) - for { - line, e := b.ReadString('\n') - if e != nil { - if e != io.EOF { - err = e - } - break - } - if strings.HasPrefix(line, "CapB") { - fmt.Sscanf(line[4:], "nd: %08x%08x", &c.bounds[1], &c.bounds[0]) - break - } - } - f.Close() - - return -} - -func (c *capsV3) Apply(kind CapType) (err error) { - if kind&BOUNDS == BOUNDS { - var data [2]capData - err = capget(&c.hdr, &data[0]) - if err != nil { - return - } - if (1< 31 { - if c.data.version == 1 { - return false - } - i = uint(what) >> 5 - what %= 32 - } - - switch which { - case EFFECTIVE: - return (1< 31 { - if c.data.version == 1 { - continue - } - i = uint(what) >> 5 - what %= 32 - } - - if which&EFFECTIVE != 0 { - c.data.effective[i] |= 1 << uint(what) - } - if which&PERMITTED != 0 { - c.data.data[i].permitted |= 1 << uint(what) - } - if which&INHERITABLE != 0 { - c.data.data[i].inheritable |= 1 << uint(what) - } - } -} - -func (c *capsFile) Unset(which CapType, caps ...Cap) { - for _, what := range caps { - var i uint - if what > 31 { - if c.data.version == 1 { - continue - } - i = uint(what) >> 5 - what %= 32 - } - - if which&EFFECTIVE != 0 { - c.data.effective[i] &= ^(1 << uint(what)) - } - if which&PERMITTED != 0 { - c.data.data[i].permitted &= ^(1 << uint(what)) - } - if which&INHERITABLE != 0 { - c.data.data[i].inheritable &= ^(1 << uint(what)) - } - } -} - -func (c *capsFile) Fill(kind CapType) { - if kind&CAPS == CAPS { - c.data.effective[0] = 0xffffffff - c.data.data[0].permitted = 0xffffffff - c.data.data[0].inheritable = 0 - if c.data.version == 2 { - c.data.effective[1] = 0xffffffff - c.data.data[1].permitted = 0xffffffff - c.data.data[1].inheritable = 0 - } - } -} - -func (c *capsFile) Clear(kind CapType) { - if kind&CAPS == CAPS { - c.data.effective[0] = 0 - c.data.data[0].permitted = 0 - c.data.data[0].inheritable = 0 - if c.data.version == 2 { - c.data.effective[1] = 0 - c.data.data[1].permitted = 0 - c.data.data[1].inheritable = 0 - } - } -} - -func (c *capsFile) StringCap(which CapType) (ret string) { - return mkStringCap(c, which) -} - -func (c *capsFile) String() (ret string) { - return mkString(c, INHERITABLE) -} - -func (c *capsFile) Load() (err error) { - return getVfsCap(c.path, &c.data) -} - -func (c *capsFile) Apply(kind CapType) (err error) { - if kind&CAPS == CAPS { - return setVfsCap(c.path, &c.data) - } - return -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability_noop.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability_noop.go deleted file mode 100644 index 9bb3070c..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability_noop.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) 2013, Suryandaru Triandana -// All rights reserved. -// -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// +build !linux - -package capability - -import "errors" - -func newPid(pid int) (Capabilities, error) { - return nil, errors.New("not supported") -} - -func newFile(path string) (Capabilities, error) { - return nil, errors.New("not supported") -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability_test.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability_test.go deleted file mode 100644 index 8108655c..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/capability_test.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2013, Suryandaru Triandana -// All rights reserved. -// -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package capability - -import "testing" - -func TestState(t *testing.T) { - testEmpty := func(name string, c Capabilities, whats CapType) { - for i := CapType(1); i <= BOUNDING; i <<= 1 { - if (i&whats) != 0 && !c.Empty(i) { - t.Errorf(name+": capabilities set %q wasn't empty", i) - } - } - } - testFull := func(name string, c Capabilities, whats CapType) { - for i := CapType(1); i <= BOUNDING; i <<= 1 { - if (i&whats) != 0 && !c.Full(i) { - t.Errorf(name+": capabilities set %q wasn't full", i) - } - } - } - testPartial := func(name string, c Capabilities, whats CapType) { - for i := CapType(1); i <= BOUNDING; i <<= 1 { - if (i&whats) != 0 && (c.Empty(i) || c.Full(i)) { - t.Errorf(name+": capabilities set %q wasn't partial", i) - } - } - } - testGet := func(name string, c Capabilities, whats CapType, max Cap) { - for i := CapType(1); i <= BOUNDING; i <<= 1 { - if (i & whats) == 0 { - continue - } - for j := Cap(0); j <= max; j++ { - if !c.Get(i, j) { - t.Errorf(name+": capability %q wasn't found on %q", j, i) - } - } - } - } - - capf := new(capsFile) - capf.data.version = 2 - for _, tc := range []struct { - name string - c Capabilities - sets CapType - max Cap - }{ - {"v1", new(capsV1), EFFECTIVE | PERMITTED, CAP_AUDIT_CONTROL}, - {"v3", new(capsV3), EFFECTIVE | PERMITTED | BOUNDING, CAP_LAST_CAP}, - {"file_v1", new(capsFile), EFFECTIVE | PERMITTED, CAP_AUDIT_CONTROL}, - {"file_v2", capf, EFFECTIVE | PERMITTED, CAP_LAST_CAP}, - } { - testEmpty(tc.name, tc.c, tc.sets) - tc.c.Fill(CAPS | BOUNDS) - testFull(tc.name, tc.c, tc.sets) - testGet(tc.name, tc.c, tc.sets, tc.max) - tc.c.Clear(CAPS | BOUNDS) - testEmpty(tc.name, tc.c, tc.sets) - for i := CapType(1); i <= BOUNDING; i <<= 1 { - for j := Cap(0); j <= CAP_LAST_CAP; j++ { - tc.c.Set(i, j) - } - } - testFull(tc.name, tc.c, tc.sets) - testGet(tc.name, tc.c, tc.sets, tc.max) - for i := CapType(1); i <= BOUNDING; i <<= 1 { - for j := Cap(0); j <= CAP_LAST_CAP; j++ { - tc.c.Unset(i, j) - } - } - testEmpty(tc.name, tc.c, tc.sets) - tc.c.Set(PERMITTED, CAP_CHOWN) - testPartial(tc.name, tc.c, PERMITTED) - tc.c.Clear(CAPS | BOUNDS) - testEmpty(tc.name, tc.c, tc.sets) - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/enum.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/enum.go deleted file mode 100644 index fd0ce7fe..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/enum.go +++ /dev/null @@ -1,264 +0,0 @@ -// Copyright (c) 2013, Suryandaru Triandana -// All rights reserved. -// -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package capability - -type CapType uint - -func (c CapType) String() string { - switch c { - case EFFECTIVE: - return "effective" - case PERMITTED: - return "permitted" - case INHERITABLE: - return "inheritable" - case BOUNDING: - return "bounding" - case CAPS: - return "caps" - } - return "unknown" -} - -const ( - EFFECTIVE CapType = 1 << iota - PERMITTED - INHERITABLE - BOUNDING - - CAPS = EFFECTIVE | PERMITTED | INHERITABLE - BOUNDS = BOUNDING -) - -//go:generate go run enumgen/gen.go -type Cap int - -// POSIX-draft defined capabilities. -const ( - // In a system with the [_POSIX_CHOWN_RESTRICTED] option defined, this - // overrides the restriction of changing file ownership and group - // ownership. - CAP_CHOWN = Cap(0) - - // Override all DAC access, including ACL execute access if - // [_POSIX_ACL] is defined. Excluding DAC access covered by - // CAP_LINUX_IMMUTABLE. - CAP_DAC_OVERRIDE = Cap(1) - - // Overrides all DAC restrictions regarding read and search on files - // and directories, including ACL restrictions if [_POSIX_ACL] is - // defined. Excluding DAC access covered by CAP_LINUX_IMMUTABLE. - CAP_DAC_READ_SEARCH = Cap(2) - - // Overrides all restrictions about allowed operations on files, where - // file owner ID must be equal to the user ID, except where CAP_FSETID - // is applicable. It doesn't override MAC and DAC restrictions. - CAP_FOWNER = Cap(3) - - // Overrides the following restrictions that the effective user ID - // shall match the file owner ID when setting the S_ISUID and S_ISGID - // bits on that file; that the effective group ID (or one of the - // supplementary group IDs) shall match the file owner ID when setting - // the S_ISGID bit on that file; that the S_ISUID and S_ISGID bits are - // cleared on successful return from chown(2) (not implemented). - CAP_FSETID = Cap(4) - - // Overrides the restriction that the real or effective user ID of a - // process sending a signal must match the real or effective user ID - // of the process receiving the signal. - CAP_KILL = Cap(5) - - // Allows setgid(2) manipulation - // Allows setgroups(2) - // Allows forged gids on socket credentials passing. - CAP_SETGID = Cap(6) - - // Allows set*uid(2) manipulation (including fsuid). - // Allows forged pids on socket credentials passing. - CAP_SETUID = Cap(7) - - // Linux-specific capabilities - - // Without VFS support for capabilities: - // Transfer any capability in your permitted set to any pid, - // remove any capability in your permitted set from any pid - // With VFS support for capabilities (neither of above, but) - // Add any capability from current's capability bounding set - // to the current process' inheritable set - // Allow taking bits out of capability bounding set - // Allow modification of the securebits for a process - CAP_SETPCAP = Cap(8) - - // Allow modification of S_IMMUTABLE and S_APPEND file attributes - CAP_LINUX_IMMUTABLE = Cap(9) - - // Allows binding to TCP/UDP sockets below 1024 - // Allows binding to ATM VCIs below 32 - CAP_NET_BIND_SERVICE = Cap(10) - - // Allow broadcasting, listen to multicast - CAP_NET_BROADCAST = Cap(11) - - // Allow interface configuration - // Allow administration of IP firewall, masquerading and accounting - // Allow setting debug option on sockets - // Allow modification of routing tables - // Allow setting arbitrary process / process group ownership on - // sockets - // Allow binding to any address for transparent proxying (also via NET_RAW) - // Allow setting TOS (type of service) - // Allow setting promiscuous mode - // Allow clearing driver statistics - // Allow multicasting - // Allow read/write of device-specific registers - // Allow activation of ATM control sockets - CAP_NET_ADMIN = Cap(12) - - // Allow use of RAW sockets - // Allow use of PACKET sockets - // Allow binding to any address for transparent proxying (also via NET_ADMIN) - CAP_NET_RAW = Cap(13) - - // Allow locking of shared memory segments - // Allow mlock and mlockall (which doesn't really have anything to do - // with IPC) - CAP_IPC_LOCK = Cap(14) - - // Override IPC ownership checks - CAP_IPC_OWNER = Cap(15) - - // Insert and remove kernel modules - modify kernel without limit - CAP_SYS_MODULE = Cap(16) - - // Allow ioperm/iopl access - // Allow sending USB messages to any device via /proc/bus/usb - CAP_SYS_RAWIO = Cap(17) - - // Allow use of chroot() - CAP_SYS_CHROOT = Cap(18) - - // Allow ptrace() of any process - CAP_SYS_PTRACE = Cap(19) - - // Allow configuration of process accounting - CAP_SYS_PACCT = Cap(20) - - // Allow configuration of the secure attention key - // Allow administration of the random device - // Allow examination and configuration of disk quotas - // Allow setting the domainname - // Allow setting the hostname - // Allow calling bdflush() - // Allow mount() and umount(), setting up new smb connection - // Allow some autofs root ioctls - // Allow nfsservctl - // Allow VM86_REQUEST_IRQ - // Allow to read/write pci config on alpha - // Allow irix_prctl on mips (setstacksize) - // Allow flushing all cache on m68k (sys_cacheflush) - // Allow removing semaphores - // Used instead of CAP_CHOWN to "chown" IPC message queues, semaphores - // and shared memory - // Allow locking/unlocking of shared memory segment - // Allow turning swap on/off - // Allow forged pids on socket credentials passing - // Allow setting readahead and flushing buffers on block devices - // Allow setting geometry in floppy driver - // Allow turning DMA on/off in xd driver - // Allow administration of md devices (mostly the above, but some - // extra ioctls) - // Allow tuning the ide driver - // Allow access to the nvram device - // Allow administration of apm_bios, serial and bttv (TV) device - // Allow manufacturer commands in isdn CAPI support driver - // Allow reading non-standardized portions of pci configuration space - // Allow DDI debug ioctl on sbpcd driver - // Allow setting up serial ports - // Allow sending raw qic-117 commands - // Allow enabling/disabling tagged queuing on SCSI controllers and sending - // arbitrary SCSI commands - // Allow setting encryption key on loopback filesystem - // Allow setting zone reclaim policy - CAP_SYS_ADMIN = Cap(21) - - // Allow use of reboot() - CAP_SYS_BOOT = Cap(22) - - // Allow raising priority and setting priority on other (different - // UID) processes - // Allow use of FIFO and round-robin (realtime) scheduling on own - // processes and setting the scheduling algorithm used by another - // process. - // Allow setting cpu affinity on other processes - CAP_SYS_NICE = Cap(23) - - // Override resource limits. Set resource limits. - // Override quota limits. - // Override reserved space on ext2 filesystem - // Modify data journaling mode on ext3 filesystem (uses journaling - // resources) - // NOTE: ext2 honors fsuid when checking for resource overrides, so - // you can override using fsuid too - // Override size restrictions on IPC message queues - // Allow more than 64hz interrupts from the real-time clock - // Override max number of consoles on console allocation - // Override max number of keymaps - CAP_SYS_RESOURCE = Cap(24) - - // Allow manipulation of system clock - // Allow irix_stime on mips - // Allow setting the real-time clock - CAP_SYS_TIME = Cap(25) - - // Allow configuration of tty devices - // Allow vhangup() of tty - CAP_SYS_TTY_CONFIG = Cap(26) - - // Allow the privileged aspects of mknod() - CAP_MKNOD = Cap(27) - - // Allow taking of leases on files - CAP_LEASE = Cap(28) - - CAP_AUDIT_WRITE = Cap(29) - CAP_AUDIT_CONTROL = Cap(30) - CAP_SETFCAP = Cap(31) - - // Override MAC access. - // The base kernel enforces no MAC policy. - // An LSM may enforce a MAC policy, and if it does and it chooses - // to implement capability based overrides of that policy, this is - // the capability it should use to do so. - CAP_MAC_OVERRIDE = Cap(32) - - // Allow MAC configuration or state changes. - // The base kernel requires no MAC configuration. - // An LSM may enforce a MAC policy, and if it does and it chooses - // to implement capability based checks on modifications to that - // policy or the data required to maintain it, this is the - // capability it should use to do so. - CAP_MAC_ADMIN = Cap(33) - - // Allow configuring the kernel's syslog (printk behaviour) - CAP_SYSLOG = Cap(34) - - // Allow triggering something that will wake the system - CAP_WAKE_ALARM = Cap(35) - - // Allow preventing system suspends - CAP_BLOCK_SUSPEND = Cap(36) - - // Allow reading audit messages from the kernel - CAP_AUDIT_READ = Cap(37) -) - -var ( - // Highest valid capability of the running kernel. - CAP_LAST_CAP = Cap(63) - - capUpperMask = ^uint32(0) -) diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/enum_gen.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/enum_gen.go deleted file mode 100644 index b9e6d2d5..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/enum_gen.go +++ /dev/null @@ -1,129 +0,0 @@ -// generated file; DO NOT EDIT - use go generate in directory with source - -package capability - -func (c Cap) String() string { - switch c { - case CAP_CHOWN: - return "chown" - case CAP_DAC_OVERRIDE: - return "dac_override" - case CAP_DAC_READ_SEARCH: - return "dac_read_search" - case CAP_FOWNER: - return "fowner" - case CAP_FSETID: - return "fsetid" - case CAP_KILL: - return "kill" - case CAP_SETGID: - return "setgid" - case CAP_SETUID: - return "setuid" - case CAP_SETPCAP: - return "setpcap" - case CAP_LINUX_IMMUTABLE: - return "linux_immutable" - case CAP_NET_BIND_SERVICE: - return "net_bind_service" - case CAP_NET_BROADCAST: - return "net_broadcast" - case CAP_NET_ADMIN: - return "net_admin" - case CAP_NET_RAW: - return "net_raw" - case CAP_IPC_LOCK: - return "ipc_lock" - case CAP_IPC_OWNER: - return "ipc_owner" - case CAP_SYS_MODULE: - return "sys_module" - case CAP_SYS_RAWIO: - return "sys_rawio" - case CAP_SYS_CHROOT: - return "sys_chroot" - case CAP_SYS_PTRACE: - return "sys_ptrace" - case CAP_SYS_PACCT: - return "sys_pacct" - case CAP_SYS_ADMIN: - return "sys_admin" - case CAP_SYS_BOOT: - return "sys_boot" - case CAP_SYS_NICE: - return "sys_nice" - case CAP_SYS_RESOURCE: - return "sys_resource" - case CAP_SYS_TIME: - return "sys_time" - case CAP_SYS_TTY_CONFIG: - return "sys_tty_config" - case CAP_MKNOD: - return "mknod" - case CAP_LEASE: - return "lease" - case CAP_AUDIT_WRITE: - return "audit_write" - case CAP_AUDIT_CONTROL: - return "audit_control" - case CAP_SETFCAP: - return "setfcap" - case CAP_MAC_OVERRIDE: - return "mac_override" - case CAP_MAC_ADMIN: - return "mac_admin" - case CAP_SYSLOG: - return "syslog" - case CAP_WAKE_ALARM: - return "wake_alarm" - case CAP_BLOCK_SUSPEND: - return "block_suspend" - case CAP_AUDIT_READ: - return "audit_read" - } - return "unknown" -} - -// List returns list of all supported capabilities -func List() []Cap { - return []Cap{ - CAP_CHOWN, - CAP_DAC_OVERRIDE, - CAP_DAC_READ_SEARCH, - CAP_FOWNER, - CAP_FSETID, - CAP_KILL, - CAP_SETGID, - CAP_SETUID, - CAP_SETPCAP, - CAP_LINUX_IMMUTABLE, - CAP_NET_BIND_SERVICE, - CAP_NET_BROADCAST, - CAP_NET_ADMIN, - CAP_NET_RAW, - CAP_IPC_LOCK, - CAP_IPC_OWNER, - CAP_SYS_MODULE, - CAP_SYS_RAWIO, - CAP_SYS_CHROOT, - CAP_SYS_PTRACE, - CAP_SYS_PACCT, - CAP_SYS_ADMIN, - CAP_SYS_BOOT, - CAP_SYS_NICE, - CAP_SYS_RESOURCE, - CAP_SYS_TIME, - CAP_SYS_TTY_CONFIG, - CAP_MKNOD, - CAP_LEASE, - CAP_AUDIT_WRITE, - CAP_AUDIT_CONTROL, - CAP_SETFCAP, - CAP_MAC_OVERRIDE, - CAP_MAC_ADMIN, - CAP_SYSLOG, - CAP_WAKE_ALARM, - CAP_BLOCK_SUSPEND, - CAP_AUDIT_READ, - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/enumgen/gen.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/enumgen/gen.go deleted file mode 100644 index 4c733809..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/enumgen/gen.go +++ /dev/null @@ -1,92 +0,0 @@ -package main - -import ( - "bytes" - "fmt" - "go/ast" - "go/format" - "go/parser" - "go/token" - "io/ioutil" - "log" - "os" - "strings" -) - -const fileName = "enum.go" -const genName = "enum_gen.go" - -type generator struct { - buf bytes.Buffer - caps []string -} - -func (g *generator) writeHeader() { - g.buf.WriteString("// generated file; DO NOT EDIT - use go generate in directory with source\n") - g.buf.WriteString("\n") - g.buf.WriteString("package capability") -} - -func (g *generator) writeStringFunc() { - g.buf.WriteString("\n") - g.buf.WriteString("func (c Cap) String() string {\n") - g.buf.WriteString("switch c {\n") - for _, cap := range g.caps { - fmt.Fprintf(&g.buf, "case %s:\n", cap) - fmt.Fprintf(&g.buf, "return \"%s\"\n", strings.ToLower(cap[4:])) - } - g.buf.WriteString("}\n") - g.buf.WriteString("return \"unknown\"\n") - g.buf.WriteString("}\n") -} - -func (g *generator) writeListFunc() { - g.buf.WriteString("\n") - g.buf.WriteString("// List returns list of all supported capabilities\n") - g.buf.WriteString("func List() []Cap {\n") - g.buf.WriteString("return []Cap{\n") - for _, cap := range g.caps { - fmt.Fprintf(&g.buf, "%s,\n", cap) - } - g.buf.WriteString("}\n") - g.buf.WriteString("}\n") -} - -func main() { - fs := token.NewFileSet() - parsedFile, err := parser.ParseFile(fs, fileName, nil, 0) - if err != nil { - log.Fatal(err) - } - var caps []string - for _, decl := range parsedFile.Decls { - decl, ok := decl.(*ast.GenDecl) - if !ok || decl.Tok != token.CONST { - continue - } - for _, spec := range decl.Specs { - vspec := spec.(*ast.ValueSpec) - name := vspec.Names[0].Name - if strings.HasPrefix(name, "CAP_") { - caps = append(caps, name) - } - } - } - g := &generator{caps: caps} - g.writeHeader() - g.writeStringFunc() - g.writeListFunc() - src, err := format.Source(g.buf.Bytes()) - if err != nil { - fmt.Println("generated invalid Go code") - fmt.Println(g.buf.String()) - log.Fatal(err) - } - fi, err := os.Stat(fileName) - if err != nil { - log.Fatal(err) - } - if err := ioutil.WriteFile(genName, src, fi.Mode().Perm()); err != nil { - log.Fatal(err) - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/syscall_linux.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/syscall_linux.go deleted file mode 100644 index dd6f4540..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/syndtr/gocapability/capability/syscall_linux.go +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright (c) 2013, Suryandaru Triandana -// All rights reserved. -// -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package capability - -import ( - "syscall" - "unsafe" -) - -type capHeader struct { - version uint32 - pid int -} - -type capData struct { - effective uint32 - permitted uint32 - inheritable uint32 -} - -func capget(hdr *capHeader, data *capData) (err error) { - _, _, e1 := syscall.Syscall(syscall.SYS_CAPGET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0) - if e1 != 0 { - err = e1 - } - return -} - -func capset(hdr *capHeader, data *capData) (err error) { - _, _, e1 := syscall.Syscall(syscall.SYS_CAPSET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0) - if e1 != 0 { - err = e1 - } - return -} - -func prctl(option int, arg2, arg3, arg4, arg5 uintptr) (err error) { - _, _, e1 := syscall.Syscall6(syscall.SYS_PRCTL, uintptr(option), arg2, arg3, arg4, arg5, 0) - if e1 != 0 { - err = e1 - } - return -} - -const ( - vfsXattrName = "security.capability" - - vfsCapVerMask = 0xff000000 - vfsCapVer1 = 0x01000000 - vfsCapVer2 = 0x02000000 - - vfsCapFlagMask = ^vfsCapVerMask - vfsCapFlageffective = 0x000001 - - vfscapDataSizeV1 = 4 * (1 + 2*1) - vfscapDataSizeV2 = 4 * (1 + 2*2) -) - -type vfscapData struct { - magic uint32 - data [2]struct { - permitted uint32 - inheritable uint32 - } - effective [2]uint32 - version int8 -} - -var ( - _vfsXattrName *byte -) - -func init() { - _vfsXattrName, _ = syscall.BytePtrFromString(vfsXattrName) -} - -func getVfsCap(path string, dest *vfscapData) (err error) { - var _p0 *byte - _p0, err = syscall.BytePtrFromString(path) - if err != nil { - return - } - r0, _, e1 := syscall.Syscall6(syscall.SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_vfsXattrName)), uintptr(unsafe.Pointer(dest)), vfscapDataSizeV2, 0, 0) - if e1 != 0 { - if e1 == syscall.ENODATA { - dest.version = 2 - return - } - err = e1 - } - switch dest.magic & vfsCapVerMask { - case vfsCapVer1: - dest.version = 1 - if r0 != vfscapDataSizeV1 { - return syscall.EINVAL - } - dest.data[1].permitted = 0 - dest.data[1].inheritable = 0 - case vfsCapVer2: - dest.version = 2 - if r0 != vfscapDataSizeV2 { - return syscall.EINVAL - } - default: - return syscall.EINVAL - } - if dest.magic&vfsCapFlageffective != 0 { - dest.effective[0] = dest.data[0].permitted | dest.data[0].inheritable - dest.effective[1] = dest.data[1].permitted | dest.data[1].inheritable - } else { - dest.effective[0] = 0 - dest.effective[1] = 0 - } - return -} - -func setVfsCap(path string, data *vfscapData) (err error) { - var _p0 *byte - _p0, err = syscall.BytePtrFromString(path) - if err != nil { - return - } - var size uintptr - if data.version == 1 { - data.magic = vfsCapVer1 - size = vfscapDataSizeV1 - } else if data.version == 2 { - data.magic = vfsCapVer2 - if data.effective[0] != 0 || data.effective[1] != 0 { - data.magic |= vfsCapFlageffective - } - size = vfscapDataSizeV2 - } else { - return syscall.EINVAL - } - _, _, e1 := syscall.Syscall6(syscall.SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_vfsXattrName)), uintptr(unsafe.Pointer(data)), size, 0, 0) - if e1 != 0 { - err = e1 - } - return -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/.gitignore b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/.gitignore deleted file mode 100644 index faf70c4c..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -*.coverprofile -node_modules/ diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/.travis.yml b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/.travis.yml deleted file mode 100644 index 94836d75..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/.travis.yml +++ /dev/null @@ -1,39 +0,0 @@ -language: go - -sudo: false - -cache: - directories: - - node_modules - -go: -- 1.2.x -- 1.3.x -- 1.4.2 -- 1.5.x -- 1.6.x -- 1.7.x -- master - -matrix: - allow_failures: - - go: master - include: - - go: 1.6.x - os: osx - - go: 1.7.x - os: osx - -before_script: -- go get github.com/urfave/gfmrun/... || true -- go get golang.org/x/tools/... || true -- if [ ! -f node_modules/.bin/markdown-toc ] ; then - npm install markdown-toc ; - fi - -script: -- ./runtests gen -- ./runtests vet -- ./runtests test -- ./runtests gfmrun -- ./runtests toc diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/CHANGELOG.md b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/CHANGELOG.md deleted file mode 100644 index 07f75464..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/CHANGELOG.md +++ /dev/null @@ -1,392 +0,0 @@ -# Change Log - -**ATTN**: This project uses [semantic versioning](http://semver.org/). - -## [Unreleased] - -## [1.19.1] - 2016-11-21 - -### Fixed - -- Fixes regression introduced in 1.19.0 where using an `ActionFunc` as - the `Action` for a command would cause it to error rather than calling the - function. Should not have a affected declarative cases using `func(c - *cli.Context) err)`. -- Shell completion now handles the case where the user specifies - `--generate-bash-completion` immediately after a flag that takes an argument. - Previously it call the application with `--generate-bash-completion` as the - flag value. - -## [1.19.0] - 2016-11-19 -### Added -- `FlagsByName` was added to make it easy to sort flags (e.g. `sort.Sort(cli.FlagsByName(app.Flags))`) -- A `Description` field was added to `App` for a more detailed description of - the application (similar to the existing `Description` field on `Command`) -- Flag type code generation via `go generate` -- Write to stderr and exit 1 if action returns non-nil error -- Added support for TOML to the `altsrc` loader -- `SkipArgReorder` was added to allow users to skip the argument reordering. - This is useful if you want to consider all "flags" after an argument as - arguments rather than flags (the default behavior of the stdlib `flag` - library). This is backported functionality from the [removal of the flag - reordering](https://github.com/urfave/cli/pull/398) in the unreleased version - 2 -- For formatted errors (those implementing `ErrorFormatter`), the errors will - be formatted during output. Compatible with `pkg/errors`. - -### Changed -- Raise minimum tested/supported Go version to 1.2+ - -### Fixed -- Consider empty environment variables as set (previously environment variables - with the equivalent of `""` would be skipped rather than their value used). -- Return an error if the value in a given environment variable cannot be parsed - as the flag type. Previously these errors were silently swallowed. -- Print full error when an invalid flag is specified (which includes the invalid flag) -- `App.Writer` defaults to `stdout` when `nil` -- If no action is specified on a command or app, the help is now printed instead of `panic`ing -- `App.Metadata` is initialized automatically now (previously was `nil` unless initialized) -- Correctly show help message if `-h` is provided to a subcommand -- `context.(Global)IsSet` now respects environment variables. Previously it - would return `false` if a flag was specified in the environment rather than - as an argument -- Removed deprecation warnings to STDERR to avoid them leaking to the end-user -- `altsrc`s import paths were updated to use `gopkg.in/urfave/cli.v1`. This - fixes issues that occurred when `gopkg.in/urfave/cli.v1` was imported as well - as `altsrc` where Go would complain that the types didn't match - -## [1.18.1] - 2016-08-28 -### Fixed -- Removed deprecation warnings to STDERR to avoid them leaking to the end-user (backported) - -## [1.18.0] - 2016-06-27 -### Added -- `./runtests` test runner with coverage tracking by default -- testing on OS X -- testing on Windows -- `UintFlag`, `Uint64Flag`, and `Int64Flag` types and supporting code - -### Changed -- Use spaces for alignment in help/usage output instead of tabs, making the - output alignment consistent regardless of tab width - -### Fixed -- Printing of command aliases in help text -- Printing of visible flags for both struct and struct pointer flags -- Display the `help` subcommand when using `CommandCategories` -- No longer swallows `panic`s that occur within the `Action`s themselves when - detecting the signature of the `Action` field - -## [1.17.1] - 2016-08-28 -### Fixed -- Removed deprecation warnings to STDERR to avoid them leaking to the end-user - -## [1.17.0] - 2016-05-09 -### Added -- Pluggable flag-level help text rendering via `cli.DefaultFlagStringFunc` -- `context.GlobalBoolT` was added as an analogue to `context.GlobalBool` -- Support for hiding commands by setting `Hidden: true` -- this will hide the - commands in help output - -### Changed -- `Float64Flag`, `IntFlag`, and `DurationFlag` default values are no longer - quoted in help text output. -- All flag types now include `(default: {value})` strings following usage when a - default value can be (reasonably) detected. -- `IntSliceFlag` and `StringSliceFlag` usage strings are now more consistent - with non-slice flag types -- Apps now exit with a code of 3 if an unknown subcommand is specified - (previously they printed "No help topic for...", but still exited 0. This - makes it easier to script around apps built using `cli` since they can trust - that a 0 exit code indicated a successful execution. -- cleanups based on [Go Report Card - feedback](https://goreportcard.com/report/github.com/urfave/cli) - -## [1.16.1] - 2016-08-28 -### Fixed -- Removed deprecation warnings to STDERR to avoid them leaking to the end-user - -## [1.16.0] - 2016-05-02 -### Added -- `Hidden` field on all flag struct types to omit from generated help text - -### Changed -- `BashCompletionFlag` (`--enable-bash-completion`) is now omitted from -generated help text via the `Hidden` field - -### Fixed -- handling of error values in `HandleAction` and `HandleExitCoder` - -## [1.15.0] - 2016-04-30 -### Added -- This file! -- Support for placeholders in flag usage strings -- `App.Metadata` map for arbitrary data/state management -- `Set` and `GlobalSet` methods on `*cli.Context` for altering values after -parsing. -- Support for nested lookup of dot-delimited keys in structures loaded from -YAML. - -### Changed -- The `App.Action` and `Command.Action` now prefer a return signature of -`func(*cli.Context) error`, as defined by `cli.ActionFunc`. If a non-nil -`error` is returned, there may be two outcomes: - - If the error fulfills `cli.ExitCoder`, then `os.Exit` will be called - automatically - - Else the error is bubbled up and returned from `App.Run` -- Specifying an `Action` with the legacy return signature of -`func(*cli.Context)` will produce a deprecation message to stderr -- Specifying an `Action` that is not a `func` type will produce a non-zero exit -from `App.Run` -- Specifying an `Action` func that has an invalid (input) signature will -produce a non-zero exit from `App.Run` - -### Deprecated -- -`cli.App.RunAndExitOnError`, which should now be done by returning an error -that fulfills `cli.ExitCoder` to `cli.App.Run`. -- the legacy signature for -`cli.App.Action` of `func(*cli.Context)`, which should now have a return -signature of `func(*cli.Context) error`, as defined by `cli.ActionFunc`. - -### Fixed -- Added missing `*cli.Context.GlobalFloat64` method - -## [1.14.0] - 2016-04-03 (backfilled 2016-04-25) -### Added -- Codebeat badge -- Support for categorization via `CategorizedHelp` and `Categories` on app. - -### Changed -- Use `filepath.Base` instead of `path.Base` in `Name` and `HelpName`. - -### Fixed -- Ensure version is not shown in help text when `HideVersion` set. - -## [1.13.0] - 2016-03-06 (backfilled 2016-04-25) -### Added -- YAML file input support. -- `NArg` method on context. - -## [1.12.0] - 2016-02-17 (backfilled 2016-04-25) -### Added -- Custom usage error handling. -- Custom text support in `USAGE` section of help output. -- Improved help messages for empty strings. -- AppVeyor CI configuration. - -### Changed -- Removed `panic` from default help printer func. -- De-duping and optimizations. - -### Fixed -- Correctly handle `Before`/`After` at command level when no subcommands. -- Case of literal `-` argument causing flag reordering. -- Environment variable hints on Windows. -- Docs updates. - -## [1.11.1] - 2015-12-21 (backfilled 2016-04-25) -### Changed -- Use `path.Base` in `Name` and `HelpName` -- Export `GetName` on flag types. - -### Fixed -- Flag parsing when skipping is enabled. -- Test output cleanup. -- Move completion check to account for empty input case. - -## [1.11.0] - 2015-11-15 (backfilled 2016-04-25) -### Added -- Destination scan support for flags. -- Testing against `tip` in Travis CI config. - -### Changed -- Go version in Travis CI config. - -### Fixed -- Removed redundant tests. -- Use correct example naming in tests. - -## [1.10.2] - 2015-10-29 (backfilled 2016-04-25) -### Fixed -- Remove unused var in bash completion. - -## [1.10.1] - 2015-10-21 (backfilled 2016-04-25) -### Added -- Coverage and reference logos in README. - -### Fixed -- Use specified values in help and version parsing. -- Only display app version and help message once. - -## [1.10.0] - 2015-10-06 (backfilled 2016-04-25) -### Added -- More tests for existing functionality. -- `ArgsUsage` at app and command level for help text flexibility. - -### Fixed -- Honor `HideHelp` and `HideVersion` in `App.Run`. -- Remove juvenile word from README. - -## [1.9.0] - 2015-09-08 (backfilled 2016-04-25) -### Added -- `FullName` on command with accompanying help output update. -- Set default `$PROG` in bash completion. - -### Changed -- Docs formatting. - -### Fixed -- Removed self-referential imports in tests. - -## [1.8.0] - 2015-06-30 (backfilled 2016-04-25) -### Added -- Support for `Copyright` at app level. -- `Parent` func at context level to walk up context lineage. - -### Fixed -- Global flag processing at top level. - -## [1.7.1] - 2015-06-11 (backfilled 2016-04-25) -### Added -- Aggregate errors from `Before`/`After` funcs. -- Doc comments on flag structs. -- Include non-global flags when checking version and help. -- Travis CI config updates. - -### Fixed -- Ensure slice type flags have non-nil values. -- Collect global flags from the full command hierarchy. -- Docs prose. - -## [1.7.0] - 2015-05-03 (backfilled 2016-04-25) -### Changed -- `HelpPrinter` signature includes output writer. - -### Fixed -- Specify go 1.1+ in docs. -- Set `Writer` when running command as app. - -## [1.6.0] - 2015-03-23 (backfilled 2016-04-25) -### Added -- Multiple author support. -- `NumFlags` at context level. -- `Aliases` at command level. - -### Deprecated -- `ShortName` at command level. - -### Fixed -- Subcommand help output. -- Backward compatible support for deprecated `Author` and `Email` fields. -- Docs regarding `Names`/`Aliases`. - -## [1.5.0] - 2015-02-20 (backfilled 2016-04-25) -### Added -- `After` hook func support at app and command level. - -### Fixed -- Use parsed context when running command as subcommand. -- Docs prose. - -## [1.4.1] - 2015-01-09 (backfilled 2016-04-25) -### Added -- Support for hiding `-h / --help` flags, but not `help` subcommand. -- Stop flag parsing after `--`. - -### Fixed -- Help text for generic flags to specify single value. -- Use double quotes in output for defaults. -- Use `ParseInt` instead of `ParseUint` for int environment var values. -- Use `0` as base when parsing int environment var values. - -## [1.4.0] - 2014-12-12 (backfilled 2016-04-25) -### Added -- Support for environment variable lookup "cascade". -- Support for `Stdout` on app for output redirection. - -### Fixed -- Print command help instead of app help in `ShowCommandHelp`. - -## [1.3.1] - 2014-11-13 (backfilled 2016-04-25) -### Added -- Docs and example code updates. - -### Changed -- Default `-v / --version` flag made optional. - -## [1.3.0] - 2014-08-10 (backfilled 2016-04-25) -### Added -- `FlagNames` at context level. -- Exposed `VersionPrinter` var for more control over version output. -- Zsh completion hook. -- `AUTHOR` section in default app help template. -- Contribution guidelines. -- `DurationFlag` type. - -## [1.2.0] - 2014-08-02 -### Added -- Support for environment variable defaults on flags plus tests. - -## [1.1.0] - 2014-07-15 -### Added -- Bash completion. -- Optional hiding of built-in help command. -- Optional skipping of flag parsing at command level. -- `Author`, `Email`, and `Compiled` metadata on app. -- `Before` hook func support at app and command level. -- `CommandNotFound` func support at app level. -- Command reference available on context. -- `GenericFlag` type. -- `Float64Flag` type. -- `BoolTFlag` type. -- `IsSet` flag helper on context. -- More flag lookup funcs at context level. -- More tests & docs. - -### Changed -- Help template updates to account for presence/absence of flags. -- Separated subcommand help template. -- Exposed `HelpPrinter` var for more control over help output. - -## [1.0.0] - 2013-11-01 -### Added -- `help` flag in default app flag set and each command flag set. -- Custom handling of argument parsing errors. -- Command lookup by name at app level. -- `StringSliceFlag` type and supporting `StringSlice` type. -- `IntSliceFlag` type and supporting `IntSlice` type. -- Slice type flag lookups by name at context level. -- Export of app and command help functions. -- More tests & docs. - -## 0.1.0 - 2013-07-22 -### Added -- Initial implementation. - -[Unreleased]: https://github.com/urfave/cli/compare/v1.18.0...HEAD -[1.18.0]: https://github.com/urfave/cli/compare/v1.17.0...v1.18.0 -[1.17.0]: https://github.com/urfave/cli/compare/v1.16.0...v1.17.0 -[1.16.0]: https://github.com/urfave/cli/compare/v1.15.0...v1.16.0 -[1.15.0]: https://github.com/urfave/cli/compare/v1.14.0...v1.15.0 -[1.14.0]: https://github.com/urfave/cli/compare/v1.13.0...v1.14.0 -[1.13.0]: https://github.com/urfave/cli/compare/v1.12.0...v1.13.0 -[1.12.0]: https://github.com/urfave/cli/compare/v1.11.1...v1.12.0 -[1.11.1]: https://github.com/urfave/cli/compare/v1.11.0...v1.11.1 -[1.11.0]: https://github.com/urfave/cli/compare/v1.10.2...v1.11.0 -[1.10.2]: https://github.com/urfave/cli/compare/v1.10.1...v1.10.2 -[1.10.1]: https://github.com/urfave/cli/compare/v1.10.0...v1.10.1 -[1.10.0]: https://github.com/urfave/cli/compare/v1.9.0...v1.10.0 -[1.9.0]: https://github.com/urfave/cli/compare/v1.8.0...v1.9.0 -[1.8.0]: https://github.com/urfave/cli/compare/v1.7.1...v1.8.0 -[1.7.1]: https://github.com/urfave/cli/compare/v1.7.0...v1.7.1 -[1.7.0]: https://github.com/urfave/cli/compare/v1.6.0...v1.7.0 -[1.6.0]: https://github.com/urfave/cli/compare/v1.5.0...v1.6.0 -[1.5.0]: https://github.com/urfave/cli/compare/v1.4.1...v1.5.0 -[1.4.1]: https://github.com/urfave/cli/compare/v1.4.0...v1.4.1 -[1.4.0]: https://github.com/urfave/cli/compare/v1.3.1...v1.4.0 -[1.3.1]: https://github.com/urfave/cli/compare/v1.3.0...v1.3.1 -[1.3.0]: https://github.com/urfave/cli/compare/v1.2.0...v1.3.0 -[1.2.0]: https://github.com/urfave/cli/compare/v1.1.0...v1.2.0 -[1.1.0]: https://github.com/urfave/cli/compare/v1.0.0...v1.1.0 -[1.0.0]: https://github.com/urfave/cli/compare/v0.1.0...v1.0.0 diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/LICENSE b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/LICENSE deleted file mode 100644 index 42a597e2..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2016 Jeremy Saenz & Contributors - -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. diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/README.md b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/README.md deleted file mode 100644 index bb5f61ea..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/README.md +++ /dev/null @@ -1,1364 +0,0 @@ -cli -=== - -[![Build Status](https://travis-ci.org/urfave/cli.svg?branch=master)](https://travis-ci.org/urfave/cli) -[![Windows Build Status](https://ci.appveyor.com/api/projects/status/rtgk5xufi932pb2v?svg=true)](https://ci.appveyor.com/project/urfave/cli) -[![GoDoc](https://godoc.org/github.com/urfave/cli?status.svg)](https://godoc.org/github.com/urfave/cli) -[![codebeat](https://codebeat.co/badges/0a8f30aa-f975-404b-b878-5fab3ae1cc5f)](https://codebeat.co/projects/github-com-urfave-cli) -[![Go Report Card](https://goreportcard.com/badge/urfave/cli)](https://goreportcard.com/report/urfave/cli) -[![top level coverage](https://gocover.io/_badge/github.com/urfave/cli?0 "top level coverage")](http://gocover.io/github.com/urfave/cli) / -[![altsrc coverage](https://gocover.io/_badge/github.com/urfave/cli/altsrc?0 "altsrc coverage")](http://gocover.io/github.com/urfave/cli/altsrc) - -**Notice:** This is the library formerly known as -`github.com/codegangsta/cli` -- Github will automatically redirect requests -to this repository, but we recommend updating your references for clarity. - -cli is a simple, fast, and fun package for building command line apps in Go. The -goal is to enable developers to write fast and distributable command line -applications in an expressive way. - - - -- [Overview](#overview) -- [Installation](#installation) - * [Supported platforms](#supported-platforms) - * [Using the `v2` branch](#using-the-v2-branch) - * [Pinning to the `v1` releases](#pinning-to-the-v1-releases) -- [Getting Started](#getting-started) -- [Examples](#examples) - * [Arguments](#arguments) - * [Flags](#flags) - + [Placeholder Values](#placeholder-values) - + [Alternate Names](#alternate-names) - + [Ordering](#ordering) - + [Values from the Environment](#values-from-the-environment) - + [Values from alternate input sources (YAML, TOML, and others)](#values-from-alternate-input-sources-yaml-toml-and-others) - * [Subcommands](#subcommands) - * [Subcommands categories](#subcommands-categories) - * [Exit code](#exit-code) - * [Bash Completion](#bash-completion) - + [Enabling](#enabling) - + [Distribution](#distribution) - + [Customization](#customization) - * [Generated Help Text](#generated-help-text) - + [Customization](#customization-1) - * [Version Flag](#version-flag) - + [Customization](#customization-2) - + [Full API Example](#full-api-example) -- [Contribution Guidelines](#contribution-guidelines) - - - -## Overview - -Command line apps are usually so tiny that there is absolutely no reason why -your code should *not* be self-documenting. Things like generating help text and -parsing command flags/options should not hinder productivity when writing a -command line app. - -**This is where cli comes into play.** cli makes command line programming fun, -organized, and expressive! - -## Installation - -Make sure you have a working Go environment. Go version 1.2+ is supported. [See -the install instructions for Go](http://golang.org/doc/install.html). - -To install cli, simply run: -``` -$ go get github.com/urfave/cli -``` - -Make sure your `PATH` includes the `$GOPATH/bin` directory so your commands can -be easily used: -``` -export PATH=$PATH:$GOPATH/bin -``` - -### Supported platforms - -cli is tested against multiple versions of Go on Linux, and against the latest -released version of Go on OS X and Windows. For full details, see -[`./.travis.yml`](./.travis.yml) and [`./appveyor.yml`](./appveyor.yml). - -### Using the `v2` branch - -**Warning**: The `v2` branch is currently unreleased and considered unstable. - -There is currently a long-lived branch named `v2` that is intended to land as -the new `master` branch once development there has settled down. The current -`master` branch (mirrored as `v1`) is being manually merged into `v2` on -an irregular human-based schedule, but generally if one wants to "upgrade" to -`v2` *now* and accept the volatility (read: "awesomeness") that comes along with -that, please use whatever version pinning of your preference, such as via -`gopkg.in`: - -``` -$ go get gopkg.in/urfave/cli.v2 -``` - -``` go -... -import ( - "gopkg.in/urfave/cli.v2" // imports as package "cli" -) -... -``` - -### Pinning to the `v1` releases - -Similarly to the section above describing use of the `v2` branch, if one wants -to avoid any unexpected compatibility pains once `v2` becomes `master`, then -pinning to `v1` is an acceptable option, e.g.: - -``` -$ go get gopkg.in/urfave/cli.v1 -``` - -``` go -... -import ( - "gopkg.in/urfave/cli.v1" // imports as package "cli" -) -... -``` - -This will pull the latest tagged `v1` release (e.g. `v1.18.1` at the time of writing). - -## Getting Started - -One of the philosophies behind cli is that an API should be playful and full of -discovery. So a cli app can be as little as one line of code in `main()`. - - -``` go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - cli.NewApp().Run(os.Args) -} -``` - -This app will run and show help text, but is not very useful. Let's give an -action to execute and some help documentation: - - -``` go -package main - -import ( - "fmt" - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - app.Name = "boom" - app.Usage = "make an explosive entrance" - app.Action = func(c *cli.Context) error { - fmt.Println("boom! I say!") - return nil - } - - app.Run(os.Args) -} -``` - -Running this already gives you a ton of functionality, plus support for things -like subcommands and flags, which are covered below. - -## Examples - -Being a programmer can be a lonely job. Thankfully by the power of automation -that is not the case! Let's create a greeter app to fend off our demons of -loneliness! - -Start by creating a directory named `greet`, and within it, add a file, -`greet.go` with the following code in it: - - -``` go -package main - -import ( - "fmt" - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - app.Name = "greet" - app.Usage = "fight the loneliness!" - app.Action = func(c *cli.Context) error { - fmt.Println("Hello friend!") - return nil - } - - app.Run(os.Args) -} -``` - -Install our command to the `$GOPATH/bin` directory: - -``` -$ go install -``` - -Finally run our new command: - -``` -$ greet -Hello friend! -``` - -cli also generates neat help text: - -``` -$ greet help -NAME: - greet - fight the loneliness! - -USAGE: - greet [global options] command [command options] [arguments...] - -VERSION: - 0.0.0 - -COMMANDS: - help, h Shows a list of commands or help for one command - -GLOBAL OPTIONS - --version Shows version information -``` - -### Arguments - -You can lookup arguments by calling the `Args` function on `cli.Context`, e.g.: - - -``` go -package main - -import ( - "fmt" - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Action = func(c *cli.Context) error { - fmt.Printf("Hello %q", c.Args().Get(0)) - return nil - } - - app.Run(os.Args) -} -``` - -### Flags - -Setting and querying flags is simple. - - -``` go -package main - -import ( - "fmt" - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Flags = []cli.Flag { - cli.StringFlag{ - Name: "lang", - Value: "english", - Usage: "language for the greeting", - }, - } - - app.Action = func(c *cli.Context) error { - name := "Nefertiti" - if c.NArg() > 0 { - name = c.Args().Get(0) - } - if c.String("lang") == "spanish" { - fmt.Println("Hola", name) - } else { - fmt.Println("Hello", name) - } - return nil - } - - app.Run(os.Args) -} -``` - -You can also set a destination variable for a flag, to which the content will be -scanned. - - -``` go -package main - -import ( - "os" - "fmt" - - "github.com/urfave/cli" -) - -func main() { - var language string - - app := cli.NewApp() - - app.Flags = []cli.Flag { - cli.StringFlag{ - Name: "lang", - Value: "english", - Usage: "language for the greeting", - Destination: &language, - }, - } - - app.Action = func(c *cli.Context) error { - name := "someone" - if c.NArg() > 0 { - name = c.Args()[0] - } - if language == "spanish" { - fmt.Println("Hola", name) - } else { - fmt.Println("Hello", name) - } - return nil - } - - app.Run(os.Args) -} -``` - -See full list of flags at http://godoc.org/github.com/urfave/cli - -#### Placeholder Values - -Sometimes it's useful to specify a flag's value within the usage string itself. -Such placeholders are indicated with back quotes. - -For example this: - - -```go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Flags = []cli.Flag{ - cli.StringFlag{ - Name: "config, c", - Usage: "Load configuration from `FILE`", - }, - } - - app.Run(os.Args) -} -``` - -Will result in help output like: - -``` ---config FILE, -c FILE Load configuration from FILE -``` - -Note that only the first placeholder is used. Subsequent back-quoted words will -be left as-is. - -#### Alternate Names - -You can set alternate (or short) names for flags by providing a comma-delimited -list for the `Name`. e.g. - - -``` go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Flags = []cli.Flag { - cli.StringFlag{ - Name: "lang, l", - Value: "english", - Usage: "language for the greeting", - }, - } - - app.Run(os.Args) -} -``` - -That flag can then be set with `--lang spanish` or `-l spanish`. Note that -giving two different forms of the same flag in the same command invocation is an -error. - -#### Ordering - -Flags for the application and commands are shown in the order they are defined. -However, it's possible to sort them from outside this library by using `FlagsByName` -with `sort`. - -For example this: - - -``` go -package main - -import ( - "os" - "sort" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Flags = []cli.Flag { - cli.StringFlag{ - Name: "lang, l", - Value: "english", - Usage: "Language for the greeting", - }, - cli.StringFlag{ - Name: "config, c", - Usage: "Load configuration from `FILE`", - }, - } - - sort.Sort(cli.FlagsByName(app.Flags)) - - app.Run(os.Args) -} -``` - -Will result in help output like: - -``` ---config FILE, -c FILE Load configuration from FILE ---lang value, -l value Language for the greeting (default: "english") -``` - -#### Values from the Environment - -You can also have the default value set from the environment via `EnvVar`. e.g. - - -``` go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Flags = []cli.Flag { - cli.StringFlag{ - Name: "lang, l", - Value: "english", - Usage: "language for the greeting", - EnvVar: "APP_LANG", - }, - } - - app.Run(os.Args) -} -``` - -The `EnvVar` may also be given as a comma-delimited "cascade", where the first -environment variable that resolves is used as the default. - - -``` go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Flags = []cli.Flag { - cli.StringFlag{ - Name: "lang, l", - Value: "english", - Usage: "language for the greeting", - EnvVar: "LEGACY_COMPAT_LANG,APP_LANG,LANG", - }, - } - - app.Run(os.Args) -} -``` - -#### Values from alternate input sources (YAML, TOML, and others) - -There is a separate package altsrc that adds support for getting flag values -from other file input sources. - -Currently supported input source formats: -* YAML -* TOML - -In order to get values for a flag from an alternate input source the following -code would be added to wrap an existing cli.Flag like below: - -``` go - altsrc.NewIntFlag(cli.IntFlag{Name: "test"}) -``` - -Initialization must also occur for these flags. Below is an example initializing -getting data from a yaml file below. - -``` go - command.Before = altsrc.InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load")) -``` - -The code above will use the "load" string as a flag name to get the file name of -a yaml file from the cli.Context. It will then use that file name to initialize -the yaml input source for any flags that are defined on that command. As a note -the "load" flag used would also have to be defined on the command flags in order -for this code snipped to work. - -Currently only the aboved specified formats are supported but developers can -add support for other input sources by implementing the -altsrc.InputSourceContext for their given sources. - -Here is a more complete sample of a command using YAML support: - - -``` go -package notmain - -import ( - "fmt" - "os" - - "github.com/urfave/cli" - "github.com/urfave/cli/altsrc" -) - -func main() { - app := cli.NewApp() - - flags := []cli.Flag{ - altsrc.NewIntFlag(cli.IntFlag{Name: "test"}), - cli.StringFlag{Name: "load"}, - } - - app.Action = func(c *cli.Context) error { - fmt.Println("yaml ist rad") - return nil - } - - app.Before = altsrc.InitInputSourceWithContext(flags, altsrc.NewYamlSourceFromFlagFunc("load")) - app.Flags = flags - - app.Run(os.Args) -} -``` - -### Subcommands - -Subcommands can be defined for a more git-like command line app. - - -```go -package main - -import ( - "fmt" - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Commands = []cli.Command{ - { - Name: "add", - Aliases: []string{"a"}, - Usage: "add a task to the list", - Action: func(c *cli.Context) error { - fmt.Println("added task: ", c.Args().First()) - return nil - }, - }, - { - Name: "complete", - Aliases: []string{"c"}, - Usage: "complete a task on the list", - Action: func(c *cli.Context) error { - fmt.Println("completed task: ", c.Args().First()) - return nil - }, - }, - { - Name: "template", - Aliases: []string{"t"}, - Usage: "options for task templates", - Subcommands: []cli.Command{ - { - Name: "add", - Usage: "add a new template", - Action: func(c *cli.Context) error { - fmt.Println("new task template: ", c.Args().First()) - return nil - }, - }, - { - Name: "remove", - Usage: "remove an existing template", - Action: func(c *cli.Context) error { - fmt.Println("removed task template: ", c.Args().First()) - return nil - }, - }, - }, - }, - } - - app.Run(os.Args) -} -``` - -### Subcommands categories - -For additional organization in apps that have many subcommands, you can -associate a category for each command to group them together in the help -output. - -E.g. - -```go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Commands = []cli.Command{ - { - Name: "noop", - }, - { - Name: "add", - Category: "template", - }, - { - Name: "remove", - Category: "template", - }, - } - - app.Run(os.Args) -} -``` - -Will include: - -``` -COMMANDS: - noop - - Template actions: - add - remove -``` - -### Exit code - -Calling `App.Run` will not automatically call `os.Exit`, which means that by -default the exit code will "fall through" to being `0`. An explicit exit code -may be set by returning a non-nil error that fulfills `cli.ExitCoder`, *or* a -`cli.MultiError` that includes an error that fulfills `cli.ExitCoder`, e.g.: - -``` go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - app.Flags = []cli.Flag{ - cli.BoolTFlag{ - Name: "ginger-crouton", - Usage: "is it in the soup?", - }, - } - app.Action = func(ctx *cli.Context) error { - if !ctx.Bool("ginger-crouton") { - return cli.NewExitError("it is not in the soup", 86) - } - return nil - } - - app.Run(os.Args) -} -``` - -### Bash Completion - -You can enable completion commands by setting the `EnableBashCompletion` -flag on the `App` object. By default, this setting will only auto-complete to -show an app's subcommands, but you can write your own completion methods for -the App or its subcommands. - - -``` go -package main - -import ( - "fmt" - "os" - - "github.com/urfave/cli" -) - -func main() { - tasks := []string{"cook", "clean", "laundry", "eat", "sleep", "code"} - - app := cli.NewApp() - app.EnableBashCompletion = true - app.Commands = []cli.Command{ - { - Name: "complete", - Aliases: []string{"c"}, - Usage: "complete a task on the list", - Action: func(c *cli.Context) error { - fmt.Println("completed task: ", c.Args().First()) - return nil - }, - BashComplete: func(c *cli.Context) { - // This will complete if no args are passed - if c.NArg() > 0 { - return - } - for _, t := range tasks { - fmt.Println(t) - } - }, - }, - } - - app.Run(os.Args) -} -``` - -#### Enabling - -Source the `autocomplete/bash_autocomplete` file in your `.bashrc` file while -setting the `PROG` variable to the name of your program: - -`PROG=myprogram source /.../cli/autocomplete/bash_autocomplete` - -#### Distribution - -Copy `autocomplete/bash_autocomplete` into `/etc/bash_completion.d/` and rename -it to the name of the program you wish to add autocomplete support for (or -automatically install it there if you are distributing a package). Don't forget -to source the file to make it active in the current shell. - -``` -sudo cp src/bash_autocomplete /etc/bash_completion.d/ -source /etc/bash_completion.d/ -``` - -Alternatively, you can just document that users should source the generic -`autocomplete/bash_autocomplete` in their bash configuration with `$PROG` set -to the name of their program (as above). - -#### Customization - -The default bash completion flag (`--generate-bash-completion`) is defined as -`cli.BashCompletionFlag`, and may be redefined if desired, e.g.: - - -``` go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - cli.BashCompletionFlag = cli.BoolFlag{ - Name: "compgen", - Hidden: true, - } - - app := cli.NewApp() - app.EnableBashCompletion = true - app.Commands = []cli.Command{ - { - Name: "wat", - }, - } - app.Run(os.Args) -} -``` - -### Generated Help Text - -The default help flag (`-h/--help`) is defined as `cli.HelpFlag` and is checked -by the cli internals in order to print generated help text for the app, command, -or subcommand, and break execution. - -#### Customization - -All of the help text generation may be customized, and at multiple levels. The -templates are exposed as variables `AppHelpTemplate`, `CommandHelpTemplate`, and -`SubcommandHelpTemplate` which may be reassigned or augmented, and full override -is possible by assigning a compatible func to the `cli.HelpPrinter` variable, -e.g.: - - -``` go -package main - -import ( - "fmt" - "io" - "os" - - "github.com/urfave/cli" -) - -func main() { - // EXAMPLE: Append to an existing template - cli.AppHelpTemplate = fmt.Sprintf(`%s - -WEBSITE: http://awesometown.example.com - -SUPPORT: support@awesometown.example.com - -`, cli.AppHelpTemplate) - - // EXAMPLE: Override a template - cli.AppHelpTemplate = `NAME: - {{.Name}} - {{.Usage}} -USAGE: - {{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command -[command options]{{end}} {{if -.ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}} - {{if len .Authors}} -AUTHOR(S): - {{range .Authors}}{{ . }}{{end}} - {{end}}{{if .Commands}} -COMMANDS: -{{range .Commands}}{{if not .HideHelp}} {{join .Names ", "}}{{ "\t" -}}{{.Usage}}{{ "\n" }}{{end}}{{end}}{{end}}{{if .VisibleFlags}} -GLOBAL OPTIONS: - {{range .VisibleFlags}}{{.}} - {{end}}{{end}}{{if .Copyright }} -COPYRIGHT: - {{.Copyright}} - {{end}}{{if .Version}} -VERSION: - {{.Version}} - {{end}} -` - - // EXAMPLE: Replace the `HelpPrinter` func - cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) { - fmt.Println("Ha HA. I pwnd the help!!1") - } - - cli.NewApp().Run(os.Args) -} -``` - -The default flag may be customized to something other than `-h/--help` by -setting `cli.HelpFlag`, e.g.: - - -``` go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - cli.HelpFlag = cli.BoolFlag{ - Name: "halp, haaaaalp", - Usage: "HALP", - EnvVar: "SHOW_HALP,HALPPLZ", - } - - cli.NewApp().Run(os.Args) -} -``` - -### Version Flag - -The default version flag (`-v/--version`) is defined as `cli.VersionFlag`, which -is checked by the cli internals in order to print the `App.Version` via -`cli.VersionPrinter` and break execution. - -#### Customization - -The default flag may be customized to something other than `-v/--version` by -setting `cli.VersionFlag`, e.g.: - - -``` go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - cli.VersionFlag = cli.BoolFlag{ - Name: "print-version, V", - Usage: "print only the version", - } - - app := cli.NewApp() - app.Name = "partay" - app.Version = "19.99.0" - app.Run(os.Args) -} -``` - -Alternatively, the version printer at `cli.VersionPrinter` may be overridden, e.g.: - - -``` go -package main - -import ( - "fmt" - "os" - - "github.com/urfave/cli" -) - -var ( - Revision = "fafafaf" -) - -func main() { - cli.VersionPrinter = func(c *cli.Context) { - fmt.Printf("version=%s revision=%s\n", c.App.Version, Revision) - } - - app := cli.NewApp() - app.Name = "partay" - app.Version = "19.99.0" - app.Run(os.Args) -} -``` - -#### Full API Example - -**Notice**: This is a contrived (functioning) example meant strictly for API -demonstration purposes. Use of one's imagination is encouraged. - - -``` go -package main - -import ( - "errors" - "flag" - "fmt" - "io" - "io/ioutil" - "os" - "time" - - "github.com/urfave/cli" -) - -func init() { - cli.AppHelpTemplate += "\nCUSTOMIZED: you bet ur muffins\n" - cli.CommandHelpTemplate += "\nYMMV\n" - cli.SubcommandHelpTemplate += "\nor something\n" - - cli.HelpFlag = cli.BoolFlag{Name: "halp"} - cli.BashCompletionFlag = cli.BoolFlag{Name: "compgen", Hidden: true} - cli.VersionFlag = cli.BoolFlag{Name: "print-version, V"} - - cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) { - fmt.Fprintf(w, "best of luck to you\n") - } - cli.VersionPrinter = func(c *cli.Context) { - fmt.Fprintf(c.App.Writer, "version=%s\n", c.App.Version) - } - cli.OsExiter = func(c int) { - fmt.Fprintf(cli.ErrWriter, "refusing to exit %d\n", c) - } - cli.ErrWriter = ioutil.Discard - cli.FlagStringer = func(fl cli.Flag) string { - return fmt.Sprintf("\t\t%s", fl.GetName()) - } -} - -type hexWriter struct{} - -func (w *hexWriter) Write(p []byte) (int, error) { - for _, b := range p { - fmt.Printf("%x", b) - } - fmt.Printf("\n") - - return len(p), nil -} - -type genericType struct{ - s string -} - -func (g *genericType) Set(value string) error { - g.s = value - return nil -} - -func (g *genericType) String() string { - return g.s -} - -func main() { - app := cli.NewApp() - app.Name = "kənˈtrīv" - app.Version = "19.99.0" - app.Compiled = time.Now() - app.Authors = []cli.Author{ - cli.Author{ - Name: "Example Human", - Email: "human@example.com", - }, - } - app.Copyright = "(c) 1999 Serious Enterprise" - app.HelpName = "contrive" - app.Usage = "demonstrate available API" - app.UsageText = "contrive - demonstrating the available API" - app.ArgsUsage = "[args and such]" - app.Commands = []cli.Command{ - cli.Command{ - Name: "doo", - Aliases: []string{"do"}, - Category: "motion", - Usage: "do the doo", - UsageText: "doo - does the dooing", - Description: "no really, there is a lot of dooing to be done", - ArgsUsage: "[arrgh]", - Flags: []cli.Flag{ - cli.BoolFlag{Name: "forever, forevvarr"}, - }, - Subcommands: cli.Commands{ - cli.Command{ - Name: "wop", - Action: wopAction, - }, - }, - SkipFlagParsing: false, - HideHelp: false, - Hidden: false, - HelpName: "doo!", - BashComplete: func(c *cli.Context) { - fmt.Fprintf(c.App.Writer, "--better\n") - }, - Before: func(c *cli.Context) error { - fmt.Fprintf(c.App.Writer, "brace for impact\n") - return nil - }, - After: func(c *cli.Context) error { - fmt.Fprintf(c.App.Writer, "did we lose anyone?\n") - return nil - }, - Action: func(c *cli.Context) error { - c.Command.FullName() - c.Command.HasName("wop") - c.Command.Names() - c.Command.VisibleFlags() - fmt.Fprintf(c.App.Writer, "dodododododoodododddooooododododooo\n") - if c.Bool("forever") { - c.Command.Run(c) - } - return nil - }, - OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error { - fmt.Fprintf(c.App.Writer, "for shame\n") - return err - }, - }, - } - app.Flags = []cli.Flag{ - cli.BoolFlag{Name: "fancy"}, - cli.BoolTFlag{Name: "fancier"}, - cli.DurationFlag{Name: "howlong, H", Value: time.Second * 3}, - cli.Float64Flag{Name: "howmuch"}, - cli.GenericFlag{Name: "wat", Value: &genericType{}}, - cli.Int64Flag{Name: "longdistance"}, - cli.Int64SliceFlag{Name: "intervals"}, - cli.IntFlag{Name: "distance"}, - cli.IntSliceFlag{Name: "times"}, - cli.StringFlag{Name: "dance-move, d"}, - cli.StringSliceFlag{Name: "names, N"}, - cli.UintFlag{Name: "age"}, - cli.Uint64Flag{Name: "bigage"}, - } - app.EnableBashCompletion = true - app.HideHelp = false - app.HideVersion = false - app.BashComplete = func(c *cli.Context) { - fmt.Fprintf(c.App.Writer, "lipstick\nkiss\nme\nlipstick\nringo\n") - } - app.Before = func(c *cli.Context) error { - fmt.Fprintf(c.App.Writer, "HEEEERE GOES\n") - return nil - } - app.After = func(c *cli.Context) error { - fmt.Fprintf(c.App.Writer, "Phew!\n") - return nil - } - app.CommandNotFound = func(c *cli.Context, command string) { - fmt.Fprintf(c.App.Writer, "Thar be no %q here.\n", command) - } - app.OnUsageError = func(c *cli.Context, err error, isSubcommand bool) error { - if isSubcommand { - return err - } - - fmt.Fprintf(c.App.Writer, "WRONG: %#v\n", err) - return nil - } - app.Action = func(c *cli.Context) error { - cli.DefaultAppComplete(c) - cli.HandleExitCoder(errors.New("not an exit coder, though")) - cli.ShowAppHelp(c) - cli.ShowCommandCompletions(c, "nope") - cli.ShowCommandHelp(c, "also-nope") - cli.ShowCompletions(c) - cli.ShowSubcommandHelp(c) - cli.ShowVersion(c) - - categories := c.App.Categories() - categories.AddCommand("sounds", cli.Command{ - Name: "bloop", - }) - - for _, category := range c.App.Categories() { - fmt.Fprintf(c.App.Writer, "%s\n", category.Name) - fmt.Fprintf(c.App.Writer, "%#v\n", category.Commands) - fmt.Fprintf(c.App.Writer, "%#v\n", category.VisibleCommands()) - } - - fmt.Printf("%#v\n", c.App.Command("doo")) - if c.Bool("infinite") { - c.App.Run([]string{"app", "doo", "wop"}) - } - - if c.Bool("forevar") { - c.App.RunAsSubcommand(c) - } - c.App.Setup() - fmt.Printf("%#v\n", c.App.VisibleCategories()) - fmt.Printf("%#v\n", c.App.VisibleCommands()) - fmt.Printf("%#v\n", c.App.VisibleFlags()) - - fmt.Printf("%#v\n", c.Args().First()) - if len(c.Args()) > 0 { - fmt.Printf("%#v\n", c.Args()[1]) - } - fmt.Printf("%#v\n", c.Args().Present()) - fmt.Printf("%#v\n", c.Args().Tail()) - - set := flag.NewFlagSet("contrive", 0) - nc := cli.NewContext(c.App, set, c) - - fmt.Printf("%#v\n", nc.Args()) - fmt.Printf("%#v\n", nc.Bool("nope")) - fmt.Printf("%#v\n", nc.BoolT("nerp")) - fmt.Printf("%#v\n", nc.Duration("howlong")) - fmt.Printf("%#v\n", nc.Float64("hay")) - fmt.Printf("%#v\n", nc.Generic("bloop")) - fmt.Printf("%#v\n", nc.Int64("bonk")) - fmt.Printf("%#v\n", nc.Int64Slice("burnks")) - fmt.Printf("%#v\n", nc.Int("bips")) - fmt.Printf("%#v\n", nc.IntSlice("blups")) - fmt.Printf("%#v\n", nc.String("snurt")) - fmt.Printf("%#v\n", nc.StringSlice("snurkles")) - fmt.Printf("%#v\n", nc.Uint("flub")) - fmt.Printf("%#v\n", nc.Uint64("florb")) - fmt.Printf("%#v\n", nc.GlobalBool("global-nope")) - fmt.Printf("%#v\n", nc.GlobalBoolT("global-nerp")) - fmt.Printf("%#v\n", nc.GlobalDuration("global-howlong")) - fmt.Printf("%#v\n", nc.GlobalFloat64("global-hay")) - fmt.Printf("%#v\n", nc.GlobalGeneric("global-bloop")) - fmt.Printf("%#v\n", nc.GlobalInt("global-bips")) - fmt.Printf("%#v\n", nc.GlobalIntSlice("global-blups")) - fmt.Printf("%#v\n", nc.GlobalString("global-snurt")) - fmt.Printf("%#v\n", nc.GlobalStringSlice("global-snurkles")) - - fmt.Printf("%#v\n", nc.FlagNames()) - fmt.Printf("%#v\n", nc.GlobalFlagNames()) - fmt.Printf("%#v\n", nc.GlobalIsSet("wat")) - fmt.Printf("%#v\n", nc.GlobalSet("wat", "nope")) - fmt.Printf("%#v\n", nc.NArg()) - fmt.Printf("%#v\n", nc.NumFlags()) - fmt.Printf("%#v\n", nc.Parent()) - - nc.Set("wat", "also-nope") - - ec := cli.NewExitError("ohwell", 86) - fmt.Fprintf(c.App.Writer, "%d", ec.ExitCode()) - fmt.Printf("made it!\n") - return ec - } - - if os.Getenv("HEXY") != "" { - app.Writer = &hexWriter{} - app.ErrWriter = &hexWriter{} - } - - app.Metadata = map[string]interface{}{ - "layers": "many", - "explicable": false, - "whatever-values": 19.99, - } - - app.Run(os.Args) -} - -func wopAction(c *cli.Context) error { - fmt.Fprintf(c.App.Writer, ":wave: over here, eh\n") - return nil -} -``` - -## Contribution Guidelines - -Feel free to put up a pull request to fix a bug or maybe add a feature. I will -give it a code review and make sure that it does not break backwards -compatibility. If I or any other collaborators agree that it is in line with -the vision of the project, we will work with you to get the code into -a mergeable state and merge it into the master branch. - -If you have contributed something significant to the project, we will most -likely add you as a collaborator. As a collaborator you are given the ability -to merge others pull requests. It is very important that new code does not -break existing code, so be careful about what code you do choose to merge. - -If you feel like you have contributed to the project but have not yet been -added as a collaborator, we probably forgot to add you, please open an issue. diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/app.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/app.go deleted file mode 100644 index 95ffc0b9..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/app.go +++ /dev/null @@ -1,492 +0,0 @@ -package cli - -import ( - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "sort" - "time" -) - -var ( - changeLogURL = "https://github.com/urfave/cli/blob/master/CHANGELOG.md" - appActionDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-action-signature", changeLogURL) - runAndExitOnErrorDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-runandexitonerror", changeLogURL) - - contactSysadmin = "This is an error in the application. Please contact the distributor of this application if this is not you." - - errInvalidActionType = NewExitError("ERROR invalid Action type. "+ - fmt.Sprintf("Must be `func(*Context`)` or `func(*Context) error). %s", contactSysadmin)+ - fmt.Sprintf("See %s", appActionDeprecationURL), 2) -) - -// App is the main structure of a cli application. It is recommended that -// an app be created with the cli.NewApp() function -type App struct { - // The name of the program. Defaults to path.Base(os.Args[0]) - Name string - // Full name of command for help, defaults to Name - HelpName string - // Description of the program. - Usage string - // Text to override the USAGE section of help - UsageText string - // Description of the program argument format. - ArgsUsage string - // Version of the program - Version string - // Description of the program - Description string - // List of commands to execute - Commands []Command - // List of flags to parse - Flags []Flag - // Boolean to enable bash completion commands - EnableBashCompletion bool - // Boolean to hide built-in help command - HideHelp bool - // Boolean to hide built-in version flag and the VERSION section of help - HideVersion bool - // Populate on app startup, only gettable through method Categories() - categories CommandCategories - // An action to execute when the bash-completion flag is set - BashComplete BashCompleteFunc - // An action to execute before any subcommands are run, but after the context is ready - // If a non-nil error is returned, no subcommands are run - Before BeforeFunc - // An action to execute after any subcommands are run, but after the subcommand has finished - // It is run even if Action() panics - After AfterFunc - - // The action to execute when no subcommands are specified - // Expects a `cli.ActionFunc` but will accept the *deprecated* signature of `func(*cli.Context) {}` - // *Note*: support for the deprecated `Action` signature will be removed in a future version - Action interface{} - - // Execute this function if the proper command cannot be found - CommandNotFound CommandNotFoundFunc - // Execute this function if an usage error occurs - OnUsageError OnUsageErrorFunc - // Compilation date - Compiled time.Time - // List of all authors who contributed - Authors []Author - // Copyright of the binary if any - Copyright string - // Name of Author (Note: Use App.Authors, this is deprecated) - Author string - // Email of Author (Note: Use App.Authors, this is deprecated) - Email string - // Writer writer to write output to - Writer io.Writer - // ErrWriter writes error output - ErrWriter io.Writer - // Other custom info - Metadata map[string]interface{} - - didSetup bool -} - -// Tries to find out when this binary was compiled. -// Returns the current time if it fails to find it. -func compileTime() time.Time { - info, err := os.Stat(os.Args[0]) - if err != nil { - return time.Now() - } - return info.ModTime() -} - -// NewApp creates a new cli Application with some reasonable defaults for Name, -// Usage, Version and Action. -func NewApp() *App { - return &App{ - Name: filepath.Base(os.Args[0]), - HelpName: filepath.Base(os.Args[0]), - Usage: "A new cli application", - UsageText: "", - Version: "0.0.0", - BashComplete: DefaultAppComplete, - Action: helpCommand.Action, - Compiled: compileTime(), - Writer: os.Stdout, - } -} - -// Setup runs initialization code to ensure all data structures are ready for -// `Run` or inspection prior to `Run`. It is internally called by `Run`, but -// will return early if setup has already happened. -func (a *App) Setup() { - if a.didSetup { - return - } - - a.didSetup = true - - if a.Author != "" || a.Email != "" { - a.Authors = append(a.Authors, Author{Name: a.Author, Email: a.Email}) - } - - newCmds := []Command{} - for _, c := range a.Commands { - if c.HelpName == "" { - c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name) - } - newCmds = append(newCmds, c) - } - a.Commands = newCmds - - if a.Command(helpCommand.Name) == nil && !a.HideHelp { - a.Commands = append(a.Commands, helpCommand) - if (HelpFlag != BoolFlag{}) { - a.appendFlag(HelpFlag) - } - } - - if !a.HideVersion { - a.appendFlag(VersionFlag) - } - - a.categories = CommandCategories{} - for _, command := range a.Commands { - a.categories = a.categories.AddCommand(command.Category, command) - } - sort.Sort(a.categories) - - if a.Metadata == nil { - a.Metadata = make(map[string]interface{}) - } - - if a.Writer == nil { - a.Writer = os.Stdout - } -} - -// Run is the entry point to the cli app. Parses the arguments slice and routes -// to the proper flag/args combination -func (a *App) Run(arguments []string) (err error) { - a.Setup() - - // handle the completion flag separately from the flagset since - // completion could be attempted after a flag, but before its value was put - // on the command line. this causes the flagset to interpret the completion - // flag name as the value of the flag before it which is undesirable - // note that we can only do this because the shell autocomplete function - // always appends the completion flag at the end of the command - shellComplete, arguments := checkShellCompleteFlag(a, arguments) - - // parse flags - set, err := flagSet(a.Name, a.Flags) - if err != nil { - return err - } - - set.SetOutput(ioutil.Discard) - err = set.Parse(arguments[1:]) - nerr := normalizeFlags(a.Flags, set) - context := NewContext(a, set, nil) - if nerr != nil { - fmt.Fprintln(a.Writer, nerr) - ShowAppHelp(context) - return nerr - } - context.shellComplete = shellComplete - - if checkCompletions(context) { - return nil - } - - if err != nil { - if a.OnUsageError != nil { - err := a.OnUsageError(context, err, false) - HandleExitCoder(err) - return err - } - fmt.Fprintf(a.Writer, "%s %s\n\n", "Incorrect Usage.", err.Error()) - ShowAppHelp(context) - return err - } - - if !a.HideHelp && checkHelp(context) { - ShowAppHelp(context) - return nil - } - - if !a.HideVersion && checkVersion(context) { - ShowVersion(context) - return nil - } - - if a.After != nil { - defer func() { - if afterErr := a.After(context); afterErr != nil { - if err != nil { - err = NewMultiError(err, afterErr) - } else { - err = afterErr - } - } - }() - } - - if a.Before != nil { - beforeErr := a.Before(context) - if beforeErr != nil { - fmt.Fprintf(a.Writer, "%v\n\n", beforeErr) - ShowAppHelp(context) - HandleExitCoder(beforeErr) - err = beforeErr - return err - } - } - - args := context.Args() - if args.Present() { - name := args.First() - c := a.Command(name) - if c != nil { - return c.Run(context) - } - } - - if a.Action == nil { - a.Action = helpCommand.Action - } - - // Run default Action - err = HandleAction(a.Action, context) - - HandleExitCoder(err) - return err -} - -// RunAndExitOnError calls .Run() and exits non-zero if an error was returned -// -// Deprecated: instead you should return an error that fulfills cli.ExitCoder -// to cli.App.Run. This will cause the application to exit with the given eror -// code in the cli.ExitCoder -func (a *App) RunAndExitOnError() { - if err := a.Run(os.Args); err != nil { - fmt.Fprintln(a.errWriter(), err) - OsExiter(1) - } -} - -// RunAsSubcommand invokes the subcommand given the context, parses ctx.Args() to -// generate command-specific flags -func (a *App) RunAsSubcommand(ctx *Context) (err error) { - // append help to commands - if len(a.Commands) > 0 { - if a.Command(helpCommand.Name) == nil && !a.HideHelp { - a.Commands = append(a.Commands, helpCommand) - if (HelpFlag != BoolFlag{}) { - a.appendFlag(HelpFlag) - } - } - } - - newCmds := []Command{} - for _, c := range a.Commands { - if c.HelpName == "" { - c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name) - } - newCmds = append(newCmds, c) - } - a.Commands = newCmds - - // parse flags - set, err := flagSet(a.Name, a.Flags) - if err != nil { - return err - } - - set.SetOutput(ioutil.Discard) - err = set.Parse(ctx.Args().Tail()) - nerr := normalizeFlags(a.Flags, set) - context := NewContext(a, set, ctx) - - if nerr != nil { - fmt.Fprintln(a.Writer, nerr) - fmt.Fprintln(a.Writer) - if len(a.Commands) > 0 { - ShowSubcommandHelp(context) - } else { - ShowCommandHelp(ctx, context.Args().First()) - } - return nerr - } - - if checkCompletions(context) { - return nil - } - - if err != nil { - if a.OnUsageError != nil { - err = a.OnUsageError(context, err, true) - HandleExitCoder(err) - return err - } - fmt.Fprintf(a.Writer, "%s %s\n\n", "Incorrect Usage.", err.Error()) - ShowSubcommandHelp(context) - return err - } - - if len(a.Commands) > 0 { - if checkSubcommandHelp(context) { - return nil - } - } else { - if checkCommandHelp(ctx, context.Args().First()) { - return nil - } - } - - if a.After != nil { - defer func() { - afterErr := a.After(context) - if afterErr != nil { - HandleExitCoder(err) - if err != nil { - err = NewMultiError(err, afterErr) - } else { - err = afterErr - } - } - }() - } - - if a.Before != nil { - beforeErr := a.Before(context) - if beforeErr != nil { - HandleExitCoder(beforeErr) - err = beforeErr - return err - } - } - - args := context.Args() - if args.Present() { - name := args.First() - c := a.Command(name) - if c != nil { - return c.Run(context) - } - } - - // Run default Action - err = HandleAction(a.Action, context) - - HandleExitCoder(err) - return err -} - -// Command returns the named command on App. Returns nil if the command does not exist -func (a *App) Command(name string) *Command { - for _, c := range a.Commands { - if c.HasName(name) { - return &c - } - } - - return nil -} - -// Categories returns a slice containing all the categories with the commands they contain -func (a *App) Categories() CommandCategories { - return a.categories -} - -// VisibleCategories returns a slice of categories and commands that are -// Hidden=false -func (a *App) VisibleCategories() []*CommandCategory { - ret := []*CommandCategory{} - for _, category := range a.categories { - if visible := func() *CommandCategory { - for _, command := range category.Commands { - if !command.Hidden { - return category - } - } - return nil - }(); visible != nil { - ret = append(ret, visible) - } - } - return ret -} - -// VisibleCommands returns a slice of the Commands with Hidden=false -func (a *App) VisibleCommands() []Command { - ret := []Command{} - for _, command := range a.Commands { - if !command.Hidden { - ret = append(ret, command) - } - } - return ret -} - -// VisibleFlags returns a slice of the Flags with Hidden=false -func (a *App) VisibleFlags() []Flag { - return visibleFlags(a.Flags) -} - -func (a *App) hasFlag(flag Flag) bool { - for _, f := range a.Flags { - if flag == f { - return true - } - } - - return false -} - -func (a *App) errWriter() io.Writer { - - // When the app ErrWriter is nil use the package level one. - if a.ErrWriter == nil { - return ErrWriter - } - - return a.ErrWriter -} - -func (a *App) appendFlag(flag Flag) { - if !a.hasFlag(flag) { - a.Flags = append(a.Flags, flag) - } -} - -// Author represents someone who has contributed to a cli project. -type Author struct { - Name string // The Authors name - Email string // The Authors email -} - -// String makes Author comply to the Stringer interface, to allow an easy print in the templating process -func (a Author) String() string { - e := "" - if a.Email != "" { - e = " <" + a.Email + ">" - } - - return fmt.Sprintf("%v%v", a.Name, e) -} - -// HandleAction attempts to figure out which Action signature was used. If -// it's an ActionFunc or a func with the legacy signature for Action, the func -// is run! -func HandleAction(action interface{}, context *Context) (err error) { - if a, ok := action.(ActionFunc); ok { - return a(context) - } else if a, ok := action.(func(*Context) error); ok { - return a(context) - } else if a, ok := action.(func(*Context)); ok { // deprecated function signature - a(context) - return nil - } else { - return errInvalidActionType - } -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/appveyor.yml b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/appveyor.yml deleted file mode 100644 index 698b188e..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/appveyor.yml +++ /dev/null @@ -1,24 +0,0 @@ -version: "{build}" - -os: Windows Server 2012 R2 - -clone_folder: c:\gopath\src\github.com\urfave\cli - -environment: - GOPATH: C:\gopath - GOVERSION: 1.6 - PYTHON: C:\Python27-x64 - PYTHON_VERSION: 2.7.x - PYTHON_ARCH: 64 - -install: -- set PATH=%GOPATH%\bin;C:\go\bin;%PATH% -- go version -- go env -- go get github.com/urfave/gfmrun/... -- go get -v -t ./... - -build_script: -- python runtests vet -- python runtests test -- python runtests gfmrun diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/category.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/category.go deleted file mode 100644 index 1a605502..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/category.go +++ /dev/null @@ -1,44 +0,0 @@ -package cli - -// CommandCategories is a slice of *CommandCategory. -type CommandCategories []*CommandCategory - -// CommandCategory is a category containing commands. -type CommandCategory struct { - Name string - Commands Commands -} - -func (c CommandCategories) Less(i, j int) bool { - return c[i].Name < c[j].Name -} - -func (c CommandCategories) Len() int { - return len(c) -} - -func (c CommandCategories) Swap(i, j int) { - c[i], c[j] = c[j], c[i] -} - -// AddCommand adds a command to a category. -func (c CommandCategories) AddCommand(category string, command Command) CommandCategories { - for _, commandCategory := range c { - if commandCategory.Name == category { - commandCategory.Commands = append(commandCategory.Commands, command) - return c - } - } - return append(c, &CommandCategory{Name: category, Commands: []Command{command}}) -} - -// VisibleCommands returns a slice of the Commands with Hidden=false -func (c *CommandCategory) VisibleCommands() []Command { - ret := []Command{} - for _, command := range c.Commands { - if !command.Hidden { - ret = append(ret, command) - } - } - return ret -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/cli.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/cli.go deleted file mode 100644 index 74fd101f..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/cli.go +++ /dev/null @@ -1,21 +0,0 @@ -// Package cli provides a minimal framework for creating and organizing command line -// Go applications. cli is designed to be easy to understand and write, the most simple -// cli application can be written as follows: -// func main() { -// cli.NewApp().Run(os.Args) -// } -// -// Of course this application does not do much, so let's make this an actual application: -// func main() { -// app := cli.NewApp() -// app.Name = "greet" -// app.Usage = "say a greeting" -// app.Action = func(c *cli.Context) error { -// println("Greetings") -// } -// -// app.Run(os.Args) -// } -package cli - -//go:generate python ./generate-flag-types cli -i flag-types.json -o flag_generated.go diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/command.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/command.go deleted file mode 100644 index 2628fbf4..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/command.go +++ /dev/null @@ -1,286 +0,0 @@ -package cli - -import ( - "fmt" - "io/ioutil" - "sort" - "strings" -) - -// Command is a subcommand for a cli.App. -type Command struct { - // The name of the command - Name string - // short name of the command. Typically one character (deprecated, use `Aliases`) - ShortName string - // A list of aliases for the command - Aliases []string - // A short description of the usage of this command - Usage string - // Custom text to show on USAGE section of help - UsageText string - // A longer explanation of how the command works - Description string - // A short description of the arguments of this command - ArgsUsage string - // The category the command is part of - Category string - // The function to call when checking for bash command completions - BashComplete BashCompleteFunc - // An action to execute before any sub-subcommands are run, but after the context is ready - // If a non-nil error is returned, no sub-subcommands are run - Before BeforeFunc - // An action to execute after any subcommands are run, but after the subcommand has finished - // It is run even if Action() panics - After AfterFunc - // The function to call when this command is invoked - Action interface{} - // TODO: replace `Action: interface{}` with `Action: ActionFunc` once some kind - // of deprecation period has passed, maybe? - - // Execute this function if a usage error occurs. - OnUsageError OnUsageErrorFunc - // List of child commands - Subcommands Commands - // List of flags to parse - Flags []Flag - // Treat all flags as normal arguments if true - SkipFlagParsing bool - // Skip argument reordering which attempts to move flags before arguments, - // but only works if all flags appear after all arguments. This behavior was - // removed n version 2 since it only works under specific conditions so we - // backport here by exposing it as an option for compatibility. - SkipArgReorder bool - // Boolean to hide built-in help command - HideHelp bool - // Boolean to hide this command from help or completion - Hidden bool - - // Full name of command for help, defaults to full command name, including parent commands. - HelpName string - commandNamePath []string -} - -// FullName returns the full name of the command. -// For subcommands this ensures that parent commands are part of the command path -func (c Command) FullName() string { - if c.commandNamePath == nil { - return c.Name - } - return strings.Join(c.commandNamePath, " ") -} - -// Commands is a slice of Command -type Commands []Command - -// Run invokes the command given the context, parses ctx.Args() to generate command-specific flags -func (c Command) Run(ctx *Context) (err error) { - if len(c.Subcommands) > 0 { - return c.startApp(ctx) - } - - if !c.HideHelp && (HelpFlag != BoolFlag{}) { - // append help to flags - c.Flags = append( - c.Flags, - HelpFlag, - ) - } - - set, err := flagSet(c.Name, c.Flags) - if err != nil { - return err - } - set.SetOutput(ioutil.Discard) - - if c.SkipFlagParsing { - err = set.Parse(append([]string{"--"}, ctx.Args().Tail()...)) - } else if !c.SkipArgReorder { - firstFlagIndex := -1 - terminatorIndex := -1 - for index, arg := range ctx.Args() { - if arg == "--" { - terminatorIndex = index - break - } else if arg == "-" { - // Do nothing. A dash alone is not really a flag. - continue - } else if strings.HasPrefix(arg, "-") && firstFlagIndex == -1 { - firstFlagIndex = index - } - } - - if firstFlagIndex > -1 { - args := ctx.Args() - regularArgs := make([]string, len(args[1:firstFlagIndex])) - copy(regularArgs, args[1:firstFlagIndex]) - - var flagArgs []string - if terminatorIndex > -1 { - flagArgs = args[firstFlagIndex:terminatorIndex] - regularArgs = append(regularArgs, args[terminatorIndex:]...) - } else { - flagArgs = args[firstFlagIndex:] - } - - err = set.Parse(append(flagArgs, regularArgs...)) - } else { - err = set.Parse(ctx.Args().Tail()) - } - } else { - err = set.Parse(ctx.Args().Tail()) - } - - nerr := normalizeFlags(c.Flags, set) - if nerr != nil { - fmt.Fprintln(ctx.App.Writer, nerr) - fmt.Fprintln(ctx.App.Writer) - ShowCommandHelp(ctx, c.Name) - return nerr - } - - context := NewContext(ctx.App, set, ctx) - if checkCommandCompletions(context, c.Name) { - return nil - } - - if err != nil { - if c.OnUsageError != nil { - err := c.OnUsageError(ctx, err, false) - HandleExitCoder(err) - return err - } - fmt.Fprintln(ctx.App.Writer, "Incorrect Usage:", err.Error()) - fmt.Fprintln(ctx.App.Writer) - ShowCommandHelp(ctx, c.Name) - return err - } - - if checkCommandHelp(context, c.Name) { - return nil - } - - if c.After != nil { - defer func() { - afterErr := c.After(context) - if afterErr != nil { - HandleExitCoder(err) - if err != nil { - err = NewMultiError(err, afterErr) - } else { - err = afterErr - } - } - }() - } - - if c.Before != nil { - err = c.Before(context) - if err != nil { - fmt.Fprintln(ctx.App.Writer, err) - fmt.Fprintln(ctx.App.Writer) - ShowCommandHelp(ctx, c.Name) - HandleExitCoder(err) - return err - } - } - - if c.Action == nil { - c.Action = helpSubcommand.Action - } - - context.Command = c - err = HandleAction(c.Action, context) - - if err != nil { - HandleExitCoder(err) - } - return err -} - -// Names returns the names including short names and aliases. -func (c Command) Names() []string { - names := []string{c.Name} - - if c.ShortName != "" { - names = append(names, c.ShortName) - } - - return append(names, c.Aliases...) -} - -// HasName returns true if Command.Name or Command.ShortName matches given name -func (c Command) HasName(name string) bool { - for _, n := range c.Names() { - if n == name { - return true - } - } - return false -} - -func (c Command) startApp(ctx *Context) error { - app := NewApp() - app.Metadata = ctx.App.Metadata - // set the name and usage - app.Name = fmt.Sprintf("%s %s", ctx.App.Name, c.Name) - if c.HelpName == "" { - app.HelpName = c.HelpName - } else { - app.HelpName = app.Name - } - - if c.Description != "" { - app.Usage = c.Description - } else { - app.Usage = c.Usage - } - - // set CommandNotFound - app.CommandNotFound = ctx.App.CommandNotFound - - // set the flags and commands - app.Commands = c.Subcommands - app.Flags = c.Flags - app.HideHelp = c.HideHelp - - app.Version = ctx.App.Version - app.HideVersion = ctx.App.HideVersion - app.Compiled = ctx.App.Compiled - app.Author = ctx.App.Author - app.Email = ctx.App.Email - app.Writer = ctx.App.Writer - - app.categories = CommandCategories{} - for _, command := range c.Subcommands { - app.categories = app.categories.AddCommand(command.Category, command) - } - - sort.Sort(app.categories) - - // bash completion - app.EnableBashCompletion = ctx.App.EnableBashCompletion - if c.BashComplete != nil { - app.BashComplete = c.BashComplete - } - - // set the actions - app.Before = c.Before - app.After = c.After - if c.Action != nil { - app.Action = c.Action - } else { - app.Action = helpSubcommand.Action - } - - for index, cc := range app.Commands { - app.Commands[index].commandNamePath = []string{c.Name, cc.Name} - } - - return app.RunAsSubcommand(ctx) -} - -// VisibleFlags returns a slice of the Flags with Hidden=false -func (c Command) VisibleFlags() []Flag { - return visibleFlags(c.Flags) -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/context.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/context.go deleted file mode 100644 index cb89e92a..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/context.go +++ /dev/null @@ -1,276 +0,0 @@ -package cli - -import ( - "errors" - "flag" - "reflect" - "strings" - "syscall" -) - -// Context is a type that is passed through to -// each Handler action in a cli application. Context -// can be used to retrieve context-specific Args and -// parsed command-line options. -type Context struct { - App *App - Command Command - shellComplete bool - flagSet *flag.FlagSet - setFlags map[string]bool - parentContext *Context -} - -// NewContext creates a new context. For use in when invoking an App or Command action. -func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context { - c := &Context{App: app, flagSet: set, parentContext: parentCtx} - - if parentCtx != nil { - c.shellComplete = parentCtx.shellComplete - } - - return c -} - -// NumFlags returns the number of flags set -func (c *Context) NumFlags() int { - return c.flagSet.NFlag() -} - -// Set sets a context flag to a value. -func (c *Context) Set(name, value string) error { - return c.flagSet.Set(name, value) -} - -// GlobalSet sets a context flag to a value on the global flagset -func (c *Context) GlobalSet(name, value string) error { - return globalContext(c).flagSet.Set(name, value) -} - -// IsSet determines if the flag was actually set -func (c *Context) IsSet(name string) bool { - if c.setFlags == nil { - c.setFlags = make(map[string]bool) - - c.flagSet.Visit(func(f *flag.Flag) { - c.setFlags[f.Name] = true - }) - - c.flagSet.VisitAll(func(f *flag.Flag) { - if _, ok := c.setFlags[f.Name]; ok { - return - } - c.setFlags[f.Name] = false - }) - - // XXX hack to support IsSet for flags with EnvVar - // - // There isn't an easy way to do this with the current implementation since - // whether a flag was set via an environment variable is very difficult to - // determine here. Instead, we intend to introduce a backwards incompatible - // change in version 2 to add `IsSet` to the Flag interface to push the - // responsibility closer to where the information required to determine - // whether a flag is set by non-standard means such as environment - // variables is avaliable. - // - // See https://github.com/urfave/cli/issues/294 for additional discussion - flags := c.Command.Flags - if c.Command.Name == "" { // cannot == Command{} since it contains slice types - if c.App != nil { - flags = c.App.Flags - } - } - for _, f := range flags { - eachName(f.GetName(), func(name string) { - if isSet, ok := c.setFlags[name]; isSet || !ok { - return - } - - val := reflect.ValueOf(f) - if val.Kind() == reflect.Ptr { - val = val.Elem() - } - - envVarValue := val.FieldByName("EnvVar") - if !envVarValue.IsValid() { - return - } - - eachName(envVarValue.String(), func(envVar string) { - envVar = strings.TrimSpace(envVar) - if _, ok := syscall.Getenv(envVar); ok { - c.setFlags[name] = true - return - } - }) - }) - } - } - - return c.setFlags[name] -} - -// GlobalIsSet determines if the global flag was actually set -func (c *Context) GlobalIsSet(name string) bool { - ctx := c - if ctx.parentContext != nil { - ctx = ctx.parentContext - } - - for ; ctx != nil; ctx = ctx.parentContext { - if ctx.IsSet(name) { - return true - } - } - return false -} - -// FlagNames returns a slice of flag names used in this context. -func (c *Context) FlagNames() (names []string) { - for _, flag := range c.Command.Flags { - name := strings.Split(flag.GetName(), ",")[0] - if name == "help" { - continue - } - names = append(names, name) - } - return -} - -// GlobalFlagNames returns a slice of global flag names used by the app. -func (c *Context) GlobalFlagNames() (names []string) { - for _, flag := range c.App.Flags { - name := strings.Split(flag.GetName(), ",")[0] - if name == "help" || name == "version" { - continue - } - names = append(names, name) - } - return -} - -// Parent returns the parent context, if any -func (c *Context) Parent() *Context { - return c.parentContext -} - -// value returns the value of the flag coressponding to `name` -func (c *Context) value(name string) interface{} { - return c.flagSet.Lookup(name).Value.(flag.Getter).Get() -} - -// Args contains apps console arguments -type Args []string - -// Args returns the command line arguments associated with the context. -func (c *Context) Args() Args { - args := Args(c.flagSet.Args()) - return args -} - -// NArg returns the number of the command line arguments. -func (c *Context) NArg() int { - return len(c.Args()) -} - -// Get returns the nth argument, or else a blank string -func (a Args) Get(n int) string { - if len(a) > n { - return a[n] - } - return "" -} - -// First returns the first argument, or else a blank string -func (a Args) First() string { - return a.Get(0) -} - -// Tail returns the rest of the arguments (not the first one) -// or else an empty string slice -func (a Args) Tail() []string { - if len(a) >= 2 { - return []string(a)[1:] - } - return []string{} -} - -// Present checks if there are any arguments present -func (a Args) Present() bool { - return len(a) != 0 -} - -// Swap swaps arguments at the given indexes -func (a Args) Swap(from, to int) error { - if from >= len(a) || to >= len(a) { - return errors.New("index out of range") - } - a[from], a[to] = a[to], a[from] - return nil -} - -func globalContext(ctx *Context) *Context { - if ctx == nil { - return nil - } - - for { - if ctx.parentContext == nil { - return ctx - } - ctx = ctx.parentContext - } -} - -func lookupGlobalFlagSet(name string, ctx *Context) *flag.FlagSet { - if ctx.parentContext != nil { - ctx = ctx.parentContext - } - for ; ctx != nil; ctx = ctx.parentContext { - if f := ctx.flagSet.Lookup(name); f != nil { - return ctx.flagSet - } - } - return nil -} - -func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) { - switch ff.Value.(type) { - case *StringSlice: - default: - set.Set(name, ff.Value.String()) - } -} - -func normalizeFlags(flags []Flag, set *flag.FlagSet) error { - visited := make(map[string]bool) - set.Visit(func(f *flag.Flag) { - visited[f.Name] = true - }) - for _, f := range flags { - parts := strings.Split(f.GetName(), ",") - if len(parts) == 1 { - continue - } - var ff *flag.Flag - for _, name := range parts { - name = strings.Trim(name, " ") - if visited[name] { - if ff != nil { - return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name) - } - ff = set.Lookup(name) - } - } - if ff == nil { - continue - } - for _, name := range parts { - name = strings.Trim(name, " ") - if !visited[name] { - copyFlag(name, ff, set) - } - } - } - return nil -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/errors.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/errors.go deleted file mode 100644 index 0206ff49..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/errors.go +++ /dev/null @@ -1,110 +0,0 @@ -package cli - -import ( - "fmt" - "io" - "os" - "strings" -) - -// OsExiter is the function used when the app exits. If not set defaults to os.Exit. -var OsExiter = os.Exit - -// ErrWriter is used to write errors to the user. This can be anything -// implementing the io.Writer interface and defaults to os.Stderr. -var ErrWriter io.Writer = os.Stderr - -// MultiError is an error that wraps multiple errors. -type MultiError struct { - Errors []error -} - -// NewMultiError creates a new MultiError. Pass in one or more errors. -func NewMultiError(err ...error) MultiError { - return MultiError{Errors: err} -} - -// Error implements the error interface. -func (m MultiError) Error() string { - errs := make([]string, len(m.Errors)) - for i, err := range m.Errors { - errs[i] = err.Error() - } - - return strings.Join(errs, "\n") -} - -type ErrorFormatter interface { - Format(s fmt.State, verb rune) -} - -// ExitCoder is the interface checked by `App` and `Command` for a custom exit -// code -type ExitCoder interface { - error - ExitCode() int -} - -// ExitError fulfills both the builtin `error` interface and `ExitCoder` -type ExitError struct { - exitCode int - message interface{} -} - -// NewExitError makes a new *ExitError -func NewExitError(message interface{}, exitCode int) *ExitError { - return &ExitError{ - exitCode: exitCode, - message: message, - } -} - -// Error returns the string message, fulfilling the interface required by -// `error` -func (ee *ExitError) Error() string { - return fmt.Sprintf("%v", ee.message) -} - -// ExitCode returns the exit code, fulfilling the interface required by -// `ExitCoder` -func (ee *ExitError) ExitCode() int { - return ee.exitCode -} - -// HandleExitCoder checks if the error fulfills the ExitCoder interface, and if -// so prints the error to stderr (if it is non-empty) and calls OsExiter with the -// given exit code. If the given error is a MultiError, then this func is -// called on all members of the Errors slice. -func HandleExitCoder(err error) { - if err == nil { - return - } - - if exitErr, ok := err.(ExitCoder); ok { - if err.Error() != "" { - if _, ok := exitErr.(ErrorFormatter); ok { - fmt.Fprintf(ErrWriter, "%+v\n", err) - } else { - fmt.Fprintln(ErrWriter, err) - } - } - OsExiter(exitErr.ExitCode()) - return - } - - if multiErr, ok := err.(MultiError); ok { - for _, merr := range multiErr.Errors { - HandleExitCoder(merr) - } - return - } - - if err.Error() != "" { - if _, ok := err.(ErrorFormatter); ok { - fmt.Fprintf(ErrWriter, "%+v\n", err) - } else { - fmt.Fprintln(ErrWriter, err) - } - } - OsExiter(1) -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/flag-types.json b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/flag-types.json deleted file mode 100644 index 12231078..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/flag-types.json +++ /dev/null @@ -1,93 +0,0 @@ -[ - { - "name": "Bool", - "type": "bool", - "value": false, - "context_default": "false", - "parser": "strconv.ParseBool(f.Value.String())" - }, - { - "name": "BoolT", - "type": "bool", - "value": false, - "doctail": " that is true by default", - "context_default": "false", - "parser": "strconv.ParseBool(f.Value.String())" - }, - { - "name": "Duration", - "type": "time.Duration", - "doctail": " (see https://golang.org/pkg/time/#ParseDuration)", - "context_default": "0", - "parser": "time.ParseDuration(f.Value.String())" - }, - { - "name": "Float64", - "type": "float64", - "context_default": "0", - "parser": "strconv.ParseFloat(f.Value.String(), 64)" - }, - { - "name": "Generic", - "type": "Generic", - "dest": false, - "context_default": "nil", - "context_type": "interface{}" - }, - { - "name": "Int64", - "type": "int64", - "context_default": "0", - "parser": "strconv.ParseInt(f.Value.String(), 0, 64)" - }, - { - "name": "Int", - "type": "int", - "context_default": "0", - "parser": "strconv.ParseInt(f.Value.String(), 0, 64)", - "parser_cast": "int(parsed)" - }, - { - "name": "IntSlice", - "type": "*IntSlice", - "dest": false, - "context_default": "nil", - "context_type": "[]int", - "parser": "(f.Value.(*IntSlice)).Value(), error(nil)" - }, - { - "name": "Int64Slice", - "type": "*Int64Slice", - "dest": false, - "context_default": "nil", - "context_type": "[]int64", - "parser": "(f.Value.(*Int64Slice)).Value(), error(nil)" - }, - { - "name": "String", - "type": "string", - "context_default": "\"\"", - "parser": "f.Value.String(), error(nil)" - }, - { - "name": "StringSlice", - "type": "*StringSlice", - "dest": false, - "context_default": "nil", - "context_type": "[]string", - "parser": "(f.Value.(*StringSlice)).Value(), error(nil)" - }, - { - "name": "Uint64", - "type": "uint64", - "context_default": "0", - "parser": "strconv.ParseUint(f.Value.String(), 0, 64)" - }, - { - "name": "Uint", - "type": "uint", - "context_default": "0", - "parser": "strconv.ParseUint(f.Value.String(), 0, 64)", - "parser_cast": "uint(parsed)" - } -] diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/flag.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/flag.go deleted file mode 100644 index 7dd8a2c4..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/flag.go +++ /dev/null @@ -1,799 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "reflect" - "runtime" - "strconv" - "strings" - "syscall" - "time" -) - -const defaultPlaceholder = "value" - -// BashCompletionFlag enables bash-completion for all commands and subcommands -var BashCompletionFlag = BoolFlag{ - Name: "generate-bash-completion", - Hidden: true, -} - -// VersionFlag prints the version for the application -var VersionFlag = BoolFlag{ - Name: "version, v", - Usage: "print the version", -} - -// HelpFlag prints the help for all commands and subcommands -// Set to the zero value (BoolFlag{}) to disable flag -- keeps subcommand -// unless HideHelp is set to true) -var HelpFlag = BoolFlag{ - Name: "help, h", - Usage: "show help", -} - -// FlagStringer converts a flag definition to a string. This is used by help -// to display a flag. -var FlagStringer FlagStringFunc = stringifyFlag - -// FlagsByName is a slice of Flag. -type FlagsByName []Flag - -func (f FlagsByName) Len() int { - return len(f) -} - -func (f FlagsByName) Less(i, j int) bool { - return f[i].GetName() < f[j].GetName() -} - -func (f FlagsByName) Swap(i, j int) { - f[i], f[j] = f[j], f[i] -} - -// Flag is a common interface related to parsing flags in cli. -// For more advanced flag parsing techniques, it is recommended that -// this interface be implemented. -type Flag interface { - fmt.Stringer - // Apply Flag settings to the given flag set - Apply(*flag.FlagSet) - GetName() string -} - -// errorableFlag is an interface that allows us to return errors during apply -// it allows flags defined in this library to return errors in a fashion backwards compatible -// TODO remove in v2 and modify the existing Flag interface to return errors -type errorableFlag interface { - Flag - - ApplyWithError(*flag.FlagSet) error -} - -func flagSet(name string, flags []Flag) (*flag.FlagSet, error) { - set := flag.NewFlagSet(name, flag.ContinueOnError) - - for _, f := range flags { - //TODO remove in v2 when errorableFlag is removed - if ef, ok := f.(errorableFlag); ok { - if err := ef.ApplyWithError(set); err != nil { - return nil, err - } - } else { - f.Apply(set) - } - } - return set, nil -} - -func eachName(longName string, fn func(string)) { - parts := strings.Split(longName, ",") - for _, name := range parts { - name = strings.Trim(name, " ") - fn(name) - } -} - -// Generic is a generic parseable type identified by a specific flag -type Generic interface { - Set(value string) error - String() string -} - -// Apply takes the flagset and calls Set on the generic flag with the value -// provided by the user for parsing by the flag -// Ignores parsing errors -func (f GenericFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError takes the flagset and calls Set on the generic flag with the value -// provided by the user for parsing by the flag -func (f GenericFlag) ApplyWithError(set *flag.FlagSet) error { - val := f.Value - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - if err := val.Set(envVal); err != nil { - return fmt.Errorf("could not parse %s as value for flag %s: %s", envVal, f.Name, err) - } - break - } - } - } - - eachName(f.Name, func(name string) { - set.Var(f.Value, name, f.Usage) - }) - - return nil -} - -// StringSlice is an opaque type for []string to satisfy flag.Value and flag.Getter -type StringSlice []string - -// Set appends the string value to the list of values -func (f *StringSlice) Set(value string) error { - *f = append(*f, value) - return nil -} - -// String returns a readable representation of this value (for usage defaults) -func (f *StringSlice) String() string { - return fmt.Sprintf("%s", *f) -} - -// Value returns the slice of strings set by this flag -func (f *StringSlice) Value() []string { - return *f -} - -// Get returns the slice of strings set by this flag -func (f *StringSlice) Get() interface{} { - return *f -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f StringSliceFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f StringSliceFlag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - newVal := &StringSlice{} - for _, s := range strings.Split(envVal, ",") { - s = strings.TrimSpace(s) - if err := newVal.Set(s); err != nil { - return fmt.Errorf("could not parse %s as string value for flag %s: %s", envVal, f.Name, err) - } - } - f.Value = newVal - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Value == nil { - f.Value = &StringSlice{} - } - set.Var(f.Value, name, f.Usage) - }) - - return nil -} - -// IntSlice is an opaque type for []int to satisfy flag.Value and flag.Getter -type IntSlice []int - -// Set parses the value into an integer and appends it to the list of values -func (f *IntSlice) Set(value string) error { - tmp, err := strconv.Atoi(value) - if err != nil { - return err - } - *f = append(*f, tmp) - return nil -} - -// String returns a readable representation of this value (for usage defaults) -func (f *IntSlice) String() string { - return fmt.Sprintf("%#v", *f) -} - -// Value returns the slice of ints set by this flag -func (f *IntSlice) Value() []int { - return *f -} - -// Get returns the slice of ints set by this flag -func (f *IntSlice) Get() interface{} { - return *f -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f IntSliceFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f IntSliceFlag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - newVal := &IntSlice{} - for _, s := range strings.Split(envVal, ",") { - s = strings.TrimSpace(s) - if err := newVal.Set(s); err != nil { - return fmt.Errorf("could not parse %s as int slice value for flag %s: %s", envVal, f.Name, err) - } - } - f.Value = newVal - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Value == nil { - f.Value = &IntSlice{} - } - set.Var(f.Value, name, f.Usage) - }) - - return nil -} - -// Int64Slice is an opaque type for []int to satisfy flag.Value and flag.Getter -type Int64Slice []int64 - -// Set parses the value into an integer and appends it to the list of values -func (f *Int64Slice) Set(value string) error { - tmp, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - *f = append(*f, tmp) - return nil -} - -// String returns a readable representation of this value (for usage defaults) -func (f *Int64Slice) String() string { - return fmt.Sprintf("%#v", *f) -} - -// Value returns the slice of ints set by this flag -func (f *Int64Slice) Value() []int64 { - return *f -} - -// Get returns the slice of ints set by this flag -func (f *Int64Slice) Get() interface{} { - return *f -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f Int64SliceFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f Int64SliceFlag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - newVal := &Int64Slice{} - for _, s := range strings.Split(envVal, ",") { - s = strings.TrimSpace(s) - if err := newVal.Set(s); err != nil { - return fmt.Errorf("could not parse %s as int64 slice value for flag %s: %s", envVal, f.Name, err) - } - } - f.Value = newVal - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Value == nil { - f.Value = &Int64Slice{} - } - set.Var(f.Value, name, f.Usage) - }) - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f BoolFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f BoolFlag) ApplyWithError(set *flag.FlagSet) error { - val := false - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - if envVal == "" { - val = false - break - } - - envValBool, err := strconv.ParseBool(envVal) - if err != nil { - return fmt.Errorf("could not parse %s as bool value for flag %s: %s", envVal, f.Name, err) - } - - val = envValBool - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.BoolVar(f.Destination, name, val, f.Usage) - return - } - set.Bool(name, val, f.Usage) - }) - - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f BoolTFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f BoolTFlag) ApplyWithError(set *flag.FlagSet) error { - val := true - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - if envVal == "" { - val = false - break - } - - envValBool, err := strconv.ParseBool(envVal) - if err != nil { - return fmt.Errorf("could not parse %s as bool value for flag %s: %s", envVal, f.Name, err) - } - - val = envValBool - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.BoolVar(f.Destination, name, val, f.Usage) - return - } - set.Bool(name, val, f.Usage) - }) - - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f StringFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f StringFlag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - f.Value = envVal - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.StringVar(f.Destination, name, f.Value, f.Usage) - return - } - set.String(name, f.Value, f.Usage) - }) - - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f IntFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f IntFlag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - envValInt, err := strconv.ParseInt(envVal, 0, 64) - if err != nil { - return fmt.Errorf("could not parse %s as int value for flag %s: %s", envVal, f.Name, err) - } - f.Value = int(envValInt) - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.IntVar(f.Destination, name, f.Value, f.Usage) - return - } - set.Int(name, f.Value, f.Usage) - }) - - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f Int64Flag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f Int64Flag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - envValInt, err := strconv.ParseInt(envVal, 0, 64) - if err != nil { - return fmt.Errorf("could not parse %s as int value for flag %s: %s", envVal, f.Name, err) - } - - f.Value = envValInt - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.Int64Var(f.Destination, name, f.Value, f.Usage) - return - } - set.Int64(name, f.Value, f.Usage) - }) - - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f UintFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f UintFlag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - envValInt, err := strconv.ParseUint(envVal, 0, 64) - if err != nil { - return fmt.Errorf("could not parse %s as uint value for flag %s: %s", envVal, f.Name, err) - } - - f.Value = uint(envValInt) - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.UintVar(f.Destination, name, f.Value, f.Usage) - return - } - set.Uint(name, f.Value, f.Usage) - }) - - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f Uint64Flag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f Uint64Flag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - envValInt, err := strconv.ParseUint(envVal, 0, 64) - if err != nil { - return fmt.Errorf("could not parse %s as uint64 value for flag %s: %s", envVal, f.Name, err) - } - - f.Value = uint64(envValInt) - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.Uint64Var(f.Destination, name, f.Value, f.Usage) - return - } - set.Uint64(name, f.Value, f.Usage) - }) - - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f DurationFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f DurationFlag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - envValDuration, err := time.ParseDuration(envVal) - if err != nil { - return fmt.Errorf("could not parse %s as duration for flag %s: %s", envVal, f.Name, err) - } - - f.Value = envValDuration - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.DurationVar(f.Destination, name, f.Value, f.Usage) - return - } - set.Duration(name, f.Value, f.Usage) - }) - - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f Float64Flag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f Float64Flag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - envValFloat, err := strconv.ParseFloat(envVal, 10) - if err != nil { - return fmt.Errorf("could not parse %s as float64 value for flag %s: %s", envVal, f.Name, err) - } - - f.Value = float64(envValFloat) - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.Float64Var(f.Destination, name, f.Value, f.Usage) - return - } - set.Float64(name, f.Value, f.Usage) - }) - - return nil -} - -func visibleFlags(fl []Flag) []Flag { - visible := []Flag{} - for _, flag := range fl { - if !flagValue(flag).FieldByName("Hidden").Bool() { - visible = append(visible, flag) - } - } - return visible -} - -func prefixFor(name string) (prefix string) { - if len(name) == 1 { - prefix = "-" - } else { - prefix = "--" - } - - return -} - -// Returns the placeholder, if any, and the unquoted usage string. -func unquoteUsage(usage string) (string, string) { - for i := 0; i < len(usage); i++ { - if usage[i] == '`' { - for j := i + 1; j < len(usage); j++ { - if usage[j] == '`' { - name := usage[i+1 : j] - usage = usage[:i] + name + usage[j+1:] - return name, usage - } - } - break - } - } - return "", usage -} - -func prefixedNames(fullName, placeholder string) string { - var prefixed string - parts := strings.Split(fullName, ",") - for i, name := range parts { - name = strings.Trim(name, " ") - prefixed += prefixFor(name) + name - if placeholder != "" { - prefixed += " " + placeholder - } - if i < len(parts)-1 { - prefixed += ", " - } - } - return prefixed -} - -func withEnvHint(envVar, str string) string { - envText := "" - if envVar != "" { - prefix := "$" - suffix := "" - sep := ", $" - if runtime.GOOS == "windows" { - prefix = "%" - suffix = "%" - sep = "%, %" - } - envText = fmt.Sprintf(" [%s%s%s]", prefix, strings.Join(strings.Split(envVar, ","), sep), suffix) - } - return str + envText -} - -func flagValue(f Flag) reflect.Value { - fv := reflect.ValueOf(f) - for fv.Kind() == reflect.Ptr { - fv = reflect.Indirect(fv) - } - return fv -} - -func stringifyFlag(f Flag) string { - fv := flagValue(f) - - switch f.(type) { - case IntSliceFlag: - return withEnvHint(fv.FieldByName("EnvVar").String(), - stringifyIntSliceFlag(f.(IntSliceFlag))) - case Int64SliceFlag: - return withEnvHint(fv.FieldByName("EnvVar").String(), - stringifyInt64SliceFlag(f.(Int64SliceFlag))) - case StringSliceFlag: - return withEnvHint(fv.FieldByName("EnvVar").String(), - stringifyStringSliceFlag(f.(StringSliceFlag))) - } - - placeholder, usage := unquoteUsage(fv.FieldByName("Usage").String()) - - needsPlaceholder := false - defaultValueString := "" - val := fv.FieldByName("Value") - - if val.IsValid() { - needsPlaceholder = true - defaultValueString = fmt.Sprintf(" (default: %v)", val.Interface()) - - if val.Kind() == reflect.String && val.String() != "" { - defaultValueString = fmt.Sprintf(" (default: %q)", val.String()) - } - } - - if defaultValueString == " (default: )" { - defaultValueString = "" - } - - if needsPlaceholder && placeholder == "" { - placeholder = defaultPlaceholder - } - - usageWithDefault := strings.TrimSpace(fmt.Sprintf("%s%s", usage, defaultValueString)) - - return withEnvHint(fv.FieldByName("EnvVar").String(), - fmt.Sprintf("%s\t%s", prefixedNames(fv.FieldByName("Name").String(), placeholder), usageWithDefault)) -} - -func stringifyIntSliceFlag(f IntSliceFlag) string { - defaultVals := []string{} - if f.Value != nil && len(f.Value.Value()) > 0 { - for _, i := range f.Value.Value() { - defaultVals = append(defaultVals, fmt.Sprintf("%d", i)) - } - } - - return stringifySliceFlag(f.Usage, f.Name, defaultVals) -} - -func stringifyInt64SliceFlag(f Int64SliceFlag) string { - defaultVals := []string{} - if f.Value != nil && len(f.Value.Value()) > 0 { - for _, i := range f.Value.Value() { - defaultVals = append(defaultVals, fmt.Sprintf("%d", i)) - } - } - - return stringifySliceFlag(f.Usage, f.Name, defaultVals) -} - -func stringifyStringSliceFlag(f StringSliceFlag) string { - defaultVals := []string{} - if f.Value != nil && len(f.Value.Value()) > 0 { - for _, s := range f.Value.Value() { - if len(s) > 0 { - defaultVals = append(defaultVals, fmt.Sprintf("%q", s)) - } - } - } - - return stringifySliceFlag(f.Usage, f.Name, defaultVals) -} - -func stringifySliceFlag(usage, name string, defaultVals []string) string { - placeholder, usage := unquoteUsage(usage) - if placeholder == "" { - placeholder = defaultPlaceholder - } - - defaultVal := "" - if len(defaultVals) > 0 { - defaultVal = fmt.Sprintf(" (default: %s)", strings.Join(defaultVals, ", ")) - } - - usageWithDefault := strings.TrimSpace(fmt.Sprintf("%s%s", usage, defaultVal)) - return fmt.Sprintf("%s\t%s", prefixedNames(name, placeholder), usageWithDefault) -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/flag_generated.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/flag_generated.go deleted file mode 100644 index 491b6195..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/flag_generated.go +++ /dev/null @@ -1,627 +0,0 @@ -package cli - -import ( - "flag" - "strconv" - "time" -) - -// WARNING: This file is generated! - -// BoolFlag is a flag with type bool -type BoolFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Destination *bool -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f BoolFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f BoolFlag) GetName() string { - return f.Name -} - -// Bool looks up the value of a local BoolFlag, returns -// false if not found -func (c *Context) Bool(name string) bool { - return lookupBool(name, c.flagSet) -} - -// GlobalBool looks up the value of a global BoolFlag, returns -// false if not found -func (c *Context) GlobalBool(name string) bool { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupBool(name, fs) - } - return false -} - -func lookupBool(name string, set *flag.FlagSet) bool { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseBool(f.Value.String()) - if err != nil { - return false - } - return parsed - } - return false -} - -// BoolTFlag is a flag with type bool that is true by default -type BoolTFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Destination *bool -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f BoolTFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f BoolTFlag) GetName() string { - return f.Name -} - -// BoolT looks up the value of a local BoolTFlag, returns -// false if not found -func (c *Context) BoolT(name string) bool { - return lookupBoolT(name, c.flagSet) -} - -// GlobalBoolT looks up the value of a global BoolTFlag, returns -// false if not found -func (c *Context) GlobalBoolT(name string) bool { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupBoolT(name, fs) - } - return false -} - -func lookupBoolT(name string, set *flag.FlagSet) bool { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseBool(f.Value.String()) - if err != nil { - return false - } - return parsed - } - return false -} - -// DurationFlag is a flag with type time.Duration (see https://golang.org/pkg/time/#ParseDuration) -type DurationFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value time.Duration - Destination *time.Duration -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f DurationFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f DurationFlag) GetName() string { - return f.Name -} - -// Duration looks up the value of a local DurationFlag, returns -// 0 if not found -func (c *Context) Duration(name string) time.Duration { - return lookupDuration(name, c.flagSet) -} - -// GlobalDuration looks up the value of a global DurationFlag, returns -// 0 if not found -func (c *Context) GlobalDuration(name string) time.Duration { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupDuration(name, fs) - } - return 0 -} - -func lookupDuration(name string, set *flag.FlagSet) time.Duration { - f := set.Lookup(name) - if f != nil { - parsed, err := time.ParseDuration(f.Value.String()) - if err != nil { - return 0 - } - return parsed - } - return 0 -} - -// Float64Flag is a flag with type float64 -type Float64Flag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value float64 - Destination *float64 -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f Float64Flag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f Float64Flag) GetName() string { - return f.Name -} - -// Float64 looks up the value of a local Float64Flag, returns -// 0 if not found -func (c *Context) Float64(name string) float64 { - return lookupFloat64(name, c.flagSet) -} - -// GlobalFloat64 looks up the value of a global Float64Flag, returns -// 0 if not found -func (c *Context) GlobalFloat64(name string) float64 { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupFloat64(name, fs) - } - return 0 -} - -func lookupFloat64(name string, set *flag.FlagSet) float64 { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseFloat(f.Value.String(), 64) - if err != nil { - return 0 - } - return parsed - } - return 0 -} - -// GenericFlag is a flag with type Generic -type GenericFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value Generic -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f GenericFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f GenericFlag) GetName() string { - return f.Name -} - -// Generic looks up the value of a local GenericFlag, returns -// nil if not found -func (c *Context) Generic(name string) interface{} { - return lookupGeneric(name, c.flagSet) -} - -// GlobalGeneric looks up the value of a global GenericFlag, returns -// nil if not found -func (c *Context) GlobalGeneric(name string) interface{} { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupGeneric(name, fs) - } - return nil -} - -func lookupGeneric(name string, set *flag.FlagSet) interface{} { - f := set.Lookup(name) - if f != nil { - parsed, err := f.Value, error(nil) - if err != nil { - return nil - } - return parsed - } - return nil -} - -// Int64Flag is a flag with type int64 -type Int64Flag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value int64 - Destination *int64 -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f Int64Flag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f Int64Flag) GetName() string { - return f.Name -} - -// Int64 looks up the value of a local Int64Flag, returns -// 0 if not found -func (c *Context) Int64(name string) int64 { - return lookupInt64(name, c.flagSet) -} - -// GlobalInt64 looks up the value of a global Int64Flag, returns -// 0 if not found -func (c *Context) GlobalInt64(name string) int64 { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupInt64(name, fs) - } - return 0 -} - -func lookupInt64(name string, set *flag.FlagSet) int64 { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseInt(f.Value.String(), 0, 64) - if err != nil { - return 0 - } - return parsed - } - return 0 -} - -// IntFlag is a flag with type int -type IntFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value int - Destination *int -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f IntFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f IntFlag) GetName() string { - return f.Name -} - -// Int looks up the value of a local IntFlag, returns -// 0 if not found -func (c *Context) Int(name string) int { - return lookupInt(name, c.flagSet) -} - -// GlobalInt looks up the value of a global IntFlag, returns -// 0 if not found -func (c *Context) GlobalInt(name string) int { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupInt(name, fs) - } - return 0 -} - -func lookupInt(name string, set *flag.FlagSet) int { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseInt(f.Value.String(), 0, 64) - if err != nil { - return 0 - } - return int(parsed) - } - return 0 -} - -// IntSliceFlag is a flag with type *IntSlice -type IntSliceFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value *IntSlice -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f IntSliceFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f IntSliceFlag) GetName() string { - return f.Name -} - -// IntSlice looks up the value of a local IntSliceFlag, returns -// nil if not found -func (c *Context) IntSlice(name string) []int { - return lookupIntSlice(name, c.flagSet) -} - -// GlobalIntSlice looks up the value of a global IntSliceFlag, returns -// nil if not found -func (c *Context) GlobalIntSlice(name string) []int { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupIntSlice(name, fs) - } - return nil -} - -func lookupIntSlice(name string, set *flag.FlagSet) []int { - f := set.Lookup(name) - if f != nil { - parsed, err := (f.Value.(*IntSlice)).Value(), error(nil) - if err != nil { - return nil - } - return parsed - } - return nil -} - -// Int64SliceFlag is a flag with type *Int64Slice -type Int64SliceFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value *Int64Slice -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f Int64SliceFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f Int64SliceFlag) GetName() string { - return f.Name -} - -// Int64Slice looks up the value of a local Int64SliceFlag, returns -// nil if not found -func (c *Context) Int64Slice(name string) []int64 { - return lookupInt64Slice(name, c.flagSet) -} - -// GlobalInt64Slice looks up the value of a global Int64SliceFlag, returns -// nil if not found -func (c *Context) GlobalInt64Slice(name string) []int64 { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupInt64Slice(name, fs) - } - return nil -} - -func lookupInt64Slice(name string, set *flag.FlagSet) []int64 { - f := set.Lookup(name) - if f != nil { - parsed, err := (f.Value.(*Int64Slice)).Value(), error(nil) - if err != nil { - return nil - } - return parsed - } - return nil -} - -// StringFlag is a flag with type string -type StringFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value string - Destination *string -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f StringFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f StringFlag) GetName() string { - return f.Name -} - -// String looks up the value of a local StringFlag, returns -// "" if not found -func (c *Context) String(name string) string { - return lookupString(name, c.flagSet) -} - -// GlobalString looks up the value of a global StringFlag, returns -// "" if not found -func (c *Context) GlobalString(name string) string { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupString(name, fs) - } - return "" -} - -func lookupString(name string, set *flag.FlagSet) string { - f := set.Lookup(name) - if f != nil { - parsed, err := f.Value.String(), error(nil) - if err != nil { - return "" - } - return parsed - } - return "" -} - -// StringSliceFlag is a flag with type *StringSlice -type StringSliceFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value *StringSlice -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f StringSliceFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f StringSliceFlag) GetName() string { - return f.Name -} - -// StringSlice looks up the value of a local StringSliceFlag, returns -// nil if not found -func (c *Context) StringSlice(name string) []string { - return lookupStringSlice(name, c.flagSet) -} - -// GlobalStringSlice looks up the value of a global StringSliceFlag, returns -// nil if not found -func (c *Context) GlobalStringSlice(name string) []string { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupStringSlice(name, fs) - } - return nil -} - -func lookupStringSlice(name string, set *flag.FlagSet) []string { - f := set.Lookup(name) - if f != nil { - parsed, err := (f.Value.(*StringSlice)).Value(), error(nil) - if err != nil { - return nil - } - return parsed - } - return nil -} - -// Uint64Flag is a flag with type uint64 -type Uint64Flag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value uint64 - Destination *uint64 -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f Uint64Flag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f Uint64Flag) GetName() string { - return f.Name -} - -// Uint64 looks up the value of a local Uint64Flag, returns -// 0 if not found -func (c *Context) Uint64(name string) uint64 { - return lookupUint64(name, c.flagSet) -} - -// GlobalUint64 looks up the value of a global Uint64Flag, returns -// 0 if not found -func (c *Context) GlobalUint64(name string) uint64 { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupUint64(name, fs) - } - return 0 -} - -func lookupUint64(name string, set *flag.FlagSet) uint64 { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseUint(f.Value.String(), 0, 64) - if err != nil { - return 0 - } - return parsed - } - return 0 -} - -// UintFlag is a flag with type uint -type UintFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value uint - Destination *uint -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f UintFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f UintFlag) GetName() string { - return f.Name -} - -// Uint looks up the value of a local UintFlag, returns -// 0 if not found -func (c *Context) Uint(name string) uint { - return lookupUint(name, c.flagSet) -} - -// GlobalUint looks up the value of a global UintFlag, returns -// 0 if not found -func (c *Context) GlobalUint(name string) uint { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupUint(name, fs) - } - return 0 -} - -func lookupUint(name string, set *flag.FlagSet) uint { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseUint(f.Value.String(), 0, 64) - if err != nil { - return 0 - } - return uint(parsed) - } - return 0 -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/funcs.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/funcs.go deleted file mode 100644 index cba5e6cb..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/funcs.go +++ /dev/null @@ -1,28 +0,0 @@ -package cli - -// BashCompleteFunc is an action to execute when the bash-completion flag is set -type BashCompleteFunc func(*Context) - -// BeforeFunc is an action to execute before any subcommands are run, but after -// the context is ready if a non-nil error is returned, no subcommands are run -type BeforeFunc func(*Context) error - -// AfterFunc is an action to execute after any subcommands are run, but after the -// subcommand has finished it is run even if Action() panics -type AfterFunc func(*Context) error - -// ActionFunc is the action to execute when no subcommands are specified -type ActionFunc func(*Context) error - -// CommandNotFoundFunc is executed if the proper command cannot be found -type CommandNotFoundFunc func(*Context, string) - -// OnUsageErrorFunc is executed if an usage error occurs. This is useful for displaying -// customized usage error messages. This function is able to replace the -// original error messages. If this function is not set, the "Incorrect usage" -// is displayed and the execution is interrupted. -type OnUsageErrorFunc func(context *Context, err error, isSubcommand bool) error - -// FlagStringFunc is used by the help generation to display a flag, which is -// expected to be a single line. -type FlagStringFunc func(Flag) string diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/generate-flag-types b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/generate-flag-types deleted file mode 100755 index 7147381c..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/generate-flag-types +++ /dev/null @@ -1,255 +0,0 @@ -#!/usr/bin/env python -""" -The flag types that ship with the cli library have many things in common, and -so we can take advantage of the `go generate` command to create much of the -source code from a list of definitions. These definitions attempt to cover -the parts that vary between flag types, and should evolve as needed. - -An example of the minimum definition needed is: - - { - "name": "SomeType", - "type": "sometype", - "context_default": "nil" - } - -In this example, the code generated for the `cli` package will include a type -named `SomeTypeFlag` that is expected to wrap a value of type `sometype`. -Fetching values by name via `*cli.Context` will default to a value of `nil`. - -A more complete, albeit somewhat redundant, example showing all available -definition keys is: - - { - "name": "VeryMuchType", - "type": "*VeryMuchType", - "value": true, - "dest": false, - "doctail": " which really only wraps a []float64, oh well!", - "context_type": "[]float64", - "context_default": "nil", - "parser": "parseVeryMuchType(f.Value.String())", - "parser_cast": "[]float64(parsed)" - } - -The meaning of each field is as follows: - - name (string) - The type "name", which will be suffixed with - `Flag` when generating the type definition - for `cli` and the wrapper type for `altsrc` - type (string) - The type that the generated `Flag` type for `cli` - is expected to "contain" as its `.Value` member - value (bool) - Should the generated `cli` type have a `Value` - member? - dest (bool) - Should the generated `cli` type support a - destination pointer? - doctail (string) - Additional docs for the `cli` flag type comment - context_type (string) - The literal type used in the `*cli.Context` - reader func signature - context_default (string) - The literal value used as the default by the - `*cli.Context` reader funcs when no value is - present - parser (string) - Literal code used to parse the flag `f`, - expected to have a return signature of - (value, error) - parser_cast (string) - Literal code used to cast the `parsed` value - returned from the `parser` code -""" - -from __future__ import print_function, unicode_literals - -import argparse -import json -import os -import subprocess -import sys -import tempfile -import textwrap - - -class _FancyFormatter(argparse.ArgumentDefaultsHelpFormatter, - argparse.RawDescriptionHelpFormatter): - pass - - -def main(sysargs=sys.argv[:]): - parser = argparse.ArgumentParser( - description='Generate flag type code!', - formatter_class=_FancyFormatter) - parser.add_argument( - 'package', - type=str, default='cli', choices=_WRITEFUNCS.keys(), - help='Package for which flag types will be generated' - ) - parser.add_argument( - '-i', '--in-json', - type=argparse.FileType('r'), - default=sys.stdin, - help='Input JSON file which defines each type to be generated' - ) - parser.add_argument( - '-o', '--out-go', - type=argparse.FileType('w'), - default=sys.stdout, - help='Output file/stream to which generated source will be written' - ) - parser.epilog = __doc__ - - args = parser.parse_args(sysargs[1:]) - _generate_flag_types(_WRITEFUNCS[args.package], args.out_go, args.in_json) - return 0 - - -def _generate_flag_types(writefunc, output_go, input_json): - types = json.load(input_json) - - tmp = tempfile.NamedTemporaryFile(suffix='.go', delete=False) - writefunc(tmp, types) - tmp.close() - - new_content = subprocess.check_output( - ['goimports', tmp.name] - ).decode('utf-8') - - print(new_content, file=output_go, end='') - output_go.flush() - os.remove(tmp.name) - - -def _set_typedef_defaults(typedef): - typedef.setdefault('doctail', '') - typedef.setdefault('context_type', typedef['type']) - typedef.setdefault('dest', True) - typedef.setdefault('value', True) - typedef.setdefault('parser', 'f.Value, error(nil)') - typedef.setdefault('parser_cast', 'parsed') - - -def _write_cli_flag_types(outfile, types): - _fwrite(outfile, """\ - package cli - - // WARNING: This file is generated! - - """) - - for typedef in types: - _set_typedef_defaults(typedef) - - _fwrite(outfile, """\ - // {name}Flag is a flag with type {type}{doctail} - type {name}Flag struct {{ - Name string - Usage string - EnvVar string - Hidden bool - """.format(**typedef)) - - if typedef['value']: - _fwrite(outfile, """\ - Value {type} - """.format(**typedef)) - - if typedef['dest']: - _fwrite(outfile, """\ - Destination *{type} - """.format(**typedef)) - - _fwrite(outfile, "\n}\n\n") - - _fwrite(outfile, """\ - // String returns a readable representation of this value - // (for usage defaults) - func (f {name}Flag) String() string {{ - return FlagStringer(f) - }} - - // GetName returns the name of the flag - func (f {name}Flag) GetName() string {{ - return f.Name - }} - - // {name} looks up the value of a local {name}Flag, returns - // {context_default} if not found - func (c *Context) {name}(name string) {context_type} {{ - return lookup{name}(name, c.flagSet) - }} - - // Global{name} looks up the value of a global {name}Flag, returns - // {context_default} if not found - func (c *Context) Global{name}(name string) {context_type} {{ - if fs := lookupGlobalFlagSet(name, c); fs != nil {{ - return lookup{name}(name, fs) - }} - return {context_default} - }} - - func lookup{name}(name string, set *flag.FlagSet) {context_type} {{ - f := set.Lookup(name) - if f != nil {{ - parsed, err := {parser} - if err != nil {{ - return {context_default} - }} - return {parser_cast} - }} - return {context_default} - }} - """.format(**typedef)) - - -def _write_altsrc_flag_types(outfile, types): - _fwrite(outfile, """\ - package altsrc - - import ( - "gopkg.in/urfave/cli.v1" - ) - - // WARNING: This file is generated! - - """) - - for typedef in types: - _set_typedef_defaults(typedef) - - _fwrite(outfile, """\ - // {name}Flag is the flag type that wraps cli.{name}Flag to allow - // for other values to be specified - type {name}Flag struct {{ - cli.{name}Flag - set *flag.FlagSet - }} - - // New{name}Flag creates a new {name}Flag - func New{name}Flag(fl cli.{name}Flag) *{name}Flag {{ - return &{name}Flag{{{name}Flag: fl, set: nil}} - }} - - // Apply saves the flagSet for later usage calls, then calls the - // wrapped {name}Flag.Apply - func (f *{name}Flag) Apply(set *flag.FlagSet) {{ - f.set = set - f.{name}Flag.Apply(set) - }} - - // ApplyWithError saves the flagSet for later usage calls, then calls the - // wrapped {name}Flag.ApplyWithError - func (f *{name}Flag) ApplyWithError(set *flag.FlagSet) error {{ - f.set = set - return f.{name}Flag.ApplyWithError(set) - }} - """.format(**typedef)) - - -def _fwrite(outfile, text): - print(textwrap.dedent(text), end='', file=outfile) - - -_WRITEFUNCS = { - 'cli': _write_cli_flag_types, - 'altsrc': _write_altsrc_flag_types -} - -if __name__ == '__main__': - sys.exit(main()) diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/help.go b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/help.go deleted file mode 100644 index c8c1aee0..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/help.go +++ /dev/null @@ -1,294 +0,0 @@ -package cli - -import ( - "fmt" - "io" - "os" - "strings" - "text/tabwriter" - "text/template" -) - -// AppHelpTemplate is the text template for the Default help topic. -// cli.go uses text/template to render templates. You can -// render custom help text by setting this variable. -var AppHelpTemplate = `NAME: - {{.Name}}{{if .Usage}} - {{.Usage}}{{end}} - -USAGE: - {{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Version}}{{if not .HideVersion}} - -VERSION: - {{.Version}}{{end}}{{end}}{{if .Description}} - -DESCRIPTION: - {{.Description}}{{end}}{{if len .Authors}} - -AUTHOR{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}: - {{range $index, $author := .Authors}}{{if $index}} - {{end}}{{$author}}{{end}}{{end}}{{if .VisibleCommands}} - -COMMANDS:{{range .VisibleCategories}}{{if .Name}} - {{.Name}}:{{end}}{{range .VisibleCommands}} - {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{end}}{{end}}{{if .VisibleFlags}} - -GLOBAL OPTIONS: - {{range $index, $option := .VisibleFlags}}{{if $index}} - {{end}}{{$option}}{{end}}{{end}}{{if .Copyright}} - -COPYRIGHT: - {{.Copyright}}{{end}} -` - -// CommandHelpTemplate is the text template for the command help topic. -// cli.go uses text/template to render templates. You can -// render custom help text by setting this variable. -var CommandHelpTemplate = `NAME: - {{.HelpName}} - {{.Usage}} - -USAGE: - {{.HelpName}}{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{if .Category}} - -CATEGORY: - {{.Category}}{{end}}{{if .Description}} - -DESCRIPTION: - {{.Description}}{{end}}{{if .VisibleFlags}} - -OPTIONS: - {{range .VisibleFlags}}{{.}} - {{end}}{{end}} -` - -// SubcommandHelpTemplate is the text template for the subcommand help topic. -// cli.go uses text/template to render templates. You can -// render custom help text by setting this variable. -var SubcommandHelpTemplate = `NAME: - {{.HelpName}} - {{.Usage}} - -USAGE: - {{.HelpName}} command{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}} - -COMMANDS:{{range .VisibleCategories}}{{if .Name}} - {{.Name}}:{{end}}{{range .VisibleCommands}} - {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}} -{{end}}{{if .VisibleFlags}} -OPTIONS: - {{range .VisibleFlags}}{{.}} - {{end}}{{end}} -` - -var helpCommand = Command{ - Name: "help", - Aliases: []string{"h"}, - Usage: "Shows a list of commands or help for one command", - ArgsUsage: "[command]", - Action: func(c *Context) error { - args := c.Args() - if args.Present() { - return ShowCommandHelp(c, args.First()) - } - - ShowAppHelp(c) - return nil - }, -} - -var helpSubcommand = Command{ - Name: "help", - Aliases: []string{"h"}, - Usage: "Shows a list of commands or help for one command", - ArgsUsage: "[command]", - Action: func(c *Context) error { - args := c.Args() - if args.Present() { - return ShowCommandHelp(c, args.First()) - } - - return ShowSubcommandHelp(c) - }, -} - -// Prints help for the App or Command -type helpPrinter func(w io.Writer, templ string, data interface{}) - -// HelpPrinter is a function that writes the help output. If not set a default -// is used. The function signature is: -// func(w io.Writer, templ string, data interface{}) -var HelpPrinter helpPrinter = printHelp - -// VersionPrinter prints the version for the App -var VersionPrinter = printVersion - -// ShowAppHelp is an action that displays the help. -func ShowAppHelp(c *Context) error { - HelpPrinter(c.App.Writer, AppHelpTemplate, c.App) - return nil -} - -// DefaultAppComplete prints the list of subcommands as the default app completion method -func DefaultAppComplete(c *Context) { - for _, command := range c.App.Commands { - if command.Hidden { - continue - } - for _, name := range command.Names() { - fmt.Fprintln(c.App.Writer, name) - } - } -} - -// ShowCommandHelp prints help for the given command -func ShowCommandHelp(ctx *Context, command string) error { - // show the subcommand help for a command with subcommands - if command == "" { - HelpPrinter(ctx.App.Writer, SubcommandHelpTemplate, ctx.App) - return nil - } - - for _, c := range ctx.App.Commands { - if c.HasName(command) { - HelpPrinter(ctx.App.Writer, CommandHelpTemplate, c) - return nil - } - } - - if ctx.App.CommandNotFound == nil { - return NewExitError(fmt.Sprintf("No help topic for '%v'", command), 3) - } - - ctx.App.CommandNotFound(ctx, command) - return nil -} - -// ShowSubcommandHelp prints help for the given subcommand -func ShowSubcommandHelp(c *Context) error { - return ShowCommandHelp(c, c.Command.Name) -} - -// ShowVersion prints the version number of the App -func ShowVersion(c *Context) { - VersionPrinter(c) -} - -func printVersion(c *Context) { - fmt.Fprintf(c.App.Writer, "%v version %v\n", c.App.Name, c.App.Version) -} - -// ShowCompletions prints the lists of commands within a given context -func ShowCompletions(c *Context) { - a := c.App - if a != nil && a.BashComplete != nil { - a.BashComplete(c) - } -} - -// ShowCommandCompletions prints the custom completions for a given command -func ShowCommandCompletions(ctx *Context, command string) { - c := ctx.App.Command(command) - if c != nil && c.BashComplete != nil { - c.BashComplete(ctx) - } -} - -func printHelp(out io.Writer, templ string, data interface{}) { - funcMap := template.FuncMap{ - "join": strings.Join, - } - - w := tabwriter.NewWriter(out, 1, 8, 2, ' ', 0) - t := template.Must(template.New("help").Funcs(funcMap).Parse(templ)) - err := t.Execute(w, data) - if err != nil { - // If the writer is closed, t.Execute will fail, and there's nothing - // we can do to recover. - if os.Getenv("CLI_TEMPLATE_ERROR_DEBUG") != "" { - fmt.Fprintf(ErrWriter, "CLI TEMPLATE ERROR: %#v\n", err) - } - return - } - w.Flush() -} - -func checkVersion(c *Context) bool { - found := false - if VersionFlag.Name != "" { - eachName(VersionFlag.Name, func(name string) { - if c.GlobalBool(name) || c.Bool(name) { - found = true - } - }) - } - return found -} - -func checkHelp(c *Context) bool { - found := false - if HelpFlag.Name != "" { - eachName(HelpFlag.Name, func(name string) { - if c.GlobalBool(name) || c.Bool(name) { - found = true - } - }) - } - return found -} - -func checkCommandHelp(c *Context, name string) bool { - if c.Bool("h") || c.Bool("help") { - ShowCommandHelp(c, name) - return true - } - - return false -} - -func checkSubcommandHelp(c *Context) bool { - if c.Bool("h") || c.Bool("help") { - ShowSubcommandHelp(c) - return true - } - - return false -} - -func checkShellCompleteFlag(a *App, arguments []string) (bool, []string) { - if !a.EnableBashCompletion { - return false, arguments - } - - pos := len(arguments) - 1 - lastArg := arguments[pos] - - if lastArg != "--"+BashCompletionFlag.Name { - return false, arguments - } - - return true, arguments[:pos] -} - -func checkCompletions(c *Context) bool { - if !c.shellComplete { - return false - } - - if args := c.Args(); args.Present() { - name := args.First() - if cmd := c.App.Command(name); cmd != nil { - // let the command handle the completion - return false - } - } - - ShowCompletions(c) - return true -} - -func checkCommandCompletions(c *Context, name string) bool { - if !c.shellComplete { - return false - } - - ShowCommandCompletions(c, name) - return true -} diff --git a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/runtests b/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/runtests deleted file mode 100755 index ee22bdee..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/Godeps/_workspace/src/github.com/urfave/cli/runtests +++ /dev/null @@ -1,122 +0,0 @@ -#!/usr/bin/env python -from __future__ import print_function - -import argparse -import os -import sys -import tempfile - -from subprocess import check_call, check_output - - -PACKAGE_NAME = os.environ.get( - 'CLI_PACKAGE_NAME', 'github.com/urfave/cli' -) - - -def main(sysargs=sys.argv[:]): - targets = { - 'vet': _vet, - 'test': _test, - 'gfmrun': _gfmrun, - 'toc': _toc, - 'gen': _gen, - } - - parser = argparse.ArgumentParser() - parser.add_argument( - 'target', nargs='?', choices=tuple(targets.keys()), default='test' - ) - args = parser.parse_args(sysargs[1:]) - - targets[args.target]() - return 0 - - -def _test(): - if check_output('go version'.split()).split()[2] < 'go1.2': - _run('go test -v .') - return - - coverprofiles = [] - for subpackage in ['', 'altsrc']: - coverprofile = 'cli.coverprofile' - if subpackage != '': - coverprofile = '{}.coverprofile'.format(subpackage) - - coverprofiles.append(coverprofile) - - _run('go test -v'.split() + [ - '-coverprofile={}'.format(coverprofile), - ('{}/{}'.format(PACKAGE_NAME, subpackage)).rstrip('/') - ]) - - combined_name = _combine_coverprofiles(coverprofiles) - _run('go tool cover -func={}'.format(combined_name)) - os.remove(combined_name) - - -def _gfmrun(): - go_version = check_output('go version'.split()).split()[2] - if go_version < 'go1.3': - print('runtests: skip on {}'.format(go_version), file=sys.stderr) - return - _run(['gfmrun', '-c', str(_gfmrun_count()), '-s', 'README.md']) - - -def _vet(): - _run('go vet ./...') - - -def _toc(): - _run('node_modules/.bin/markdown-toc -i README.md') - _run('git diff --exit-code') - - -def _gen(): - go_version = check_output('go version'.split()).split()[2] - if go_version < 'go1.5': - print('runtests: skip on {}'.format(go_version), file=sys.stderr) - return - - _run('go generate ./...') - _run('git diff --exit-code') - - -def _run(command): - if hasattr(command, 'split'): - command = command.split() - print('runtests: {}'.format(' '.join(command)), file=sys.stderr) - check_call(command) - - -def _gfmrun_count(): - with open('README.md') as infile: - lines = infile.read().splitlines() - return len(filter(_is_go_runnable, lines)) - - -def _is_go_runnable(line): - return line.startswith('package main') - - -def _combine_coverprofiles(coverprofiles): - combined = tempfile.NamedTemporaryFile( - suffix='.coverprofile', delete=False - ) - combined.write('mode: set\n') - - for coverprofile in coverprofiles: - with open(coverprofile, 'r') as infile: - for line in infile.readlines(): - if not line.startswith('mode: '): - combined.write(line) - - combined.flush() - name = combined.name - combined.close() - return name - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/vendor/github.com/opencontainers/runtime-tools/MAINTAINERS b/vendor/github.com/opencontainers/runtime-tools/MAINTAINERS index 33b9f562..75d24a12 100644 --- a/vendor/github.com/opencontainers/runtime-tools/MAINTAINERS +++ b/vendor/github.com/opencontainers/runtime-tools/MAINTAINERS @@ -1,5 +1,4 @@ Michael Crosby (@crosbymichael) -Alexander Morozov (@LK4D4) Vishnu Kannan (@vishh) Mrunal Patel (@mrunalp) Vincent Batts (@vbatts) diff --git a/vendor/github.com/opencontainers/runtime-tools/Makefile b/vendor/github.com/opencontainers/runtime-tools/Makefile index 25e1e6c5..aeca9665 100644 --- a/vendor/github.com/opencontainers/runtime-tools/Makefile +++ b/vendor/github.com/opencontainers/runtime-tools/Makefile @@ -2,6 +2,7 @@ PREFIX ?= $(DESTDIR)/usr BINDIR ?= $(DESTDIR)/usr/bin BUILDTAGS= +RUNTIME ?= runc RUNTIME_TOOLS_LINK := $(CURDIR)/Godeps/_workspace/src/github.com/opencontainers/runtime-tools export GOPATH:=$(CURDIR)/Godeps/_workspace:$(GOPATH) @@ -35,6 +36,10 @@ clean: $(RUNTIME_TOOLS_LINK): ln -sf $(CURDIR) $(RUNTIME_TOOLS_LINK) +localvalidation: + RUNTIME=$(RUNTIME) go test -tags "$(BUILDTAGS)" ${TESTFLAGS} -v github.com/opencontainers/runtime-tools/validation + + .PHONY: test .gofmt .govet .golint test: .gofmt .govet .golint diff --git a/vendor/github.com/opencontainers/runtime-tools/README.md b/vendor/github.com/opencontainers/runtime-tools/README.md index d8d406d9..2b24c19b 100644 --- a/vendor/github.com/opencontainers/runtime-tools/README.md +++ b/vendor/github.com/opencontainers/runtime-tools/README.md @@ -30,18 +30,48 @@ INFO[0000] Bundle validation succeeded. ## Testing OCI runtimes ```sh -$ make -$ sudo make install -$ sudo ./test_runtime.sh -r runc ------------------------------------------------------------------------------------ -VALIDATING RUNTIME: runc ------------------------------------------------------------------------------------ -validating container process -validating capabilities -validating hostname -validating rlimits -validating sysctls -Runtime runc passed validation +$ sudo make RUNTIME=runc localvalidation +RUNTIME=runc go test -tags "" -v github.com/opencontainers/runtime-tools/validation +=== RUN TestValidateBasic +TAP version 13 +ok 1 - root filesystem +ok 2 - hostname +ok 3 - mounts +ok 4 - capabilities +ok 5 - default symlinks +ok 6 - default devices +ok 7 - linux devices +ok 8 - linux process +ok 9 - masked paths +ok 10 - oom score adj +ok 11 - read only paths +ok 12 - rlimits +ok 13 - sysctls +ok 14 - uid mappings +ok 15 - gid mappings +1..15 +--- PASS: TestValidateBasic (0.08s) +=== RUN TestValidateSysctls +TAP version 13 +ok 1 - root filesystem +ok 2 - hostname +ok 3 - mounts +ok 4 - capabilities +ok 5 - default symlinks +ok 6 - default devices +ok 7 - linux devices +ok 8 - linux process +ok 9 - masked paths +ok 10 - oom score adj +ok 11 - read only paths +ok 12 - rlimits +ok 13 - sysctls +ok 14 - uid mappings +ok 15 - gid mappings +1..15 +--- PASS: TestValidateSysctls (0.20s) +PASS +ok github.com/opencontainers/runtime-tools/validation 0.281s ``` [bundle]: https://github.com/opencontainers/runtime-spec/blob/master/bundle.md diff --git a/vendor/github.com/opencontainers/runtime-tools/cmd/oci-runtime-tool/generate.go b/vendor/github.com/opencontainers/runtime-tools/cmd/oci-runtime-tool/generate.go index 225a16dd..e8aeaec8 100644 --- a/vendor/github.com/opencontainers/runtime-tools/cmd/oci-runtime-tool/generate.go +++ b/vendor/github.com/opencontainers/runtime-tools/cmd/oci-runtime-tool/generate.go @@ -26,6 +26,9 @@ var generateFlags = []cli.Flag{ cli.StringSliceFlag{Name: "cap-drop", Usage: "drop Linux capabilities"}, cli.StringFlag{Name: "cgroups-path", Usage: "specify the path to the cgroups"}, cli.StringFlag{Name: "cwd", Value: "/", Usage: "current working directory for the process"}, + cli.StringSliceFlag{Name: "device-add", Usage: "add a device which must be made available in the container"}, + cli.StringSliceFlag{Name: "device-remove", Usage: "remove a device which must be made available in the container"}, + cli.BoolFlag{Name: "device-remove-all", Usage: "remove all devices which must be made available in the container"}, cli.BoolFlag{Name: "disable-oom-kill", Usage: "disable OOM Killer"}, cli.StringSliceFlag{Name: "env", Usage: "add environment variable e.g. key=value"}, cli.StringSliceFlag{Name: "env-file", Usage: "read in a file of environment variables"}, @@ -51,8 +54,8 @@ var generateFlags = []cli.Flag{ cli.IntFlag{Name: "linux-network-classid", Usage: "specifies class identifier tagged by container's network packets"}, cli.StringSliceFlag{Name: "linux-network-priorities", Usage: "specifies priorities of network traffic"}, cli.Int64Flag{Name: "linux-pids-limit", Usage: "maximum number of PIDs"}, - cli.Uint64Flag{Name: "linux-realtime-period", Usage: "CPU period to be used for realtime scheduling (in usecs)"}, - cli.Uint64Flag{Name: "linux-realtime-runtime", Usage: "the time realtime scheduling may use (in usecs)"}, + cli.Int64Flag{Name: "linux-realtime-period", Usage: "CPU period to be used for realtime scheduling (in usecs)"}, + cli.Int64Flag{Name: "linux-realtime-runtime", Usage: "the time realtime scheduling may use (in usecs)"}, cli.StringSliceFlag{Name: "masked-paths", Usage: "specifies paths can not be read inside container"}, cli.StringFlag{Name: "mount-cgroups", Value: "no", Usage: "mount cgroups (rw,ro,no)"}, cli.StringFlag{Name: "mount-label", Usage: "selinux mount context label"}, @@ -384,11 +387,11 @@ func setupSpec(g *generate.Generator, context *cli.Context) error { } if context.IsSet("linux-cpu-quota") { - g.SetLinuxResourcesCPUQuota(context.Uint64("linux-cpu-quota")) + g.SetLinuxResourcesCPUQuota(context.Int64("linux-cpu-quota")) } if context.IsSet("linux-realtime-runtime") { - g.SetLinuxResourcesCPURealtimeRuntime(context.Uint64("linux-realtime-runtime")) + g.SetLinuxResourcesCPURealtimeRuntime(context.Int64("linux-realtime-runtime")) } if context.IsSet("linux-pids-limit") { @@ -501,6 +504,31 @@ func setupSpec(g *generate.Generator, context *cli.Context) error { g.ClearProcessRlimits() } + if context.IsSet("device-add") { + devices := context.StringSlice("device-add") + for _, deviceArg := range devices { + dev, err := parseDevice(deviceArg, g) + if err != nil { + return err + } + g.AddDevice(dev) + } + } + + if context.IsSet("device-remove") { + devices := context.StringSlice("device-remove") + for _, device := range devices { + err := g.RemoveDevice(device) + if err != nil { + return err + } + } + } + + if context.Bool("device-remove-all") { + g.ClearLinuxDevices() + } + err := addSeccomp(context, g) return err } @@ -625,6 +653,85 @@ func parseNamespace(ns string) (string, string, error) { return nsType, nsPath, nil } +var deviceType = map[string]bool{ + "b": true, // a block (buffered) special file + "c": true, // a character special file + "u": true, // a character (unbuffered) special file + "p": true, // a FIFO +} + +// parseDevice takes the raw string passed with the --device-add flag +func parseDevice(device string, g *generate.Generator) (rspec.LinuxDevice, error) { + dev := rspec.LinuxDevice{} + + // The required part and optional part are separated by ":" + argsParts := strings.Split(device, ":") + if len(argsParts) < 4 { + return dev, fmt.Errorf("Incomplete device arguments: %s", device) + } + requiredPart := argsParts[0:4] + optionalPart := argsParts[4:] + + // The required part must contain type, major, minor, and path + dev.Type = requiredPart[0] + if !deviceType[dev.Type] { + return dev, fmt.Errorf("Invalid device type: %s", dev.Type) + } + + i, err := strconv.ParseInt(requiredPart[1], 10, 64) + if err != nil { + return dev, err + } + dev.Major = i + + i, err = strconv.ParseInt(requiredPart[2], 10, 64) + if err != nil { + return dev, err + } + dev.Minor = i + dev.Path = requiredPart[3] + + // The optional part include all optional property + for _, s := range optionalPart { + parts := strings.SplitN(s, "=", 2) + + if len(parts) != 2 { + return dev, fmt.Errorf("Incomplete device arguments: %s", s) + } + + name, value := parts[0], parts[1] + + switch name { + case "fileMode": + i, err := strconv.ParseInt(value, 10, 32) + if err != nil { + return dev, err + } + mode := os.FileMode(i) + dev.FileMode = &mode + case "uid": + i, err := strconv.ParseInt(value, 10, 32) + if err != nil { + return dev, err + } + uid := uint32(i) + dev.UID = &uid + + case "gid": + i, err := strconv.ParseInt(value, 10, 32) + if err != nil { + return dev, err + } + gid := uint32(i) + dev.GID = &gid + default: + return dev, fmt.Errorf("'%s' is not supported by device section", name) + } + } + + return dev, nil +} + func addSeccomp(context *cli.Context, g *generate.Generator) error { // Set the DefaultAction of seccomp diff --git a/vendor/github.com/opencontainers/runtime-tools/cmd/oci-runtime-tool/validate.go b/vendor/github.com/opencontainers/runtime-tools/cmd/oci-runtime-tool/validate.go index 60b767f9..a07741e9 100644 --- a/vendor/github.com/opencontainers/runtime-tools/cmd/oci-runtime-tool/validate.go +++ b/vendor/github.com/opencontainers/runtime-tools/cmd/oci-runtime-tool/validate.go @@ -4,9 +4,8 @@ import ( "fmt" "strings" - "github.com/urfave/cli" - "github.com/opencontainers/runtime-tools/validate" + "github.com/urfave/cli" ) var bundleValidateFlags = []cli.Flag{ diff --git a/vendor/github.com/opencontainers/runtime-tools/cmd/runtimetest/main.go b/vendor/github.com/opencontainers/runtime-tools/cmd/runtimetest/main.go index 371052c3..0aaa5e2c 100644 --- a/vendor/github.com/opencontainers/runtime-tools/cmd/runtimetest/main.go +++ b/vendor/github.com/opencontainers/runtime-tools/cmd/runtimetest/main.go @@ -29,13 +29,6 @@ const PR_GET_NO_NEW_PRIVS = 39 const specConfig = "config.json" var ( - defaultFS = map[string]string{ - "/proc": "proc", - "/sys": "sysfs", - "/dev/pts": "devpts", - "/dev/shm": "tmpfs", - } - defaultSymlinks = map[string]string{ "/dev/fd": "/proc/self/fd", "/dev/stdin": "/proc/self/fd/0", @@ -129,7 +122,7 @@ func validateLinuxProcess(spec *rspec.Spec) error { } } - cmdlineBytes, err := ioutil.ReadFile("/proc/1/cmdline") + cmdlineBytes, err := ioutil.ReadFile("/proc/self/cmdline") if err != nil { return err } @@ -167,14 +160,30 @@ func validateCapabilities(spec *rspec.Spec) error { last = capability.CAP_BLOCK_SUSPEND } - processCaps, err := capability.NewPid(1) + processCaps, err := capability.NewPid(0) if err != nil { return err } - expectedCaps := make(map[string]bool) - for _, ec := range spec.Process.Capabilities { - expectedCaps[ec] = true + expectedCaps1 := make(map[string]bool) + expectedCaps2 := make(map[string]bool) + expectedCaps3 := make(map[string]bool) + expectedCaps4 := make(map[string]bool) + expectedCaps5 := make(map[string]bool) + for _, ec := range spec.Process.Capabilities.Bounding { + expectedCaps1[ec] = true + } + for _, ec := range spec.Process.Capabilities.Effective { + expectedCaps2[ec] = true + } + for _, ec := range spec.Process.Capabilities.Inheritable { + expectedCaps3[ec] = true + } + for _, ec := range spec.Process.Capabilities.Permitted { + expectedCaps4[ec] = true + } + for _, ec := range spec.Process.Capabilities.Ambient { + expectedCaps5[ec] = true } for _, cap := range capability.List() { @@ -183,13 +192,45 @@ func validateCapabilities(spec *rspec.Spec) error { } capKey := fmt.Sprintf("CAP_%s", strings.ToUpper(cap.String())) - expectedSet := expectedCaps[capKey] - actuallySet := processCaps.Get(capability.EFFECTIVE, cap) + expectedSet := expectedCaps1[capKey] + actuallySet := processCaps.Get(capability.BOUNDING, cap) if expectedSet != actuallySet { if expectedSet { - return fmt.Errorf("Expected Capability %v not set for process", cap.String()) + return fmt.Errorf("Expected bounding capability %v not set for process", cap.String()) } - return fmt.Errorf("Unexpected Capability %v set for process", cap.String()) + return fmt.Errorf("Unexpected bounding capability %v set for process", cap.String()) + } + expectedSet = expectedCaps2[capKey] + actuallySet = processCaps.Get(capability.EFFECTIVE, cap) + if expectedSet != actuallySet { + if expectedSet { + return fmt.Errorf("Expected effective capability %v not set for process", cap.String()) + } + return fmt.Errorf("Unexpected effective capability %v set for process", cap.String()) + } + expectedSet = expectedCaps3[capKey] + actuallySet = processCaps.Get(capability.INHERITABLE, cap) + if expectedSet != actuallySet { + if expectedSet { + return fmt.Errorf("Expected inheritable capability %v not set for process", cap.String()) + } + return fmt.Errorf("Unexpected inheritable capability %v set for process", cap.String()) + } + expectedSet = expectedCaps4[capKey] + actuallySet = processCaps.Get(capability.PERMITTED, cap) + if expectedSet != actuallySet { + if expectedSet { + return fmt.Errorf("Expected permitted capability %v not set for process", cap.String()) + } + return fmt.Errorf("Unexpected permitted capability %v set for process", cap.String()) + } + expectedSet = expectedCaps5[capKey] + actuallySet = processCaps.Get(capability.AMBIENT, cap) + if expectedSet != actuallySet { + if expectedSet { + return fmt.Errorf("Expected ambient capability %v not set for process", cap.String()) + } + return fmt.Errorf("Unexpected ambient capability %v set for process", cap.String()) } } @@ -271,28 +312,6 @@ func validateRootFS(spec *rspec.Spec) error { return nil } -func validateDefaultFS(spec *rspec.Spec) error { - logrus.Debugf("validating linux default filesystem") - - mountInfos, err := mount.GetMounts() - if err != nil { - return err - } - - mountsMap := make(map[string]string) - for _, mountInfo := range mountInfos { - mountsMap[mountInfo.Mountpoint] = mountInfo.Fstype - } - - for fs, fstype := range defaultFS { - if !(mountsMap[fs] == fstype) { - return fmt.Errorf("%v must exist and expected type is %v", fs, fstype) - } - } - - return nil -} - func validateLinuxDevices(spec *rspec.Spec) error { logrus.Debugf("validating linux devices") @@ -309,13 +328,10 @@ func validateLinuxDevices(spec *rspec.Spec) error { switch fStat.Mode & syscall.S_IFMT { case syscall.S_IFCHR: devType = "c" - break case syscall.S_IFBLK: devType = "b" - break case syscall.S_IFIFO: devType = "p" - break default: devType = "unmatched" } @@ -455,8 +471,8 @@ func validateOOMScoreAdj(spec *rspec.Spec) error { return nil } -func getIDMappings(path string) ([]rspec.IDMapping, error) { - var idMaps []rspec.IDMapping +func getIDMappings(path string) ([]rspec.LinuxIDMapping, error) { + var idMaps []rspec.LinuxIDMapping f, err := os.Open(path) if err != nil { return nil, err @@ -483,7 +499,7 @@ func getIDMappings(path string) ([]rspec.IDMapping, error) { if err != nil { return nil, err } - idMaps = append(idMaps, rspec.IDMapping{HostID: uint32(hostID), ContainerID: uint32(containerID), Size: uint32(mapSize)}) + idMaps = append(idMaps, rspec.LinuxIDMapping{HostID: uint32(hostID), ContainerID: uint32(containerID), Size: uint32(mapSize)}) } else { return nil, fmt.Errorf("invalid format in %v", path) } @@ -492,7 +508,7 @@ func getIDMappings(path string) ([]rspec.IDMapping, error) { return idMaps, nil } -func validateIDMappings(mappings []rspec.IDMapping, path string, property string) error { +func validateIDMappings(mappings []rspec.LinuxIDMapping, path string, property string) error { idMaps, err := getIDMappings(path) if err != nil { return fmt.Errorf("can not get items: %v", err) @@ -615,10 +631,6 @@ func validate(context *cli.Context) error { test: validateDefaultSymlinks, description: "default symlinks", }, - { - test: validateDefaultFS, - description: "default file system", - }, { test: validateDefaultDevices, description: "default devices", diff --git a/vendor/github.com/opencontainers/runtime-tools/completions/bash/oci-runtime-tool b/vendor/github.com/opencontainers/runtime-tools/completions/bash/oci-runtime-tool index 6327425a..08195346 100644 --- a/vendor/github.com/opencontainers/runtime-tools/completions/bash/oci-runtime-tool +++ b/vendor/github.com/opencontainers/runtime-tools/completions/bash/oci-runtime-tool @@ -94,12 +94,12 @@ __oci-runtime-tool_subcommands() { # List groups __oci-runtime-tool_groups() { - cat /etc/group | cut -d: -f 1 + cut -d: -f 1 /etc/group } # List installed hooks __oci-runtime-tool_hooks() { - ls /usr/libexec/oci/hooks.d/* + ls /usr/libexec/oci/hooks.d/* } # suppress trailing whitespace @@ -137,6 +137,14 @@ __oci-runtime-tool_complete_arches() { 386 amd64 arm + arm64 + mips + mips64 + mips64le + mipsle + ppc64 + ppc64le + s390x " -- "$cur" ) ) } @@ -160,6 +168,8 @@ __oci-runtime-tool_complete_seccomp_arches() { ppc64le s390 s390x + parisc + parisc64 " -- "$cur" ) ) } @@ -227,8 +237,7 @@ _oci-runtime-tool_oci-runtime-tool() { " local boolean_options=" - $global_boolean_options - --help + --help -h --host-specific --version -v " @@ -236,23 +245,18 @@ _oci-runtime-tool_oci-runtime-tool() { local all_options="$options_with_args $boolean_options" case "$prev" in - $(__oci-runtime-tool_to_extglob "$global_options_with_args") ) - return - ;; - --log-level) __oci-runtime-tool_complete_log_level return ;; - esac case "$cur" in -*) - COMPREPLY=( $( compgen -W "$all_options $global_options_with_args" -- "$cur" ) ) + COMPREPLY=( $( compgen -W "$all_options" -- "$cur" ) ) ;; *) - local counter=$( __oci-runtime-tool_pos_first_nonflag $(__oci-runtime-tool_to_extglob "$global_options_with_args") ) + local counter=$( __oci-runtime-tool_pos_first_nonflag $(__oci-runtime-tool_to_extglob "$options_with_args") ) if [ $cword -eq $counter ]; then COMPREPLY=( $( compgen -W "${commands[*]} help" -- "$cur" ) ) fi @@ -282,7 +286,7 @@ _oci-runtime-tool_validate() { case "$cur" in -*) - COMPREPLY=( $( compgen -W "--path --help" -- "$cur" ) ) + COMPREPLY=( $( compgen -W "--path --help -h" -- "$cur" ) ) ;; esac @@ -305,6 +309,8 @@ _oci-runtime-tool_generate() { --cap-drop --cgroups-path --cwd + --device-add + --device-remove --env --env-file --gid @@ -362,7 +368,9 @@ _oci-runtime-tool_generate() { " local boolean_options=" + --device-remove-all --disable-oom-kill + --help -h --linux-namespace-remove-all --no-new-privileges --privileged @@ -376,23 +384,8 @@ _oci-runtime-tool_generate() { local all_options="$options_with_args $boolean_options" case "$prev" in - --seccomp-arch) - __oci-runtime-tool_complete_seccomp_arches - return - ;; - --arch) - __oci-runtime-tool_complete_arches - return - ;; - - --seccomp-default) - __oci-runtime-tool_complete_seccomp_actions - return - ;; - - --root-propagation) - __oci-runtime-tool_complete_propagations + __oci-runtime-tool_complete_arches return ;; @@ -401,13 +394,20 @@ _oci-runtime-tool_generate() { return ;; - --mount-cgroups) - COMPREPLY=( $( compgen -W "ro" -- "$cur" ) ) + --env|-e) + COMPREPLY=( $( compgen -e -- "$cur" ) ) + __oci-runtime-tool_nospace return ;; - --os) - COMPREPLY=( $( compgen -W "linux windows" -- "$cur" ) ) + --env-file) + _filedir + __oci-runtime-tool_nospace + return + ;; + + --gid) + _gids return ;; @@ -417,12 +417,27 @@ _oci-runtime-tool_generate() { return ;; + --mount-cgroups) + COMPREPLY=( $( compgen -W "no ro rw" -- "$cur" ) ) + return + ;; + + --os) + COMPREPLY=( $( compgen -W "linux windows" -- "$cur" ) ) + return + ;; + --poststart|--poststop|--prestart) COMPREPLY=( $( compgen -W "$( __oci-runtime-tool_hooks )" -- "$cur" ) ) __oci-runtime-tool_nospace return ;; + --root-propagation) + __oci-runtime-tool_complete_propagations + return + ;; + --rootfs|--tmpfs|--bind|--cwd) case "$cur" in *:*) @@ -439,17 +454,19 @@ _oci-runtime-tool_generate() { esac return ;; - --env|-e) - COMPREPLY=( $( compgen -e -- "$cur" ) ) - __oci-runtime-tool_nospace + + --seccomp-arch) + __oci-runtime-tool_complete_seccomp_arches return ;; - --env-file) - _filedir - __oci-runtime-tool_nospace - return - ;; - $(__oci-runtime-tool_to_extglob "$options_with_args") ) + + --seccomp-default) + __oci-runtime-tool_complete_seccomp_actions + return + ;; + + --uid) + _uids return ;; esac @@ -470,17 +487,6 @@ _oci-runtime-tool() { generate ) - # These options are valid as global options for all client commands - # and valid as command options for `oci-runtime-tool daemon` - local global_boolean_options=" - --help -h - --version -v - " - - local global_options_with_args=" - --help - " - COMPREPLY=() local cur prev words cword _get_comp_words_by_ref -n : cur prev words cword diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/generate.go b/vendor/github.com/opencontainers/runtime-tools/generate/generate.go index 60d92adc..737cd9e0 100644 --- a/vendor/github.com/opencontainers/runtime-tools/generate/generate.go +++ b/vendor/github.com/opencontainers/runtime-tools/generate/generate.go @@ -11,6 +11,7 @@ import ( rspec "github.com/opencontainers/runtime-spec/specs-go" "github.com/opencontainers/runtime-tools/generate/seccomp" + "github.com/opencontainers/runtime-tools/validate" "github.com/syndtr/gocapability/capability" ) @@ -53,23 +54,89 @@ func New() Generator { "TERM=xterm", }, Cwd: "/", - Capabilities: []string{ - "CAP_CHOWN", - "CAP_DAC_OVERRIDE", - "CAP_FSETID", - "CAP_FOWNER", - "CAP_MKNOD", - "CAP_NET_RAW", - "CAP_SETGID", - "CAP_SETUID", - "CAP_SETFCAP", - "CAP_SETPCAP", - "CAP_NET_BIND_SERVICE", - "CAP_SYS_CHROOT", - "CAP_KILL", - "CAP_AUDIT_WRITE", + Capabilities: &rspec.LinuxCapabilities{ + Bounding: []string{ + "CAP_CHOWN", + "CAP_DAC_OVERRIDE", + "CAP_FSETID", + "CAP_FOWNER", + "CAP_MKNOD", + "CAP_NET_RAW", + "CAP_SETGID", + "CAP_SETUID", + "CAP_SETFCAP", + "CAP_SETPCAP", + "CAP_NET_BIND_SERVICE", + "CAP_SYS_CHROOT", + "CAP_KILL", + "CAP_AUDIT_WRITE", + }, + Permitted: []string{ + "CAP_CHOWN", + "CAP_DAC_OVERRIDE", + "CAP_FSETID", + "CAP_FOWNER", + "CAP_MKNOD", + "CAP_NET_RAW", + "CAP_SETGID", + "CAP_SETUID", + "CAP_SETFCAP", + "CAP_SETPCAP", + "CAP_NET_BIND_SERVICE", + "CAP_SYS_CHROOT", + "CAP_KILL", + "CAP_AUDIT_WRITE", + }, + Inheritable: []string{ + "CAP_CHOWN", + "CAP_DAC_OVERRIDE", + "CAP_FSETID", + "CAP_FOWNER", + "CAP_MKNOD", + "CAP_NET_RAW", + "CAP_SETGID", + "CAP_SETUID", + "CAP_SETFCAP", + "CAP_SETPCAP", + "CAP_NET_BIND_SERVICE", + "CAP_SYS_CHROOT", + "CAP_KILL", + "CAP_AUDIT_WRITE", + }, + Effective: []string{ + "CAP_CHOWN", + "CAP_DAC_OVERRIDE", + "CAP_FSETID", + "CAP_FOWNER", + "CAP_MKNOD", + "CAP_NET_RAW", + "CAP_SETGID", + "CAP_SETUID", + "CAP_SETFCAP", + "CAP_SETPCAP", + "CAP_NET_BIND_SERVICE", + "CAP_SYS_CHROOT", + "CAP_KILL", + "CAP_AUDIT_WRITE", + }, + Ambient: []string{ + "CAP_CHOWN", + "CAP_DAC_OVERRIDE", + "CAP_FSETID", + "CAP_FOWNER", + "CAP_MKNOD", + "CAP_NET_RAW", + "CAP_SETGID", + "CAP_SETUID", + "CAP_SETFCAP", + "CAP_SETPCAP", + "CAP_NET_BIND_SERVICE", + "CAP_SYS_CHROOT", + "CAP_KILL", + "CAP_AUDIT_WRITE", + }, }, - Rlimits: []rspec.Rlimit{ + Rlimits: []rspec.LinuxRlimit{ { Type: "RLIMIT_NOFILE", Hard: uint64(1024), @@ -117,15 +184,15 @@ func New() Generator { }, }, Linux: &rspec.Linux{ - Resources: &rspec.Resources{ - Devices: []rspec.DeviceCgroup{ + Resources: &rspec.LinuxResources{ + Devices: []rspec.LinuxDeviceCgroup{ { Allow: false, - Access: strPtr("rwm"), + Access: "rwm", }, }, }, - Namespaces: []rspec.Namespace{ + Namespaces: []rspec.LinuxNamespace{ { Type: "pid", }, @@ -142,7 +209,7 @@ func New() Generator { Type: "mount", }, }, - Devices: []rspec.Device{}, + Devices: []rspec.LinuxDevice{}, }, } spec.Linux.Seccomp = seccomp.DefaultProfile(&spec) @@ -367,7 +434,7 @@ func (g *Generator) AddProcessRlimits(rType string, rHard uint64, rSoft uint64) } } - newRlimit := rspec.Rlimit{ + newRlimit := rspec.LinuxRlimit{ Type: rType, Hard: rHard, Soft: rSoft, @@ -394,7 +461,7 @@ func (g *Generator) ClearProcessRlimits() { if g.spec == nil { return } - g.spec.Process.Rlimits = []rspec.Rlimit{} + g.spec.Process.Rlimits = []rspec.LinuxRlimit{} } // ClearProcessAdditionalGids clear g.spec.Process.AdditionalGids. @@ -425,7 +492,7 @@ func (g *Generator) SetProcessSelinuxLabel(label string) { // SetLinuxCgroupsPath sets g.spec.Linux.CgroupsPath. func (g *Generator) SetLinuxCgroupsPath(path string) { g.initSpecLinux() - g.spec.Linux.CgroupsPath = strPtr(path) + g.spec.Linux.CgroupsPath = path } // SetLinuxMountLabel sets g.spec.Linux.MountLabel. @@ -453,7 +520,7 @@ func (g *Generator) SetLinuxResourcesCPUShares(shares uint64) { } // SetLinuxResourcesCPUQuota sets g.spec.Linux.Resources.CPU.Quota. -func (g *Generator) SetLinuxResourcesCPUQuota(quota uint64) { +func (g *Generator) SetLinuxResourcesCPUQuota(quota int64) { g.initSpecLinuxResourcesCPU() g.spec.Linux.Resources.CPU.Quota = "a } @@ -465,7 +532,7 @@ func (g *Generator) SetLinuxResourcesCPUPeriod(period uint64) { } // SetLinuxResourcesCPURealtimeRuntime sets g.spec.Linux.Resources.CPU.RealtimeRuntime. -func (g *Generator) SetLinuxResourcesCPURealtimeRuntime(time uint64) { +func (g *Generator) SetLinuxResourcesCPURealtimeRuntime(time int64) { g.initSpecLinuxResourcesCPU() g.spec.Linux.Resources.CPU.RealtimeRuntime = &time } @@ -479,13 +546,13 @@ func (g *Generator) SetLinuxResourcesCPURealtimePeriod(period uint64) { // SetLinuxResourcesCPUCpus sets g.spec.Linux.Resources.CPU.Cpus. func (g *Generator) SetLinuxResourcesCPUCpus(cpus string) { g.initSpecLinuxResourcesCPU() - g.spec.Linux.Resources.CPU.Cpus = &cpus + g.spec.Linux.Resources.CPU.Cpus = cpus } // SetLinuxResourcesCPUMems sets g.spec.Linux.Resources.CPU.Mems. func (g *Generator) SetLinuxResourcesCPUMems(mems string) { g.initSpecLinuxResourcesCPU() - g.spec.Linux.Resources.CPU.Mems = &mems + g.spec.Linux.Resources.CPU.Mems = mems } // SetLinuxResourcesMemoryLimit sets g.spec.Linux.Resources.Memory.Limit. @@ -539,7 +606,7 @@ func (g *Generator) AddLinuxResourcesNetworkPriorities(name string, prio uint32) return } } - interfacePrio := new(rspec.InterfacePriority) + interfacePrio := new(rspec.LinuxInterfacePriority) interfacePrio.Name = name interfacePrio.Priority = prio g.spec.Linux.Resources.Network.Priorities = append(g.spec.Linux.Resources.Network.Priorities, *interfacePrio) @@ -559,7 +626,7 @@ func (g *Generator) DropLinuxResourcesNetworkPriorities(name string) { // SetLinuxResourcesPidsLimit sets g.spec.Linux.Resources.Pids.Limit. func (g *Generator) SetLinuxResourcesPidsLimit(limit int64) { g.initSpecLinuxResourcesPids() - g.spec.Linux.Resources.Pids.Limit = &limit + g.spec.Linux.Resources.Pids.Limit = limit } // ClearLinuxSysctl clears g.spec.Linux.Sysctl. @@ -589,12 +656,12 @@ func (g *Generator) ClearLinuxUIDMappings() { if g.spec == nil || g.spec.Linux == nil { return } - g.spec.Linux.UIDMappings = []rspec.IDMapping{} + g.spec.Linux.UIDMappings = []rspec.LinuxIDMapping{} } // AddLinuxUIDMapping adds uidMap into g.spec.Linux.UIDMappings. func (g *Generator) AddLinuxUIDMapping(hid, cid, size uint32) { - idMapping := rspec.IDMapping{ + idMapping := rspec.LinuxIDMapping{ HostID: hid, ContainerID: cid, Size: size, @@ -609,12 +676,12 @@ func (g *Generator) ClearLinuxGIDMappings() { if g.spec == nil || g.spec.Linux == nil { return } - g.spec.Linux.GIDMappings = []rspec.IDMapping{} + g.spec.Linux.GIDMappings = []rspec.LinuxIDMapping{} } // AddLinuxGIDMapping adds gidMap into g.spec.Linux.GIDMappings. func (g *Generator) AddLinuxGIDMapping(hid, cid, size uint32) { - idMapping := rspec.IDMapping{ + idMapping := rspec.LinuxIDMapping{ HostID: hid, ContainerID: cid, Size: size, @@ -705,7 +772,6 @@ func (g *Generator) AddCgroupsMount(mountCgroupOption string) error { switch mountCgroupOption { case "ro": case "rw": - break case "no": return nil default: @@ -755,92 +821,125 @@ func (g *Generator) AddBindMount(source, dest string, options []string) { // SetupPrivileged sets up the privilege-related fields inside g.spec. func (g *Generator) SetupPrivileged(privileged bool) { - if privileged { - // Add all capabilities in privileged mode. + if privileged { // Add all capabilities in privileged mode. var finalCapList []string for _, cap := range capability.List() { - if g.HostSpecific && cap > lastCap() { + if g.HostSpecific && cap > validate.LastCap() { continue } finalCapList = append(finalCapList, fmt.Sprintf("CAP_%s", strings.ToUpper(cap.String()))) } g.initSpecLinux() - g.spec.Process.Capabilities = finalCapList + g.spec.Process.Capabilities.Bounding = finalCapList + g.spec.Process.Capabilities.Effective = finalCapList + g.spec.Process.Capabilities.Inheritable = finalCapList + g.spec.Process.Capabilities.Permitted = finalCapList + g.spec.Process.Capabilities.Ambient = finalCapList g.spec.Process.SelinuxLabel = "" g.spec.Process.ApparmorProfile = "" g.spec.Linux.Seccomp = nil } } -func lastCap() capability.Cap { - last := capability.CAP_LAST_CAP - // hack for RHEL6 which has no /proc/sys/kernel/cap_last_cap - if last == capability.Cap(63) { - last = capability.CAP_BLOCK_SUSPEND - } - - return last -} - -func checkCap(c string, hostSpecific bool) error { - isValid := false - cp := strings.ToUpper(c) - - for _, cap := range capability.List() { - if cp == strings.ToUpper(cap.String()) { - if hostSpecific && cap > lastCap() { - return fmt.Errorf("CAP_%s is not supported on the current host", cp) - } - isValid = true - break - } - } - - if !isValid { - return fmt.Errorf("Invalid value passed for adding capability") - } - return nil -} - // ClearProcessCapabilities clear g.spec.Process.Capabilities. func (g *Generator) ClearProcessCapabilities() { if g.spec == nil { return } - g.spec.Process.Capabilities = []string{} + g.spec.Process.Capabilities.Bounding = []string{} + g.spec.Process.Capabilities.Effective = []string{} + g.spec.Process.Capabilities.Inheritable = []string{} + g.spec.Process.Capabilities.Permitted = []string{} + g.spec.Process.Capabilities.Ambient = []string{} } // AddProcessCapability adds a process capability into g.spec.Process.Capabilities. func (g *Generator) AddProcessCapability(c string) error { - if err := checkCap(c, g.HostSpecific); err != nil { + cp := strings.ToUpper(c) + if err := validate.CapValid(cp, g.HostSpecific); err != nil { return err } - cp := fmt.Sprintf("CAP_%s", strings.ToUpper(c)) - g.initSpec() - for _, cap := range g.spec.Process.Capabilities { + + for _, cap := range g.spec.Process.Capabilities.Bounding { if strings.ToUpper(cap) == cp { return nil } } + g.spec.Process.Capabilities.Bounding = append(g.spec.Process.Capabilities.Bounding, cp) + + for _, cap := range g.spec.Process.Capabilities.Effective { + if strings.ToUpper(cap) == cp { + return nil + } + } + g.spec.Process.Capabilities.Effective = append(g.spec.Process.Capabilities.Effective, cp) + + for _, cap := range g.spec.Process.Capabilities.Inheritable { + if strings.ToUpper(cap) == cp { + return nil + } + } + g.spec.Process.Capabilities.Inheritable = append(g.spec.Process.Capabilities.Inheritable, cp) + + for _, cap := range g.spec.Process.Capabilities.Permitted { + if strings.ToUpper(cap) == cp { + return nil + } + } + g.spec.Process.Capabilities.Permitted = append(g.spec.Process.Capabilities.Permitted, cp) + + for _, cap := range g.spec.Process.Capabilities.Ambient { + if strings.ToUpper(cap) == cp { + return nil + } + } + g.spec.Process.Capabilities.Ambient = append(g.spec.Process.Capabilities.Ambient, cp) - g.spec.Process.Capabilities = append(g.spec.Process.Capabilities, cp) return nil } // DropProcessCapability drops a process capability from g.spec.Process.Capabilities. func (g *Generator) DropProcessCapability(c string) error { - if err := checkCap(c, g.HostSpecific); err != nil { + cp := strings.ToUpper(c) + if err := validate.CapValid(cp, g.HostSpecific); err != nil { return err } - cp := fmt.Sprintf("CAP_%s", strings.ToUpper(c)) - g.initSpec() - for i, cap := range g.spec.Process.Capabilities { + + for i, cap := range g.spec.Process.Capabilities.Bounding { if strings.ToUpper(cap) == cp { - g.spec.Process.Capabilities = append(g.spec.Process.Capabilities[:i], g.spec.Process.Capabilities[i+1:]...) + g.spec.Process.Capabilities.Bounding = append(g.spec.Process.Capabilities.Bounding[:i], g.spec.Process.Capabilities.Bounding[i+1:]...) + return nil + } + } + + for i, cap := range g.spec.Process.Capabilities.Effective { + if strings.ToUpper(cap) == cp { + g.spec.Process.Capabilities.Effective = append(g.spec.Process.Capabilities.Effective[:i], g.spec.Process.Capabilities.Effective[i+1:]...) + return nil + } + } + + for i, cap := range g.spec.Process.Capabilities.Inheritable { + if strings.ToUpper(cap) == cp { + g.spec.Process.Capabilities.Inheritable = append(g.spec.Process.Capabilities.Inheritable[:i], g.spec.Process.Capabilities.Inheritable[i+1:]...) + return nil + } + } + + for i, cap := range g.spec.Process.Capabilities.Permitted { + if strings.ToUpper(cap) == cp { + g.spec.Process.Capabilities.Permitted = append(g.spec.Process.Capabilities.Permitted[:i], g.spec.Process.Capabilities.Permitted[i+1:]...) + return nil + } + } + + for i, cap := range g.spec.Process.Capabilities.Ambient { + if strings.ToUpper(cap) == cp { + g.spec.Process.Capabilities.Ambient = append(g.spec.Process.Capabilities.Ambient[:i], g.spec.Process.Capabilities.Ambient[i+1:]...) return nil } } @@ -848,24 +947,24 @@ func (g *Generator) DropProcessCapability(c string) error { return nil } -func mapStrToNamespace(ns string, path string) (rspec.Namespace, error) { +func mapStrToNamespace(ns string, path string) (rspec.LinuxNamespace, error) { switch ns { case "network": - return rspec.Namespace{Type: rspec.NetworkNamespace, Path: path}, nil + return rspec.LinuxNamespace{Type: rspec.NetworkNamespace, Path: path}, nil case "pid": - return rspec.Namespace{Type: rspec.PIDNamespace, Path: path}, nil + return rspec.LinuxNamespace{Type: rspec.PIDNamespace, Path: path}, nil case "mount": - return rspec.Namespace{Type: rspec.MountNamespace, Path: path}, nil + return rspec.LinuxNamespace{Type: rspec.MountNamespace, Path: path}, nil case "ipc": - return rspec.Namespace{Type: rspec.IPCNamespace, Path: path}, nil + return rspec.LinuxNamespace{Type: rspec.IPCNamespace, Path: path}, nil case "uts": - return rspec.Namespace{Type: rspec.UTSNamespace, Path: path}, nil + return rspec.LinuxNamespace{Type: rspec.UTSNamespace, Path: path}, nil case "user": - return rspec.Namespace{Type: rspec.UserNamespace, Path: path}, nil + return rspec.LinuxNamespace{Type: rspec.UserNamespace, Path: path}, nil case "cgroup": - return rspec.Namespace{Type: rspec.CgroupNamespace, Path: path}, nil + return rspec.LinuxNamespace{Type: rspec.CgroupNamespace, Path: path}, nil default: - return rspec.Namespace{}, fmt.Errorf("Should not reach here!") + return rspec.LinuxNamespace{}, fmt.Errorf("Should not reach here!") } } @@ -874,7 +973,7 @@ func (g *Generator) ClearLinuxNamespaces() { if g.spec == nil || g.spec.Linux == nil { return } - g.spec.Linux.Namespaces = []rspec.Namespace{} + g.spec.Linux.Namespaces = []rspec.LinuxNamespace{} } // AddOrReplaceLinuxNamespace adds or replaces a namespace inside @@ -915,6 +1014,46 @@ func (g *Generator) RemoveLinuxNamespace(ns string) error { return nil } +// AddDevice - add a device into g.spec.Linux.Devices +func (g *Generator) AddDevice(device rspec.LinuxDevice) { + g.initSpecLinux() + + for i, dev := range g.spec.Linux.Devices { + if dev.Path == device.Path { + g.spec.Linux.Devices[i] = device + return + } + if dev.Type == device.Type && dev.Major == device.Major && dev.Minor == device.Minor { + fmt.Fprintln(os.Stderr, "WARNING: The same type, major and minor should not be used for multiple devices.") + } + } + + g.spec.Linux.Devices = append(g.spec.Linux.Devices, device) +} + +//RemoveDevice remove a device from g.spec.Linux.Devices +func (g *Generator) RemoveDevice(path string) error { + if g.spec == nil || g.spec.Linux == nil || g.spec.Linux.Devices == nil { + return nil + } + + for i, device := range g.spec.Linux.Devices { + if device.Path == path { + g.spec.Linux.Devices = append(g.spec.Linux.Devices[:i], g.spec.Linux.Devices[i+1:]...) + return nil + } + } + return nil +} + +func (g *Generator) ClearLinuxDevices() { + if g.spec == nil || g.spec.Linux == nil || g.spec.Linux.Devices == nil { + return + } + + g.spec.Linux.Devices = []rspec.LinuxDevice{} +} + // strPtr returns the pointer pointing to the string s. func strPtr(s string) *string { return &s } diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_action.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_action.go index 13cace24..853b9c23 100644 --- a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_action.go +++ b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_action.go @@ -20,7 +20,7 @@ type SyscallOpts struct { // ParseSyscallFlag takes a SyscallOpts struct and the seccomp configuration // and sets the new syscall rule accordingly -func ParseSyscallFlag(args SyscallOpts, config *rspec.Seccomp) error { +func ParseSyscallFlag(args SyscallOpts, config *rspec.LinuxSeccomp) error { var arguments []string if args.Index != "" && args.Value != "" && args.ValueTwo != "" && args.Operator != "" { arguments = []string{args.Action, args.Syscall, args.Index, args.Value, @@ -34,7 +34,7 @@ func ParseSyscallFlag(args SyscallOpts, config *rspec.Seccomp) error { return fmt.Errorf("default action already set as %s", action) } - var newSyscall rspec.Syscall + var newSyscall rspec.LinuxSyscall numOfArgs := len(arguments) if numOfArgs == 6 || numOfArgs == 2 { argStruct, err := parseArguments(arguments[1:]) @@ -67,7 +67,7 @@ func ParseSyscallFlag(args SyscallOpts, config *rspec.Seccomp) error { return nil } -var actions = map[string]rspec.Action{ +var actions = map[string]rspec.LinuxSeccompAction{ "allow": rspec.ActAllow, "errno": rspec.ActErrno, "kill": rspec.ActKill, @@ -76,7 +76,7 @@ var actions = map[string]rspec.Action{ } // Take passed action, return the SCMP_ACT_ version of it -func parseAction(action string) (rspec.Action, error) { +func parseAction(action string) (rspec.LinuxSeccompAction, error) { a, ok := actions[action] if !ok { return "", fmt.Errorf("unrecognized action: %s", action) @@ -86,7 +86,7 @@ func parseAction(action string) (rspec.Action, error) { // ParseDefaultAction sets the default action of the seccomp configuration // and then removes any rules that were already specified with this action -func ParseDefaultAction(action string, config *rspec.Seccomp) error { +func ParseDefaultAction(action string, config *rspec.LinuxSeccomp) error { if action == "" { return nil } @@ -104,7 +104,7 @@ func ParseDefaultAction(action string, config *rspec.Seccomp) error { } // ParseDefaultActionForce simply sets the default action of the seccomp configuration -func ParseDefaultActionForce(action string, config *rspec.Seccomp) error { +func ParseDefaultActionForce(action string, config *rspec.LinuxSeccomp) error { if action == "" { return nil } @@ -117,9 +117,9 @@ func ParseDefaultActionForce(action string, config *rspec.Seccomp) error { return nil } -func newSyscallStruct(name string, action rspec.Action, args []rspec.Arg) rspec.Syscall { - syscallStruct := rspec.Syscall{ - Name: name, +func newSyscallStruct(name string, action rspec.LinuxSeccompAction, args []rspec.LinuxSeccompArg) rspec.LinuxSyscall { + syscallStruct := rspec.LinuxSyscall{ + Names: []string{name}, Action: action, Args: args, } diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_architecture.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_architecture.go index 9d45fabc..9b2bdfd2 100644 --- a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_architecture.go +++ b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_architecture.go @@ -8,7 +8,7 @@ import ( // ParseArchitectureFlag takes the raw string passed with the --arch flag, parses it // and updates the Seccomp config accordingly -func ParseArchitectureFlag(architectureArg string, config *rspec.Seccomp) error { +func ParseArchitectureFlag(architectureArg string, config *rspec.LinuxSeccomp) error { correctedArch, err := parseArch(architectureArg) if err != nil { return err @@ -39,6 +39,8 @@ func parseArch(arch string) (rspec.Arch, error) { "mipsel": rspec.ArchMIPSEL, "mipsel64": rspec.ArchMIPSEL64, "mipsel64n32": rspec.ArchMIPSEL64N32, + "parisc": rspec.ArchPARISC, + "parisc64": rspec.ArchPARISC64, "ppc": rspec.ArchPPC, "ppc64": rspec.ArchPPC64, "ppc64le": rspec.ArchPPC64LE, diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_arguments.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_arguments.go index 72f0b13d..2b4c394e 100644 --- a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_arguments.go +++ b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_arguments.go @@ -9,8 +9,8 @@ import ( // parseArguments takes a list of arguments (delimArgs). It parses and fills out // the argument information and returns a slice of arg structs -func parseArguments(delimArgs []string) ([]rspec.Arg, error) { - nilArgSlice := []rspec.Arg{} +func parseArguments(delimArgs []string) ([]rspec.LinuxSeccompArg, error) { + nilArgSlice := []rspec.LinuxSeccompArg{} numberOfArgs := len(delimArgs) // No parameters passed with syscall @@ -40,14 +40,14 @@ func parseArguments(delimArgs []string) ([]rspec.Arg, error) { return nilArgSlice, err } - argStruct := rspec.Arg{ + argStruct := rspec.LinuxSeccompArg{ Index: uint(syscallIndex), Value: syscallValue, ValueTwo: syscallValueTwo, Op: syscallOp, } - argSlice := []rspec.Arg{} + argSlice := []rspec.LinuxSeccompArg{} argSlice = append(argSlice, argStruct) return argSlice, nil } @@ -55,8 +55,8 @@ func parseArguments(delimArgs []string) ([]rspec.Arg, error) { return nilArgSlice, fmt.Errorf("incorrect number of arguments passed with syscall: %d", numberOfArgs) } -func parseOperator(operator string) (rspec.Operator, error) { - operators := map[string]rspec.Operator{ +func parseOperator(operator string) (rspec.LinuxSeccompOperator, error) { + operators := map[string]rspec.LinuxSeccompOperator{ "NE": rspec.OpNotEqual, "LT": rspec.OpLessThan, "LE": rspec.OpLessEqual, diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_remove.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_remove.go index ce68e66d..ef5870e9 100644 --- a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_remove.go +++ b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_remove.go @@ -10,7 +10,7 @@ import ( // RemoveAction takes the argument string that was passed with the --remove flag, // parses it, and updates the Seccomp config accordingly -func RemoveAction(arguments string, config *rspec.Seccomp) error { +func RemoveAction(arguments string, config *rspec.LinuxSeccomp) error { if config == nil { return fmt.Errorf("Cannot remove action from nil Seccomp pointer") } @@ -22,28 +22,27 @@ func RemoveAction(arguments string, config *rspec.Seccomp) error { syscallsToRemove = append(syscallsToRemove, arguments) } - for _, syscall := range syscallsToRemove { - for counter, syscallStruct := range config.Syscalls { - if syscallStruct.Name == syscall { - config.Syscalls = append(config.Syscalls[:counter], config.Syscalls[counter+1:]...) - } + for counter, syscallStruct := range config.Syscalls { + if reflect.DeepEqual(syscallsToRemove, syscallStruct.Names) { + config.Syscalls = append(config.Syscalls[:counter], config.Syscalls[counter+1:]...) } } + return nil } // RemoveAllSeccompRules removes all seccomp syscall rules -func RemoveAllSeccompRules(config *rspec.Seccomp) error { +func RemoveAllSeccompRules(config *rspec.LinuxSeccomp) error { if config == nil { return fmt.Errorf("Cannot remove action from nil Seccomp pointer") } - newSyscallSlice := []rspec.Syscall{} + newSyscallSlice := []rspec.LinuxSyscall{} config.Syscalls = newSyscallSlice return nil } // RemoveAllMatchingRules will remove any syscall rules that match the specified action -func RemoveAllMatchingRules(config *rspec.Seccomp, action string) error { +func RemoveAllMatchingRules(config *rspec.LinuxSeccomp, action string) error { if config == nil { return fmt.Errorf("Cannot remove action from nil Seccomp pointer") } @@ -53,16 +52,11 @@ func RemoveAllMatchingRules(config *rspec.Seccomp, action string) error { return err } - syscallsToRemove := []string{} for _, syscall := range config.Syscalls { if reflect.DeepEqual(syscall.Action, seccompAction) { - syscallsToRemove = append(syscallsToRemove, syscall.Name) + RemoveAction(strings.Join(syscall.Names, ","), config) } } - for i := range syscallsToRemove { - RemoveAction(syscallsToRemove[i], config) - } - return nil } diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default.go index 2e1d4687..8f57f6ab 100644 --- a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default.go +++ b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default.go @@ -32,851 +32,333 @@ func arches() []rspec.Arch { } // DefaultProfile defines the whitelist for the default seccomp profile. -func DefaultProfile(rs *specs.Spec) *rspec.Seccomp { +func DefaultProfile(rs *specs.Spec) *rspec.LinuxSeccomp { - syscalls := []rspec.Syscall{ - { - Name: "accept", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "accept4", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "access", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "alarm", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "bind", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "brk", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "capget", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "capset", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "chdir", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "chmod", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "chown", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "chown32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - - { - Name: "clock_getres", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "clock_gettime", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "clock_nanosleep", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "close", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "connect", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "copy_file_range", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "creat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "dup", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "dup2", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "dup3", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "epoll_create", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "epoll_create1", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "epoll_ctl", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "epoll_ctl_old", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "epoll_pwait", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "epoll_wait", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "epoll_wait_old", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "eventfd", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "eventfd2", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "execve", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "execveat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "exit", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "exit_group", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "faccessat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fadvise64", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fadvise64_64", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fallocate", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fanotify_mark", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fchdir", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fchmod", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fchmodat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fchown", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fchown32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fchownat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fcntl", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fcntl64", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fdatasync", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fgetxattr", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "flistxattr", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "flock", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fork", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fremovexattr", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fsetxattr", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fstat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fstat64", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fstatat64", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fstatfs", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fstatfs64", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fsync", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "ftruncate", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "ftruncate64", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "futex", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "futimesat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getcpu", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getcwd", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getdents", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getdents64", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getegid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getegid32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "geteuid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "geteuid32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getgid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getgid32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getgroups", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getgroups32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getitimer", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getpeername", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getpgid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getpgrp", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getpid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getppid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getpriority", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getrandom", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getresgid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getresgid32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getresuid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getresuid32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getrlimit", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "get_robust_list", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getrusage", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getsid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getsockname", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getsockopt", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "get_thread_area", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "gettid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "gettimeofday", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getuid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getuid32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "getxattr", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "inotify_add_watch", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "inotify_init", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "inotify_init1", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "inotify_rm_watch", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "io_cancel", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "ioctl", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "io_destroy", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "io_getevents", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "ioprio_get", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "ioprio_set", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "io_setup", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "io_submit", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "ipc", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "kill", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "lchown", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "lchown32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "lgetxattr", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "link", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "linkat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "listen", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "listxattr", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "llistxattr", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "_llseek", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "lremovexattr", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "lseek", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "lsetxattr", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "lstat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "lstat64", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "madvise", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "memfd_create", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mincore", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mkdir", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mkdirat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mknod", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mknodat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mlock", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mlock2", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mlockall", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mmap", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mmap2", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mprotect", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mq_getsetattr", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mq_notify", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mq_open", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mq_timedreceive", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mq_timedsend", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mq_unlink", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mremap", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "msgctl", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "msgget", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "msgrcv", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "msgsnd", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "msync", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "munlock", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "munlockall", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "munmap", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "nanosleep", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "newfstatat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "_newselect", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "open", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "openat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "pause", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "personality", - Action: rspec.ActAllow, - Args: []rspec.Arg{ + syscalls := []rspec.LinuxSyscall{ + { + Names: []string{ + "accept", + "accept4", + "access", + "alarm", + "bind", + "brk", + "capget", + "capset", + "chdir", + "chmod", + "chown", + "chown32", + "clock_getres", + "clock_gettime", + "clock_nanosleep", + "close", + "connect", + "copy_file_range", + "creat", + "dup", + "dup2", + "dup3", + "epoll_create", + "epoll_create1", + "epoll_ctl", + "epoll_ctl_old", + "epoll_pwait", + "epoll_wait", + "epoll_wait_old", + "eventfd", + "eventfd2", + "execve", + "execveat", + "exit", + "exit_group", + "faccessat", + "fadvise64", + "fadvise64_64", + "fallocate", + "fanotify_mark", + "fchdir", + "fchmod", + "fchmodat", + "fchown", + "fchown32", + "fchownat", + "fcntl", + "fcntl64", + "fdatasync", + "fgetxattr", + "flistxattr", + "flock", + "fork", + "fremovexattr", + "fsetxattr", + "fstat", + "fstat64", + "fstatat64", + "fstatfs", + "fstatfs64", + "fsync", + "ftruncate", + "ftruncate64", + "futex", + "futimesat", + "getcpu", + "getcwd", + "getdents", + "getdents64", + "getegid", + "getegid32", + "geteuid", + "geteuid32", + "getgid", + "getgid32", + "getgroups", + "getgroups32", + "getitimer", + "getpeername", + "getpgid", + "getpgrp", + "getpid", + "getppid", + "getpriority", + "getrandom", + "getresgid", + "getresgid32", + "getresuid", + "getresuid32", + "getrlimit", + "get_robust_list", + "getrusage", + "getsid", + "getsockname", + "getsockopt", + "get_thread_area", + "gettid", + "gettimeofday", + "getuid", + "getuid32", + "getxattr", + "inotify_add_watch", + "inotify_init", + "inotify_init1", + "inotify_rm_watch", + "io_cancel", + "ioctl", + "io_destroy", + "io_getevents", + "ioprio_get", + "ioprio_set", + "io_setup", + "io_submit", + "ipc", + "kill", + "lchown", + "lchown32", + "lgetxattr", + "link", + "linkat", + "listen", + "listxattr", + "llistxattr", + "_llseek", + "lremovexattr", + "lseek", + "lsetxattr", + "lstat", + "lstat64", + "madvise", + "memfd_create", + "mincore", + "mkdir", + "mkdirat", + "mknod", + "mknodat", + "mlock", + "mlock2", + "mlockall", + "mmap", + "mmap2", + "mprotect", + "mq_getsetattr", + "mq_notify", + "mq_open", + "mq_timedreceive", + "mq_timedsend", + "mq_unlink", + "mremap", + "msgctl", + "msgget", + "msgrcv", + "msgsnd", + "msync", + "munlock", + "munlockall", + "munmap", + "nanosleep", + "newfstatat", + "_newselect", + "open", + "openat", + "pause", + "pipe", + "pipe2", + "poll", + "ppoll", + "prctl", + "pread64", + "preadv", + "prlimit64", + "pselect6", + "pwrite64", + "pwritev", + "read", + "readahead", + "readlink", + "readlinkat", + "readv", + "recv", + "recvfrom", + "recvmmsg", + "recvmsg", + "remap_file_pages", + "removexattr", + "rename", + "renameat", + "renameat2", + "restart_syscall", + "rmdir", + "rt_sigaction", + "rt_sigpending", + "rt_sigprocmask", + "rt_sigqueueinfo", + "rt_sigreturn", + "rt_sigsuspend", + "rt_sigtimedwait", + "rt_tgsigqueueinfo", + "sched_getaffinity", + "sched_getattr", + "sched_getparam", + "sched_get_priority_max", + "sched_get_priority_min", + "sched_getscheduler", + "sched_rr_get_interval", + "sched_setaffinity", + "sched_setattr", + "sched_setparam", + "sched_setscheduler", + "sched_yield", + "seccomp", + "select", + "semctl", + "semget", + "semop", + "semtimedop", + "send", + "sendfile", + "sendfile64", + "sendmmsg", + "sendmsg", + "sendto", + "setfsgid", + "setfsgid32", + "setfsuid", + "setfsuid32", + "setgid", + "setgid32", + "setgroups", + "setgroups32", + "setitimer", + "setpgid", + "setpriority", + "setregid", + "setregid32", + "setresgid", + "setresgid32", + "setresuid", + "setresuid32", + "setreuid", + "setreuid32", + "setrlimit", + "set_robust_list", + "setsid", + "setsockopt", + "set_thread_area", + "set_tid_address", + "setuid", + "setuid32", + "setxattr", + "shmat", + "shmctl", + "shmdt", + "shmget", + "shutdown", + "sigaltstack", + "signalfd", + "signalfd4", + "sigreturn", + "socket", + "socketcall", + "socketpair", + "splice", + "stat", + "stat64", + "statfs", + "statfs64", + "symlink", + "symlinkat", + "sync", + "sync_file_range", + "syncfs", + "sysinfo", + "syslog", + "tee", + "tgkill", + "time", + "timer_create", + "timer_delete", + "timerfd_create", + "timerfd_gettime", + "timerfd_settime", + "timer_getoverrun", + "timer_gettime", + "timer_settime", + "times", + "tkill", + "truncate", + "truncate64", + "ugetrlimit", + "umask", + "uname", + "unlink", + "unlinkat", + "utime", + "utimensat", + "utimes", + "vfork", + "vmsplice", + "wait4", + "waitid", + "waitpid", + "write", + "writev", + }, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{}, + }, + { + Names: []string{"personality"}, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{ { Index: 0, Value: 0x0, Op: rspec.OpEqualTo, }, - }, - }, - { - Name: "personality", - Action: rspec.ActAllow, - Args: []rspec.Arg{ { Index: 0, Value: 0x0008, Op: rspec.OpEqualTo, }, - }, - }, - { - Name: "personality", - Action: rspec.ActAllow, - Args: []rspec.Arg{ { Index: 0, Value: 0xffffffff, @@ -884,914 +366,152 @@ func DefaultProfile(rs *specs.Spec) *rspec.Seccomp { }, }, }, - { - Name: "pipe", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "pipe2", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "poll", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "ppoll", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "prctl", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "pread64", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "preadv", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "prlimit64", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "pselect6", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "pwrite64", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "pwritev", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "read", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "readahead", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "readlink", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "readlinkat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "readv", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "recv", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "recvfrom", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "recvmmsg", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "recvmsg", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "remap_file_pages", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "removexattr", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "rename", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "renameat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "renameat2", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "restart_syscall", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "rmdir", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "rt_sigaction", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "rt_sigpending", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "rt_sigprocmask", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "rt_sigqueueinfo", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "rt_sigreturn", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "rt_sigsuspend", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "rt_sigtimedwait", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "rt_tgsigqueueinfo", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sched_getaffinity", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sched_getattr", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sched_getparam", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sched_get_priority_max", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sched_get_priority_min", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sched_getscheduler", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sched_rr_get_interval", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sched_setaffinity", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sched_setattr", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sched_setparam", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sched_setscheduler", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sched_yield", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "seccomp", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "select", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "semctl", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "semget", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "semop", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "semtimedop", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "send", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sendfile", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sendfile64", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sendmmsg", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sendmsg", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sendto", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setfsgid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setfsgid32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setfsuid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setfsuid32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setgid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setgid32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setgroups", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setgroups32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setitimer", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setpgid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setpriority", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setregid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setregid32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setresgid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setresgid32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setresuid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setresuid32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setreuid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setreuid32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setrlimit", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "set_robust_list", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setsid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setsockopt", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "set_thread_area", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "set_tid_address", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setuid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setuid32", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setxattr", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "shmat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "shmctl", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "shmdt", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "shmget", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "shutdown", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sigaltstack", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "signalfd", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "signalfd4", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sigreturn", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "socket", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "socketcall", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "socketpair", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "splice", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "stat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "stat64", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "statfs", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "statfs64", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "symlink", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "symlinkat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sync", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sync_file_range", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "syncfs", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sysinfo", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "syslog", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "tee", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "tgkill", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "time", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "timer_create", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "timer_delete", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "timerfd_create", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "timerfd_gettime", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "timerfd_settime", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "timer_getoverrun", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "timer_gettime", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "timer_settime", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "times", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "tkill", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "truncate", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "truncate64", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "ugetrlimit", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "umask", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "uname", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "unlink", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "unlinkat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "utime", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "utimensat", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "utimes", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "vfork", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "vmsplice", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "wait4", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "waitid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "waitpid", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "write", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "writev", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, } var sysCloneFlagsIndex uint capSysAdmin := false var cap string + var caps []string - for _, cap = range rs.Process.Capabilities { + for _, cap = range rs.Process.Capabilities.Bounding { + caps = append(caps, cap) + } + for _, cap = range rs.Process.Capabilities.Effective { + caps = append(caps, cap) + } + for _, cap = range rs.Process.Capabilities.Inheritable { + caps = append(caps, cap) + } + for _, cap = range rs.Process.Capabilities.Permitted { + caps = append(caps, cap) + } + for _, cap = range rs.Process.Capabilities.Ambient { + caps = append(caps, cap) + } + + for _, cap = range caps { switch cap { case "CAP_DAC_READ_SEARCH": - syscalls = append(syscalls, []rspec.Syscall{ + syscalls = append(syscalls, []rspec.LinuxSyscall{ { - Name: "open_by_handle_at", + Names: []string{"open_by_handle_at"}, Action: rspec.ActAllow, - Args: []rspec.Arg{}, + Args: []rspec.LinuxSeccompArg{}, }, }...) case "CAP_SYS_ADMIN": capSysAdmin = true - syscalls = append(syscalls, []rspec.Syscall{ + syscalls = append(syscalls, []rspec.LinuxSyscall{ { - Name: "bpf", + Names: []string{ + "bpf", + "clone", + "fanotify_init", + "lookup_dcookie", + "mount", + "name_to_handle_at", + "perf_event_open", + "setdomainname", + "sethostname", + "setns", + "umount", + "umount2", + "unshare", + }, Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "clone", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "fanotify_init", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "lookup_dcookie", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "mount", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "name_to_handle_at", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "perf_event_open", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setdomainname", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "sethostname", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "setns", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "umount", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "umount2", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "unshare", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, + Args: []rspec.LinuxSeccompArg{}, }, }...) case "CAP_SYS_BOOT": - syscalls = append(syscalls, []rspec.Syscall{ + syscalls = append(syscalls, []rspec.LinuxSyscall{ { - Name: "reboot", + Names: []string{"reboot"}, Action: rspec.ActAllow, - Args: []rspec.Arg{}, + Args: []rspec.LinuxSeccompArg{}, }, }...) case "CAP_SYS_CHROOT": - syscalls = append(syscalls, []rspec.Syscall{ + syscalls = append(syscalls, []rspec.LinuxSyscall{ { - Name: "chroot", + Names: []string{"chroot"}, Action: rspec.ActAllow, - Args: []rspec.Arg{}, + Args: []rspec.LinuxSeccompArg{}, }, }...) case "CAP_SYS_MODULE": - syscalls = append(syscalls, []rspec.Syscall{ + syscalls = append(syscalls, []rspec.LinuxSyscall{ { - Name: "delete_module", + Names: []string{ + "delete_module", + "init_module", + "finit_module", + "query_module", + }, Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "init_module", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "finit_module", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "query_module", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, + Args: []rspec.LinuxSeccompArg{}, }, }...) case "CAP_SYS_PACCT": - syscalls = append(syscalls, []rspec.Syscall{ + syscalls = append(syscalls, []rspec.LinuxSyscall{ { - Name: "acct", + Names: []string{"acct"}, Action: rspec.ActAllow, - Args: []rspec.Arg{}, + Args: []rspec.LinuxSeccompArg{}, }, }...) case "CAP_SYS_PTRACE": - syscalls = append(syscalls, []rspec.Syscall{ + syscalls = append(syscalls, []rspec.LinuxSyscall{ { - Name: "kcmp", + Names: []string{ + "kcmp", + "process_vm_readv", + "process_vm_writev", + "ptrace", + }, Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "process_vm_readv", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "process_vm_writev", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "ptrace", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, + Args: []rspec.LinuxSeccompArg{}, }, }...) case "CAP_SYS_RAWIO": - syscalls = append(syscalls, []rspec.Syscall{ + syscalls = append(syscalls, []rspec.LinuxSyscall{ { - Name: "iopl", + Names: []string{ + "iopl", + "ioperm", + }, Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "ioperm", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, + Args: []rspec.LinuxSeccompArg{}, }, }...) case "CAP_SYS_TIME": - syscalls = append(syscalls, []rspec.Syscall{ + syscalls = append(syscalls, []rspec.LinuxSyscall{ { - Name: "settimeofday", + Names: []string{ + "settimeofday", + "stime", + "adjtimex", + }, Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "stime", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "adjtimex", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, + Args: []rspec.LinuxSeccompArg{}, }, }...) case "CAP_SYS_TTY_CONFIG": - syscalls = append(syscalls, []rspec.Syscall{ + syscalls = append(syscalls, []rspec.LinuxSyscall{ { - Name: "vhangup", + Names: []string{"vhangup"}, Action: rspec.ActAllow, - Args: []rspec.Arg{}, + Args: []rspec.LinuxSeccompArg{}, }, }...) } } if !capSysAdmin { - syscalls = append(syscalls, []rspec.Syscall{ + syscalls = append(syscalls, []rspec.LinuxSyscall{ { - Name: "clone", + Names: []string{"clone"}, Action: rspec.ActAllow, - Args: []rspec.Arg{ + Args: []rspec.LinuxSeccompArg{ { Index: sysCloneFlagsIndex, Value: syscall.CLONE_NEWNS | syscall.CLONE_NEWUTS | syscall.CLONE_NEWIPC | syscall.CLONE_NEWUSER | syscall.CLONE_NEWPID | syscall.CLONE_NEWNET, @@ -1807,62 +527,50 @@ func DefaultProfile(rs *specs.Spec) *rspec.Seccomp { arch := runtime.GOARCH switch arch { case "arm", "arm64": - syscalls = append(syscalls, []rspec.Syscall{ + syscalls = append(syscalls, []rspec.LinuxSyscall{ { - Name: "breakpoint", + Names: []string{ + "breakpoint", + "cacheflush", + "set_tls", + }, Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "cacheflush", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "set_tls", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, + Args: []rspec.LinuxSeccompArg{}, }, }...) case "amd64", "x32": - syscalls = append(syscalls, []rspec.Syscall{ + syscalls = append(syscalls, []rspec.LinuxSyscall{ { - Name: "arch_prctl", + Names: []string{"arch_prctl"}, Action: rspec.ActAllow, - Args: []rspec.Arg{}, + Args: []rspec.LinuxSeccompArg{}, }, }...) fallthrough case "x86": - syscalls = append(syscalls, []rspec.Syscall{ + syscalls = append(syscalls, []rspec.LinuxSyscall{ { - Name: "modify_ldt", + Names: []string{"modify_ldt"}, Action: rspec.ActAllow, - Args: []rspec.Arg{}, + Args: []rspec.LinuxSeccompArg{}, }, }...) case "s390", "s390x": - syscalls = append(syscalls, []rspec.Syscall{ + syscalls = append(syscalls, []rspec.LinuxSyscall{ { - Name: "s390_pci_mmio_read", + Names: []string{ + "s390_pci_mmio_read", + "s390_pci_mmio_write", + "s390_runtime_instr", + }, Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "s390_pci_mmio_write", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, - }, - { - Name: "s390_runtime_instr", - Action: rspec.ActAllow, - Args: []rspec.Arg{}, + Args: []rspec.LinuxSeccompArg{}, }, }...) /* Flags parameter of the clone syscall is the 2nd on s390 */ } - return &rspec.Seccomp{ + return &rspec.LinuxSeccomp{ DefaultAction: rspec.ActErrno, Architectures: arches(), Syscalls: syscalls, diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/syscall_compare.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/syscall_compare.go index 01dc2e30..dbf2aec1 100644 --- a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/syscall_compare.go +++ b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/syscall_compare.go @@ -11,12 +11,12 @@ import ( // Determine if a new syscall rule should be appended, overwrite an existing rule // or if no action should be taken at all -func decideCourseOfAction(newSyscall *rspec.Syscall, syscalls []rspec.Syscall) (string, error) { +func decideCourseOfAction(newSyscall *rspec.LinuxSyscall, syscalls []rspec.LinuxSyscall) (string, error) { ruleForSyscallAlreadyExists := false var sliceOfDeterminedActions []string for i, syscall := range syscalls { - if syscall.Name == newSyscall.Name { + if sameName(&syscall, newSyscall) { ruleForSyscallAlreadyExists = true if identical(newSyscall, &syscall) { @@ -83,16 +83,16 @@ func decideCourseOfAction(newSyscall *rspec.Syscall, syscalls []rspec.Syscall) ( return "", fmt.Errorf("Trouble determining action: %s", sliceOfDeterminedActions) } -func hasArguments(config *rspec.Syscall) bool { - nilSyscall := new(rspec.Syscall) +func hasArguments(config *rspec.LinuxSyscall) bool { + nilSyscall := new(rspec.LinuxSyscall) return !sameArgs(nilSyscall, config) } -func identical(config1, config2 *rspec.Syscall) bool { +func identical(config1, config2 *rspec.LinuxSyscall) bool { return reflect.DeepEqual(config1, config2) } -func identicalExceptAction(config1, config2 *rspec.Syscall) bool { +func identicalExceptAction(config1, config2 *rspec.LinuxSyscall) bool { samename := sameName(config1, config2) sameAction := sameAction(config1, config2) sameArgs := sameArgs(config1, config2) @@ -100,7 +100,7 @@ func identicalExceptAction(config1, config2 *rspec.Syscall) bool { return samename && !sameAction && sameArgs } -func identicalExceptArgs(config1, config2 *rspec.Syscall) bool { +func identicalExceptArgs(config1, config2 *rspec.LinuxSyscall) bool { samename := sameName(config1, config2) sameAction := sameAction(config1, config2) sameArgs := sameArgs(config1, config2) @@ -108,33 +108,33 @@ func identicalExceptArgs(config1, config2 *rspec.Syscall) bool { return samename && sameAction && !sameArgs } -func sameName(config1, config2 *rspec.Syscall) bool { - return config1.Name == config2.Name +func sameName(config1, config2 *rspec.LinuxSyscall) bool { + return reflect.DeepEqual(config1.Names, config2.Names) } -func sameAction(config1, config2 *rspec.Syscall) bool { +func sameAction(config1, config2 *rspec.LinuxSyscall) bool { return config1.Action == config2.Action } -func sameArgs(config1, config2 *rspec.Syscall) bool { +func sameArgs(config1, config2 *rspec.LinuxSyscall) bool { return reflect.DeepEqual(config1.Args, config2.Args) } -func bothHaveArgs(config1, config2 *rspec.Syscall) bool { +func bothHaveArgs(config1, config2 *rspec.LinuxSyscall) bool { return hasArguments(config1) && hasArguments(config2) } -func onlyOneHasArgs(config1, config2 *rspec.Syscall) bool { +func onlyOneHasArgs(config1, config2 *rspec.LinuxSyscall) bool { conf1 := hasArguments(config1) conf2 := hasArguments(config2) return (conf1 && !conf2) || (!conf1 && conf2) } -func neitherHasArgs(config1, config2 *rspec.Syscall) bool { +func neitherHasArgs(config1, config2 *rspec.LinuxSyscall) bool { return !hasArguments(config1) && !hasArguments(config2) } -func firstParamOnlyHasArgs(config1, config2 *rspec.Syscall) bool { +func firstParamOnlyHasArgs(config1, config2 *rspec.LinuxSyscall) bool { return !hasArguments(config1) && hasArguments(config2) } diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/spec.go b/vendor/github.com/opencontainers/runtime-tools/generate/spec.go index 657ed8b2..4498aa14 100644 --- a/vendor/github.com/opencontainers/runtime-tools/generate/spec.go +++ b/vendor/github.com/opencontainers/runtime-tools/generate/spec.go @@ -34,41 +34,41 @@ func (g *Generator) initSpecLinuxSysctl() { func (g *Generator) initSpecLinuxSeccomp() { g.initSpecLinux() if g.spec.Linux.Seccomp == nil { - g.spec.Linux.Seccomp = &rspec.Seccomp{} + g.spec.Linux.Seccomp = &rspec.LinuxSeccomp{} } } func (g *Generator) initSpecLinuxResources() { g.initSpecLinux() if g.spec.Linux.Resources == nil { - g.spec.Linux.Resources = &rspec.Resources{} + g.spec.Linux.Resources = &rspec.LinuxResources{} } } func (g *Generator) initSpecLinuxResourcesCPU() { g.initSpecLinuxResources() if g.spec.Linux.Resources.CPU == nil { - g.spec.Linux.Resources.CPU = &rspec.CPU{} + g.spec.Linux.Resources.CPU = &rspec.LinuxCPU{} } } func (g *Generator) initSpecLinuxResourcesMemory() { g.initSpecLinuxResources() if g.spec.Linux.Resources.Memory == nil { - g.spec.Linux.Resources.Memory = &rspec.Memory{} + g.spec.Linux.Resources.Memory = &rspec.LinuxMemory{} } } func (g *Generator) initSpecLinuxResourcesNetwork() { g.initSpecLinuxResources() if g.spec.Linux.Resources.Network == nil { - g.spec.Linux.Resources.Network = &rspec.Network{} + g.spec.Linux.Resources.Network = &rspec.LinuxNetwork{} } } func (g *Generator) initSpecLinuxResourcesPids() { g.initSpecLinuxResources() if g.spec.Linux.Resources.Pids == nil { - g.spec.Linux.Resources.Pids = &rspec.Pids{} + g.spec.Linux.Resources.Pids = &rspec.LinuxPids{} } } diff --git a/vendor/github.com/opencontainers/runtime-tools/man/oci-runtime-tool-generate.1.md b/vendor/github.com/opencontainers/runtime-tools/man/oci-runtime-tool-generate.1.md index 43f74f8e..32bdcffa 100644 --- a/vendor/github.com/opencontainers/runtime-tools/man/oci-runtime-tool-generate.1.md +++ b/vendor/github.com/opencontainers/runtime-tools/man/oci-runtime-tool-generate.1.md @@ -51,6 +51,24 @@ read the configuration from `config.json`. **--cwd**=PATH Current working directory for the process. The deafult is */*. +**--device-add**=*TYPE:MAJOR:MINOR:PATH[:OPTIONS...]* + Add a device file in container. e.g. --device=c:10:229:/dev/fuse:fileMode=438:uid=0:gid=0 + The *TYPE*, *MAJOR*, *MINOR*, *PATH* are required. + *TYPE* is the device type. The acceptable values are b (block), c (character), u (unbuffered), p (FIFO). + *MAJOR*/*MINOR* is the major/minor device id. + *PATH* is the device path. + The *fileMode*, *uid*, *gid* are optional. + *fileMode* is the file mode of the device file. + *uid*/*gid* is the user/group id of the device file. + This option can be specified multiple times. + +**--device-remove**=*PATH* + Remove a device file in container. + This option can be specified multiple times. + +**--device-remove-all**=true|false + Remove all devices for linux inside the container. The default is *false*. + **--disable-oom-kill**=true|false Whether to disable OOM Killer for the container or not. @@ -322,19 +340,19 @@ During container image development, containers often need to write to the image content. Installing packages into /usr, for example. In production, applications seldom need to write to the image. Container applications write to volumes if they need to write to file systems at all. Applications can be -made more secure by generating them in read-only mode using the --read-only switch. +made more secure by generating them in read-only mode using the --rootfs-readonly switch. This protects the containers image from modification. Read only containers may still need to write temporary data. The best way to handle this is to mount tmpfs directories on /generate and /tmp. - # oci-runtime-tool generate --read-only --tmpfs /generate --tmpfs /tmp --tmpfs /run --rootfs /var/lib/containers/fedora /bin/bash + $ oci-runtime-tool generate --rootfs-readonly --tmpfs /generate --tmpfs /tmp --tmpfs /run --rootfs-path /var/lib/containers/fedora --args bash ## Exposing log messages from the container to the host's log If you want messages that are logged in your container to show up in the host's syslog/journal then you should bind mount the /dev/log directory as follows. - # oci-runtime-tool generate --bind /dev/log:/dev/log --rootfs /var/lib/containers/fedora /bin/bash + $ oci-runtime-tool generate --bind /dev/log:/dev/log --rootfs-path /var/lib/containers/fedora --args bash From inside the container you can test this by sending a message to the log. @@ -354,13 +372,13 @@ To mount a host directory as a container volume, specify the absolute path to the directory and the absolute path for the container directory separated by a colon: - # oci-runtime-tool generate --bind /var/db:/data1 --rootfs /var/lib/containers/fedora --args bash + $ oci-runtime-tool generate --bind /var/db:/data1 --rootfs-path /var/lib/containers/fedora --args bash ## Using SELinux You can use SELinux to add security to the container. You must specify the process label to run the init process inside of the container using the --selinux-label. - # oci-runtime-tool generate --bind /var/db:/data1 --selinux-label system_u:system_r:svirt_lxc_net_t:s0:c1,c2 --mount-label system_u:object_r:svirt_sandbox_file_t:s0:c1,c2 --rootfs /var/lib/containers/fedora --args bash + $ oci-runtime-tool generate --bind /var/db:/data1 --selinux-label system_u:system_r:svirt_lxc_net_t:s0:c1,c2 --mount-label system_u:object_r:svirt_sandbox_file_t:s0:c1,c2 --rootfs-path /var/lib/containers/fedora --args bash Not in the above example we used a type of svirt_lxc_net_t and an MCS Label of s0:c1,c2. If you want to guarantee separation between containers, you need to make sure that each container gets launched with a different MCS Label pair. diff --git a/vendor/github.com/opencontainers/runtime-tools/man/oci-runtime-tool.1.md b/vendor/github.com/opencontainers/runtime-tools/man/oci-runtime-tool.1.md index b63d31b6..27b2e170 100644 --- a/vendor/github.com/opencontainers/runtime-tools/man/oci-runtime-tool.1.md +++ b/vendor/github.com/opencontainers/runtime-tools/man/oci-runtime-tool.1.md @@ -38,11 +38,11 @@ oci-runtime-tool is a collection of tools for working with the [OCI runtime spec # COMMANDS **validate** Validating OCI bundle - See **oci-runtime-tool-validate(1)** for full documentation on the **validate** command. + See **oci-runtime-tool-validate**(1) for full documentation on the **validate** command. **generate** Generating OCI runtime spec configuration files - See **oci-runtime-tool-generate(1)** for full documentation on the **generate** command. + See **oci-runtime-tool-generate**(1) for full documentation on the **generate** command. # SEE ALSO **oci-runtime-tool-validate**(1), **oci-runtime-tool-generate**(1) diff --git a/vendor/github.com/opencontainers/runtime-tools/test_runtime.sh b/vendor/github.com/opencontainers/runtime-tools/test_runtime.sh deleted file mode 100755 index c1ed0b15..00000000 --- a/vendor/github.com/opencontainers/runtime-tools/test_runtime.sh +++ /dev/null @@ -1,89 +0,0 @@ -#!/bin/bash -set -o errexit -set -o nounset -set -o pipefail - -BASH="${BASH_VERSION%.*}" -BASH_MAJOR="${BASH%.*}" -BASH_MINOR="${BASH#*.}" - -if test "${BASH_MAJOR}" -eq 3 && test "${BASH_MINOR}" -eq 0 -then - echo "ERROR: ${0} requires Bash version >= 3.1" >&2 - echo "you're running ${BASH}, which doesn't support += array assignment" >&2 - exit 1 -fi - -RUNTIME="runc" -TEST_ARGS=('--args' '/runtimetest') -KEEP=0 # Track whether we keep the test directory around or clean it up - -usage() { - echo "$0 -l -r -k -h" -} - -error() { - echo $* - exit 1 -} - -info() { - echo $* -} - -while getopts "l:r:kh" opt; do - case "${opt}" in - l) - TEST_ARGS+=('--args' "--log-level=${OPTARG}") - ;; - r) - RUNTIME=${OPTARG} - ;; - h) - usage - exit 0 - ;; - k) - KEEP=1 - ;; - \?) - usage - exit 1 - ;; - esac -done - -info "-----------------------------------------------------------------------------------" -info " VALIDATING RUNTIME: ${RUNTIME}" -info "-----------------------------------------------------------------------------------" - -if ! command -v ${RUNTIME} > /dev/null; then - error "Runtime ${RUNTIME} not found in the path" -fi - -TMPDIR=$(mktemp -d) -TESTDIR=${TMPDIR}/busybox -mkdir -p ${TESTDIR} - -cleanup() { - if [ "${KEEP}" -eq 0 ]; then - rm -rf ${TMPDIR} - else - info "Remove the test directory ${TMPDIR} after use" - fi -} -trap cleanup EXIT - -tar -xf rootfs.tar.gz -C ${TESTDIR} -cp runtimetest ${TESTDIR} - -oci-runtime-tool generate --output "${TESTDIR}/config.json" "${TEST_ARGS[@]}" --rootfs-path '.' - -TESTCMD="${RUNTIME} start $(uuidgen)" -pushd $TESTDIR > /dev/null -if ! ${TESTCMD}; then - error "Runtime ${RUNTIME} failed validation" -else - info "Runtime ${RUNTIME} passed validation" -fi -popd > /dev/null diff --git a/vendor/github.com/opencontainers/runtime-tools/validate/validate.go b/vendor/github.com/opencontainers/runtime-tools/validate/validate.go index 0eb3ad3b..95172e9a 100644 --- a/vendor/github.com/opencontainers/runtime-tools/validate/validate.go +++ b/vendor/github.com/opencontainers/runtime-tools/validate/validate.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "io/ioutil" + "net" "os" "path/filepath" "reflect" @@ -15,28 +16,29 @@ import ( "github.com/Sirupsen/logrus" "github.com/blang/semver" rspec "github.com/opencontainers/runtime-spec/specs-go" + "github.com/syndtr/gocapability/capability" ) const specConfig = "config.json" var ( defaultRlimits = []string{ - "RLIMIT_CPU", - "RLIMIT_FSIZE", - "RLIMIT_DATA", - "RLIMIT_STACK", - "RLIMIT_CORE", - "RLIMIT_RSS", - "RLIMIT_NPROC", - "RLIMIT_NOFILE", - "RLIMIT_MEMLOCK", "RLIMIT_AS", + "RLIMIT_CORE", + "RLIMIT_CPU", + "RLIMIT_DATA", + "RLIMIT_FSIZE", "RLIMIT_LOCKS", - "RLIMIT_SIGPENDING", + "RLIMIT_MEMLOCK", "RLIMIT_MSGQUEUE", "RLIMIT_NICE", + "RLIMIT_NOFILE", + "RLIMIT_NPROC", + "RLIMIT_RSS", "RLIMIT_RTPRIO", "RLIMIT_RTTIME", + "RLIMIT_SIGPENDING", + "RLIMIT_STACK", } defaultCaps = []string{ "CAP_CHOWN", @@ -56,16 +58,19 @@ var ( } ) +// Validator represents a validator for runtime bundle type Validator struct { spec *rspec.Spec bundlePath string HostSpecific bool } +// NewValidator creates a Validator func NewValidator(spec *rspec.Spec, bundlePath string, hostSpecific bool) Validator { return Validator{spec: spec, bundlePath: bundlePath, HostSpecific: hostSpecific} } +// NewValidatorFromPath creates a Validator with specified bundle path func NewValidatorFromPath(bundlePath string, hostSpecific bool) (Validator, error) { if bundlePath == "" { return Validator{}, fmt.Errorf("Bundle path shouldn't be empty") @@ -91,6 +96,7 @@ func NewValidatorFromPath(bundlePath string, hostSpecific bool) (Validator, erro return NewValidator(&spec, bundlePath, hostSpecific), nil } +// CheckAll checks all parts of runtime bundle func (v *Validator) CheckAll() (msgs []string) { msgs = append(msgs, v.CheckRootfsPath()...) msgs = append(msgs, v.CheckMandatoryFields()...) @@ -98,20 +104,34 @@ func (v *Validator) CheckAll() (msgs []string) { msgs = append(msgs, v.CheckMounts()...) msgs = append(msgs, v.CheckPlatform()...) msgs = append(msgs, v.CheckProcess()...) + msgs = append(msgs, v.CheckOS()...) msgs = append(msgs, v.CheckLinux()...) msgs = append(msgs, v.CheckHooks()...) return } +// CheckRootfsPath checks status of v.spec.Root.Path func (v *Validator) CheckRootfsPath() (msgs []string) { logrus.Debugf("check rootfs path") + absBundlePath, err := filepath.Abs(v.bundlePath) + if err != nil { + msgs = append(msgs, fmt.Sprintf("unable to convert %q to an absolute path", v.bundlePath)) + } + var rootfsPath string + var absRootPath string if filepath.IsAbs(v.spec.Root.Path) { rootfsPath = v.spec.Root.Path + absRootPath = filepath.Clean(rootfsPath) } else { + var err error rootfsPath = filepath.Join(v.bundlePath, v.spec.Root.Path) + absRootPath, err = filepath.Abs(rootfsPath) + if err != nil { + msgs = append(msgs, fmt.Sprintf("unable to convert %q to an absolute path", rootfsPath)) + } } if fi, err := os.Stat(rootfsPath); err != nil { @@ -120,9 +140,16 @@ func (v *Validator) CheckRootfsPath() (msgs []string) { msgs = append(msgs, fmt.Sprintf("The root path %q is not a directory.", rootfsPath)) } + rootParent := filepath.Dir(absRootPath) + if absRootPath == string(filepath.Separator) || rootParent != absBundlePath { + msgs = append(msgs, fmt.Sprintf("root.path is %q, but it MUST be a child of %q", v.spec.Root.Path, absBundlePath)) + } + return } + +// CheckSemVer checks v.spec.Version func (v *Validator) CheckSemVer() (msgs []string) { logrus.Debugf("check semver") @@ -138,6 +165,7 @@ func (v *Validator) CheckSemVer() (msgs []string) { return } +// CheckPlatform checks v.spec.Platform func (v *Validator) CheckPlatform() (msgs []string) { logrus.Debugf("check platform") @@ -168,12 +196,15 @@ func (v *Validator) CheckPlatform() (msgs []string) { return } +// CheckHooks check v.spec.Hooks func (v *Validator) CheckHooks() (msgs []string) { logrus.Debugf("check hooks") - msgs = append(msgs, checkEventHooks("pre-start", v.spec.Hooks.Prestart, v.HostSpecific)...) - msgs = append(msgs, checkEventHooks("post-start", v.spec.Hooks.Poststart, v.HostSpecific)...) - msgs = append(msgs, checkEventHooks("post-stop", v.spec.Hooks.Poststop, v.HostSpecific)...) + if v.spec.Hooks != nil { + msgs = append(msgs, checkEventHooks("pre-start", v.spec.Hooks.Prestart, v.HostSpecific)...) + msgs = append(msgs, checkEventHooks("post-start", v.spec.Hooks.Poststart, v.HostSpecific)...) + msgs = append(msgs, checkEventHooks("post-stop", v.spec.Hooks.Poststop, v.HostSpecific)...) + } return } @@ -204,6 +235,7 @@ func checkEventHooks(hookType string, hooks []rspec.Hook, hostSpecific bool) (ms return } +// CheckProcess checks v.spec.Process func (v *Validator) CheckProcess() (msgs []string) { logrus.Debugf("check process") @@ -218,27 +250,96 @@ func (v *Validator) CheckProcess() (msgs []string) { } } - for index := 0; index < len(process.Capabilities); index++ { - capability := process.Capabilities[index] - if !capValid(capability) { - msgs = append(msgs, fmt.Sprintf("capability %q is not valid, man capabilities(7)", process.Capabilities[index])) + if len(process.Args) == 0 { + msgs = append(msgs, fmt.Sprintf("args must not be empty")) + } else { + if filepath.IsAbs(process.Args[0]) { + var rootfsPath string + if filepath.IsAbs(v.spec.Root.Path) { + rootfsPath = v.spec.Root.Path + } else { + rootfsPath = filepath.Join(v.bundlePath, v.spec.Root.Path) + } + absPath := filepath.Join(rootfsPath, process.Args[0]) + fileinfo, err := os.Stat(absPath) + if os.IsNotExist(err) { + logrus.Warnf("executable %q is not available in rootfs currently", process.Args[0]) + } else if err != nil { + msgs = append(msgs, err.Error()) + } else { + m := fileinfo.Mode() + if m.IsDir() || m&0111 == 0 { + msgs = append(msgs, fmt.Sprintf("arg %q is not executable", process.Args[0])) + } + } } } - for index := 0; index < len(process.Rlimits); index++ { - if !rlimitValid(process.Rlimits[index].Type) { - msgs = append(msgs, fmt.Sprintf("rlimit type %q is invalid.", process.Rlimits[index].Type)) - } - if process.Rlimits[index].Hard < process.Rlimits[index].Soft { - msgs = append(msgs, fmt.Sprintf("hard limit of rlimit %s should not be less than soft limit.", process.Rlimits[index].Type)) + msgs = append(msgs, v.CheckCapablities()...) + msgs = append(msgs, v.CheckRlimits()...) + + if v.spec.Platform.OS == "linux" { + + if len(process.ApparmorProfile) > 0 { + profilePath := filepath.Join(v.bundlePath, v.spec.Root.Path, "/etc/apparmor.d", process.ApparmorProfile) + _, err := os.Stat(profilePath) + if err != nil { + msgs = append(msgs, err.Error()) + } } } - if len(process.ApparmorProfile) > 0 { - profilePath := filepath.Join(v.bundlePath, v.spec.Root.Path, "/etc/apparmor.d", process.ApparmorProfile) - _, err := os.Stat(profilePath) - if err != nil { - msgs = append(msgs, err.Error()) + return +} + +func (v *Validator) CheckCapablities() (msgs []string) { + process := v.spec.Process + if v.spec.Platform.OS == "linux" { + var caps []string + + for _, cap := range process.Capabilities.Bounding { + caps = append(caps, cap) + } + for _, cap := range process.Capabilities.Effective { + caps = append(caps, cap) + } + for _, cap := range process.Capabilities.Inheritable { + caps = append(caps, cap) + } + for _, cap := range process.Capabilities.Permitted { + caps = append(caps, cap) + } + for _, cap := range process.Capabilities.Ambient { + caps = append(caps, cap) + } + + for _, capability := range caps { + if err := CapValid(capability, v.HostSpecific); err != nil { + msgs = append(msgs, fmt.Sprintf("capability %q is not valid, man capabilities(7)", capability)) + } + } + } else { + logrus.Warnf("process.capabilities validation not yet implemented for OS %q", v.spec.Platform.OS) + } + + return +} + +func (v *Validator) CheckRlimits() (msgs []string) { + process := v.spec.Process + for index, rlimit := range process.Rlimits { + for i := index + 1; i < len(process.Rlimits); i++ { + if process.Rlimits[index].Type == process.Rlimits[i].Type { + msgs = append(msgs, fmt.Sprintf("rlimit can not contain the same type %q.", process.Rlimits[index].Type)) + } + } + + if v.spec.Platform.OS == "linux" { + if err := rlimitValid(rlimit); err != nil { + msgs = append(msgs, err.Error()) + } + } else { + logrus.Warnf("process.rlimits validation not yet implemented for OS %q", v.spec.Platform.OS) } } @@ -286,6 +387,7 @@ func supportedMountTypes(OS string, hostSpecific bool) (map[string]bool, error) return nil, nil } +// CheckMounts checks v.spec.Mounts func (v *Validator) CheckMounts() (msgs []string) { logrus.Debugf("check mounts") @@ -310,35 +412,67 @@ func (v *Validator) CheckMounts() (msgs []string) { return } -//Linux only -func (v *Validator) CheckLinux() (msgs []string) { - logrus.Debugf("check linux") +// CheckOS checks v.spec.Platform.OS +func (v *Validator) CheckOS() (msgs []string) { + logrus.Debugf("check os") - utsExists := false - ipcExists := false - mountExists := false - netExists := false - userExists := false - - for index := 0; index < len(v.spec.Linux.Namespaces); index++ { - if !namespaceValid(v.spec.Linux.Namespaces[index]) { - msgs = append(msgs, fmt.Sprintf("namespace %v is invalid.", v.spec.Linux.Namespaces[index])) - } else if len(v.spec.Linux.Namespaces[index].Path) == 0 { - if v.spec.Linux.Namespaces[index].Type == rspec.UTSNamespace { - utsExists = true - } else if v.spec.Linux.Namespaces[index].Type == rspec.IPCNamespace { - ipcExists = true - } else if v.spec.Linux.Namespaces[index].Type == rspec.NetworkNamespace { - netExists = true - } else if v.spec.Linux.Namespaces[index].Type == rspec.MountNamespace { - mountExists = true - } else if v.spec.Linux.Namespaces[index].Type == rspec.UserNamespace { - userExists = true - } + if v.spec.Platform.OS != "linux" { + if v.spec.Linux != nil { + msgs = append(msgs, fmt.Sprintf("'linux' MUST NOT be set when platform.os is %q", v.spec.Platform.OS)) } } - if (len(v.spec.Linux.UIDMappings) > 0 || len(v.spec.Linux.GIDMappings) > 0) && !userExists { + if v.spec.Platform.OS != "solaris" { + if v.spec.Solaris != nil { + msgs = append(msgs, fmt.Sprintf("'solaris' MUST NOT be set when platform.os is %q", v.spec.Platform.OS)) + } + } + + if v.spec.Platform.OS != "windows" { + if v.spec.Windows != nil { + msgs = append(msgs, fmt.Sprintf("'windows' MUST NOT be set when platform.os is %q", v.spec.Platform.OS)) + } + } + + return +} + +// CheckLinux checks v.spec.Linux +func (v *Validator) CheckLinux() (msgs []string) { + logrus.Debugf("check linux") + + var typeList = map[rspec.LinuxNamespaceType]struct { + num int + newExist bool + }{ + rspec.PIDNamespace: {0, false}, + rspec.NetworkNamespace: {0, false}, + rspec.MountNamespace: {0, false}, + rspec.IPCNamespace: {0, false}, + rspec.UTSNamespace: {0, false}, + rspec.UserNamespace: {0, false}, + rspec.CgroupNamespace: {0, false}, + } + + for index := 0; index < len(v.spec.Linux.Namespaces); index++ { + ns := v.spec.Linux.Namespaces[index] + if !namespaceValid(ns) { + msgs = append(msgs, fmt.Sprintf("namespace %v is invalid.", ns)) + } + + tmpItem := typeList[ns.Type] + tmpItem.num = tmpItem.num + 1 + if tmpItem.num > 1 { + msgs = append(msgs, fmt.Sprintf("duplicated namespace %q", ns.Type)) + } + + if len(ns.Path) == 0 { + tmpItem.newExist = true + } + typeList[ns.Type] = tmpItem + } + + if (len(v.spec.Linux.UIDMappings) > 0 || len(v.spec.Linux.GIDMappings) > 0) && !typeList[rspec.UserNamespace].newExist { msgs = append(msgs, "UID/GID mappings requires a new User namespace to be specified as well") } else if len(v.spec.Linux.UIDMappings) > 5 { msgs = append(msgs, "Only 5 UID mappings are allowed (linux kernel restriction).") @@ -347,17 +481,17 @@ func (v *Validator) CheckLinux() (msgs []string) { } for k := range v.spec.Linux.Sysctl { - if strings.HasPrefix(k, "net.") && !netExists { + if strings.HasPrefix(k, "net.") && !typeList[rspec.NetworkNamespace].newExist { msgs = append(msgs, fmt.Sprintf("Sysctl %v requires a new Network namespace to be specified as well", k)) } if strings.HasPrefix(k, "fs.mqueue.") { - if !mountExists || !ipcExists { + if !typeList[rspec.MountNamespace].newExist || !typeList[rspec.IPCNamespace].newExist { msgs = append(msgs, fmt.Sprintf("Sysctl %v requires a new IPC namespace and Mount namespace to be specified as well", k)) } } } - if v.spec.Platform.OS == "linux" && !utsExists && v.spec.Hostname != "" { + if v.spec.Platform.OS == "linux" && !typeList[rspec.UTSNamespace].newExist && v.spec.Hostname != "" { msgs = append(msgs, fmt.Sprintf("On Linux, hostname requires a new UTS namespace to be specified as well")) } @@ -404,6 +538,7 @@ func (v *Validator) CheckLinux() (msgs []string) { return } +// CheckLinuxResources checks v.spec.Linux.Resources func (v *Validator) CheckLinuxResources() (msgs []string) { logrus.Debugf("check linux resources") @@ -416,10 +551,31 @@ func (v *Validator) CheckLinuxResources() (msgs []string) { msgs = append(msgs, fmt.Sprintf("Minimum memory limit should be larger than memory reservation")) } } + if r.Network != nil && v.HostSpecific { + var exist bool + interfaces, err := net.Interfaces() + if err != nil { + msgs = append(msgs, err.Error()) + return + } + for _, prio := range r.Network.Priorities { + exist = false + for _, ni := range interfaces { + if prio.Name == ni.Name { + exist = true + break + } + } + if !exist { + msgs = append(msgs, fmt.Sprintf("Interface %s does not exist currently", prio.Name)) + } + } + } return } +// CheckSeccomp checkc v.spec.Linux.Seccomp func (v *Validator) CheckSeccomp() (msgs []string) { logrus.Debugf("check linux seccomp") @@ -450,6 +606,8 @@ func (v *Validator) CheckSeccomp() (msgs []string) { case rspec.ArchPPC64LE: case rspec.ArchS390: case rspec.ArchS390X: + case rspec.ArchPARISC: + case rspec.ArchPARISC64: default: msgs = append(msgs, fmt.Sprintf("seccomp architecture %q is invalid", s.Architectures[index])) } @@ -458,6 +616,40 @@ func (v *Validator) CheckSeccomp() (msgs []string) { return } +// CapValid checks whether a capability is valid +func CapValid(c string, hostSpecific bool) error { + isValid := false + + if !strings.HasPrefix(c, "CAP_") { + return fmt.Errorf("capability %s must start with CAP_", c) + } + for _, cap := range capability.List() { + if c == fmt.Sprintf("CAP_%s", strings.ToUpper(cap.String())) { + if hostSpecific && cap > LastCap() { + return fmt.Errorf("CAP_%s is not supported on the current host", c) + } + isValid = true + break + } + } + + if !isValid { + return fmt.Errorf("Invalid capability: %s", c) + } + return nil +} + +// LastCap return last cap of system +func LastCap() capability.Cap { + last := capability.CAP_LAST_CAP + // hack for RHEL6 which has no /proc/sys/kernel/cap_last_cap + if last == capability.Cap(63) { + last = capability.CAP_BLOCK_SUSPEND + } + + return last +} + func envValid(env string) bool { items := strings.Split(env, "=") if len(items) < 2 { @@ -474,25 +666,19 @@ func envValid(env string) bool { return true } -func capValid(capability string) bool { - for _, val := range defaultCaps { - if val == capability { - return true - } +func rlimitValid(rlimit rspec.LinuxRlimit) error { + if rlimit.Hard < rlimit.Soft { + return fmt.Errorf("hard limit of rlimit %s should not be less than soft limit", rlimit.Type) } - return false -} - -func rlimitValid(rlimit string) bool { for _, val := range defaultRlimits { - if val == rlimit { - return true + if val == rlimit.Type { + return nil } } - return false + return fmt.Errorf("rlimit type %q is invalid", rlimit.Type) } -func namespaceValid(ns rspec.Namespace) bool { +func namespaceValid(ns rspec.LinuxNamespace) bool { switch ns.Type { case rspec.PIDNamespace: case rspec.NetworkNamespace: @@ -504,10 +690,15 @@ func namespaceValid(ns rspec.Namespace) bool { default: return false } + + if ns.Path != "" && !filepath.IsAbs(ns.Path) { + return false + } + return true } -func deviceValid(d rspec.Device) bool { +func deviceValid(d rspec.LinuxDevice) bool { switch d.Type { case "b": case "c": @@ -528,7 +719,7 @@ func deviceValid(d rspec.Device) bool { return true } -func seccompActionValid(secc rspec.Action) bool { +func seccompActionValid(secc rspec.LinuxSeccompAction) bool { switch secc { case "": case rspec.ActKill: @@ -542,7 +733,7 @@ func seccompActionValid(secc rspec.Action) bool { return true } -func syscallValid(s rspec.Syscall) bool { +func syscallValid(s rspec.LinuxSyscall) bool { if !seccompActionValid(s.Action) { return false } @@ -637,6 +828,7 @@ func checkMandatory(obj interface{}) (msgs []string) { return } +// CheckMandatoryFields checks mandatory field of container's config file func (v *Validator) CheckMandatoryFields() []string { logrus.Debugf("check mandatory fields") diff --git a/vendor/github.com/opencontainers/runtime-tools/validation/validation_test.go b/vendor/github.com/opencontainers/runtime-tools/validation/validation_test.go new file mode 100644 index 00000000..419299ac --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/validation/validation_test.go @@ -0,0 +1,98 @@ +package validation + +import ( + "fmt" + "io/ioutil" + "os" + "os/exec" + "path/filepath" + "testing" + + "github.com/mrunalp/fileutils" + "github.com/opencontainers/runtime-tools/generate" + "github.com/satori/go.uuid" +) + +var ( + runtime = "runc" +) + +func init() { + runtime = os.Getenv("RUNTIME") +} + +func runtimeValidate(runtime string, g *generate.Generator) error { + // Find the runtime binary in the PATH + runtimePath, err := exec.LookPath(runtime) + if err != nil { + return err + } + + // Setup a temporary test directory + tmpDir, err := ioutil.TempDir("", "ocitest") + if err != nil { + return err + } + defer os.RemoveAll(tmpDir) + + // Create bundle directory for the test container + bundleDir := tmpDir + "/busybox" + if err := os.MkdirAll(bundleDir, 0755); err != nil { + return err + } + + // Untar the root fs + untarCmd := exec.Command("tar", "-xf", "../rootfs.tar.gz", "-C", bundleDir) + output, err := untarCmd.CombinedOutput() + if err != nil { + fmt.Println(string(output)) + return err + } + + // Copy the runtimetest binary to the rootfs + err = fileutils.CopyFile("../runtimetest", filepath.Join(bundleDir, "runtimetest")) + + // Generate test configuration + err = g.SaveToFile(filepath.Join(bundleDir, "config.json"), generate.ExportOptions{}) + if err != nil { + return err + } + + // TODO: Use a library to split run into create/start + // Launch the OCI runtime + containerID := uuid.NewV4() + runtimeCmd := exec.Command(runtimePath, "run", containerID.String()) + runtimeCmd.Dir = bundleDir + runtimeCmd.Stdin = os.Stdin + runtimeCmd.Stdout = os.Stdout + runtimeCmd.Stderr = os.Stderr + if err = runtimeCmd.Run(); err != nil { + return err + } + + return nil +} + +func getDefaultGenerator() *generate.Generator { + g := generate.New() + g.SetRootPath(".") + g.SetProcessArgs([]string{"/runtimetest"}) + return &g +} + +func TestValidateBasic(t *testing.T) { + g := getDefaultGenerator() + + if err := runtimeValidate(runtime, g); err != nil { + t.Errorf("%s failed validation: %v", runtime, err) + } +} + +func TestValidateSysctls(t *testing.T) { + g := getDefaultGenerator() + g.AddLinuxSysctl("net.ipv4.ip_forward", "1") + + if err := runtimeValidate(runtime, g); err != nil { + t.Errorf("%s failed validation: %v", runtime, err) + } +}