diff options
author | Daniel J Walsh <dwalsh@redhat.com> | 2017-12-18 13:53:42 -0500 |
---|---|---|
committer | Atomic Bot <atomic-devel@projectatomic.io> | 2017-12-18 21:19:30 +0000 |
commit | 34572abc707f2684cfcbfb64222497aeb842d662 (patch) | |
tree | 53d6190c5cb9d9142bdd18627fda2437c5ae7f14 /vendor/github.com/opencontainers | |
parent | 5770dc2640c216525ab84031e3712fcc46b3b087 (diff) | |
download | podman-34572abc707f2684cfcbfb64222497aeb842d662.tar.gz podman-34572abc707f2684cfcbfb64222497aeb842d662.tar.bz2 podman-34572abc707f2684cfcbfb64222497aeb842d662.zip |
Vendor in latest storage, image and runtime-tools
Need to pull in the latest containers/storage and containers/image to fix lots of
issues. Also want to update runtime-tools to take advantage of newer generate
code.
Signed-off-by: Daniel J Walsh <dwalsh@redhat.com>
Closes: #152
Approved by: rhatdan
Diffstat (limited to 'vendor/github.com/opencontainers')
18 files changed, 1120 insertions, 394 deletions
diff --git a/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_linux.go b/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_linux.go deleted file mode 100644 index 461dc097c..000000000 --- a/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_linux.go +++ /dev/null @@ -1,100 +0,0 @@ -package devices - -import ( - "errors" - "io/ioutil" - "os" - "path/filepath" - - "github.com/opencontainers/runc/libcontainer/configs" - - "golang.org/x/sys/unix" -) - -var ( - ErrNotADevice = errors.New("not a device node") -) - -// Testing dependencies -var ( - unixLstat = unix.Lstat - ioutilReadDir = ioutil.ReadDir -) - -// Given the path to a device and its cgroup_permissions(which cannot be easily queried) look up the information about a linux device and return that information as a Device struct. -func DeviceFromPath(path, permissions string) (*configs.Device, error) { - var stat unix.Stat_t - err := unixLstat(path, &stat) - if err != nil { - return nil, err - } - var ( - devType rune - mode = stat.Mode - ) - switch { - case mode&unix.S_IFBLK == unix.S_IFBLK: - devType = 'b' - case mode&unix.S_IFCHR == unix.S_IFCHR: - devType = 'c' - default: - return nil, ErrNotADevice - } - devNumber := int(stat.Rdev) - uid := stat.Uid - gid := stat.Gid - return &configs.Device{ - Type: devType, - Path: path, - Major: Major(devNumber), - Minor: Minor(devNumber), - Permissions: permissions, - FileMode: os.FileMode(mode), - Uid: uid, - Gid: gid, - }, nil -} - -func HostDevices() ([]*configs.Device, error) { - return getDevices("/dev") -} - -func getDevices(path string) ([]*configs.Device, error) { - files, err := ioutilReadDir(path) - if err != nil { - return nil, err - } - out := []*configs.Device{} - for _, f := range files { - switch { - case f.IsDir(): - switch f.Name() { - // ".lxc" & ".lxd-mounts" added to address https://github.com/lxc/lxd/issues/2825 - case "pts", "shm", "fd", "mqueue", ".lxc", ".lxd-mounts": - continue - default: - sub, err := getDevices(filepath.Join(path, f.Name())) - if err != nil { - return nil, err - } - - out = append(out, sub...) - continue - } - case f.Name() == "console": - continue - } - device, err := DeviceFromPath(filepath.Join(path, f.Name()), "rwm") - if err != nil { - if err == ErrNotADevice { - continue - } - if os.IsNotExist(err) { - continue - } - return nil, err - } - out = append(out, device) - } - return out, nil -} diff --git a/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unsupported.go b/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unsupported.go deleted file mode 100644 index 6649b9f2d..000000000 --- a/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unsupported.go +++ /dev/null @@ -1,3 +0,0 @@ -// +build !linux - -package devices diff --git a/vendor/github.com/opencontainers/runc/libcontainer/devices/number.go b/vendor/github.com/opencontainers/runc/libcontainer/devices/number.go deleted file mode 100644 index 885b6e5dd..000000000 --- a/vendor/github.com/opencontainers/runc/libcontainer/devices/number.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build linux freebsd - -package devices - -/* - -This code provides support for manipulating linux device numbers. It should be replaced by normal syscall functions once http://code.google.com/p/go/issues/detail?id=8106 is solved. - -You can read what they are here: - - - http://www.makelinux.net/ldd3/chp-3-sect-2 - - http://www.linux-tutorial.info/modules.php?name=MContent&pageid=94 - -Note! These are NOT the same as the MAJOR(dev_t device);, MINOR(dev_t device); and MKDEV(int major, int minor); functions as defined in <linux/kdev_t.h> as the representation of device numbers used by go is different than the one used internally to the kernel! - https://github.com/torvalds/linux/blob/master/include/linux/kdev_t.h#L9 - -*/ - -func Major(devNumber int) int64 { - return int64((devNumber >> 8) & 0xfff) -} - -func Minor(devNumber int) int64 { - return int64((devNumber & 0xff) | ((devNumber >> 12) & 0xfff00)) -} diff --git a/vendor/github.com/opencontainers/runtime-tools/filepath/abs.go b/vendor/github.com/opencontainers/runtime-tools/filepath/abs.go new file mode 100644 index 000000000..c19bba26a --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/filepath/abs.go @@ -0,0 +1,52 @@ +package filepath + +import ( + "errors" + "regexp" + "strings" +) + +var windowsAbs = regexp.MustCompile(`^[a-zA-Z]:\\.*$`) + +// Abs is a version of path/filepath's Abs with an explicit operating +// system and current working directory. +func Abs(os, path, cwd string) (_ string, err error) { + if os == "windows" { + return "", errors.New("Abs() does not support windows yet") + } + if IsAbs(os, path) { + return Clean(os, path), nil + } + return Clean(os, Join(os, cwd, path)), nil +} + +// IsAbs is a version of path/filepath's IsAbs with an explicit +// operating system. +func IsAbs(os, path string) bool { + if os == "windows" { + // FIXME: copy hideous logic from Go's + // src/path/filepath/path_windows.go into somewhere where we can + // put 3-clause BSD licensed code. + return windowsAbs.MatchString(path) + } + sep := Separator(os) + + // POSIX has [1]: + // + // > If a pathname begins with two successive <slash> characters, + // > the first component following the leading <slash> characters + // > may be interpreted in an implementation-defined manner, + // > although more than two leading <slash> characters shall be + // > treated as a single <slash> character. + // + // And Boost treats // as non-absolute [2], but Linux [3,4], Python + // [5] and Go [6] all treat // as absolute. + // + // [1]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13 + // [2]: https://github.com/boostorg/filesystem/blob/boost-1.64.0/test/path_test.cpp#L861 + // [3]: http://man7.org/linux/man-pages/man7/path_resolution.7.html + // [4]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/filesystems/path-lookup.md?h=v4.12#n41 + // [5]: https://github.com/python/cpython/blob/v3.6.1/Lib/posixpath.py#L64-L66 + // [6]: https://go.googlesource.com/go/+/go1.8.3/src/path/path.go#199 + return strings.HasPrefix(path, string(sep)) +} diff --git a/vendor/github.com/opencontainers/runtime-tools/filepath/ancestor.go b/vendor/github.com/opencontainers/runtime-tools/filepath/ancestor.go new file mode 100644 index 000000000..896cd8206 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/filepath/ancestor.go @@ -0,0 +1,32 @@ +package filepath + +import ( + "fmt" + "strings" +) + +// IsAncestor returns true when pathB is an strict ancestor of pathA, +// and false where the paths are equal or pathB is outside of pathA. +// Paths that are not absolute will be made absolute with Abs. +func IsAncestor(os, pathA, pathB, cwd string) (_ bool, err error) { + if pathA == pathB { + return false, nil + } + + pathA, err = Abs(os, pathA, cwd) + if err != nil { + return false, err + } + pathB, err = Abs(os, pathB, cwd) + if err != nil { + return false, err + } + sep := Separator(os) + if !strings.HasSuffix(pathA, string(sep)) { + pathA = fmt.Sprintf("%s%c", pathA, sep) + } + if pathA == pathB { + return false, nil + } + return strings.HasPrefix(pathB, pathA), nil +} diff --git a/vendor/github.com/opencontainers/runtime-tools/filepath/clean.go b/vendor/github.com/opencontainers/runtime-tools/filepath/clean.go new file mode 100644 index 000000000..b70c575f2 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/filepath/clean.go @@ -0,0 +1,56 @@ +package filepath + +import ( + "fmt" + "strings" +) + +// Clean is an explicit-OS version of path/filepath's Clean. +func Clean(os, path string) string { + abs := IsAbs(os, path) + sep := Separator(os) + elements := strings.Split(path, string(sep)) + + // Replace multiple Separator elements with a single one. + for i := 0; i < len(elements); i++ { + if len(elements[i]) == 0 { + elements = append(elements[:i], elements[i+1:]...) + i-- + } + } + + // Eliminate each . path name element (the current directory). + for i := 0; i < len(elements); i++ { + if elements[i] == "." && len(elements) > 1 { + elements = append(elements[:i], elements[i+1:]...) + i-- + } + } + + // Eliminate each inner .. path name element (the parent directory) + // along with the non-.. element that precedes it. + for i := 1; i < len(elements); i++ { + if i > 0 && elements[i] == ".." { + elements = append(elements[:i-1], elements[i+1:]...) + i -= 2 + } + } + + // Eliminate .. elements that begin a rooted path: + // that is, replace "/.." by "/" at the beginning of a path, + // assuming Separator is '/'. + if abs && len(elements) > 0 { + for elements[0] == ".." { + elements = elements[1:] + } + } + + cleaned := strings.Join(elements, string(sep)) + if abs { + cleaned = fmt.Sprintf("%c%s", sep, cleaned) + } + if cleaned == path { + return path + } + return Clean(os, cleaned) +} diff --git a/vendor/github.com/opencontainers/runtime-tools/filepath/doc.go b/vendor/github.com/opencontainers/runtime-tools/filepath/doc.go new file mode 100644 index 000000000..7ee085bf4 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/filepath/doc.go @@ -0,0 +1,6 @@ +// Package filepath implements Go's filepath package with explicit +// operating systems (and for some functions and explicit working +// directory). This allows tools built for one OS to operate on paths +// targeting another OS. For example, a Linux build can determine +// whether a path is absolute on Linux or on Windows. +package filepath diff --git a/vendor/github.com/opencontainers/runtime-tools/filepath/join.go b/vendor/github.com/opencontainers/runtime-tools/filepath/join.go new file mode 100644 index 000000000..b865d237c --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/filepath/join.go @@ -0,0 +1,9 @@ +package filepath + +import "strings" + +// Join is an explicit-OS version of path/filepath's Join. +func Join(os string, elem ...string) string { + sep := Separator(os) + return Clean(os, strings.Join(elem, string(sep))) +} diff --git a/vendor/github.com/opencontainers/runtime-tools/filepath/separator.go b/vendor/github.com/opencontainers/runtime-tools/filepath/separator.go new file mode 100644 index 000000000..2c5e8905a --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/filepath/separator.go @@ -0,0 +1,9 @@ +package filepath + +// Separator is an explicit-OS version of path/filepath's Separator. +func Separator(os string) rune { + if os == "windows" { + return '\\' + } + return '/' +} diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/generate.go b/vendor/github.com/opencontainers/runtime-tools/generate/generate.go index fce88f5e2..5a1f5543e 100644 --- a/vendor/github.com/opencontainers/runtime-tools/generate/generate.go +++ b/vendor/github.com/opencontainers/runtime-tools/generate/generate.go @@ -17,6 +17,12 @@ import ( var ( // Namespaces include the names of supported namespaces. Namespaces = []string{"network", "pid", "mount", "ipc", "uts", "user", "cgroup"} + + // we don't care about order...and this is way faster... + removeFunc = func(s []string, i int) []string { + s[i] = s[len(s)-1] + return s[:len(s)-1] + } ) // Generator represents a generator for a container spec. @@ -35,7 +41,7 @@ func New() Generator { spec := rspec.Spec{ Version: rspec.Version, Root: &rspec.Root{ - Path: "", + Path: "rootfs", Readonly: false, }, Process: &rspec.Process{ @@ -392,7 +398,7 @@ func (g *Generator) SetProcessArgs(args []string) { // ClearProcessEnv clears g.spec.Process.Env. func (g *Generator) ClearProcessEnv() { - if g.spec == nil { + if g.spec == nil || g.spec.Process == nil { return } g.spec.Process.Env = []string{} @@ -434,7 +440,7 @@ func (g *Generator) AddProcessRlimits(rType string, rHard uint64, rSoft uint64) // RemoveProcessRlimits removes a rlimit from g.spec.Process.Rlimits. func (g *Generator) RemoveProcessRlimits(rType string) error { - if g.spec == nil { + if g.spec == nil || g.spec.Process == nil { return nil } for i, rlimit := range g.spec.Process.Rlimits { @@ -448,7 +454,7 @@ func (g *Generator) RemoveProcessRlimits(rType string) error { // ClearProcessRlimits clear g.spec.Process.Rlimits. func (g *Generator) ClearProcessRlimits() { - if g.spec == nil { + if g.spec == nil || g.spec.Process == nil { return } g.spec.Process.Rlimits = []rspec.POSIXRlimit{} @@ -456,7 +462,7 @@ func (g *Generator) ClearProcessRlimits() { // ClearProcessAdditionalGids clear g.spec.Process.AdditionalGids. func (g *Generator) ClearProcessAdditionalGids() { - if g.spec == nil { + if g.spec == nil || g.spec.Process == nil { return } g.spec.Process.User.AdditionalGids = []uint32{} @@ -716,13 +722,11 @@ func (g *Generator) SetLinuxRootPropagation(rp string) error { switch rp { case "": case "private": - case "rprivate": case "slave": - case "rslave": case "shared": - case "rshared": + case "unbindable": default: - return fmt.Errorf("rootfs-propagation must be empty or one of private|rprivate|slave|rslave|shared|rshared") + return fmt.Errorf("rootfs-propagation must be empty or one of private|slave|shared|unbindable") } g.initSpecLinux() g.spec.Linux.RootfsPropagation = rp @@ -731,10 +735,7 @@ func (g *Generator) SetLinuxRootPropagation(rp string) error { // ClearPreStartHooks clear g.spec.Hooks.Prestart. func (g *Generator) ClearPreStartHooks() { - if g.spec == nil { - return - } - if g.spec.Hooks == nil { + if g.spec == nil || g.spec.Hooks == nil { return } g.spec.Hooks.Prestart = []rspec.Hook{} @@ -781,10 +782,7 @@ func (g *Generator) AddPreStartHookTimeout(path string, timeout int) { // ClearPostStopHooks clear g.spec.Hooks.Poststop. func (g *Generator) ClearPostStopHooks() { - if g.spec == nil { - return - } - if g.spec.Hooks == nil { + if g.spec == nil || g.spec.Hooks == nil { return } g.spec.Hooks.Poststop = []rspec.Hook{} @@ -831,10 +829,7 @@ func (g *Generator) AddPostStopHookTimeout(path string, timeout int) { // ClearPostStartHooks clear g.spec.Hooks.Poststart. func (g *Generator) ClearPostStartHooks() { - if g.spec == nil { - return - } - if g.spec.Hooks == nil { + if g.spec == nil || g.spec.Hooks == nil { return } g.spec.Hooks.Poststart = []rspec.Hook{} @@ -970,7 +965,7 @@ func (g *Generator) SetupPrivileged(privileged bool) { // ClearProcessCapabilities clear g.spec.Process.Capabilities. func (g *Generator) ClearProcessCapabilities() { - if g.spec == nil { + if g.spec == nil || g.spec.Process == nil || g.spec.Process.Capabilities == nil { return } g.spec.Process.Capabilities.Bounding = []string{} @@ -980,8 +975,32 @@ func (g *Generator) ClearProcessCapabilities() { g.spec.Process.Capabilities.Ambient = []string{} } -// AddProcessCapability adds a process capability into g.spec.Process.Capabilities. -func (g *Generator) AddProcessCapability(c string) error { +// AddProcessCapabilityAmbient adds a process capability into g.spec.Process.Capabilities.Ambient. +func (g *Generator) AddProcessCapabilityAmbient(c string) error { + cp := strings.ToUpper(c) + if err := validate.CapValid(cp, g.HostSpecific); err != nil { + return err + } + + g.initSpecProcessCapabilities() + + var foundAmbient bool + for _, cap := range g.spec.Process.Capabilities.Ambient { + if strings.ToUpper(cap) == cp { + foundAmbient = true + break + } + } + + if !foundAmbient { + g.spec.Process.Capabilities.Ambient = append(g.spec.Process.Capabilities.Ambient, cp) + } + + return nil +} + +// AddProcessCapabilityBounding adds a process capability into g.spec.Process.Capabilities.Bounding. +func (g *Generator) AddProcessCapabilityBounding(c string) error { cp := strings.ToUpper(c) if err := validate.CapValid(cp, g.HostSpecific); err != nil { return err @@ -1000,6 +1019,18 @@ func (g *Generator) AddProcessCapability(c string) error { g.spec.Process.Capabilities.Bounding = append(g.spec.Process.Capabilities.Bounding, cp) } + return nil +} + +// AddProcessCapabilityEffective adds a process capability into g.spec.Process.Capabilities.Effective. +func (g *Generator) AddProcessCapabilityEffective(c string) error { + cp := strings.ToUpper(c) + if err := validate.CapValid(cp, g.HostSpecific); err != nil { + return err + } + + g.initSpecProcessCapabilities() + var foundEffective bool for _, cap := range g.spec.Process.Capabilities.Effective { if strings.ToUpper(cap) == cp { @@ -1011,6 +1042,18 @@ func (g *Generator) AddProcessCapability(c string) error { g.spec.Process.Capabilities.Effective = append(g.spec.Process.Capabilities.Effective, cp) } + return nil +} + +// AddProcessCapabilityInheritable adds a process capability into g.spec.Process.Capabilities.Inheritable. +func (g *Generator) AddProcessCapabilityInheritable(c string) error { + cp := strings.ToUpper(c) + if err := validate.CapValid(cp, g.HostSpecific); err != nil { + return err + } + + g.initSpecProcessCapabilities() + var foundInheritable bool for _, cap := range g.spec.Process.Capabilities.Inheritable { if strings.ToUpper(cap) == cp { @@ -1022,6 +1065,18 @@ func (g *Generator) AddProcessCapability(c string) error { g.spec.Process.Capabilities.Inheritable = append(g.spec.Process.Capabilities.Inheritable, cp) } + return nil +} + +// AddProcessCapabilityPermitted adds a process capability into g.spec.Process.Capabilities.Permitted. +func (g *Generator) AddProcessCapabilityPermitted(c string) error { + cp := strings.ToUpper(c) + if err := validate.CapValid(cp, g.HostSpecific); err != nil { + return err + } + + g.initSpecProcessCapabilities() + var foundPermitted bool for _, cap := range g.spec.Process.Capabilities.Permitted { if strings.ToUpper(cap) == cp { @@ -1033,66 +1088,85 @@ func (g *Generator) AddProcessCapability(c string) error { g.spec.Process.Capabilities.Permitted = append(g.spec.Process.Capabilities.Permitted, cp) } - var foundAmbient bool - for _, cap := range g.spec.Process.Capabilities.Ambient { + return nil +} + +// DropProcessCapabilityAmbient drops a process capability from g.spec.Process.Capabilities.Ambient. +func (g *Generator) DropProcessCapabilityAmbient(c string) error { + cp := strings.ToUpper(c) + + g.initSpecProcessCapabilities() + + for i, cap := range g.spec.Process.Capabilities.Ambient { if strings.ToUpper(cap) == cp { - foundAmbient = true - break + g.spec.Process.Capabilities.Ambient = removeFunc(g.spec.Process.Capabilities.Ambient, i) } } - if !foundAmbient { - g.spec.Process.Capabilities.Ambient = append(g.spec.Process.Capabilities.Ambient, cp) - } - return nil + return validate.CapValid(cp, false) } -// DropProcessCapability drops a process capability from g.spec.Process.Capabilities. -func (g *Generator) DropProcessCapability(c string) error { +// DropProcessCapabilityBounding drops a process capability from g.spec.Process.Capabilities.Bounding. +func (g *Generator) DropProcessCapabilityBounding(c string) error { cp := strings.ToUpper(c) - if err := validate.CapValid(cp, g.HostSpecific); err != nil { - return err - } g.initSpecProcessCapabilities() - // we don't care about order...and this is way faster... - removeFunc := func(s []string, i int) []string { - s[i] = s[len(s)-1] - return s[:len(s)-1] - } - for i, cap := range g.spec.Process.Capabilities.Bounding { if strings.ToUpper(cap) == cp { g.spec.Process.Capabilities.Bounding = removeFunc(g.spec.Process.Capabilities.Bounding, i) } } + return validate.CapValid(cp, false) +} + +// DropProcessCapabilityEffective drops a process capability from g.spec.Process.Capabilities.Effective. +func (g *Generator) DropProcessCapabilityEffective(c string) error { + cp := strings.ToUpper(c) + + g.initSpecProcessCapabilities() + for i, cap := range g.spec.Process.Capabilities.Effective { if strings.ToUpper(cap) == cp { g.spec.Process.Capabilities.Effective = removeFunc(g.spec.Process.Capabilities.Effective, i) } } + return validate.CapValid(cp, false) +} + +// DropProcessCapabilityInheritable drops a process capability from g.spec.Process.Capabilities.Inheritable. +func (g *Generator) DropProcessCapabilityInheritable(c string) error { + cp := strings.ToUpper(c) + if err := validate.CapValid(cp, g.HostSpecific); err != nil { + return err + } + + g.initSpecProcessCapabilities() + for i, cap := range g.spec.Process.Capabilities.Inheritable { if strings.ToUpper(cap) == cp { g.spec.Process.Capabilities.Inheritable = removeFunc(g.spec.Process.Capabilities.Inheritable, i) } } - for i, cap := range g.spec.Process.Capabilities.Permitted { - if strings.ToUpper(cap) == cp { - g.spec.Process.Capabilities.Permitted = removeFunc(g.spec.Process.Capabilities.Permitted, i) - } - } + return validate.CapValid(cp, false) +} - for i, cap := range g.spec.Process.Capabilities.Ambient { +// DropProcessCapabilityPermitted drops a process capability from g.spec.Process.Capabilities.Permitted. +func (g *Generator) DropProcessCapabilityPermitted(c string) error { + cp := strings.ToUpper(c) + + g.initSpecProcessCapabilities() + + for i, cap := range g.spec.Process.Capabilities.Permitted { if strings.ToUpper(cap) == cp { g.spec.Process.Capabilities.Ambient = removeFunc(g.spec.Process.Capabilities.Ambient, i) } } - return nil + return validate.CapValid(cp, false) } func mapStrToNamespace(ns string, path string) (rspec.LinuxNamespace, error) { @@ -1203,6 +1277,39 @@ func (g *Generator) ClearLinuxDevices() { g.spec.Linux.Devices = []rspec.LinuxDevice{} } +// AddLinuxResourcesDevice - add a device into g.spec.Linux.Resources.Devices +func (g *Generator) AddLinuxResourcesDevice(allow bool, devType string, major, minor *int64, access string) { + g.initSpecLinuxResources() + + device := rspec.LinuxDeviceCgroup{ + Allow: allow, + Type: devType, + Access: access, + Major: major, + Minor: minor, + } + g.spec.Linux.Resources.Devices = append(g.spec.Linux.Resources.Devices, device) +} + +// RemoveLinuxResourcesDevice - remove a device from g.spec.Linux.Resources.Devices +func (g *Generator) RemoveLinuxResourcesDevice(allow bool, devType string, major, minor *int64, access string) { + if g.spec == nil || g.spec.Linux == nil || g.spec.Linux.Resources == nil { + return + } + for i, device := range g.spec.Linux.Resources.Devices { + if device.Allow == allow && + (devType == device.Type || (devType != "" && device.Type != "" && devType == device.Type)) && + (access == device.Access || (access != "" && device.Access != "" && access == device.Access)) && + (major == device.Major || (major != nil && device.Major != nil && *major == *device.Major)) && + (minor == device.Minor || (minor != nil && device.Minor != nil && *minor == *device.Minor)) { + + g.spec.Linux.Resources.Devices = append(g.spec.Linux.Resources.Devices[:i], g.spec.Linux.Resources.Devices[i+1:]...) + return + } + } + return +} + // 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/specerror/bundle.go b/vendor/github.com/opencontainers/runtime-tools/specerror/bundle.go new file mode 100644 index 000000000..0a6b2d423 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/specerror/bundle.go @@ -0,0 +1,29 @@ +package specerror + +import ( + "fmt" + + rfc2119 "github.com/opencontainers/runtime-tools/error" +) + +// define error codes +const ( + // ConfigInRootBundleDir represents "This REQUIRED file MUST reside in the root of the bundle directory" + ConfigInRootBundleDir = "This REQUIRED file MUST reside in the root of the bundle directory." + // ConfigConstName represents "This REQUIRED file MUST be named `config.json`." + ConfigConstName = "This REQUIRED file MUST be named `config.json`." + // ArtifactsInSingleDir represents "When supplied, while these artifacts MUST all be present in a single directory on the local filesystem, that directory itself is not part of the bundle." + ArtifactsInSingleDir = "When supplied, while these artifacts MUST all be present in a single directory on the local filesystem, that directory itself is not part of the bundle." +) + +var ( + containerFormatRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "bundle.md#container-format"), nil + } +) + +func init() { + register(ConfigInRootBundleDir, rfc2119.Must, containerFormatRef) + register(ConfigConstName, rfc2119.Must, containerFormatRef) + register(ArtifactsInSingleDir, rfc2119.Must, containerFormatRef) +} diff --git a/vendor/github.com/opencontainers/runtime-tools/specerror/config-linux.go b/vendor/github.com/opencontainers/runtime-tools/specerror/config-linux.go new file mode 100644 index 000000000..2967adcef --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/specerror/config-linux.go @@ -0,0 +1,134 @@ +package specerror + +import ( + "fmt" + + rfc2119 "github.com/opencontainers/runtime-tools/error" +) + +// define error codes +const ( + // DefaultFilesystems represents "The following filesystems SHOULD be made available in each container's filesystem:" + DefaultFilesystems = "The following filesystems SHOULD be made available in each container's filesystem:" + // NSPathAbs represents "This value MUST be an absolute path in the runtime mount namespace." + NSPathAbs = "This value MUST be an absolute path in the runtime mount namespace." + // NSProcInPath represents "The runtime MUST place the container process in the namespace associated with that `path`." + NSProcInPath = "The runtime MUST place the container process in the namespace associated with that `path`." + // NSPathMatchTypeError represents "The runtime MUST generate an error if `path` is not associated with a namespace of type `type`." + NSPathMatchTypeError = "The runtime MUST generate an error if `path` is not associated with a namespace of type `type`." + // NSNewNSWithoutPath represents "If `path` is not specified, the runtime MUST create a new container namespace of type `type`." + NSNewNSWithoutPath = "If `path` is not specified, the runtime MUST create a new container namespace of type `type`." + // NSInheritWithoutType represents "If a namespace type is not specified in the `namespaces` array, the container MUST inherit the runtime namespace of that type." + NSInheritWithoutType = "If a namespace type is not specified in the `namespaces` array, the container MUST inherit the runtime namespace of that type." + // NSErrorOnDup represents "If a `namespaces` field contains duplicated namespaces with same `type`, the runtime MUST generate an error." + NSErrorOnDup = "If a `namespaces` field contains duplicated namespaces with same `type`, the runtime MUST generate an error." + // UserNSMapOwnershipRO represents "The runtime SHOULD NOT modify the ownership of referenced filesystems to realize the mapping." + UserNSMapOwnershipRO = "The runtime SHOULD NOT modify the ownership of referenced filesystems to realize the mapping." + // DevicesAvailable represents "devices (array of objects, OPTIONAL) lists devices that MUST be available in the container." + DevicesAvailable = "devices (array of objects, OPTIONAL) lists devices that MUST be available in the container." + // DevicesFileNotMatch represents "If a file already exists at `path` that does not match the requested device, the runtime MUST generate an error." + DevicesFileNotMatch = "If a file already exists at `path` that does not match the requested device, the runtime MUST generate an error." + // DevicesMajMinRequired represents "`major, minor` (int64, REQUIRED unless `type` is `p`) - major, minor numbers for the device." + DevicesMajMinRequired = "`major, minor` (int64, REQUIRED unless `type` is `p`) - major, minor numbers for the device." + // DevicesErrorOnDup represents "The same `type`, `major` and `minor` SHOULD NOT be used for multiple devices." + DevicesErrorOnDup = "The same `type`, `major` and `minor` SHOULD NOT be used for multiple devices." + // DefaultDevices represents "In addition to any devices configured with this setting, the runtime MUST also supply default devices." + DefaultDevices = "In addition to any devices configured with this setting, the runtime MUST also supply default devices." + // CgroupsPathAbsOrRel represents "The value of `cgroupsPath` MUST be either an absolute path or a relative path." + CgroupsPathAbsOrRel = "The value of `cgroupsPath` MUST be either an absolute path or a relative path." + // CgroupsAbsPathRelToMount represents "In the case of an absolute path (starting with `/`), the runtime MUST take the path to be relative to the cgroups mount point." + CgroupsAbsPathRelToMount = "In the case of an absolute path (starting with `/`), the runtime MUST take the path to be relative to the cgroups mount point." + // CgroupsPathAttach represents "If the value is specified, the runtime MUST consistently attach to the same place in the cgroups hierarchy given the same value of `cgroupsPath`." + CgroupsPathAttach = "If the value is specified, the runtime MUST consistently attach to the same place in the cgroups hierarchy given the same value of `cgroupsPath`." + // CgroupsPathError represents "Runtimes MAY consider certain `cgroupsPath` values to be invalid, and MUST generate an error if this is the case." + CgroupsPathError = "Runtimes MAY consider certain `cgroupsPath` values to be invalid, and MUST generate an error if this is the case." + // DevicesApplyInOrder represents "The runtime MUST apply entries in the listed order." + DevicesApplyInOrder = "The runtime MUST apply entries in the listed order." + // BlkIOWeightOrLeafWeightExist represents "You MUST specify at least one of `weight` or `leafWeight` in a given entry, and MAY specify both." + BlkIOWeightOrLeafWeightExist = "You MUST specify at least one of `weight` or `leafWeight` in a given entry, and MAY specify both." + // IntelRdtPIDWrite represents "If `intelRdt` is set, the runtime MUST write the container process ID to the `<container-id>/tasks` file in a mounted `resctrl` pseudo-filesystem, using the container ID from `start` and creating the `container-id` directory if necessary." + IntelRdtPIDWrite = "If `intelRdt` is set, the runtime MUST write the container process ID to the `<container-id>/tasks` file in a mounted `resctrl` pseudo-filesystem, using the container ID from `start` and creating the `<container-id>` directory if necessary." + // IntelRdtNoMountedResctrlError represents "If no mounted `resctrl` pseudo-filesystem is available in the runtime mount namespace, the runtime MUST generate an error." + IntelRdtNoMountedResctrlError = "If no mounted `resctrl` pseudo-filesystem is available in the runtime mount namespace, the runtime MUST generate an error." + // NotManipResctrlWithoutIntelRdt represents "If `intelRdt` is not set, the runtime MUST NOT manipulate any `resctrl` pseudo-filesystems." + NotManipResctrlWithoutIntelRdt = "If `intelRdt` is not set, the runtime MUST NOT manipulate any `resctrl` pseudo-filesystems." + // IntelRdtL3CacheSchemaWrite represents "If `l3CacheSchema` is set, runtimes MUST write the value to the `schemata` file in the `<container-id>` directory discussed in `intelRdt`." + IntelRdtL3CacheSchemaWrite = "If `l3CacheSchema` is set, runtimes MUST write the value to the `schemata` file in the `<container-id>` directory discussed in `intelRdt`." + // IntelRdtL3CacheSchemaNotWrite represents "If `l3CacheSchema` is not set, runtimes MUST NOT write to `schemata` files in any `resctrl` pseudo-filesystems." + IntelRdtL3CacheSchemaNotWrite = "If `l3CacheSchema` is not set, runtimes MUST NOT write to `schemata` files in any `resctrl` pseudo-filesystems." + // SeccSyscallsNamesRequired represents "`names` MUST contain at least one entry." + SeccSyscallsNamesRequired = "`names` MUST contain at least one entry." + // MaskedPathsAbs represents "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." + MaskedPathsAbs = "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." + // ReadonlyPathsAbs represents "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." + ReadonlyPathsAbs = "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." +) + +var ( + defaultFilesystemsRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config-linux.md#default-filesystems"), nil + } + namespacesRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config-linux.md#namespaces"), nil + } + userNamespaceMappingsRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config-linux.md#user-namespace-mappings"), nil + } + devicesRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config-linux.md#devices"), nil + } + defaultDevicesRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config-linux.md#default-devices"), nil + } + cgroupsPathRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config-linux.md#cgroups-path"), nil + } + deviceWhitelistRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config-linux.md#device-whitelist"), nil + } + blockIoRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config-linux.md#block-io"), nil + } + intelrdtRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config-linux.md#intelrdt"), nil + } + seccompRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config-linux.md#seccomp"), nil + } + maskedPathsRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config-linux.md#masked-paths"), nil + } + readonlyPathsRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config-linux.md#readonly-paths"), nil + } +) + +func init() { + register(DefaultFilesystems, rfc2119.Should, defaultFilesystemsRef) + register(NSPathAbs, rfc2119.Must, namespacesRef) + register(NSProcInPath, rfc2119.Must, namespacesRef) + register(NSPathMatchTypeError, rfc2119.Must, namespacesRef) + register(NSNewNSWithoutPath, rfc2119.Must, namespacesRef) + register(NSInheritWithoutType, rfc2119.Must, namespacesRef) + register(NSErrorOnDup, rfc2119.Must, namespacesRef) + register(UserNSMapOwnershipRO, rfc2119.Should, userNamespaceMappingsRef) + register(DevicesAvailable, rfc2119.Must, devicesRef) + register(DevicesFileNotMatch, rfc2119.Must, devicesRef) + register(DevicesMajMinRequired, rfc2119.Required, devicesRef) + register(DevicesErrorOnDup, rfc2119.Should, devicesRef) + register(DefaultDevices, rfc2119.Must, defaultDevicesRef) + register(CgroupsPathAbsOrRel, rfc2119.Must, cgroupsPathRef) + register(CgroupsAbsPathRelToMount, rfc2119.Must, cgroupsPathRef) + register(CgroupsPathAttach, rfc2119.Must, cgroupsPathRef) + register(CgroupsPathError, rfc2119.Must, cgroupsPathRef) + register(DevicesApplyInOrder, rfc2119.Must, deviceWhitelistRef) + register(BlkIOWeightOrLeafWeightExist, rfc2119.Must, blockIoRef) + register(IntelRdtPIDWrite, rfc2119.Must, intelrdtRef) + register(IntelRdtNoMountedResctrlError, rfc2119.Must, intelrdtRef) + register(NotManipResctrlWithoutIntelRdt, rfc2119.Must, intelrdtRef) + register(IntelRdtL3CacheSchemaWrite, rfc2119.Must, intelrdtRef) + register(IntelRdtL3CacheSchemaNotWrite, rfc2119.Must, intelrdtRef) + register(SeccSyscallsNamesRequired, rfc2119.Must, seccompRef) + register(MaskedPathsAbs, rfc2119.Must, maskedPathsRef) + register(ReadonlyPathsAbs, rfc2119.Must, readonlyPathsRef) +} diff --git a/vendor/github.com/opencontainers/runtime-tools/specerror/config-windows.go b/vendor/github.com/opencontainers/runtime-tools/specerror/config-windows.go new file mode 100644 index 000000000..58765286b --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/specerror/config-windows.go @@ -0,0 +1,32 @@ +package specerror + +import ( + "fmt" + + rfc2119 "github.com/opencontainers/runtime-tools/error" +) + +// define error codes +const ( + // WindowsLayerFoldersRequired represents "`layerFolders` MUST contain at least one entry." + WindowsLayerFoldersRequired = "`layerFolders` MUST contain at least one entry." + // WindowsHyperVPresent represents "If present, the container MUST be run with Hyper-V isolation." + WindowsHyperVPresent = "If present, the container MUST be run with Hyper-V isolation." + // WindowsHyperVOmit represents "If omitted, the container MUST be run as a Windows Server container." + WindowsHyperVOmit = "If omitted, the container MUST be run as a Windows Server container." +) + +var ( + layerfoldersRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config-windows.md#layerfolders"), nil + } + hypervRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config-windows.md#hyperv"), nil + } +) + +func init() { + register(WindowsLayerFoldersRequired, rfc2119.Must, layerfoldersRef) + register(WindowsHyperVPresent, rfc2119.Must, hypervRef) + register(WindowsHyperVOmit, rfc2119.Must, hypervRef) +} diff --git a/vendor/github.com/opencontainers/runtime-tools/specerror/config.go b/vendor/github.com/opencontainers/runtime-tools/specerror/config.go new file mode 100644 index 000000000..e59b459c1 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/specerror/config.go @@ -0,0 +1,188 @@ +package specerror + +import ( + "fmt" + + rfc2119 "github.com/opencontainers/runtime-tools/error" +) + +// define error codes +const ( + // SpecVersionInSemVer represents "`ociVersion` (string, REQUIRED) MUST be in SemVer v2.0.0 format and specifies the version of the Open Container Initiative Runtime Specification with which the bundle complies." + SpecVersionInSemVer = "`ociVersion` (string, REQUIRED) MUST be in SemVer v2.0.0 format and specifies the version of the Open Container Initiative Runtime Specification with which the bundle complies." + // RootOnWindowsRequired represents "On Windows, for Windows Server Containers, this field is REQUIRED." + RootOnWindowsRequired = "On Windows, for Windows Server Containers, this field is REQUIRED." + // RootOnHyperVNotSet represents "For Hyper-V Containers, this field MUST NOT be set." + RootOnHyperVNotSet = "For Hyper-V Containers, this field MUST NOT be set." + // RootOnNonHyperVRequired represents "On all other platforms, this field is REQUIRED." + RootOnNonHyperVRequired = "On all other platforms, this field is REQUIRED." + // RootPathOnWindowsGUID represents "On Windows, `path` MUST be a volume GUID path." + RootPathOnWindowsGUID = "On Windows, `path` MUST be a volume GUID path." + // RootPathOnPosixConvention represents "The value SHOULD be the conventional `rootfs`." + RootPathOnPosixConvention = "The value SHOULD be the conventional `rootfs`." + // RootPathExist represents "A directory MUST exist at the path declared by the field." + RootPathExist = "A directory MUST exist at the path declared by the field." + // RootReadonlyImplement represents "`readonly` (bool, OPTIONAL) If true then the root filesystem MUST be read-only inside the container, defaults to false." + RootReadonlyImplement = "`readonly` (bool, OPTIONAL) If true then the root filesystem MUST be read-only inside the container, defaults to false." + // RootReadonlyOnWindowsFalse represents "* On Windows, this field MUST be omitted or false." + RootReadonlyOnWindowsFalse = "On Windows, this field MUST be omitted or false." + // MountsInOrder represents "The runtime MUST mount entries in the listed order." + MountsInOrder = "The runtime MUST mount entries in the listed order." + // MountsDestAbs represents "Destination of mount point: path inside container. This value MUST be an absolute path." + MountsDestAbs = "Destination of mount point: path inside container. This value MUST be an absolute path." + // MountsDestOnWindowsNotNested represents "Windows: one mount destination MUST NOT be nested within another mount (e.g., c:\\foo and c:\\foo\\bar)." + MountsDestOnWindowsNotNested = "Windows: one mount destination MUST NOT be nested within another mount (e.g., c:\\foo and c:\\foo\\bar)." + // MountsOptionsOnWindowsROSupport represents "Windows: runtimes MUST support `ro`, mounting the filesystem read-only when `ro` is given." + MountsOptionsOnWindowsROSupport = "Windows: runtimes MUST support `ro`, mounting the filesystem read-only when `ro` is given." + // ProcRequiredAtStart represents "This property is REQUIRED when `start` is called." + ProcRequiredAtStart = "This property is REQUIRED when `start` is called." + // ProcConsoleSizeIgnore represents "Runtimes MUST ignore `consoleSize` if `terminal` is `false` or unset." + ProcConsoleSizeIgnore = "Runtimes MUST ignore `consoleSize` if `terminal` is `false` or unset." + // ProcCwdAbs represents "cwd (string, REQUIRED) is the working directory that will be set for the executable. This value MUST be an absolute path." + ProcCwdAbs = "cwd (string, REQUIRED) is the working directory that will be set for the executable. This value MUST be an absolute path." + // ProcArgsOneEntryRequired represents "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*." + ProcArgsOneEntryRequired = "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*." + // PosixProcRlimitsTypeGenError represents "The runtime MUST generate an error for any values which cannot be mapped to a relevant kernel interface." + PosixProcRlimitsTypeGenError = "The runtime MUST generate an error for any values which cannot be mapped to a relevant kernel interface." + // PosixProcRlimitsTypeGet represents "For each entry in `rlimits`, a `getrlimit(3)` on `type` MUST succeed." + PosixProcRlimitsTypeGet = "For each entry in `rlimits`, a `getrlimit(3)` on `type` MUST succeed." + // PosixProcRlimitsTypeValueError represents "valid values are defined in the ... man page" + PosixProcRlimitsTypeValueError = "valid values are defined in the ... man page" + // PosixProcRlimitsSoftMatchCur represents "`rlim.rlim_cur` MUST match the configured value." + PosixProcRlimitsSoftMatchCur = "`rlim.rlim_cur` MUST match the configured value." + // PosixProcRlimitsHardMatchMax represents "`rlim.rlim_max` MUST match the configured value." + PosixProcRlimitsHardMatchMax = "`rlim.rlim_max` MUST match the configured value." + // PosixProcRlimitsErrorOnDup represents "If `rlimits` contains duplicated entries with same `type`, the runtime MUST generate an error." + PosixProcRlimitsErrorOnDup = "If `rlimits` contains duplicated entries with same `type`, the runtime MUST generate an error." + // LinuxProcCapError represents "Any value which cannot be mapped to a relevant kernel interface MUST cause an error." + LinuxProcCapError = "Any value which cannot be mapped to a relevant kernel interface MUST cause an error." + // LinuxProcOomScoreAdjSet represents "If `oomScoreAdj` is set, the runtime MUST set `oom_score_adj` to the given value." + LinuxProcOomScoreAdjSet = "If `oomScoreAdj` is set, the runtime MUST set `oom_score_adj` to the given value." + // LinuxProcOomScoreAdjNotSet represents "If `oomScoreAdj` is not set, the runtime MUST NOT change the value of `oom_score_adj`." + LinuxProcOomScoreAdjNotSet = "If `oomScoreAdj` is not set, the runtime MUST NOT change the value of `oom_score_adj`." + // PlatformSpecConfOnWindowsSet represents "This MUST be set if the target platform of this spec is `windows`." + PlatformSpecConfOnWindowsSet = "This MUST be set if the target platform of this spec is `windows`." + // PosixHooksPathAbs represents "This specification extends the IEEE standard in that `path` MUST be absolute." + PosixHooksPathAbs = "This specification extends the IEEE standard in that `path` MUST be absolute." + // PosixHooksTimeoutPositive represents "If set, `timeout` MUST be greater than zero." + PosixHooksTimeoutPositive = "If set, `timeout` MUST be greater than zero." + // PosixHooksCalledInOrder represents "Hooks MUST be called in the listed order." + PosixHooksCalledInOrder = "Hooks MUST be called in the listed order." + // PosixHooksStateToStdin represents "The 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." + PosixHooksStateToStdin = "The 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." + // PrestartTiming represents "The pre-start hooks MUST be called after the `start` operation is called but before the user-specified program command is executed." + PrestartTiming = "The pre-start hooks MUST be called after the `start` operation is called but before the user-specified program command is executed." + // PoststartTiming represents "The post-start hooks MUST be called after the user-specified process is executed but before the `start` operation returns." + PoststartTiming = "The post-start hooks MUST be called after the user-specified process is executed but before the `start` operation returns." + // PoststopTiming represents "The post-stop hooks MUST be called after the container is deleted but before the `delete` operation returns." + PoststopTiming = "The post-stop hooks MUST be called after the container is deleted but before the `delete` operation returns." + // AnnotationsKeyValueMap represents "Annotations MUST be a key-value map." + AnnotationsKeyValueMap = "Annotations MUST be a key-value map." + // AnnotationsKeyString represents "Keys MUST be strings." + AnnotationsKeyString = "Keys MUST be strings." + // AnnotationsKeyRequired represents "Keys MUST NOT be an empty string." + AnnotationsKeyRequired = "Keys MUST NOT be an empty string." + // AnnotationsKeyReversedDomain represents "Keys SHOULD be named using a reverse domain notation - e.g. `com.example.myKey`." + AnnotationsKeyReversedDomain = "Keys SHOULD be named using a reverse domain notation - e.g. `com.example.myKey`." + // AnnotationsKeyReservedNS represents "Keys using the `org.opencontainers` namespace are reserved and MUST NOT be used by subsequent specifications." + AnnotationsKeyReservedNS = "Keys using the `org.opencontainers` namespace are reserved and MUST NOT be used by subsequent specifications." + // AnnotationsKeyIgnoreUnknown represents "Implementations that are reading/processing this configuration file MUST NOT generate an error if they encounter an unknown annotation key." + AnnotationsKeyIgnoreUnknown = "Implementations that are reading/processing this configuration file MUST NOT generate an error if they encounter an unknown annotation key." + // AnnotationsValueString represents "Values MUST be strings." + AnnotationsValueString = "Values MUST be strings." + // ExtensibilityIgnoreUnknownProp represents "Runtimes that are reading or processing this configuration file MUST NOT generate an error if they encounter an unknown property." + ExtensibilityIgnoreUnknownProp = "Runtimes that are reading or processing this configuration file MUST NOT generate an error if they encounter an unknown property.\nInstead they MUST ignore unknown properties." + // ValidValues represents "Runtimes that are reading or processing this configuration file MUST generate an error when invalid or unsupported values are encountered." + ValidValues = "Runtimes that are reading or processing this configuration file MUST generate an error when invalid or unsupported values are encountered." +) + +var ( + specificationVersionRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config.md#specification-version"), nil + } + rootRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config.md#root"), nil + } + mountsRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config.md#mounts"), nil + } + processRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config.md#process"), nil + } + posixProcessRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config.md#posix-process"), nil + } + linuxProcessRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config.md#linux-process"), nil + } + platformSpecificConfigurationRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config.md#platform-specific-configuration"), nil + } + posixPlatformHooksRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config.md#posix-platform-hooks"), nil + } + prestartRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config.md#prestart"), nil + } + poststartRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config.md#poststart"), nil + } + poststopRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config.md#poststop"), nil + } + annotationsRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config.md#annotations"), nil + } + extensibilityRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config.md#extensibility"), nil + } + validValuesRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "config.md#valid-values"), nil + } +) + +func init() { + register(SpecVersionInSemVer, rfc2119.Must, specificationVersionRef) + register(RootOnWindowsRequired, rfc2119.Required, rootRef) + register(RootOnHyperVNotSet, rfc2119.Must, rootRef) + register(RootOnNonHyperVRequired, rfc2119.Required, rootRef) + register(RootPathOnWindowsGUID, rfc2119.Must, rootRef) + register(RootPathOnPosixConvention, rfc2119.Should, rootRef) + register(RootPathExist, rfc2119.Must, rootRef) + register(RootReadonlyImplement, rfc2119.Must, rootRef) + register(RootReadonlyOnWindowsFalse, rfc2119.Must, rootRef) + register(MountsInOrder, rfc2119.Must, mountsRef) + register(MountsDestAbs, rfc2119.Must, mountsRef) + register(MountsDestOnWindowsNotNested, rfc2119.Must, mountsRef) + register(MountsOptionsOnWindowsROSupport, rfc2119.Must, mountsRef) + register(ProcRequiredAtStart, rfc2119.Required, processRef) + register(ProcConsoleSizeIgnore, rfc2119.Must, processRef) + register(ProcCwdAbs, rfc2119.Must, processRef) + register(ProcArgsOneEntryRequired, rfc2119.Required, processRef) + register(PosixProcRlimitsTypeGenError, rfc2119.Must, posixProcessRef) + register(PosixProcRlimitsTypeGet, rfc2119.Must, posixProcessRef) + register(PosixProcRlimitsTypeValueError, rfc2119.Should, posixProcessRef) + register(PosixProcRlimitsSoftMatchCur, rfc2119.Must, posixProcessRef) + register(PosixProcRlimitsHardMatchMax, rfc2119.Must, posixProcessRef) + register(PosixProcRlimitsErrorOnDup, rfc2119.Must, posixProcessRef) + register(LinuxProcCapError, rfc2119.Must, linuxProcessRef) + register(LinuxProcOomScoreAdjSet, rfc2119.Must, linuxProcessRef) + register(LinuxProcOomScoreAdjNotSet, rfc2119.Must, linuxProcessRef) + register(PlatformSpecConfOnWindowsSet, rfc2119.Must, platformSpecificConfigurationRef) + register(PosixHooksPathAbs, rfc2119.Must, posixPlatformHooksRef) + register(PosixHooksTimeoutPositive, rfc2119.Must, posixPlatformHooksRef) + register(PosixHooksCalledInOrder, rfc2119.Must, posixPlatformHooksRef) + register(PosixHooksStateToStdin, rfc2119.Must, posixPlatformHooksRef) + register(PrestartTiming, rfc2119.Must, prestartRef) + register(PoststartTiming, rfc2119.Must, poststartRef) + register(PoststopTiming, rfc2119.Must, poststopRef) + register(AnnotationsKeyValueMap, rfc2119.Must, annotationsRef) + register(AnnotationsKeyString, rfc2119.Must, annotationsRef) + register(AnnotationsKeyRequired, rfc2119.Must, annotationsRef) + register(AnnotationsKeyReversedDomain, rfc2119.Should, annotationsRef) + register(AnnotationsKeyReservedNS, rfc2119.Must, annotationsRef) + register(AnnotationsKeyIgnoreUnknown, rfc2119.Must, annotationsRef) + register(AnnotationsValueString, rfc2119.Must, annotationsRef) + register(ExtensibilityIgnoreUnknownProp, rfc2119.Must, extensibilityRef) + register(ValidValues, rfc2119.Must, validValuesRef) +} diff --git a/vendor/github.com/opencontainers/runtime-tools/specerror/error.go b/vendor/github.com/opencontainers/runtime-tools/specerror/error.go index c75bb6b14..1cfe054c2 100644 --- a/vendor/github.com/opencontainers/runtime-tools/specerror/error.go +++ b/vendor/github.com/opencontainers/runtime-tools/specerror/error.go @@ -13,46 +13,13 @@ const referenceTemplate = "https://github.com/opencontainers/runtime-spec/blob/v // Code represents the spec violation, enumerating both // configuration violations and runtime violations. -type Code int +type Code string const ( // NonError represents that an input is not an error - NonError Code = iota + NonError = "the input is not an error" // NonRFCError represents that an error is not a rfc2119 error - NonRFCError - - // ConfigFileExistence represents the error code of 'config.json' existence test - ConfigFileExistence - // ArtifactsInSingleDir represents the error code of artifacts place test - ArtifactsInSingleDir - - // SpecVersion represents the error code of specfication version test - SpecVersion - - // RootOnNonHyperV represents the error code of root setting test on non hyper-v containers - RootOnNonHyperV - // RootOnHyperV represents the error code of root setting test on hyper-v containers - RootOnHyperV - // PathFormatOnWindows represents the error code of the path format test on Window - PathFormatOnWindows - // PathName represents the error code of the path name test - PathName - // PathExistence represents the error code of the path existence test - PathExistence - // ReadonlyFilesystem represents the error code of readonly test - ReadonlyFilesystem - // ReadonlyOnWindows represents the error code of readonly setting test on Windows - ReadonlyOnWindows - - // DefaultFilesystems represents the error code of default filesystems test - DefaultFilesystems - - // CreateWithID represents the error code of 'create' lifecyle test with 'id' provided - CreateWithID - // CreateWithUniqueID represents the error code of 'create' lifecyle test with unique 'id' provided - CreateWithUniqueID - // CreateNewContainer represents the error code 'create' lifecyle test that creates new container - CreateNewContainer + NonRFCError = "the error is not a rfc2119 error" ) type errorTemplate struct { @@ -69,52 +36,24 @@ type Error struct { Code Code } -var ( - containerFormatRef = func(version string) (reference string, err error) { - return fmt.Sprintf(referenceTemplate, version, "bundle.md#container-format"), nil - } - specVersionRef = func(version string) (reference string, err error) { - return fmt.Sprintf(referenceTemplate, version, "config.md#specification-version"), nil - } - rootRef = func(version string) (reference string, err error) { - return fmt.Sprintf(referenceTemplate, version, "config.md#root"), nil - } - defaultFSRef = func(version string) (reference string, err error) { - return fmt.Sprintf(referenceTemplate, version, "config-linux.md#default-filesystems"), nil - } - runtimeCreateRef = func(version string) (reference string, err error) { - return fmt.Sprintf(referenceTemplate, version, "runtime.md#create"), nil +// LevelErrors represents Errors filtered into fatal and warnings. +type LevelErrors struct { + // Warnings holds Errors that were below a compliance-level threshold. + Warnings []*Error + + // Error holds errors that were at or above a compliance-level + // threshold, as well as errors that are not Errors. + Error *multierror.Error +} + +var ociErrors = map[Code]errorTemplate{} + +func register(code Code, level rfc2119.Level, ref func(versiong string) (string, error)) { + if _, ok := ociErrors[code]; ok { + panic(fmt.Sprintf("should not regist a same code twice: %s", code)) } -) -var ociErrors = map[Code]errorTemplate{ - // Bundle.md - // Container Format - ConfigFileExistence: {Level: rfc2119.Must, Reference: containerFormatRef}, - ArtifactsInSingleDir: {Level: rfc2119.Must, Reference: containerFormatRef}, - - // Config.md - // Specification Version - SpecVersion: {Level: rfc2119.Must, Reference: specVersionRef}, - // Root - RootOnNonHyperV: {Level: rfc2119.Required, Reference: rootRef}, - RootOnHyperV: {Level: rfc2119.Must, Reference: rootRef}, - // TODO: add tests for 'PathFormatOnWindows' - PathFormatOnWindows: {Level: rfc2119.Must, Reference: rootRef}, - PathName: {Level: rfc2119.Should, Reference: rootRef}, - PathExistence: {Level: rfc2119.Must, Reference: rootRef}, - ReadonlyFilesystem: {Level: rfc2119.Must, Reference: rootRef}, - ReadonlyOnWindows: {Level: rfc2119.Must, Reference: rootRef}, - - // Config-Linux.md - // Default Filesystems - DefaultFilesystems: {Level: rfc2119.Should, Reference: defaultFSRef}, - - // Runtime.md - // Create - CreateWithID: {Level: rfc2119.Must, Reference: runtimeCreateRef}, - CreateWithUniqueID: {Level: rfc2119.Must, Reference: runtimeCreateRef}, - CreateNewContainer: {Level: rfc2119.Must, Reference: runtimeCreateRef}, + ociErrors[code] = errorTemplate{Level: level, Reference: ref} } // Error returns the error message with specification reference. @@ -168,3 +107,23 @@ func FindError(err error, code Code) Code { } return NonRFCError } + +// SplitLevel removes RFC 2119 errors with a level less than 'level' +// from the source error. If the source error is not a multierror, it +// is returned unchanged. +func SplitLevel(errIn error, level rfc2119.Level) (levelErrors LevelErrors, errOut error) { + merr, ok := errIn.(*multierror.Error) + if !ok { + return levelErrors, errIn + } + for _, err := range merr.Errors { + e, ok := err.(*Error) + if ok && e.Err.Level < level { + fmt.Println(e) + levelErrors.Warnings = append(levelErrors.Warnings, e) + continue + } + levelErrors.Error = multierror.Append(levelErrors.Error, err) + } + return levelErrors, nil +} diff --git a/vendor/github.com/opencontainers/runtime-tools/specerror/runtime-linux.go b/vendor/github.com/opencontainers/runtime-tools/specerror/runtime-linux.go new file mode 100644 index 000000000..3ce7c3ed4 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/specerror/runtime-linux.go @@ -0,0 +1,23 @@ +package specerror + +import ( + "fmt" + + rfc2119 "github.com/opencontainers/runtime-tools/error" +) + +// define error codes +const ( + // DefaultRuntimeLinuxSymlinks represents "While creating the container (step 2 in the lifecycle), runtimes MUST create default symlinks if the source file exists after processing `mounts`." + DefaultRuntimeLinuxSymlinks = "While creating the container (step 2 in the lifecycle), runtimes MUST create the default symlinks if the source file exists after processing `mounts`." +) + +var ( + devSymbolicLinksRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "runtime-linux.md#dev-symbolic-links"), nil + } +) + +func init() { + register(DefaultRuntimeLinuxSymlinks, rfc2119.Must, devSymbolicLinksRef) +} diff --git a/vendor/github.com/opencontainers/runtime-tools/specerror/runtime.go b/vendor/github.com/opencontainers/runtime-tools/specerror/runtime.go new file mode 100644 index 000000000..7552b3c84 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/specerror/runtime.go @@ -0,0 +1,179 @@ +package specerror + +import ( + "fmt" + + rfc2119 "github.com/opencontainers/runtime-tools/error" +) + +// define error codes +const ( + // EntityOperSameContainer represents "The entity using a runtime to create a container MUST be able to use the operations defined in this specification against that same container." + EntityOperSameContainer = "The entity using a runtime to create a container MUST be able to use the operations defined in this specification against that same container." + // StateIDUniq represents "`id` (string, REQUIRED) is the container's ID. This MUST be unique across all containers on this host." + StateIDUniq = "`id` (string, REQUIRED) is the container's ID. This MUST be unique across all containers on this host." + // StateNewStatus represents "Additional values MAY be defined by the runtime, however, they MUST be used to represent new runtime states not defined above." + StateNewStatus = "Additional values MAY be defined by the runtime, however, they MUST be used to represent new runtime states not defined above." + // DefaultStateJSONPattern represents "When serialized in JSON, the format MUST adhere to the default pattern." + DefaultStateJSONPattern = "When serialized in JSON, the format MUST adhere to the default pattern." + // EnvCreateImplement represents "The container's runtime environment MUST be created according to the configuration in `config.json`." + EnvCreateImplement = "The container's runtime environment MUST be created according to the configuration in `config.json`." + // EnvCreateError represents "If the runtime is unable to create the environment specified in the `config.json`, it MUST generate an error." + EnvCreateError = "If the runtime is unable to create the environment specified in the `config.json`. it MUST generate an error." + // ProcNotRunAtResRequest represents "While the resources requested in the `config.json` MUST be created, the user-specified program (from `process`) MUST NOT be run at this time." + ProcNotRunAtResRequest = "While the resources requested in the `config.json` MUST be created, the user-specified program (from `process`) MUST NOT be run at this time." + // ConfigUpdatesWithoutAffect represents "Any updates to `config.json` after this step MUST NOT affect the container." + ConfigUpdatesWithoutAffect = "Any updates to `config.json` after this step MUST NOT affect the container." + // PrestartHooksInvoke represents "The prestart hooks MUST be invoked by the runtime." + PrestartHooksInvoke = "The prestart hooks MUST be invoked by the runtime." + // PrestartHookFailGenError represents "If any prestart hook fails, the runtime MUST generate an error, stop the container, and continue the lifecycle at step 9." + PrestartHookFailGenError = "If any prestart hook fails, the runtime MUST generate an error, stop the container, and continue the lifecycle at step 9." + // ProcImplement represents "The runtime MUST run the user-specified program, as specified by `process`." + ProcImplement = "The runtime MUST run the user-specified program, as specified by `process`." + // PoststartHooksInvoke represents "The poststart hooks MUST be invoked by the runtime." + PoststartHooksInvoke = "The poststart hooks MUST be invoked by the runtime." + // PoststartHookFailGenWarn represents "If any poststart hook fails, the runtime MUST log a warning, but the remaining hooks and lifecycle continue as if the hook had succeeded." + PoststartHookFailGenWarn = "If any poststart hook fails, the runtime MUST log a warning, but the remaining hooks and lifecycle continue as if the hook had succeeded." + // UndoCreateSteps represents "The container MUST be destroyed by undoing the steps performed during create phase (step 2)." + UndoCreateSteps = "The container MUST be destroyed by undoing the steps performed during create phase (step 2)." + // PoststopHooksInvoke represents "The poststop hooks MUST be invoked by the runtime." + PoststopHooksInvoke = "The poststop hooks MUST be invoked by the runtime." + // PoststopHookFailGenWarn represents "If any poststop hook fails, the runtime MUST log a warning, but the remaining hooks and lifecycle continue as if the hook had succeeded." + PoststopHookFailGenWarn = "If any poststop hook fails, the runtime MUST log a warning, but the remaining hooks and lifecycle continue as if the hook had succeeded." + // ErrorsLeaveStateUnchange represents "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." + ErrorsLeaveStateUnchange = "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." + // WarnsLeaveFlowUnchange represents "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." + WarnsLeaveFlowUnchange = "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." + // DefaultOperations represents "Unless otherwise stated, runtimes MUST support the default operations." + DefaultOperations = "Unless otherwise stated, runtimes MUST support the default operations." + // QueryWithoutIDGenError represents "This operation MUST generate an error if it is not provided the ID of a container." + QueryWithoutIDGenError = "This operation MUST generate an error if it is not provided the ID of a container." + // QueryNonExistGenError represents "Attempting to query a container that does not exist MUST generate an error." + QueryNonExistGenError = "Attempting to query a container that does not exist MUST generate an error." + // QueryStateImplement represents "This operation MUST return the state of a container as specified in the State section." + QueryStateImplement = "This operation MUST return the state of a container as specified in the State section." + // CreateWithBundlePathAndID represents "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." + CreateWithBundlePathAndID = "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." + // CreateWithUniqueID represents "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." + CreateWithUniqueID = "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." + // CreateNewContainer represents "This operation MUST create a new container." + CreateNewContainer = "This operation MUST create a new container." + // PropsApplyExceptProcOnCreate represents "All of the properties configured in `config.json` except for `process` MUST be applied." + PropsApplyExceptProcOnCreate = "All of the properties configured in `config.json` except for `process` MUST be applied." + // ProcArgsApplyUntilStart represents `process.args` MUST NOT be applied until triggered by the `start` operation." + ProcArgsApplyUntilStart = "`process.args` MUST NOT be applied until triggered by the `start` operation." + // PropApplyFailGenError represents "If the runtime cannot apply a property as specified in the configuration, it MUST generate an error." + PropApplyFailGenError = "If the runtime cannot apply a property as specified in the configuration, it MUST generate an error." + // PropApplyFailNotCreate represents "If the runtime cannot apply a property as specified in the configuration, a new container MUST NOT be created." + PropApplyFailNotCreate = "If the runtime cannot apply a property as specified in the configuration, a new container MUST NOT be created." + // StartWithoutIDGenError represents "`start` operation MUST generate an error if it is not provided the container ID." + StartWithoutIDGenError = "`start` operation MUST generate an error if it is not provided the container ID." + // StartNonCreateHaveNoEffect represents "Attempting to `start` a container that is not `created` MUST have no effect on the container." + StartNonCreateHaveNoEffect = "Attempting to `start` a container that is not `created` MUST have no effect on the container." + // StartNonCreateGenError represents "Attempting to `start` a container that is not `created` MUST generate an error." + StartNonCreateGenError = "Attempting to `start` a container that is not `created` MUST generate an error." + // StartProcImplement represents "`start` operation MUST run the user-specified program as specified by `process`." + StartProcImplement = "`start` operation MUST run the user-specified program as specified by `process`." + // StartWithProcUnsetGenError represents "`start` operation MUST generate an error if `process` was not set." + StartWithProcUnsetGenError = "`start` operation MUST generate an error if `process` was not set." + // KillWithoutIDGenError represents "`kill` operation MUST generate an error if it is not provided the container ID." + KillWithoutIDGenError = "`kill` operation MUST generate an error if it is not provided the container ID." + // KillNonCreateRunHaveNoEffect represents "Attempting to send a signal to a container that is neither `created` nor `running` MUST have no effect on the container." + KillNonCreateRunHaveNoEffect = "Attempting to send a signal to a container that is neither `created` nor `running` MUST have no effect on the container." + // KillNonCreateRunGenError represents "Attempting to send a signal to a container that is neither `created` nor `running` MUST generate an error." + KillNonCreateRunGenError = "Attempting to send a signal to a container that is neither `created` nor `running` MUST generate an error." + // KillSignalImplement represents "`kill` operation MUST send the specified signal to the container process." + KillSignalImplement = "`kill` operation MUST send the specified signal to the container process." + // DeleteWithoutIDGenError represents "`delete` operation MUST generate an error if it is not provided the container ID." + DeleteWithoutIDGenError = "`delete` operation MUST generate an error if it is not provided the container ID." + // DeleteNonStopHaveNoEffect represents "Attempting to `delete` a container that is not `stopped` MUST have no effect on the container." + DeleteNonStopHaveNoEffect = "Attempting to `delete` a container that is not `stopped` MUST have no effect on the container." + // DeleteNonStopGenError represents "Attempting to `delete` a container that is not `stopped` MUST generate an error." + DeleteNonStopGenError = "Attempting to `delete` a container that is not `stopped` MUST generate an error." + // DeleteResImplement represents "Deleting a container MUST delete the resources that were created during the `create` step." + DeleteResImplement = "Deleting a container MUST delete the resources that were created during the `create` step." + // DeleteOnlyCreatedRes represents "Note that resources associated with the container, but not created by this container, MUST NOT be deleted." + DeleteOnlyCreatedRes = "Note that resources associated with the container, but not created by this container, MUST NOT be deleted." +) + +var ( + scopeOfAContainerRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "runtime.md#scope-of-a-container"), nil + } + stateRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "runtime.md#state"), nil + } + lifecycleRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "runtime.md#lifecycle"), nil + } + errorsRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "runtime.md#errors"), nil + } + warningsRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "runtime.md#warnings"), nil + } + operationsRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "runtime.md#operations"), nil + } + queryStateRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "runtime.md#query-state"), nil + } + createRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "runtime.md#create"), nil + } + startRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "runtime.md#start"), nil + } + killRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "runtime.md#kill"), nil + } + deleteRef = func(version string) (reference string, err error) { + return fmt.Sprintf(referenceTemplate, version, "runtime.md#delete"), nil + } +) + +func init() { + register(EntityOperSameContainer, rfc2119.Must, scopeOfAContainerRef) + register(StateIDUniq, rfc2119.Must, stateRef) + register(StateNewStatus, rfc2119.Must, stateRef) + register(DefaultStateJSONPattern, rfc2119.Must, stateRef) + register(EnvCreateImplement, rfc2119.Must, lifecycleRef) + register(EnvCreateError, rfc2119.Must, lifecycleRef) + register(ProcNotRunAtResRequest, rfc2119.Must, lifecycleRef) + register(ConfigUpdatesWithoutAffect, rfc2119.Must, lifecycleRef) + register(PrestartHooksInvoke, rfc2119.Must, lifecycleRef) + register(PrestartHookFailGenError, rfc2119.Must, lifecycleRef) + register(ProcImplement, rfc2119.Must, lifecycleRef) + register(PoststartHooksInvoke, rfc2119.Must, lifecycleRef) + register(PoststartHookFailGenWarn, rfc2119.Must, lifecycleRef) + register(UndoCreateSteps, rfc2119.Must, lifecycleRef) + register(PoststopHooksInvoke, rfc2119.Must, lifecycleRef) + register(PoststopHookFailGenWarn, rfc2119.Must, lifecycleRef) + register(ErrorsLeaveStateUnchange, rfc2119.Must, errorsRef) + register(WarnsLeaveFlowUnchange, rfc2119.Must, warningsRef) + register(DefaultOperations, rfc2119.Must, operationsRef) + register(QueryWithoutIDGenError, rfc2119.Must, queryStateRef) + register(QueryNonExistGenError, rfc2119.Must, queryStateRef) + register(QueryStateImplement, rfc2119.Must, queryStateRef) + register(CreateWithBundlePathAndID, rfc2119.Must, createRef) + register(CreateWithUniqueID, rfc2119.Must, createRef) + register(CreateNewContainer, rfc2119.Must, createRef) + register(PropsApplyExceptProcOnCreate, rfc2119.Must, createRef) + register(ProcArgsApplyUntilStart, rfc2119.Must, createRef) + register(PropApplyFailGenError, rfc2119.Must, createRef) + register(PropApplyFailNotCreate, rfc2119.Must, createRef) + register(StartWithoutIDGenError, rfc2119.Must, startRef) + register(StartNonCreateHaveNoEffect, rfc2119.Must, startRef) + register(StartNonCreateGenError, rfc2119.Must, startRef) + register(StartProcImplement, rfc2119.Must, startRef) + register(StartWithProcUnsetGenError, rfc2119.Must, startRef) + register(KillWithoutIDGenError, rfc2119.Must, killRef) + register(KillNonCreateRunHaveNoEffect, rfc2119.Must, killRef) + register(KillNonCreateRunGenError, rfc2119.Must, killRef) + register(KillSignalImplement, rfc2119.Must, killRef) + register(DeleteWithoutIDGenError, rfc2119.Must, deleteRef) + register(DeleteNonStopHaveNoEffect, rfc2119.Must, deleteRef) + register(DeleteNonStopGenError, rfc2119.Must, deleteRef) + register(DeleteResImplement, rfc2119.Must, deleteRef) + register(DeleteOnlyCreatedRes, rfc2119.Must, deleteRef) +} diff --git a/vendor/github.com/opencontainers/runtime-tools/validate/validate.go b/vendor/github.com/opencontainers/runtime-tools/validate/validate.go index bbdb29c60..0914bc691 100644 --- a/vendor/github.com/opencontainers/runtime-tools/validate/validate.go +++ b/vendor/github.com/opencontainers/runtime-tools/validate/validate.go @@ -20,33 +20,41 @@ import ( "github.com/blang/semver" "github.com/hashicorp/go-multierror" rspec "github.com/opencontainers/runtime-spec/specs-go" + osFilepath "github.com/opencontainers/runtime-tools/filepath" "github.com/sirupsen/logrus" "github.com/syndtr/gocapability/capability" "github.com/opencontainers/runtime-tools/specerror" + "github.com/xeipuuv/gojsonschema" ) const specConfig = "config.json" var ( - defaultRlimits = []string{ + // http://pubs.opengroup.org/onlinepubs/9699919799/functions/getrlimit.html + posixRlimits = []string{ "RLIMIT_AS", "RLIMIT_CORE", "RLIMIT_CPU", "RLIMIT_DATA", "RLIMIT_FSIZE", - "RLIMIT_LOCKS", + "RLIMIT_NOFILE", + "RLIMIT_STACK", + } + + // https://git.kernel.org/pub/scm/docs/man-pages/man-pages.git/tree/man2/getrlimit.2?h=man-pages-4.13 + linuxRlimits = append(posixRlimits, []string{ "RLIMIT_MEMLOCK", "RLIMIT_MSGQUEUE", "RLIMIT_NICE", - "RLIMIT_NOFILE", "RLIMIT_NPROC", "RLIMIT_RSS", "RLIMIT_RTPRIO", "RLIMIT_RTTIME", "RLIMIT_SIGPENDING", - "RLIMIT_STACK", - } + }...) + + configSchemaTemplate = "https://raw.githubusercontent.com/opencontainers/runtime-spec/v%s/schema/config-schema.json" ) // Validator represents a validator for runtime bundle @@ -86,7 +94,7 @@ func NewValidatorFromPath(bundlePath string, hostSpecific bool, platform string) configPath := filepath.Join(bundlePath, specConfig) content, err := ioutil.ReadFile(configPath) if err != nil { - return Validator{}, specerror.NewError(specerror.ConfigFileExistence, err, rspec.Version) + return Validator{}, specerror.NewError(specerror.ConfigInRootBundleDir, err, rspec.Version) } if !utf8.Valid(content) { return Validator{}, fmt.Errorf("%q is not encoded in UTF-8", configPath) @@ -100,7 +108,9 @@ func NewValidatorFromPath(bundlePath string, hostSpecific bool, platform string) } // CheckAll checks all parts of runtime bundle -func (v *Validator) CheckAll() (errs error) { +func (v *Validator) CheckAll() error { + var errs *multierror.Error + errs = multierror.Append(errs, v.CheckJSONSchema()) errs = multierror.Append(errs, v.CheckPlatform()) errs = multierror.Append(errs, v.CheckRoot()) errs = multierror.Append(errs, v.CheckMandatoryFields()) @@ -110,7 +120,50 @@ func (v *Validator) CheckAll() (errs error) { errs = multierror.Append(errs, v.CheckHooks()) errs = multierror.Append(errs, v.CheckLinux()) - return + return errs.ErrorOrNil() +} + +// JSONSchemaURL returns the URL for the JSON Schema specifying the +// configuration format. It consumes configSchemaTemplate, but we +// provide it as a function to isolate consumers from inconsistent +// naming as runtime-spec evolves. +func JSONSchemaURL(version string) (url string, err error) { + ver, err := semver.Parse(version) + if err != nil { + return "", specerror.NewError(specerror.SpecVersionInSemVer, err, rspec.Version) + } + configRenamedToConfigSchemaVersion, err := semver.Parse("1.0.0-rc2") // config.json became config-schema.json in 1.0.0-rc2 + if ver.Compare(configRenamedToConfigSchemaVersion) == -1 { + return "", fmt.Errorf("unsupported configuration version (older than %s)", configRenamedToConfigSchemaVersion) + } + return fmt.Sprintf(configSchemaTemplate, version), nil +} + +// CheckJSONSchema validates the configuration against the +// runtime-spec JSON Schema, using the version of the schema that +// matches the configuration's declared version. +func (v *Validator) CheckJSONSchema() (errs error) { + url, err := JSONSchemaURL(v.spec.Version) + if err != nil { + errs = multierror.Append(errs, err) + return errs + } + + schemaLoader := gojsonschema.NewReferenceLoader(url) + documentLoader := gojsonschema.NewGoLoader(v.spec) + result, err := gojsonschema.Validate(schemaLoader, documentLoader) + if err != nil { + errs = multierror.Append(errs, err) + return errs + } + + if !result.Valid() { + for _, resultError := range result.Errors() { + errs = multierror.Append(errs, errors.New(resultError.String())) + } + } + + return errs } // CheckRoot checks status of v.spec.Root @@ -120,13 +173,30 @@ func (v *Validator) CheckRoot() (errs error) { if v.platform == "windows" && v.spec.Windows != nil && v.spec.Windows.HyperV != nil { if v.spec.Root != nil { errs = multierror.Append(errs, - specerror.NewError(specerror.RootOnHyperV, fmt.Errorf("for Hyper-V containers, Root must not be set"), rspec.Version)) + specerror.NewError(specerror.RootOnHyperVNotSet, fmt.Errorf("for Hyper-V containers, Root must not be set"), rspec.Version)) return } return } else if v.spec.Root == nil { errs = multierror.Append(errs, - specerror.NewError(specerror.RootOnNonHyperV, fmt.Errorf("for non-Hyper-V containers, Root must be set"), rspec.Version)) + specerror.NewError(specerror.RootOnNonHyperVRequired, fmt.Errorf("for non-Hyper-V containers, Root must be set"), rspec.Version)) + return + } + + if v.platform == "windows" { + matched, err := regexp.MatchString(`\\\\[?]\\Volume[{][a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}[}]\\`, v.spec.Root.Path) + if err != nil { + errs = multierror.Append(errs, err) + } else if !matched { + errs = multierror.Append(errs, + specerror.NewError(specerror.RootPathOnWindowsGUID, fmt.Errorf("root.path is %q, but it MUST be a volume GUID path when target platform is windows", v.spec.Root.Path), rspec.Version)) + } + + if v.spec.Root.Readonly { + errs = multierror.Append(errs, + specerror.NewError(specerror.RootReadonlyOnWindowsFalse, fmt.Errorf("root.readonly field MUST be omitted or false when target platform is windows"), rspec.Version)) + } + return } @@ -138,7 +208,7 @@ func (v *Validator) CheckRoot() (errs error) { if filepath.Base(v.spec.Root.Path) != "rootfs" { errs = multierror.Append(errs, - specerror.NewError(specerror.PathName, fmt.Errorf("path name should be the conventional 'rootfs'"), rspec.Version)) + specerror.NewError(specerror.RootPathOnPosixConvention, fmt.Errorf("path name should be the conventional 'rootfs'"), rspec.Version)) } var rootfsPath string @@ -158,10 +228,10 @@ func (v *Validator) CheckRoot() (errs error) { if fi, err := os.Stat(rootfsPath); err != nil { errs = multierror.Append(errs, - specerror.NewError(specerror.PathExistence, fmt.Errorf("cannot find the root path %q", rootfsPath), rspec.Version)) + specerror.NewError(specerror.RootPathExist, fmt.Errorf("cannot find the root path %q", rootfsPath), rspec.Version)) } else if !fi.IsDir() { errs = multierror.Append(errs, - specerror.NewError(specerror.PathExistence, fmt.Errorf("root.path %q is not a directory", rootfsPath), rspec.Version)) + specerror.NewError(specerror.RootPathExist, fmt.Errorf("root.path %q is not a directory", rootfsPath), rspec.Version)) } rootParent := filepath.Dir(absRootPath) @@ -170,13 +240,6 @@ func (v *Validator) CheckRoot() (errs error) { specerror.NewError(specerror.ArtifactsInSingleDir, fmt.Errorf("root.path is %q, but it MUST be a child of %q", v.spec.Root.Path, absBundlePath), rspec.Version)) } - if v.platform == "windows" { - if v.spec.Root.Readonly { - errs = multierror.Append(errs, - specerror.NewError(specerror.ReadonlyOnWindows, fmt.Errorf("root.readonly field MUST be omitted or false when target platform is windows"), rspec.Version)) - } - } - return } @@ -188,7 +251,7 @@ func (v *Validator) CheckSemVer() (errs error) { _, err := semver.Parse(version) if err != nil { errs = multierror.Append(errs, - specerror.NewError(specerror.SpecVersion, fmt.Errorf("%q is not valid SemVer: %s", version, err.Error()), rspec.Version)) + specerror.NewError(specerror.SpecVersionInSemVer, fmt.Errorf("%q is not valid SemVer: %s", version, err.Error()), rspec.Version)) } if version != rspec.Version { errs = multierror.Append(errs, fmt.Errorf("validate currently only handles version %s, but the supplied configuration targets %s", rspec.Version, version)) @@ -202,18 +265,23 @@ func (v *Validator) CheckHooks() (errs error) { logrus.Debugf("check hooks") if v.spec.Hooks != nil { - errs = multierror.Append(errs, checkEventHooks("pre-start", v.spec.Hooks.Prestart, v.HostSpecific)) - errs = multierror.Append(errs, checkEventHooks("post-start", v.spec.Hooks.Poststart, v.HostSpecific)) - errs = multierror.Append(errs, checkEventHooks("post-stop", v.spec.Hooks.Poststop, v.HostSpecific)) + errs = multierror.Append(errs, v.checkEventHooks("prestart", v.spec.Hooks.Prestart, v.HostSpecific)) + errs = multierror.Append(errs, v.checkEventHooks("poststart", v.spec.Hooks.Poststart, v.HostSpecific)) + errs = multierror.Append(errs, v.checkEventHooks("poststop", v.spec.Hooks.Poststop, v.HostSpecific)) } return } -func checkEventHooks(hookType string, hooks []rspec.Hook, hostSpecific bool) (errs error) { - for _, hook := range hooks { - if !filepath.IsAbs(hook.Path) { - errs = multierror.Append(errs, fmt.Errorf("the %s hook %v: is not absolute path", hookType, hook.Path)) +func (v *Validator) checkEventHooks(hookType string, hooks []rspec.Hook, hostSpecific bool) (errs error) { + for i, hook := range hooks { + if !osFilepath.IsAbs(v.platform, hook.Path) { + errs = multierror.Append(errs, + specerror.NewError( + specerror.PosixHooksPathAbs, + fmt.Errorf("hooks.%s[%d].path %v: is not absolute path", + hookType, i, hook.Path), + rspec.Version)) } if hostSpecific { @@ -245,8 +313,12 @@ func (v *Validator) CheckProcess() (errs error) { } process := v.spec.Process - if !filepath.IsAbs(process.Cwd) { - errs = multierror.Append(errs, fmt.Errorf("cwd %q is not an absolute path", process.Cwd)) + if !osFilepath.IsAbs(v.platform, process.Cwd) { + errs = multierror.Append(errs, + specerror.NewError( + specerror.ProcCwdAbs, + fmt.Errorf("cwd %q is not an absolute path", process.Cwd), + rspec.Version)) } for _, env := range process.Env { @@ -256,7 +328,11 @@ func (v *Validator) CheckProcess() (errs error) { } if len(process.Args) == 0 { - errs = multierror.Append(errs, fmt.Errorf("args must not be empty")) + errs = multierror.Append(errs, + specerror.NewError( + specerror.ProcArgsOneEntryRequired, + fmt.Errorf("args must not be empty"), + rspec.Version)) } else { if filepath.IsAbs(process.Args[0]) { var rootfsPath string @@ -348,7 +424,7 @@ func (v *Validator) CheckCapabilities() (errs error) { if effective && !permitted { errs = multierror.Append(errs, fmt.Errorf("effective capability %q is not allowed, as it's not permitted", capability)) } - if ambient && !(effective && inheritable) { + if ambient && !(permitted && inheritable) { errs = multierror.Append(errs, fmt.Errorf("ambient capability %q is not allowed, as it's not permitted and inheribate", capability)) } } @@ -361,11 +437,20 @@ func (v *Validator) CheckCapabilities() (errs error) { // CheckRlimits checks v.spec.Process.Rlimits func (v *Validator) CheckRlimits() (errs error) { + if v.platform == "windows" { + return + } + 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 { - errs = multierror.Append(errs, fmt.Errorf("rlimit can not contain the same type %q", process.Rlimits[index].Type)) + errs = multierror.Append(errs, + specerror.NewError( + specerror.PosixProcRlimitsErrorOnDup, + fmt.Errorf("rlimit can not contain the same type %q", + process.Rlimits[index].Type), + rspec.Version)) } } errs = multierror.Append(errs, v.rlimitValid(rlimit)) @@ -429,31 +514,33 @@ func (v *Validator) CheckMounts() (errs error) { if supportedTypes != nil && !supportedTypes[mountA.Type] { errs = multierror.Append(errs, fmt.Errorf("unsupported mount type %q", mountA.Type)) } - if v.platform == "windows" { - if err := pathValid(v.platform, mountA.Destination); err != nil { - errs = multierror.Append(errs, err) - } - if err := pathValid(v.platform, mountA.Source); err != nil { - errs = multierror.Append(errs, err) - } - } else { - if err := pathValid(v.platform, mountA.Destination); err != nil { - errs = multierror.Append(errs, err) - } + if !osFilepath.IsAbs(v.platform, mountA.Destination) { + errs = multierror.Append(errs, + specerror.NewError( + specerror.MountsDestAbs, + fmt.Errorf("mounts[%d].destination %q is not absolute", + i, + mountA.Destination), + rspec.Version)) } for j, mountB := range v.spec.Mounts { if i == j { continue } // whether B.Desination is nested within A.Destination - nested, err := nestedValid(v.platform, mountA.Destination, mountB.Destination) + nested, err := osFilepath.IsAncestor(v.platform, mountA.Destination, mountB.Destination, ".") if err != nil { errs = multierror.Append(errs, err) continue } if nested { if v.platform == "windows" && i < j { - errs = multierror.Append(errs, fmt.Errorf("on Windows, %v nested within %v is forbidden", mountB.Destination, mountA.Destination)) + errs = multierror.Append(errs, + specerror.NewError( + specerror.MountsDestOnWindowsNotNested, + fmt.Errorf("on Windows, %v nested within %v is forbidden", + mountB.Destination, mountA.Destination), + rspec.Version)) } if i > j { logrus.Warnf("%v will be covered by %v", mountB.Destination, mountA.Destination) @@ -476,7 +563,11 @@ func (v *Validator) CheckPlatform() (errs error) { if v.platform == "windows" { if v.spec.Windows == nil { - errs = multierror.Append(errs, errors.New("'windows' MUST be set when platform is `windows`")) + errs = multierror.Append(errs, + specerror.NewError( + specerror.PlatformSpecConfOnWindowsSet, + fmt.Errorf("'windows' MUST be set when platform is `windows`"), + rspec.Version)) } } @@ -506,14 +597,14 @@ func (v *Validator) CheckLinux() (errs error) { for index := 0; index < len(v.spec.Linux.Namespaces); index++ { ns := v.spec.Linux.Namespaces[index] - if !namespaceValid(ns) { + if !v.namespaceValid(ns) { errs = multierror.Append(errs, fmt.Errorf("namespace %v is invalid", ns)) } tmpItem := nsTypeList[ns.Type] tmpItem.num = tmpItem.num + 1 if tmpItem.num > 1 { - errs = multierror.Append(errs, fmt.Errorf("duplicated namespace %q", ns.Type)) + errs = multierror.Append(errs, specerror.NewError(specerror.NSErrorOnDup, fmt.Errorf("duplicated namespace %q", ns.Type), rspec.Version)) } if len(ns.Path) == 0 { @@ -572,7 +663,8 @@ func (v *Validator) CheckLinux() (errs error) { } else { fStat, ok := fi.Sys().(*syscall.Stat_t) if !ok { - errs = multierror.Append(errs, fmt.Errorf("cannot determine state for device %s", device.Path)) + errs = multierror.Append(errs, specerror.NewError(specerror.DevicesAvailable, + fmt.Errorf("cannot determine state for device %s", device.Path), rspec.Version)) continue } var devType string @@ -587,7 +679,8 @@ func (v *Validator) CheckLinux() (errs error) { devType = "unmatched" } if devType != device.Type || (devType == "c" && device.Type == "u") { - errs = multierror.Append(errs, fmt.Errorf("unmatched %s already exists in filesystem", device.Path)) + errs = multierror.Append(errs, specerror.NewError(specerror.DevicesFileNotMatch, + fmt.Errorf("unmatched %s already exists in filesystem", device.Path), rspec.Version)) continue } if devType != "p" { @@ -595,7 +688,8 @@ func (v *Validator) CheckLinux() (errs error) { major := (dev >> 8) & 0xfff minor := (dev & 0xff) | ((dev >> 12) & 0xfff00) if int64(major) != device.Major || int64(minor) != device.Minor { - errs = multierror.Append(errs, fmt.Errorf("unmatched %s already exists in filesystem", device.Path)) + errs = multierror.Append(errs, specerror.NewError(specerror.DevicesFileNotMatch, + fmt.Errorf("unmatched %s already exists in filesystem", device.Path), rspec.Version)) continue } } @@ -603,19 +697,22 @@ func (v *Validator) CheckLinux() (errs error) { expectedPerm := *device.FileMode & os.ModePerm actualPerm := fi.Mode() & os.ModePerm if expectedPerm != actualPerm { - errs = multierror.Append(errs, fmt.Errorf("unmatched %s already exists in filesystem", device.Path)) + errs = multierror.Append(errs, specerror.NewError(specerror.DevicesFileNotMatch, + fmt.Errorf("unmatched %s already exists in filesystem", device.Path), rspec.Version)) continue } } if device.UID != nil { if *device.UID != fStat.Uid { - errs = multierror.Append(errs, fmt.Errorf("unmatched %s already exists in filesystem", device.Path)) + errs = multierror.Append(errs, specerror.NewError(specerror.DevicesFileNotMatch, + fmt.Errorf("unmatched %s already exists in filesystem", device.Path), rspec.Version)) continue } } if device.GID != nil { if *device.GID != fStat.Gid { - errs = multierror.Append(errs, fmt.Errorf("unmatched %s already exists in filesystem", device.Path)) + errs = multierror.Append(errs, specerror.NewError(specerror.DevicesFileNotMatch, + fmt.Errorf("unmatched %s already exists in filesystem", device.Path), rspec.Version)) continue } } @@ -645,29 +742,23 @@ func (v *Validator) CheckLinux() (errs error) { errs = multierror.Append(errs, v.CheckSeccomp()) } - switch v.spec.Linux.RootfsPropagation { - case "": - case "private": - case "rprivate": - case "slave": - case "rslave": - case "shared": - case "rshared": - case "unbindable": - case "runbindable": - default: - errs = multierror.Append(errs, errors.New("rootfsPropagation must be empty or one of \"private|rprivate|slave|rslave|shared|rshared|unbindable|runbindable\"")) - } - for _, maskedPath := range v.spec.Linux.MaskedPaths { if !strings.HasPrefix(maskedPath, "/") { - errs = multierror.Append(errs, fmt.Errorf("maskedPath %v is not an absolute path", maskedPath)) + errs = multierror.Append(errs, + specerror.NewError( + specerror.MaskedPathsAbs, + fmt.Errorf("maskedPath %v is not an absolute path", maskedPath), + rspec.Version)) } } for _, readonlyPath := range v.spec.Linux.ReadonlyPaths { if !strings.HasPrefix(readonlyPath, "/") { - errs = multierror.Append(errs, fmt.Errorf("readonlyPath %v is not an absolute path", readonlyPath)) + errs = multierror.Append(errs, + specerror.NewError( + specerror.ReadonlyPathsAbs, + fmt.Errorf("readonlyPath %v is not an absolute path", readonlyPath), + rspec.Version)) } } @@ -709,7 +800,7 @@ func (v *Validator) CheckLinuxResources() (errs error) { } for index := 0; index < len(r.Devices); index++ { switch r.Devices[index].Type { - case "a", "b", "c": + case "a", "b", "c", "": default: errs = multierror.Append(errs, fmt.Errorf("type of devices %s is invalid", r.Devices[index].Type)) } @@ -825,12 +916,19 @@ func (v *Validator) rlimitValid(rlimit rspec.POSIXRlimit) (errs error) { } if v.platform == "linux" { - for _, val := range defaultRlimits { + for _, val := range linuxRlimits { + if val == rlimit.Type { + return + } + } + errs = multierror.Append(errs, specerror.NewError(specerror.PosixProcRlimitsTypeValueError, fmt.Errorf("rlimit type %q may not be valid", rlimit.Type), v.spec.Version)) + } else if v.platform == "solaris" { + for _, val := range posixRlimits { if val == rlimit.Type { return } } - errs = multierror.Append(errs, fmt.Errorf("rlimit type %q is invalid", rlimit.Type)) + errs = multierror.Append(errs, specerror.NewError(specerror.PosixProcRlimitsTypeValueError, fmt.Errorf("rlimit type %q may not be valid", rlimit.Type), v.spec.Version)) } else { logrus.Warnf("process.rlimits validation not yet implemented for platform %q", v.platform) } @@ -838,7 +936,7 @@ func (v *Validator) rlimitValid(rlimit rspec.POSIXRlimit) (errs error) { return } -func namespaceValid(ns rspec.LinuxNamespace) bool { +func (v *Validator) namespaceValid(ns rspec.LinuxNamespace) bool { switch ns.Type { case rspec.PIDNamespace: case rspec.NetworkNamespace: @@ -851,72 +949,13 @@ func namespaceValid(ns rspec.LinuxNamespace) bool { return false } - if ns.Path != "" && !filepath.IsAbs(ns.Path) { + if ns.Path != "" && !osFilepath.IsAbs(v.platform, ns.Path) { return false } return true } -func pathValid(os, path string) error { - if os == "windows" { - matched, err := regexp.MatchString("^[a-zA-Z]:(\\\\[^\\\\/<>|:*?\"]+)+$", path) - if err != nil { - return err - } - if !matched { - return fmt.Errorf("invalid windows path %v", path) - } - return nil - } - if !filepath.IsAbs(path) { - return fmt.Errorf("%v is not an absolute path", path) - } - return nil -} - -// Check whether pathB is nested whithin pathA -func nestedValid(os, pathA, pathB string) (bool, error) { - if pathA == pathB { - return false, nil - } - if pathA == "/" && pathB != "" { - return true, nil - } - - var sep string - if os == "windows" { - sep = "\\" - } else { - sep = "/" - } - - splitedPathA := strings.Split(filepath.Clean(pathA), sep) - splitedPathB := strings.Split(filepath.Clean(pathB), sep) - lenA := len(splitedPathA) - lenB := len(splitedPathB) - - if lenA > lenB { - if (lenA - lenB) == 1 { - // if pathA is longer but not end with separator - if splitedPathA[lenA-1] != "" { - return false, nil - } - splitedPathA = splitedPathA[:lenA-1] - } else { - return false, nil - } - } - - for i, partA := range splitedPathA { - if partA != splitedPathB[i] { - return false, nil - } - } - - return true, nil -} - func deviceValid(d rspec.LinuxDevice) bool { switch d.Type { case "b", "c", "u": @@ -924,7 +963,7 @@ func deviceValid(d rspec.LinuxDevice) bool { return false } case "p": - if d.Major > 0 || d.Minor > 0 { + if d.Major != 0 || d.Minor != 0 { return false } default: @@ -935,7 +974,6 @@ func deviceValid(d rspec.LinuxDevice) bool { func seccompActionValid(secc rspec.LinuxSeccompAction) bool { switch secc { - case "": case rspec.ActKill: case rspec.ActTrap: case rspec.ActErrno: |